from __future__ import annotations

import json

from app.core.agent.processes.v2.intent_router.routers.route_catalog import V2RouteCatalog
from app.core.agent.utils.llm import AgentLlmService


class V2LlmRouter:
    def __init__(
        self,
        llm: AgentLlmService,
        prompt_name: str = "v2_intent_router.route",
        catalog: V2RouteCatalog | None = None,
    ) -> None:
        self._llm = llm
        self._prompt_name = prompt_name
        self._catalog = catalog or V2RouteCatalog()

    def classify(
        self,
        *,
        normalized_query: str,
        target_terms: list[str],
        anchors: dict,
        scope_type: str = "unknown",
    ) -> dict | None:
        payload = {
            "normalized_query": normalized_query,
            "target_terms": target_terms,
            "scope_type": scope_type,
            "anchors": anchors,
            "allowed_routes": self._catalog.allowed_routes(),
        }
        raw = self._llm.generate(
            self._prompt_name,
            json.dumps(payload, ensure_ascii=False, indent=2),
            log_context="v2_intent_router",
        )
        return self._parse(raw)

    def _parse(self, raw: str) -> dict | None:
        try:
            data = json.loads(str(raw or "").strip())
        except json.JSONDecodeError:
            return None
        return {
            "routing_domain": str(data.get("routing_domain") or "").strip(),
            "intent": str(data.get("intent") or "").strip(),
            "subintent": str(data.get("subintent") or "").strip(),
            "confidence": data.get("confidence"),
            "reason_short": str(data.get("reason_short") or "").strip(),
        }
