from __future__ import annotations

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


class V2RouteValidator:
    def __init__(self, catalog: V2RouteCatalog | None = None) -> None:
        self._catalog = catalog or V2RouteCatalog()

    def validate(self, candidate: dict | None) -> dict | None:
        if not isinstance(candidate, dict):
            return None
        routing_domain = self._value(candidate, "routing_domain")
        intent = self._value(candidate, "intent")
        subintent = self._value(candidate, "subintent")
        if not self._catalog.is_allowed(routing_domain, intent, subintent):
            return None
        return {
            "routing_domain": routing_domain,
            "intent": intent,
            "subintent": subintent,
            "confidence": self._coerce_confidence(candidate.get("confidence")),
            "reason_short": self._value(candidate, "reason_short"),
        }

    def _value(self, candidate: dict, key: str) -> str:
        return str(candidate.get(key) or "").strip()

    def _coerce_confidence(self, value: object) -> float:
        try:
            confidence = float(value)
        except (TypeError, ValueError):
            return 0.0
        return max(0.0, min(1.0, confidence))
