#!/usr/bin/env python3
"""Go / no-go helper (written by Claude; runs on the Mac, not on the Arduino).

Starts the clock when your fingers touch, says when to breathe, and saves every
number the Arduino sends, with its time. It never changes the numbers.
"""
import csv, glob, os, select, subprocess, sys, termios, time

HERE = os.path.dirname(os.path.abspath(__file__))
CUES = [(60, "breathe"), (90, "breathe"), (120, "breathe"), (150, "lift")]
TOUCH_LEVEL = 20  # untouched reads about 0


def speak(word):
    subprocess.Popen(["say", word])


def open_port():
    ports = glob.glob("/dev/cu.usbmodem*")
    if not ports:
        sys.exit("The Mac does not see the Arduino. Check the USB cable.")
    try:
        fd = os.open(ports[0], os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
        a = termios.tcgetattr(fd)
        a[0] = a[1] = a[3] = 0
        a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
        a[4] = a[5] = termios.B9600
        termios.tcsetattr(fd, termios.TCSANOW, a)
    except OSError:
        sys.exit("The port is busy. Press Control + C in the old number screen, then run this again.")
    return fd


def readings(fd):
    buf, last = b"", time.time()
    while True:
        if select.select([fd], [], [], 0.2)[0]:
            try:
                buf += os.read(fd, 256)
            except BlockingIOError:
                time.sleep(0.02)
        *lines, buf = buf.split(b"\n")
        for line in lines:
            text = line.strip()
            if text.isdigit() and int(text) <= 1023:
                last = time.time()
                yield int(text)
        if time.time() - last > 8:
            sys.exit("No numbers for 8 seconds. Check the USB cable, then run this again.")


def main():
    n = 2
    while os.path.exists(os.path.join(HERE, f"breath-test-{n}.csv")):
        n += 1
    path = os.path.join(HERE, f"breath-test-{n}.csv")

    stream = readings(open_port())
    for _ in range(20):  # skip the first two seconds after the board restarts
        next(stream)

    print("\nReady. Rest your two fingers flat on the arms. The clock starts when you touch.\n")
    speak("ready")
    touched = 0
    for value in stream:
        touched = touched + 1 if value > TOUCH_LEVEL else 0
        if touched >= 10:  # one full second of contact
            break

    start = time.time()
    cues = list(CUES)
    shown = -1
    with open(path, "w", newline="") as f:
        out = csv.writer(f)
        out.writerow(["seconds", "value", "cue"])
        for value in stream:
            t = time.time() - start
            cue = ""
            if cues and t >= cues[0][0]:
                cue = cues.pop(0)[1]
                speak(cue)
                print(f"\n>>>>>  {cue.upper()}  <<<<<\n")
            out.writerow([f"{t:.1f}", value, cue])
            if int(t) != shown:
                shown = int(t)
                print(f"time {shown // 60}:{shown % 60:02d}   number {value}")
            if cue == "lift":
                break
    print(f"\nFinished. Saved: {os.path.basename(path)}")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nStopped.")
