from __future__ import annotations

from dataclasses import dataclass

from pygui.backend.models.frame import Frame
from pygui.backend.models.frame_stats import Stats, compute_stats
from pygui.backend.models.stability_detector import StabilityDetector
from pygui.backend.models.threshold_classifier import ThresholdConfig, classify, resolve_bounds


@dataclass(frozen=True)
class SessionUpdate:
    seq: int
    values: list[float]
    bands: list[str]
    stats: Stats
    state: str
    target: float
    margin: float

class SessionModel:
    def __init__(self, thresholds: ThresholdConfig | None = None) -> None:
        self._config = thresholds or ThresholdConfig()
        self._stability = StabilityDetector()

    def set_thresholds(self, config: ThresholdConfig) -> None:
        self._config = config

    @property
    def auto(self) -> bool:
        return self._config.auto

    def reset(self) -> None:
        self._stability.reset()

    def process(self, frame: Frame) -> SessionUpdate:
        stats = compute_stats(frame.values)
        target, margin = resolve_bounds(frame.values, self._config)
        bands = [classify(v, target, margin)for v in frame.values]
        # State always track the user's process set_point, even in auto-color mode.
        state = self._stability.update(stats.avg, frame.time, self._config.set_point)
        return SessionUpdate(
            seq=frame.seq, values=frame.values, bands=bands,
            stats=stats, state=state, target=target, margin=margin,
        )
