from __future__ import annotations

from dataclasses import dataclass, field

from app.core.agent.utils.process_v2.anchor_signals import anchor_signal_types
from app.core.agent.utils.process_v2.models import RetrievedFile, RetrievedSummary, V2AnchorType, V2Intent, V2RouteResult


@dataclass(slots=True)
class EvidenceGateDecision:
    passed: bool
    answer_mode: str
    reason: str
    message: str = ""
    supporting_paths: list[str] = field(default_factory=list)


class DocsEvidenceGate:
    def check_summaries(self, route: V2RouteResult, documents: list[RetrievedSummary]) -> EvidenceGateDecision:
        if route.intent == V2Intent.GENERAL_QA:
            if documents:
                return EvidenceGateDecision(True, "grounded_summary", "general_docs_found")
            return EvidenceGateDecision(
                False,
                "insufficient_evidence",
                "general_docs_missing",
                "В найденной документации нет достаточной опоры для общего summary по запросу.",
            )
        if self._has_target_document(route, [item.path for item in documents]):
            return EvidenceGateDecision(True, "grounded_summary", "target_doc_found")
        return EvidenceGateDecision(
            False,
            "insufficient_evidence",
            "target_doc_missing",
            self._summary_insufficiency(route, documents),
            [item.path for item in documents[:3]],
        )

    def check_files(self, route: V2RouteResult, files: list[RetrievedFile]) -> EvidenceGateDecision:
        if not files:
            return EvidenceGateDecision(
                False,
                "insufficient_evidence",
                "no_file_candidates",
                "Не нашёл файлов документации, которые уверенно соответствуют запросу.",
            )
        if files[0].confidence >= 0.8:
            return EvidenceGateDecision(True, "deterministic", "primary_file_confident")
        return EvidenceGateDecision(
            False,
            "deterministic",
            "low_confidence_shortlist",
            "Нашёл только ближайшие кандидаты по запросу.",
            [item.path for item in files[:4]],
        )

    def _has_target_document(self, route: V2RouteResult, paths: list[str]) -> bool:
        if any(path in route.anchors.target_doc_hints for path in paths):
            return True
        signals = anchor_signal_types(route)
        if V2AnchorType.API_ENDPOINT in signals:
            return any(path.startswith("docs/api/") for path in paths)
        if V2AnchorType.ARCHITECTURE in signals:
            return any(path.startswith("docs/architecture/") for path in paths)
        if V2AnchorType.LOGIC_FLOW in signals:
            return any(path.startswith("docs/logic/") for path in paths)
        if V2AnchorType.DOMAIN_ENTITY in signals:
            return any(path.startswith("docs/domains/") for path in paths)
        return bool(paths)

    def _summary_insufficiency(self, route: V2RouteResult, documents: list[RetrievedSummary]) -> str:
        base = "В поднятом контексте не найден целевой документ по запросу."
        if not documents:
            return base
        nearby = ", ".join(item.path for item in documents[:3])
        return f"{base} Ближайшие документы: {nearby}."
