#!/usr/bin/env python3
# agent-lamp - IKEA TRADFRI bulb as a notification light for coding agents
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Light an IKEA TRADFRI colour bulb when a coding agent needs you.

Usage: agent-lamp STATE SESSION        permission|question|error|complete|clear
       agent-lamp claude               a Claude Code hook payload on stdin
       agent-lamp reset                clear every session, restore the bulb
       agent-lamp --pair HOST CODE     pair with the gateway, list its bulbs
       agent-lamp --selftest

Purple: a permission waits. Amber: a question waits. Red: an agent failed.
Green: an agent finished. A permission or question left waiting starts to
breathe; several agents wanting different things cycle through their
colours. When nothing is left the bulb goes back to how it was. Unknown
state words do nothing, so hook callers never break. Without a paired
gateway or without coap-client, every command does nothing.
"""
import colorsys
import contextlib
import fcntl
import json
import os
import secrets
import shutil
import subprocess
import sys
import time
from pathlib import Path

# Colours are tuned on the real bulb; only the hue survives the saturation
# floor, so they are effectively hue picks.
COLOURS = {"permission": "#a000ff", "question": "#ffa000",
           "error": "#ff0000", "complete": "#00ff40"}
CLEARS = ("clear", "user_message", "user_cancelled")

# Highest first: the order a multi-colour cycle walks.
PRIORITY = ("permission", "question", "error", "complete")
WAITING = ("permission", "question")

# Calibration. Brightness 0..254. Times in seconds.
BRIGHT = 254
DIM = 60
ESCALATE = 120   # a wait this long starts to breathe
BREATHE = 2      # each half of a breath
CYCLE = 4        # each colour of a multi-colour cycle
TICK = 1         # renderer loop period
FADE = 20        # transition, tenths of a second
TIMEOUT = 5      # per gateway request
RESTORE_TRIES = 10  # ticks a failing restore is retried before giving up

CONFIG = Path.home() / ".config/agent-lamp/tradfri.json"
# No XDG_RUNTIME_DIR, no lamp: a shared /tmp fallback could be squatted.
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or "/nonexistent")
DIR = RUNTIME / "agent-lamp"
# quickshell's statusctl mode file; read directly so the shell need not run.
NOLAMP = RUNTIME / "status.nolamp"

# IPSO object ids the gateway uses: 15001 devices, 3311 light control,
# 5850 on/off, 5851 brightness, 5707 hue, 5708 saturation, 5709/5710 colour
# xy, 5712 transition. Hue and saturation run 0..65279.
DEVICES, LIGHT = "15001", "3311"
HUE_MAX = 65279

# When the last brightness fade started (monotonic). The gateway drops a
# colour sent while a brightness fade runs, so colour waits for it to end.
level_at = 0.0


def word(w):
    """The state a CLI or opencode-notifier event word means, or None."""
    if w in COLOURS:
        return w
    return "clear" if w in CLEARS else None


def from_claude(payload):
    """(state, session) for a Claude Code hook payload, or None to ignore."""
    if not isinstance(payload, dict) or not isinstance(payload.get("session_id"), str) \
            or not payload["session_id"]:
        return None
    event = payload.get("hook_event_name")
    if event == "Notification":
        state = {"permission_prompt": "permission",
                 "elicitation_dialog": "question"}.get(payload.get("notification_type"))
    elif event == "PreToolUse":
        state = "question" if payload.get("tool_name") == "AskUserQuestion" else None
    else:
        state = {"Stop": "complete", "StopFailure": "error", "PostToolUse": "clear",
                 "UserPromptSubmit": "clear", "SessionEnd": "clear"}.get(event)
    return (state, payload["session_id"]) if state else None


def apply(sessions, session, state, now):
    """Record one event in sessions, in place. True if anything changed."""
    if state == "reset":
        changed = bool(sessions)
        sessions.clear()
        return changed
    if state == "clear":
        return sessions.pop(session, None) is not None
    if sessions.get(session, {}).get("state") == state:
        return False
    sessions[session] = {"state": state, "since": now}
    return True


def frame(sessions, now):
    """(colour, brightness) the bulb shows at `now`, or None for nothing."""
    active = [p for p in PRIORITY if any(v["state"] == p for v in sessions.values())]
    if not active:
        return None
    if len(active) > 1:
        return COLOURS[active[int(now // CYCLE) % len(active)]], BRIGHT
    state = active[0]
    since = min(v["since"] for v in sessions.values() if v["state"] == state)
    if state in WAITING and now - since > ESCALATE and int(now // BREATHE) % 2:
        return COLOURS[state], DIM
    return COLOURS[state], BRIGHT


def coap(method, url, ident, key, payload=None):
    """The response body of one coaps request, or None on any failure."""
    cmd = ["coap-client", "-m", method, "-u", ident, "-k", key, "-B", str(TIMEOUT)]
    if payload is not None:
        cmd += ["-e", json.dumps(payload, separators=(",", ":"))]
    try:
        done = subprocess.run(cmd + [url], capture_output=True, text=True,
                              timeout=TIMEOUT + 2)
    except (subprocess.SubprocessError, OSError):
        return None
    # coap-client exits 0 on a 4.xx/5.xx response and prints the code on
    # stderr only (verified against the gateway: "4.04 Not Found").
    if done.returncode or done.stderr.lstrip()[:2] in ("4.", "5."):
        return None
    return done.stdout.strip()


def put(url, auth, state):
    return coap("put", url, *auth, {LIGHT: [state]}) is not None


def colour_state(colour):
    """The 3311 state fading to #rrggbb. Pastels wash out to white on the
    bulb, so saturation is floored to full and only the hue counts."""
    h, _, _ = colorsys.rgb_to_hsv(*(int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5)))
    return {"5707": round(h * HUE_MAX), "5708": HUE_MAX, "5712": FADE}


def show(urls, auth, target, shown):
    """Move the bulbs from `shown` to `target`; the new shown state.

    The gateway drops part of a request setting colour and brightness at
    once, so they go separately, colour first, and only what changed is sent.
    A colour waits out a running brightness fade, which would drop it. On a
    failed or deferred request the old state is returned, so the next tick
    retries.
    """
    global level_at
    colour, level = target
    if colour != shown[0] and time.monotonic() < level_at + FADE / 10:
        return shown
    ok = True
    for url in urls:
        if colour != shown[0]:
            ok &= put(url, auth, colour_state(colour))
        if level != shown[1]:
            ok &= put(url, auth, {"5850": 1, "5851": level, "5712": FADE})
    if level != shown[1]:
        level_at = time.monotonic()
    return target if ok else shown


def snapshot(urls, auth):
    """Each bulb's on/off, brightness and colour, or None if one is silent."""
    snap = []
    for url in urls:
        try:
            light = json.loads(coap("get", url, *auth))[LIGHT][0]
            snap.append({k: light[k] for k in ("5850", "5851", "5709", "5710")})
        except (TypeError, ValueError, KeyError, IndexError):
            return None
    return snap


