#!/usr/bin/env python3
"""Send a message to the door sign (Arduino Uno + 1602 LCD).

Usage:
  python3 door_sign.py rec on|rec off       turn Recording mode on or off, then update the sign
  python3 door_sign.py auto                 pick the message from the time of day / Recording Studio
  python3 door_sign.py MORNING|RECORDING|SLEEP|BUSY
  python3 door_sign.py "Back in|10 minutes" top|bottom text, 16 characters per row
  python3 door_sign.py "Back in 10 minutes"  one text, split over two rows for you

Standard library only. No Arduino plugged in: says so and exits 0.
Opening the port restarts the Uno once, so a call takes about 2 seconds.
"""
import datetime, fcntl, glob, json, os, sys, termios, textwrap, time

PRESETS = {
    "MORNING":   ("Good morning", "Have a great day"),
    "RECORDING": ("RECORDING", "Do not disturb"),
    "SLEEP":     ("Sleeping", "Shh..."),
    "BUSY":      ("Studying", "Please knock"),
}
MORNING_FROM, MORNING_UNTIL = 7, 11      # morning message hours
SLEEP_FROM, SLEEP_UNTIL = 23, 7          # sleeping hours (wraps midnight)
# Recording mode is a flag file. "door_sign.py rec on" / "rec off" flips it.
# (The Recording Studio app being open does not mean it is recording, so we do not guess from that.
#  Hooking the real record button to this flag comes later, with Pep's yes.)
FLAG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "RECORDING.flag")


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


HERE = os.path.dirname(os.path.abspath(__file__))
STATE = os.path.join(HERE, "state.json")   # shared with ../claude-light/claude_light.py
LOCK = os.path.join(HERE, ".port.lock")


def load_state():
    try:
        return json.load(open(STATE))
    except Exception:
        return {}


def save_state(st):
    try:
        json.dump(st, open(STATE, "w"))
    except Exception:
        pass


def send(port, top, bottom):
    """Opens the port, sends, closes. A lock makes door_sign and claude_light take turns.
    The Uno restarts on open, so we also re-send the last status word (WORK/WAIT/FAIL) afterwards."""
    st = load_state()
    st["top"], st["bottom"] = top[:16], bottom[:16]
    lk = open(LOCK, "w")
    fcntl.flock(lk, fcntl.LOCK_EX)
    fd = os.open(port, os.O_RDWR | os.O_NOCTTY)
    try:
        a = termios.tcgetattr(fd)
        a[0] = 0; a[1] = 0; a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL; a[3] = 0
        a[4] = termios.B9600; a[5] = termios.B9600
        termios.tcsetattr(fd, termios.TCSANOW, a)
        time.sleep(2.0)  # Uno restarts when the port opens
        os.write(fd, f"{top[:16]}|{bottom[:16]}\n".encode("ascii", "replace"))
        if st.get("status") in ("WORK", "WAIT", "FAIL"):
            time.sleep(0.1)
            os.write(fd, (st["status"] + "\n").encode())
        time.sleep(0.2)
    finally:
        os.close(fd)
        fcntl.flock(lk, fcntl.LOCK_UN); lk.close()
        save_state(st)


def recording_now():
    return os.path.exists(FLAG)


def auto_preset():
    if recording_now():
        return "RECORDING"
    h = datetime.datetime.now().hour
    if h >= SLEEP_FROM or h < SLEEP_UNTIL:
        return "SLEEP"
    if MORNING_FROM <= h < MORNING_UNTIL:
        return "MORNING"
    return "BUSY"


def via_desk_brain(words):
    """If desk_brain.py is running it owns the USB port: hand the words to it. True if sent."""
    import socket as _s
    sock = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "desk-senses", ".desk_brain.sock")
    try:
        c = _s.socket(_s.AF_UNIX, _s.SOCK_DGRAM)
        c.sendto(("\n".join(words) + "\n").encode(), sock)
        c.close()
        return True
    except OSError:
        return False


def main():
    if len(sys.argv) < 2:
        print(__doc__); return 2
    arg = " ".join(sys.argv[1:]).strip()
    if arg.lower() in ("rec on", "rec off"):
        if arg.lower().endswith("on"): open(FLAG, "w").close()
        elif os.path.exists(FLAG): os.remove(FLAG)
        arg = "auto"
    if arg.lower() == "auto":
        arg = auto_preset()
    if arg.upper() in PRESETS:
        top, bottom = PRESETS[arg.upper()]
    elif "|" in arg:
        top, bottom = arg.split("|", 1)
    else:
        rows = textwrap.wrap(arg, 16)[:2] + ["", ""]
        top, bottom = rows[0], rows[1]
    if via_desk_brain([f"{top}|{bottom}"]):
        try:
            st = json.load(open(STATE))
        except Exception:
            st = {}
        st["top"], st["bottom"] = top, bottom
        json.dump(st, open(STATE, "w"))
        print(f"door_sign: {top!r} / {bottom!r} -> desk brain"); return 0
    port = find_port()
    if not port:
        print("door_sign: no Arduino plugged in, nothing sent"); return 0
    try:
        send(port, top, bottom)
    except OSError as e:
        print(f"door_sign: could not use {port}: {e}"); return 0
    print(f"door_sign: {top!r} / {bottom!r} -> {port}")
    return 0


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