"""Performance metrics for SalTTS."""

import time
from typing import Dict, List, Optional

import numpy as np
from prometheus_client import Counter, Gauge, Histogram


class LatencyTracker:
    """Track latency metrics."""

    def __init__(self):
        """Initialize latency tracker."""
        self.latencies: List[float] = []
        self.histogram = Histogram(
            "saltts_latency_seconds",
            "Latency in seconds",
            buckets=[0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.5, 1.0],
        )

    def record(self, latency: float) -> None:
        """Record a latency measurement.

        Args:
            latency: Latency in seconds
        """
        self.latencies.append(latency)
        self.histogram.observe(latency)

    def get_stats(self) -> Dict[str, float]:
        """Get latency statistics.

        Returns:
            Dictionary of statistics
        """
        if not self.latencies:
            return {}

        latencies = np.array(self.latencies)
        return {
            "mean": float(np.mean(latencies)),
            "median": float(np.median(latencies)),
            "p50": float(np.percentile(latencies, 50)),
            "p95": float(np.percentile(latencies, 95)),
            "p99": float(np.percentile(latencies, 99)),
            "min": float(np.min(latencies)),
            "max": float(np.max(latencies)),
        }

    def reset(self) -> None:
        """Reset latency measurements."""
        self.latencies.clear()


class MetricsCollector:
    """Collect and track various metrics."""

    def __init__(self):
        """Initialize metrics collector."""
        self.latency_tracker = LatencyTracker()
        self.request_counter = Counter("saltts_requests_total", "Total requests")
        self.error_counter = Counter("saltts_errors_total", "Total errors")
        self.active_requests = Gauge("saltts_active_requests", "Active requests")

    def record_request(self) -> None:
        """Record a request."""
        self.request_counter.inc()
        self.active_requests.inc()

    def record_completion(self, latency: float) -> None:
        """Record request completion.

        Args:
            latency: Request latency in seconds
        """
        self.latency_tracker.record(latency)
        self.active_requests.dec()

    def record_error(self) -> None:
        """Record an error."""
        self.error_counter.inc()
        self.active_requests.dec()

    def get_summary(self) -> Dict[str, any]:
        """Get metrics summary.

        Returns:
            Dictionary of metrics
        """
        return {
            "latency": self.latency_tracker.get_stats(),
            "total_requests": self.request_counter._value.get(),
            "total_errors": self.error_counter._value.get(),
            "active_requests": self.active_requests._value.get(),
        }
