from __future__ import annotations

from app.core.agent.processes.v2.intent_router.models import QueryFeatures
from app.core.agent.utils.process_v2.models import V2Domain, V2Intent, V2RouteResult, V2Subintent
from app.core.agent.processes.v2.intent_router.routers.docs_subintent_resolver import DocsSubintentResolver


class V2DeterministicRouter:
    _GENERAL_MARKERS = (
        "что это за сервис",
        "для чего нужен",
        "какую задачу решает",
        "что входит в документацию",
        "какие документы стоит читать сначала",
        "дай короткое summary",
        "с чего начать",
        "что тут есть кроме api",
        "как в целом устроено приложение",
        "какие основные части есть",
        "из чего состоит telegram notify app",
    )

    def __init__(self, subintent_resolver: DocsSubintentResolver | None = None) -> None:
        self._subintent_resolver = subintent_resolver or DocsSubintentResolver()

    def route(self, user_query: str, features: QueryFeatures, anchors) -> V2RouteResult | None:
        subintent = self._subintent_resolver.resolve(features)
        if subintent == V2Subintent.FIND_FILES:
            return self._build_docs_route(user_query, features, anchors, subintent, "deterministic file anchor")
        if subintent is not None and not self._has_conflicting_doc_anchors(features):
            return self._build_docs_route(user_query, features, anchors, subintent, "deterministic signal")
        if self._is_general_summary(features.normalized_query):
            return V2RouteResult(
                routing_domain=V2Domain.GENERAL,
                intent=V2Intent.GENERAL_QA,
                subintent=V2Subintent.SUMMARY,
                user_query=user_query,
                normalized_query=features.normalized_query,
                target_terms=features.target_terms,
                anchors=anchors,
                confidence=1.0,
                routing_mode="deterministic",
                llm_router_used=False,
                reason_short="general fallback signal",
            )
        return None

    def _build_docs_route(self, user_query: str, features: QueryFeatures, anchors, subintent: str, reason: str) -> V2RouteResult:
        return V2RouteResult(
            routing_domain=V2Domain.DOCS,
            intent=V2Intent.DOC_EXPLAIN,
            subintent=subintent,
            user_query=user_query,
            normalized_query=features.normalized_query,
            target_terms=features.target_terms,
            anchors=anchors,
            confidence=1.0,
            routing_mode="deterministic",
            llm_router_used=False,
            reason_short=reason,
        )

    def _is_general_summary(self, normalized_query: str) -> bool:
        query = normalized_query.lower()
        return any(marker in query for marker in self._GENERAL_MARKERS)

    def _has_conflicting_doc_anchors(self, features: QueryFeatures) -> bool:
        signals = 0
        signals += 1 if features.endpoint_paths or features.endpoint_markers else 0
        signals += 1 if features.architecture_markers else 0
        signals += 1 if features.logic_markers else 0
        signals += 1 if features.domain_markers else 0
        return signals > 1
