import numpy as np


class ReplayStatsTracker:
    """Accumulates per-frame statistics across a replay session."""

    def __init__(self) -> None:
        self.history: list[dict] = []
        self.running_avg: float = 0.0

    def track(self, frame_index: int, temperatures: list[float]) -> dict:
        arr = np.array(temperatures, dtype=np.float32)
        clean_arr = arr[np.isfinite(arr)]

        if clean_arr.size == 0:
            stats = {"frame": frame_index, "min":0.0, "max":0.0, "avg":0.0, "std":0.0}
        else:
            stats = {
                "frame": frame_index,
                "min": float(np.min(clean_arr)),
                "max": float(np.max(clean_arr)),
                "avg": float(np.mean(clean_arr)),
                "std": float(np.std(clean_arr)),
            }

        self.history.append(stats)
        self.running_avg = float(np.mean([s["avg"] for s in self.history]))
        return stats

    def get_trend(self) -> list[float]:
        """Return list of per-frame averages for the trend chart."""
        return [s["avg"] for s in self.history]

    def reset(self) -> None:
        self.history.clear()
        self.running_avg = 0.0