def restore(urls, auth, snap):
    """Put the bulbs back as snapshot. Any colour change switches a bulb on,
    so an off bulb gets its colour first and is switched off after. True if
    every request went through."""
    time.sleep(max(0.0, level_at + FADE / 10 - time.monotonic()))
    ok = True
    for url, s in zip(urls, snap):
        ok &= put(url, auth, {"5709": s["5709"], "5710": s["5710"], "5712": FADE})
        ok &= put(url, auth, {"5850": 1, "5851": s["5851"], "5712": FADE} if s["5850"]
                  else {"5850": 0})
    return ok


def configured():
    """The gateway config, or None when there is nothing to drive."""
    if not RUNTIME.is_dir():
        return None
    try:
        cfg = json.loads(CONFIG.read_text())
    except (OSError, ValueError):
        return None
    if not cfg.get("bulbs") or not shutil.which("coap-client"):
        return None
    return cfg


@contextlib.contextmanager
def locked():
    """Hold the state lock: every read-modify-write of the state is inside."""
    DIR.mkdir(parents=True, exist_ok=True)
    with open(DIR / "state.lock", "w") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        yield


def load():
    try:
        sessions = json.loads((DIR / "state.json").read_text())
    except (OSError, ValueError):
        return {}
    return sessions if isinstance(sessions, dict) else {}


def save(sessions):
    tmp = DIR / "state.json.tmp"
    tmp.write_text(json.dumps(sessions))
    tmp.replace(DIR / "state.json")


def nolamp():
    try:
        return NOLAMP.read_text().strip() == "1"
    except OSError:
        return False


def update(session, state):
    """Record one event and wake the renderer if the state changed."""
    if not configured():
        return
    try:
        with locked():
            sessions = load()
            changed = apply(sessions, session, state, time.time())
            if changed:
                save(sessions)
    except OSError:
        return  # hook callers must never break
    if changed and state != "reset":
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--run"],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)


def wait_renderer(seconds):
    """Return once no renderer holds the run lock, or after `seconds`.

    `reset` runs right before logout, suspend or poweroff; waiting lets the
    renderer restore the bulb before the network goes.
    """
    if not configured():
        return
    DIR.mkdir(parents=True, exist_ok=True)
    end = time.monotonic() + seconds
    with open(DIR / "run.lock", "w") as f:
        while time.monotonic() < end:
            try:
                fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return
            except BlockingIOError:
                time.sleep(0.2)


