from __future__ import annotations

from dataclasses import asdict

from app.core.agent.utils.process_v2.models import V2RouteAnchors, V2RouteResult
from app.core.agent.utils.process_v2.plan_resolver import V2RetrievalPolicyResolver
from tests.pipeline_setup_v4.core.models import ExecutionPayload, V4Case


class ProcessV2RetrievalPolicyExecutor:
    def __init__(self) -> None:
        self._resolver = V2RetrievalPolicyResolver()

    def execute(self, case: V4Case) -> ExecutionPayload:
        route = self._build_route(case.route)
        plan = self._resolver.resolve(route)
        actual = {
            "profile": plan.profile,
            "layers": list(plan.layers),
            "limit": plan.limit,
            "filters": dict(plan.filters),
        }
        details = {
            "route": asdict(route),
            "plan": actual,
        }
        return ExecutionPayload(actual=actual, details=details)

    def _build_route(self, raw: dict[str, object]) -> V2RouteResult:
        anchors_raw = dict(raw.get("anchors") or {})
        return V2RouteResult(
            routing_domain=str(raw.get("routing_domain") or ""),
            intent=str(raw.get("intent") or ""),
            subintent=str(raw.get("subintent") or ""),
            user_query=str(raw.get("user_query") or raw.get("normalized_query") or raw.get("name") or "resolver case"),
            normalized_query=str(raw.get("normalized_query") or raw.get("user_query") or "resolver case"),
            target_terms=[str(item) for item in raw.get("target_terms") or [] if str(item).strip()],
            anchors=V2RouteAnchors(
                entity_names=[str(item) for item in anchors_raw.get("entity_names") or [] if str(item).strip()],
                file_names=[str(item) for item in anchors_raw.get("file_names") or [] if str(item).strip()],
                endpoint_paths=[str(item) for item in anchors_raw.get("endpoint_paths") or [] if str(item).strip()],
                target_doc_hints=[str(item) for item in anchors_raw.get("target_doc_hints") or [] if str(item).strip()],
                matched_aliases=[str(item) for item in anchors_raw.get("matched_aliases") or [] if str(item).strip()],
                process_domain=str(anchors_raw.get("process_domain") or "").strip() or None,
                process_subdomain=str(anchors_raw.get("process_subdomain") or "").strip() or None,
            ),
            confidence=float(raw.get("confidence") or 1.0),
            routing_mode=str(raw.get("routing_mode") or "test_fixture"),
            llm_router_used=bool(raw.get("llm_router_used") or False),
            reason_short=str(raw.get("reason_short") or "fixture route"),
        )
