"""Module-level telemetry singleton."""

from __future__ import annotations

import contextlib

from llmhosts.telemetry.emitter import TelemetryEmitter
from llmhosts.telemetry.events import PerformanceEvent, RoutingEvent, TelemetryTier

# Module-level singleton -- one per uvicorn worker process
_emitter: TelemetryEmitter | None = None


def get_emitter() -> TelemetryEmitter:
    global _emitter
    if _emitter is None:
        _emitter = TelemetryEmitter(enabled=True)
    return _emitter


def emit_routing_event(
    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 = "",
) -> None:
    """Emit a routing event. Never raises."""
    try:
        event = RoutingEvent.from_request(
            query=query,
            tier=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,
        )
        get_emitter().emit(event)
    except Exception:
        pass  # telemetry must never affect the request path


def emit_performance_event(event: PerformanceEvent) -> None:
    """Emit a GPU performance event. Never raises."""
    with contextlib.suppress(Exception):
        get_emitter().emit_performance(event)


def telemetry_status() -> dict:
    """Return current telemetry status."""
    try:
        return get_emitter().status()
    except Exception:
        return {"enabled": False, "error": "unavailable"}
