"""Latency analysis: statistics over a sequence of Quotes."""

from __future__ import annotations

from dataclasses import dataclass
from typing import List, Optional

from sd_api.models.quote import Quote


@dataclass
class LatencyStats:
    """Latency statistics computed from a sequence of quotes.

    Attributes
    ----------
    latency_mean : float | None
        Average latency in milliseconds.
    latency_max : int | None
        Maximum observed latency in ms.
    latency_min : int | None
        Minimum observed latency in ms.
    latency_std : float | None
        Standard deviation of latency.
    stale_ratio : float | None
        Fraction of quotes where is_stale == True.
    total : int
        Total number of quotes considered.
    """
    latency_mean: Optional[float]
    latency_max: Optional[int]
    latency_min: Optional[int]
    latency_std: Optional[float]
    stale_ratio: Optional[float]
    total: int


def latency_summary(quotes: List[Quote]) -> LatencyStats:
    """Compute latency statistics from a list of Quotes.

    Parameters
    ----------
    quotes : List[Quote]
        Chronological list of Quote objects.

    Returns
    -------
    LatencyStats
        Aggregate statistics. Fields may be None if no valid data.
    """
    latencies = [q.latency_ms for q in quotes if q.latency_ms is not None]
    stale_count = sum(1 for q in quotes if q.is_stale is True)

    if not latencies:
        return LatencyStats(
            latency_mean=None,
            latency_max=None,
            latency_min=None,
            latency_std=None,
            stale_ratio=0.0 if quotes else None,
            total=len(quotes),
        )

    mean = sum(latencies) / len(latencies)
    mx = max(latencies)
    mn = min(latencies)
    variance = sum((x - mean) ** 2 for x in latencies) / len(latencies)
    std = variance ** 0.5

    return LatencyStats(
        latency_mean=round(mean, 2),
        latency_max=mx,
        latency_min=mn,
        latency_std=round(std, 2),
        stale_ratio=round(stale_count / len(quotes), 4),
        total=len(quotes),
    )
