#!/usr/bin/env python3
"""
Claude Code Stop hook — writes last assistant text to Runabout outbox.
Only fires when the Runabout binary is running.
"""
import sys, json, os, datetime, subprocess

try:
    payload = json.load(sys.stdin)
except Exception:
    sys.exit(0)

OUTBOX = "/var/lib/solace/runabout-outbox"

# Check if Runabout binary is running (pgrep -x = exact process name match)
result = subprocess.run(["pgrep", "-x", "runabout"], capture_output=True, text=True)
if not result.stdout.strip():
    sys.exit(0)

transcript_path = payload.get("transcript_path", "")
if not transcript_path or not os.path.exists(transcript_path):
    sys.exit(0)

# Find last assistant text block
last_text = ""
try:
    with open(transcript_path) as f:
        for line in f:
            try:
                d = json.loads(line)
            except Exception:
                continue
            if d.get("type") != "assistant":
                continue
            msg = d.get("message", {})
            if msg.get("role") != "assistant":
                continue
            for block in msg.get("content", []):
                if isinstance(block, dict) and block.get("type") == "text":
                    t = block["text"].strip()
                    if t:
                        last_text = t
except Exception:
    sys.exit(0)

if not last_text:
    sys.exit(0)

ts = datetime.datetime.now().strftime("%H:%M")

# One bubble per paragraph (double-newline split)
paragraphs = [p.strip() for p in last_text.split("\n\n") if p.strip()]

with open(OUTBOX, "a") as f:
    for p in paragraphs:
        line = p.replace("\n", " ")
        f.write(f"[{ts}] {line}\n")
