from __future__ import annotations

from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from typing import Any

import yaml


ROOT = Path(__file__).resolve().parents[3]
PROFILE_ROOT = ROOT / "config" / "company_profiles"


@dataclass(frozen=True)
class CompanyWorkflowProfile:
    company: str
    name: str
    version: str
    defaults: dict[str, Any] = field(default_factory=dict)
    documents: dict[str, Any] = field(default_factory=dict)
    payment_terms: dict[str, str] = field(default_factory=dict)
    delivery_terms: dict[str, str] = field(default_factory=dict)
    commercial_stages: list[dict[str, str]] = field(default_factory=list)
    actions: dict[str, Any] = field(default_factory=dict)
    followups: dict[str, Any] = field(default_factory=dict)
    ui: dict[str, Any] = field(default_factory=dict)
    email_intents: dict[str, Any] = field(default_factory=dict)

    def action_label(self, code: str, fallback: str | None = None) -> str:
        raw = self.actions.get(str(code or ""), {})
        if isinstance(raw, dict) and raw.get("label"):
            return str(raw["label"])
        return fallback or str(code or "Acompanhar")

    def action_description(self, code: str, fallback: str = "") -> str:
        raw = self.actions.get(str(code or ""), {})
        if isinstance(raw, dict) and raw.get("description"):
            return str(raw["description"])
        return fallback


def _read_yaml(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
    return data if isinstance(data, dict) else {}


@lru_cache(maxsize=16)
def load_company_profile(company: str = "blif") -> CompanyWorkflowProfile:
    """Load a workflow profile from config/company_profiles.

    Missing optional files are allowed so a new company can start with only a
    workflow.yaml and inherit conservative defaults.
    """

    key = str(company or "blif").strip().lower() or "blif"
    profile_dir = PROFILE_ROOT / key
    if not profile_dir.exists():
        profile_dir = PROFILE_ROOT / "default"
        key = "default"

    workflow = _read_yaml(profile_dir / "workflow.yaml")
    labels = _read_yaml(profile_dir / "labels.yaml")
    ui = _read_yaml(profile_dir / "ui.yaml")
    email_intents = _read_yaml(profile_dir / "email_intents.yaml")

    return CompanyWorkflowProfile(
        company=str(workflow.get("company") or key),
        name=str(workflow.get("profile_name") or labels.get("profile_name") or key.upper()),
        version=str(workflow.get("version") or "workflow-profile-v1"),
        defaults=dict(workflow.get("defaults") or {}),
        documents=dict(workflow.get("documents") or {}),
        payment_terms=dict(workflow.get("payment_terms") or {}),
        delivery_terms=dict(workflow.get("delivery_terms") or {}),
        commercial_stages=list(workflow.get("commercial_stages") or []),
        actions=dict(labels.get("actions") or workflow.get("actions") or {}),
        followups=dict(workflow.get("followups") or {}),
        ui=dict(ui or workflow.get("ui") or {}),
        email_intents=dict(email_intents.get("email_intents") or email_intents or {}),
    )
