"""Pydantic models for outcome tracking."""

from __future__ import annotations

import uuid
from datetime import datetime, timezone
from typing import Literal

from pydantic import BaseModel, Field

TaskType = Literal["coding", "reasoning", "analysis", "simple_qa", "creative", "general"]


class OutcomeRecord(BaseModel):
    """A single routing outcome to persist.

    Captures the full routing decision context: what model was selected,
    what it cost vs baseline, task classification, and (optionally) whether
    the response was successful.
    """

    request_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
    timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))

    # Routing decision
    task_type: str
    model_used: str
    model_baseline: str
    provider: str

    # Token counts
    input_tokens: int = 0
    output_tokens: int = 0

    # Cost tracking (USD)
    cost_actual: float = 0.0
    cost_baseline: float = 0.0
    cost_saved: float = 0.0

    # Outcome
    success: bool | None = None
    latency_ms: int = 0

    # Routing quality metadata
    detection_confidence: float | None = None
    capability_score: float | None = None
    savings_percent: float | None = None

    model_config = {"frozen": True}


class OutcomeSummary(BaseModel):
    """Aggregated outcome statistics for a time period."""

    total_requests: int = 0
    total_cost_actual: float = 0.0
    total_cost_baseline: float = 0.0
    total_cost_saved: float = 0.0
    total_input_tokens: int = 0
    total_output_tokens: int = 0
    avg_latency_ms: float = 0.0
    avg_savings_percent: float = 0.0
    success_rate: float | None = None

    by_task_type: dict[str, int] = Field(default_factory=dict)
    by_model: dict[str, int] = Field(default_factory=dict)
    by_provider: dict[str, int] = Field(default_factory=dict)