def run():
    """The renderer: one at a time, by the run lock. A second one exits at
    once. No event is lost: writers spawn after releasing the state lock, and
    the renderer decides to exit and drops the run lock under that same lock,
    so either it sees the new state or the run lock is already free.
    """
    cfg = configured()
    if not cfg:
        return
    auth = cfg["identity"], cfg["key"]
    urls = [f"coaps://{cfg['host']}:5684/{DEVICES}/{b}" for b in cfg["bulbs"]]
    DIR.mkdir(parents=True, exist_ok=True)
    with open(DIR / "run.lock", "w") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return
        snap, shown, fails = None, (None, None), 0
        while True:
            with locked():
                target = frame(load(), time.time())
                paused = nolamp()
                if (target is None or paused) and snap:
                    # A failed restore keeps the snapshot and retries, so a
                    # slow gateway does not strand the bulb in an agent colour.
                    fails += 1
                    if restore(urls, auth, snap) or fails >= RESTORE_TRIES:
                        snap, shown, fails = None, (None, None), 0
                if target is None and not snap:
                    fcntl.flock(lock, fcntl.LOCK_UN)
                    return
            if target is not None and not paused:
                # ponytail: a silent gateway (just after resume) is retried
                # every tick, no backoff; add one if it ever floods the log.
                if snap is None:
                    snap = snapshot(urls, auth)
                if snap is not None:
                    shown = show(urls, auth, target, shown)
            time.sleep(TICK)


def pair(host, code):
    ident = "agent-lamp-" + secrets.token_hex(4)
    base = f"coaps://{host}:5684"
    reply = coap("post", f"{base}/15011/9063", "Client_identity", code, {"9090": ident})
    try:
        key = json.loads(reply)["9091"]
    except (TypeError, ValueError, KeyError):
        sys.exit(f"agent-lamp: pairing with {host} failed: {reply or 'no reply'}")
    bulbs = []
    for dev in json.loads(coap("get", f"{base}/{DEVICES}", ident, key) or "[]"):
        info = json.loads(coap("get", f"{base}/{DEVICES}/{dev}", ident, key) or "{}")
        # Colour bulbs report a hue; white-spectrum ones only a colour temperature.
        if "5707" in (info.get(LIGHT) or [{}])[0]:
            bulbs.append(str(dev))
            print(f"{dev}: {info.get('9001', '?')}")
    CONFIG.parent.mkdir(parents=True, exist_ok=True)
    CONFIG.write_text(json.dumps({"host": host, "identity": ident, "key": key,
                                  "bulbs": bulbs}))
    CONFIG.chmod(0o600)
    print(f"{len(bulbs)} colour bulb(s) recorded in {CONFIG}")


