from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Any

_started_at = time.monotonic()
_total_requests = 0
_auth_failures = 0
_throttle_rejections = 0


@dataclass
class _ToolMetrics:
    calls: int = 0
    errors: int = 0
    total_latency_ms: float = 0


_tool_metrics: dict[str, _ToolMetrics] = {}


def _get_or_create(tool: str) -> _ToolMetrics:
    if tool not in _tool_metrics:
        _tool_metrics[tool] = _ToolMetrics()
    return _tool_metrics[tool]


def record_tool_call(tool: str, duration_ms: float, is_error: bool) -> None:
    global _total_requests
    _total_requests += 1
    m = _get_or_create(tool)
    m.calls += 1
    m.total_latency_ms += duration_ms
    if is_error:
        m.errors += 1


def record_auth_failure() -> None:
    global _auth_failures
    _auth_failures += 1


def record_throttle_rejection() -> None:
    global _throttle_rejections
    _throttle_rejections += 1


def metrics_snapshot(active_sessions: int = 0, active_waits: int = 0) -> dict[str, Any]:
    tools: dict[str, Any] = {}
    for name, m in _tool_metrics.items():
        tools[name] = {
            "calls": m.calls,
            "errors": m.errors,
            "avgLatencyMs": round(m.total_latency_ms / m.calls) if m.calls > 0 else 0,
        }

    return {
        "uptimeSeconds": int(time.monotonic() - _started_at),
        "activeSessions": active_sessions,
        "activeWaits": active_waits,
        "totalRequests": _total_requests,
        "authFailures": _auth_failures,
        "throttleRejections": _throttle_rejections,
        "tools": tools,
    }
