"""Output contract for finance policy knowledge organizing tasks."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


@dataclass(frozen=True, slots=True)
class PolicySourceRef:
    source_id: str
    title: str
    location: str = ""
    page: str = ""

    def as_dict(self) -> dict[str, Any]:
        return {
            "source_id": self.source_id,
            "title": self.title,
            "location": self.location,
            "page": self.page,
        }


@dataclass(frozen=True, slots=True)
class PolicyKnowledgeItem:
    policy_ref: str
    title: str
    summary: str
    expense_type: str = ""
    control_stage: str = ""
    trigger_conditions: list[str] = field(default_factory=list)
    source_refs: list[PolicySourceRef] = field(default_factory=list)
    review_status: str = "pending_review"

    def as_dict(self) -> dict[str, Any]:
        return {
            "policy_ref": self.policy_ref,
            "title": self.title,
            "summary": self.summary,
            "expense_type": self.expense_type,
            "control_stage": self.control_stage,
            "trigger_conditions": list(self.trigger_conditions),
            "source_refs": [item.as_dict() for item in self.source_refs],
            "review_status": self.review_status,
        }


@dataclass(slots=True)
class PolicyKnowledgeOrganizingReport:
    summary: str
    categories: list[str] = field(default_factory=list)
    knowledge_items: list[PolicyKnowledgeItem] = field(default_factory=list)
    source_refs: list[PolicySourceRef] = field(default_factory=list)
    open_questions: list[str] = field(default_factory=list)
    next_actions: list[str] = field(default_factory=list)

    def as_dict(self) -> dict[str, Any]:
        return {
            "summary": self.summary,
            "categories": list(self.categories),
            "knowledge_items": [item.as_dict() for item in self.knowledge_items],
            "source_refs": [item.as_dict() for item in self.source_refs],
            "open_questions": list(self.open_questions),
            "next_actions": list(self.next_actions),
            "risk_policy_refs": self.risk_policy_refs(),
        }

    def risk_policy_refs(self) -> list[str]:
        return list(
            dict.fromkeys(
                item.policy_ref
                for item in self.knowledge_items
                if item.policy_ref and item.review_status in {"pending_review", "confirmed"}
            )
        )


def build_policy_ref(expense_type: str, signal: str, *, prefix: str = "policy") -> str:
    expense = _token(expense_type) or "general"
    risk_signal = _token(signal) or "control"
    return f"{prefix}.{expense}.{risk_signal}"


def _token(value: str) -> str:
    return "_".join(str(value or "").strip().lower().split())
