#!/usr/bin/env python3
"""Send one status word to the Claude status light on the Arduino.

Usage:  python3 claude_light.py WORK|WAIT|DONE|FAIL|IDLE

Standard library only (no pyserial). Finds /dev/cu.usbmodem*, sends the word,
exits. If no Arduino is plugged in it says so and exits 0, so a Claude Code
hook that calls this can never block a session.

Note: opening the port makes the UNO restart once, so each call takes about
2 seconds. A faster always-on version comes later if we like the light.
"""
import glob
import os
import sys
import termios
import time

STATES = {"IDLE", "WORK", "WAIT", "DONE", "FAIL"}


def find_port():
    ports = sorted(glob.glob("/dev/cu.usbmodem*"))
    return ports[0] if ports else None


def send(port, word):
    fd = os.open(port, os.O_RDWR | os.O_NOCTTY)
    try:
        attrs = termios.tcgetattr(fd)
        # raw 8N1 at 9600 baud
        attrs[0] = 0
        attrs[1] = 0
        attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
        attrs[3] = 0
        attrs[4] = termios.B9600
        attrs[5] = termios.B9600
        termios.tcsetattr(fd, termios.TCSANOW, attrs)
        time.sleep(2.0)  # UNO restarts when the port opens
        os.write(fd, (word + "\n").encode())
        time.sleep(0.2)
    finally:
        os.close(fd)


def main():
    if len(sys.argv) != 2 or sys.argv[1].upper() not in STATES:
        print("usage: claude_light.py IDLE|WORK|WAIT|DONE|FAIL")
        return 2
    word = sys.argv[1].upper()
    port = find_port()
    if not port:
        print("claude_light: no Arduino plugged in, nothing sent")
        return 0
    try:
        send(port, word)
    except OSError as e:
        print(f"claude_light: could not use {port}: {e}")
        return 0
    print(f"claude_light: sent {word} to {port}")
    return 0


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