#!/bin/bash
# Claude Code hook for the Gremlets "Claude buddy". While Claude works, a Gremlet goes to that Claude window and
# gardens, paints or builds; when Claude is done (or needs you) it tells you, naming the project.
#
# Add to ~/.claude/settings.json (one command for every event):
#   "hooks": {
#     "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "Stop":             [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "Notification":     [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "SessionEnd":       [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "PostToolUse":      [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "SubagentStop":     [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "PostToolUseFailure": [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }],
#     "PreCompact":       [{ "hooks": [{ "type": "command", "command": "~/.local/bin/gremlet-claude-hook" }] }]
#
# PostToolUse sends only the tool's *name* (Edit, Read, Bash...), never its input or output: an edit places a block on
# the Gremlet's island, a subagent brings a tiny helper along. PreCompact makes the project's tree shed a few leaves.
#   }
#
# Never blocks or fails Claude: prints nothing (UserPromptSubmit output would reach Claude), makes one 1-second local
# request and always exits 0. Sends only the event, the session id, the project folder's name and a process id
# (used to find the window). Everything goes to 127.0.0.1: nothing leaves your Mac.
PORT="${GREMLETS_PORT:-47920}"
input="$(cat)"
query="$(printf '%s' "$input" | /usr/bin/python3 -c '
import json, os, re, sys, urllib.parse
try:
    d = json.load(sys.stdin)
except Exception:
    sys.exit(0)
name = d.get("hook_event_name", "")
event = {"UserPromptSubmit": "start", "Stop": "done", "Notification": "attention", "SessionEnd": "end",
         "PostToolUse": "tool", "PostToolUseFailure": "toolfail", "SubagentStop": "helperdone",
         "PreCompact": "compact"}.get(name)
if not event:
    sys.exit(0)
q = {
    "event": event,
    "session": d.get("session_id", "default"),
    "project": os.path.basename((d.get("cwd") or "").rstrip("/")) or "Claude",
    "pid": sys.argv[1],
}
if event == "start":
    # The git history of the project, as two numbers (commit count, first commit time), so an old repo grows an old tree.
    import subprocess
    try:
        cwd = d.get("cwd") or "."
        if os.path.isdir(os.path.join(cwd, ".git")):
            n = subprocess.run(["git", "-C", cwd, "rev-list", "--count", "HEAD"], capture_output=True, text=True, timeout=1).stdout.strip()
            first = subprocess.run(["git", "-C", cwd, "log", "--reverse", "--format=%ct", "--max-count=1", "HEAD"], capture_output=True, text=True, timeout=1).stdout.strip()
            if first == "":
                first = subprocess.run(["git", "-C", cwd, "rev-list", "--max-parents=0", "--format=%ct", "HEAD"], capture_output=True, text=True, timeout=1).stdout.strip().split()[-1]
            if n.isdigit(): q["commits"] = n
            if first.isdigit(): q["since"] = first
    except Exception:
        pass
if event in ("tool", "toolfail"):
    q["tool"] = str(d.get("tool_name", ""))[:60]
    # Only a yes/no "was this a test run?", never the command itself (it drives the weather).
    cmd = str((d.get("tool_input") or {}).get("command", "")) if q["tool"] == "Bash" else ""
    import re
    if re.search(r"\b(test|tests|pytest|jest|vitest|mocha|rspec|go test|cargo test|swift test|xcodebuild test|npm t)\b", cmd):
        q["kind"] = "test"
    # The to-do list, as two numbers (steps, steps done): it builds the plan bridge. Never the text of a step.
    todos = (d.get("tool_input") or {}).get("todos") if q["tool"] == "TodoWrite" else None
    if isinstance(todos, list):
        q["todos"] = str(len(todos))
        q["done"] = str(sum(1 for t in todos if isinstance(t, dict) and t.get("status") == "completed"))
if event == "done":
    # The first words of what Claude said at the end, for the little sign its Gremlet holds up (stays on this Mac:
    # it only goes to the Gremlets app at 127.0.0.1).
    try:
        text = d.get("last_assistant_message") or ""
        path = d.get("transcript_path") or ""
        if not text and path and os.path.isfile(path):
            with open(path, "rb") as f:
                f.seek(0, 2); size = f.tell(); f.seek(max(0, size - 400000))
                lines = f.read().decode("utf-8", "ignore").splitlines()
            for line in reversed(lines):
                try:
                    e = json.loads(line)
                except Exception:
                    continue
                if e.get("type") != "assistant":
                    continue
                parts = (e.get("message") or {}).get("content") or []
                if isinstance(parts, str):
                    text = parts
                else:
                    text = " ".join(p.get("text", "") for p in parts if isinstance(p, dict) and p.get("type") == "text")
                if text.strip():
                    break
        text = re.sub(r"[`*_#>\[\]]", "", " ".join(text.split()))
        # A sentence or two, enough to say something ("Done." alone says nothing).
        first = ""
        for sentence in re.split(r"(?<=[.!?])\s", text):
            first = (first + " " + sentence).strip()
            if len(first) >= 28:
                break
        if len(first) > 64:
            first = first[:63].rsplit(" ", 1)[0] + "…"
        if first:
            q["summary"] = first[:64]
    except Exception:
        pass
if event == "attention":
    q["kind"] = "permission" if "permission" in (d.get("message") or "").lower() else "waiting"
print(urllib.parse.urlencode(q))
' "$PPID" 2>/dev/null)"
[ -n "$query" ] && curl -s -m 1 -X POST -H 'X-Gremlets: 1' "http://127.0.0.1:${PORT}/claude?${query}" >/dev/null 2>&1
exit 0
