#!/usr/bin/env python3
"""Cycle each health status LED through red, orange, green, then off.

Hardware smoke test for the three RGB LEDs (red + green channels only).
Pin map matches overview.md. Do not run while a health daemon owns these GPIOs.

On the Pi:
    python3 health/led_test.py
    python3 health/led_test.py --dry-run   # off-Pi / no GPIO

Requires: python3-gpiozero (sudo apt install python3-gpiozero)
"""

from __future__ import annotations

import argparse
import signal
import sys
import time
from pathlib import Path

# Allow: cd src && python3 health/led_test.py
_SRC = Path(__file__).resolve().parent.parent
if str(_SRC) not in sys.path:
    sys.path.insert(0, str(_SRC))

from health.leds import DEFAULT_LED_PINS, Color, RgLed  # noqa: E402

STEP_S = 1.0
COLORS: tuple[Color, ...] = ("red", "orange", "green", "off")

_stop = False


def _handle_signal(signum: int, _frame: object) -> None:
    global _stop
    print(f"\nReceived signal {signum}, stopping…", flush=True)
    _stop = True


def run_cycle(leds: list[RgLed]) -> None:
    for led in leds:
        if _stop:
            return
        print(f"{led.name} LED", flush=True)
        for color in COLORS:
            if _stop:
                return
            led.set_color(color)
            if color != "off":
                time.sleep(STEP_S)


def main() -> int:
    global _stop
    parser = argparse.ArgumentParser(description="Cycle health status LEDs through red/orange/green/off.")
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Print sequence only; do not use GPIO.",
    )
    args = parser.parse_args()

    signal.signal(signal.SIGINT, _handle_signal)
    signal.signal(signal.SIGTERM, _handle_signal)

    leds = [RgLed(name, r, g, dry_run=args.dry_run) for name, r, g in DEFAULT_LED_PINS]
    try:
        for led in leds:
            led.open()
        print("Cycling Temp → Control → Web (Ctrl+C to stop)", flush=True)
        while not _stop:
            run_cycle(leds)
    finally:
        for led in leds:
            led.off()
            led.close()
        print("All LED channels off.", flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
