"""Service Requested (helpreq.mp4) HDMI session.

Heltec PIN11 Call Attendant sends /flag/helpreq/1, then /flag/helpreq/0 when
the lamp stops blinking. HDMI plays until Cancel or 30s, whichever first.
A Cancel after timeout is ignored. Heartbeat holds the Heltec assertion
after timeout so the same session cannot retrigger. A new /1 after /0
starts another 30s.
"""

from __future__ import annotations

import time
from typing import Callable


HELPREQ_DISPLAY_SEC = 30.0


class HelpreqSession:
    def __init__(
        self,
        display_sec: float = HELPREQ_DISPLAY_SEC,
        monotonic: Callable[[], float] = time.monotonic,
    ) -> None:
        self.display_sec = float(display_sec)
        self._mono = monotonic
        self.showing = False
        self.held = False
        self.until = 0.0

    def on_flag(self, state: int) -> bool:
        """Apply /flag/helpreq/0|1. True if HDMI showing just turned on."""
        if state == 1:
            if self.held:
                return False
            was = self.showing
            self.held = True
            self.showing = True
            self.until = self._mono() + self.display_sec
            return not was
        if state == 0:
            self.held = False
            self.showing = False
            return False
        return False

    def poll(self) -> bool:
        """Clear HDMI after 30s. True if showing just expired."""
        if self.showing and self._mono() >= self.until:
            self.showing = False
            return True
        return False
