#!/usr/bin/env python3
"""
display_toggle.py

Repeatedly toggles the display ON/OFF via HTTP PUT.
Run this while probing the 1.8 V rail manually on the scope.

Usage:
    python display_toggle.py                  # default: 2s ON, 1s OFF, forever
    python display_toggle.py --on 5 --off 2   # 5s ON, 2s OFF
    python display_toggle.py --count 20       # stop after 20 cycles
    python display_toggle.py --on 0.5         # fast toggle

Ctrl+C to stop cleanly.
"""

import argparse
import requests
import time

DEVICE_URL = "http://192.168.45.8:5000/display"


def toggle(state: str) -> bool:
    try:
        r = requests.put(DEVICE_URL, json={"state": state}, timeout=3)
        return r.ok
    except requests.exceptions.RequestException as e:
        print(f"  WARNING: {state.upper()} request failed — {e}")
        return False


def main():
    parser = argparse.ArgumentParser(description="Toggle display ON/OFF for scope probing")
    parser.add_argument("--on",    type=float, default=2.0, metavar="SEC",
                        help="Seconds to hold display ON  (default: 2.0)")
    parser.add_argument("--off",   type=float, default=1.0, metavar="SEC",
                        help="Seconds to hold display OFF (default: 1.0)")
    parser.add_argument("--count", type=int,   default=0,   metavar="N",
                        help="Number of ON/OFF cycles, 0 = run forever (default: 0)")
    args = parser.parse_args()

    cycles = 0
    print(f"Display toggle — ON: {args.on}s  OFF: {args.off}s  "
          f"Cycles: {'∞' if args.count == 0 else args.count}")
    print("Ctrl+C to stop\n")

    try:
        while args.count == 0 or cycles < args.count:
            cycles += 1
            label = f"Cycle {cycles}" + (f"/{args.count}" if args.count else "")

            toggle("on")
            print(f"[{label}] ON", flush=True)
            time.sleep(args.on)

            toggle("off")
            print(f"[{label}] OFF", flush=True)
            time.sleep(args.off)

    except KeyboardInterrupt:
        print(f"\nStopped after {cycles} cycle(s). Display left in last state.")


if __name__ == "__main__":
    main()
