"""LLMHosts audit data models -- Pydantic v2 schemas for audit log entries, queries, and summaries."""

from __future__ import annotations

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

from pydantic import BaseModel, ConfigDict


class AuditEntry(BaseModel):
    """A single audit log record capturing the full lifecycle of one API request."""

    model_config = ConfigDict(frozen=False)

    request_id: str
    timestamp: datetime
    source_ip: str
    method: str  # POST
    path: str  # /v1/chat/completions
    dialect: str  # "openai" or "anthropic"
    model_requested: str
    model_used: str
    backend_type: str  # "ollama", "openai", etc.
    routing_tier: str  # "rule", "knn", etc.
    routing_reasoning: str
    routing_confidence: float
    input_tokens: int
    output_tokens: int
    actual_cost: float
    cloud_equivalent_cost: float
    cached: bool
    cache_tier: str | None = None  # "exact", "namespace", "semantic"
    latency_ms: float
    status_code: int
    error: str | None = None
    api_key_id: str = ""  # truncated API key identifier (first 8 chars + "...")
    user_id: str = ""  # user identifier from auth header or API key lookup
    hmac: str | None = None  # HMAC chain hash (TrustLedger)


class AuditQuery(BaseModel):
    """Filter parameters for querying the audit log."""

    limit: int = 100
    offset: int = 0
    start_date: datetime | None = None
    end_date: datetime | None = None
    model: str | None = None
    backend_type: str | None = None
    cached_only: bool = False


class AuditSummary(BaseModel):
    """Aggregated audit statistics for a given time period."""

    period: str
    total_requests: int
    unique_models: int
    by_backend: dict[str, int]
    by_dialect: dict[str, int]
    cache_hit_rate: float
    avg_latency_ms: float
    total_cost: float
    total_savings: float
