"""Anonymized routing telemetry events."""

from __future__ import annotations

import dataclasses
import datetime
import hashlib
from datetime import timezone
from enum import Enum


class TelemetryTier(str, Enum):
    RULE_BASED = "rule_based"
    KNNCLASSIFIER = "knn"
    MODERNBERT = "modernbert"
    LOCAL = "local"


@dataclasses.dataclass
class PerformanceEvent:
    """GPU throughput measurement event. No PII ever stored."""

    model_id: str  # e.g. "llama3.1:8b"
    quantization: str  # e.g. "Q4_K_M" or "unknown"
    gpu_model: str  # from nvidia-smi, e.g. "RTX 4060" or "cpu"
    vram_total_mb: int  # 0 if CPU
    vram_used_mb: int  # 0 if CPU
    tokens_per_second: float
    first_token_latency_ms: float
    context_length_tokens: int
    success: bool
    timestamp: datetime.datetime = dataclasses.field(
        default_factory=lambda: datetime.datetime.now(datetime.timezone.utc)
    )

    def to_dict(self) -> dict:
        return dataclasses.asdict(self)


@dataclasses.dataclass
class RoutingEvent:
    """Privacy-safe routing event. No PII ever stored."""

    query_hash: str  # SHA-256 of query, never the query itself
    tier_used: TelemetryTier
    model: str
    latency_ms: float
    input_tokens: int
    output_tokens: int
    cache_hit: bool
    privacy_level: str  # "personal", "private", "external" -- from router
    timestamp: str = dataclasses.field(default_factory=lambda: datetime.datetime.now(timezone.utc).isoformat())
    node_id: str = ""  # opaque device fingerprint (not user-identifiable)

    def to_dict(self) -> dict:
        return dataclasses.asdict(self)

    @classmethod
    def from_request(
        cls,
        query: str,
        tier: TelemetryTier,
        model: str,
        latency_ms: float,
        input_tokens: int,
        output_tokens: int,
        cache_hit: bool = False,
        privacy_level: str = "external",
        node_id: str = "",
    ) -> RoutingEvent:
        """Create event with SHA-256 hashed query -- query text is never stored."""
        query_hash = hashlib.sha256(query.encode()).hexdigest()
        return cls(
            query_hash=query_hash,
            tier_used=tier,
            model=model,
            latency_ms=latency_ms,
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            cache_hit=cache_hit,
            privacy_level=privacy_level,
            node_id=node_id,
        )