def selftest():
    assert word("permission") == "permission"
    assert word("complete") == "complete"
    assert word("user_message") == "clear"
    assert word("user_cancelled") == "clear"
    assert word("session_started") is None
    assert word("reset") is None

    def hook(event, **kw):
        return from_claude({"hook_event_name": event, "session_id": "s", **kw})
    assert hook("Notification", notification_type="permission_prompt") == ("permission", "s")
    assert hook("Notification", notification_type="elicitation_dialog") == ("question", "s")
    assert hook("Notification", notification_type="idle_prompt") is None
    assert hook("PreToolUse", tool_name="AskUserQuestion") == ("question", "s")
    assert hook("PreToolUse", tool_name="Bash") is None
    assert hook("Stop") == ("complete", "s")
    assert hook("StopFailure") == ("error", "s")
    for clearing in ("PostToolUse", "UserPromptSubmit", "SessionEnd"):
        assert hook(clearing) == ("clear", "s")
    assert hook("SubagentStop") is None
    assert from_claude({"hook_event_name": "Stop"}) is None
    assert from_claude([]) is None
    assert from_claude({"hook_event_name": "Stop", "session_id": 1}) is None
    # apply: a session holds one state; the same state again keeps its
    # start time, so repeated notifications do not reset the escalation.
    s = {}
    assert apply(s, "a", "permission", 10) and s == {"a": {"state": "permission", "since": 10}}
    assert not apply(s, "a", "permission", 20) and s["a"]["since"] == 10
    assert apply(s, "a", "complete", 30) and s["a"] == {"state": "complete", "since": 30}
    assert apply(s, "b", "error", 30)
    assert apply(s, "a", "clear", 40) and list(s) == ["b"]
    assert not apply(s, "a", "clear", 40)
    assert apply(s, None, "reset", 50) and s == {}
    assert not apply(s, None, "reset", 50)

    # frame: what the bulb shows at a moment, (colour, brightness) or None.
    def st(state, since=0):
        return {"state": state, "since": since}
    assert frame({}, 0) is None
    assert frame({"a": st("complete")}, 500) == (COLOURS["complete"], BRIGHT)
    assert frame({"a": st("error"), "b": st("error")}, 5) == (COLOURS["error"], BRIGHT)
    # Waiting past ESCALATE breathes; a finished agent never does.
    waiting = ESCALATE + BREATHE
    dim_at = waiting if int(waiting // BREATHE) % 2 else waiting + BREATHE
    assert frame({"a": st("permission")}, dim_at) == (COLOURS["permission"], DIM)
    assert frame({"a": st("permission")}, dim_at + BREATHE) == (COLOURS["permission"], BRIGHT)
    assert frame({"a": st("question")}, dim_at) == (COLOURS["question"], DIM)
    assert frame({"a": st("question", dim_at - 1)}, dim_at) == (COLOURS["question"], BRIGHT)
    assert frame({"a": st("complete")}, dim_at) == (COLOURS["complete"], BRIGHT)
    # Several colours cycle in priority order, at full brightness.
    two = {"a": st("error"), "b": st("permission")}
    assert frame(two, 0) == (COLOURS["permission"], BRIGHT)
    assert frame(two, CYCLE) == (COLOURS["error"], BRIGHT)
    assert frame(two, 2 * CYCLE) == (COLOURS["permission"], BRIGHT)
    assert frame(two, dim_at)[1] == BRIGHT
    # colour_state: hue from #rrggbb, saturation floored to full.
    assert colour_state("#ff0000") == {"5707": 0, "5708": HUE_MAX, "5712": FADE}
    pale = colour_state("#8080ff")
    assert (pale["5707"], pale["5708"]) == (round(HUE_MAX * 2 / 3), HUE_MAX)

    # show and restore against a fake gateway that records every request.
    global coap, level_at
    real, sent = coap, []

    def fake(method, url, ident, key, payload=None):
        sent.append((method, url, payload))
        return json.dumps({LIGHT: [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}]})
    coap = fake
    try:
        auth, urls = ("i", "k"), ["u1"]
        shown = show(urls, auth, ("#ff0000", BRIGHT), (None, None))
        assert shown == ("#ff0000", BRIGHT)
        # Colour first, brightness after, in requests of their own.
        assert [p[LIGHT][0] for _, _, p in sent] == [
            colour_state("#ff0000"), {"5850": 1, "5851": BRIGHT, "5712": FADE}]
        sent.clear()
        assert show(urls, auth, ("#ff0000", BRIGHT), shown) == shown and sent == []
        dimmed = show(urls, auth, ("#ff0000", DIM), shown)
        assert [p[LIGHT][0] for _, _, p in sent] == [{"5850": 1, "5851": DIM, "5712": FADE}]
        sent.clear()
        # A colour change waits out the brightness fade just started.
        assert show(urls, auth, ("#00ff00", DIM), dimmed) == dimmed and sent == []
        level_at = 0.0
        assert show(urls, auth, ("#00ff00", DIM), dimmed) == ("#00ff00", DIM)
        sent.clear()
        snap = snapshot(urls, auth)
        assert snap == [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}]
        sent.clear()
        assert restore(urls, auth, snap)
        # An off bulb gets its colour back, then is switched off.
        assert [p[LIGHT][0] for _, _, p in sent] == [
            {"5709": 1, "5710": 2, "5712": FADE}, {"5850": 0}]
        coap = lambda *a, **k: None
        assert snapshot(urls, auth) is None
        assert not restore(urls, auth, snap)
        assert show(urls, auth, ("#ff0000", BRIGHT), (None, None)) == (None, None)
    finally:
        coap = real
    print("ok")


def main():
    args = sys.argv[1:]
    if args == ["--selftest"]:
        return selftest()
    if args == ["--run"]:
        return run()
    if len(args) == 3 and args[0] == "--pair":
        return pair(*args[1:])
    if args == ["reset"]:
        update(None, "reset")
        return wait_renderer(15)
    if args == ["claude"]:
        try:
            event = from_claude(json.load(sys.stdin))
        except ValueError:
            return
        if event:
            update(event[1], event[0])
        return
    if len(args) == 2:
        state = word(args[0])
        if state:
            update(args[1], state)
        return
    sys.exit(__doc__.split("\n\n")[1])


if __name__ == "__main__":
    main()
