"""Router data models -- Pydantic v2 schemas for routing decisions and configuration."""

from __future__ import annotations

from datetime import datetime  # noqa: TC003 — Pydantic needs this at runtime
from typing import Any

from pydantic import BaseModel, Field


class AlternativeRoute(BaseModel):
    """A routing option that was considered but not selected."""

    backend_type: str
    model: str
    score: float
    reason_not_chosen: str


class RoutingDecision(BaseModel):
    """The result of the router's decision-making process."""

    backend_type: str  # "ollama", "openai", "anthropic", "openrouter", etc.
    backend_url: str  # actual URL to hit
    model: str  # resolved model name for this backend
    tier: str  # "rule" (T0), "knn" (T1), "modernbert" (T2), "qwen" (T3)
    confidence: float  # 0.0-1.0
    reasoning: str  # human-readable explanation
    factors: dict[str, Any] = Field(default_factory=dict)
    alternatives: list[AlternativeRoute] = Field(default_factory=list)
    latency_ms: float = 0.0  # how long the routing decision took
    privacy_tier: str = "public"  # "public", "private", "sensitive"
    privacy_pii_types: list[str] = Field(default_factory=list)  # PII types found in request


class RoutingRule(BaseModel):
    """A configurable routing rule.

    Supported condition types:
        - ``model_exact``: route when the requested model matches exactly
        - ``model_prefix``: route when the requested model starts with a prefix
        - ``prefer_local``: prefer Ollama when the model is available locally
        - ``cost_optimize``: prefer the cheapest backend for equivalent quality
        - ``provider_preference``: prefer a specific provider
        - ``cloud_fallback``: fall back to cloud APIs when local is unavailable
    """

    name: str
    priority: int  # lower = higher priority
    condition: str  # rule type identifier
    parameters: dict[str, Any] = Field(default_factory=dict)
    enabled: bool = True


class BackendInfo(BaseModel):
    """Information about an available backend."""

    backend_type: str  # "ollama", "openai", "anthropic", "openrouter"
    url: str
    models: list[str] = Field(default_factory=list)
    is_local: bool = False
    is_healthy: bool = True
    avg_latency_ms: float = 0.0
    last_check: datetime | None = None


class CostEstimate(BaseModel):
    """Estimated cost for a request on a specific backend."""

    backend_type: str
    model: str
    estimated_input_tokens: int = 0
    estimated_output_tokens: int = 0
    cost_per_input_token: float = 0.0
    cost_per_output_token: float = 0.0
    total_estimated_cost: float = 0.0
    currency: str = "USD"
