#!/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 json
import sys

# 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")


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 payload.get("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 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
    print("ok")


def main():
    args = sys.argv[1:]
    if args == ["--selftest"]:
        return selftest()
    sys.exit(__doc__.split("\n\n")[1])


if __name__ == "__main__":
    main()
