"""Detect process state (Idle, Ramp, Set) from the running average temp"""
from __future__ import annotations

from typing import Optional

STATE_IDLE = "idle"
STATE_RAMP = "ramp"
STATE_SET = "set"


class StabilityDetector:
    def __init__(self, idle_below: float = 50.0, tolerance: float = 1.0,
                 settle_seconds: float = 10.0) -> None:
        self._idle_below = idle_below
        self._tolerance = tolerance
        self._settle_seconds = settle_seconds
        self._near_since: Optional[float] = None    # When avg entered the +- tolerance band


    def reset(self) -> None:
        self._near_since = None

    def update(self, avg: float, time: float, set_point: float) ->str:
        if avg < self._idle_below:
            self._near_since = None
            return STATE_IDLE
        if abs(avg - set_point) <= self._tolerance:
            if self._near_since is None:
                self._near_since = time
            if time - self._near_since >= self._settle_seconds:
                return STATE_SET
            return STATE_RAMP
        self._near_since = None
        return STATE_RAMP
