"""ScoreDistribution — estadisticas de distribucion de scores para retrieval."""

from __future__ import annotations

from dataclasses import dataclass, field


@dataclass
class ScoreDistribution:
    """Estadisticas de distribucion de scores para visualizacion y debugging de retrieval.

    Attributes:
        scores:     Lista de tuplas (uri, score) ordenadas de mayor a menor score.
        min_score:  Score minimo en la distribucion.
        max_score:  Score maximo en la distribucion.
        mean_score: Score medio de la distribucion.
        threshold:  Umbral aplicado para filtrar resultados.
    """

    scores: list[tuple[str, float]] = field(default_factory=list)
    min_score: float = 0.0
    max_score: float = 0.0
    mean_score: float = 0.0
    threshold: float = 0.0

    @classmethod
    def from_scores(
        cls,
        uri_scores: list[tuple[str, float]],
        threshold: float = 0.0,
    ) -> ScoreDistribution:
        """Construye ScoreDistribution calculando estadisticas desde una lista de scores.

        Args:
            uri_scores: Lista de tuplas (uri, score), no necesariamente ordenada.
            threshold:  Umbral de inclusion. Solo afecta el campo `threshold` del resultado.

        Returns:
            ScoreDistribution con scores ordenados desc y estadisticas calculadas.
        """
        if not uri_scores:
            return cls(scores=[], threshold=threshold)

        sorted_scores = sorted(uri_scores, key=lambda x: x[1], reverse=True)
        raw_scores = [s for _, s in sorted_scores]

        return cls(
            scores=sorted_scores,
            min_score=min(raw_scores),
            max_score=max(raw_scores),
            mean_score=sum(raw_scores) / len(raw_scores),
            threshold=threshold,
        )

    def to_dict(self) -> dict:
        """Serializa la distribucion a dict incluyendo count y above_threshold.

        Returns:
            dict con scores, stats, count total y count de scores sobre el umbral.
        """
        above = [s for _, s in self.scores if s >= self.threshold]
        return {
            "scores": [{"uri": uri, "score": score} for uri, score in self.scores],
            "min_score": self.min_score,
            "max_score": self.max_score,
            "mean_score": self.mean_score,
            "threshold": self.threshold,
            "count": len(self.scores),
            "above_threshold": len(above),
        }
