"""Spread analysis over a quote sequence."""

from __future__ import annotations

from dataclasses import dataclass
from typing import List, Optional

from sd_api.models.quote import Quote


@dataclass
class SpreadStats:
    """Spread statistics.

    Attributes
    ----------
    spread_mean : float | None
        Mean spread value.
    spread_max : float | None
        Maximum spread.
    spread_min : float | None
        Minimum spread.
    spread_std : float | None
        Standard deviation of spread.
    total : int
        Total number of quotes.
    """
    spread_mean: Optional[float]
    spread_max: Optional[float]
    spread_min: Optional[float]
    spread_std: Optional[float]
    total: int


def spread_series(quotes: List[Quote]) -> List[float]:
    """Extract the spread series from a list of Quotes.

    Returns a list of spread values (None → 0).
    """
    return [q.spread if q.spread is not None else 0.0 for q in quotes]


def spread_stats(quotes: List[Quote]) -> SpreadStats:
    """Compute spread statistics from a list of Quotes.

    Parameters
    ----------
    quotes : List[Quote]

    Returns
    -------
    SpreadStats
    """
    spreads = [q.spread for q in quotes if q.spread is not None]

    if not spreads:
        return SpreadStats(
            spread_mean=None,
            spread_max=None,
            spread_min=None,
            spread_std=None,
            total=len(quotes),
        )

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

    return SpreadStats(
        spread_mean=round(mean, 4),
        spread_max=mx,
        spread_min=mn,
        spread_std=round(std, 4),
        total=len(quotes),
    )
