#!/usr/bin/env bash
# spool Stop hook (managed by `spool mcp install`).
#
# Claude Code sends this hook a JSON payload on stdin describing the
# session that just ended:
#
#   {
#     "session_id": "...",
#     "transcript_path": "/abs/path/to/<session>.jsonl",
#     "hook_event_name": "Stop",
#     ...
#   }
#
# We forward the raw JSON to `spool hook stop --hook-input "..."` so
# the Rust side can extract `transcript_path` and run the distill
# pipeline (R3 self-tag heuristics → ledger).
#
# Failure-silent: any non-zero exit from spool is swallowed (D7).
set -e

SPOOL_BIN="@@SPOOL_BIN@@"
SPOOL_CONFIG="@@SPOOL_CONFIG@@"
CWD="${CLAUDE_PROJECT_DIR:-$PWD}"

if [ ! -x "$SPOOL_BIN" ]; then
  exit 0
fi

# Capture stdin (Claude Code's hook payload). Bash's `read -d ''`
# trick is the cleanest way to slurp the whole stream into a single
# variable without spawning a subshell.
HOOK_INPUT=""
if [ -t 0 ]; then
  # No stdin attached (manual invocation) — leave HOOK_INPUT empty;
  # spool will fall back to scanning ~/.claude/projects/.../ for the
  # most recent transcript jsonl.
  :
else
  HOOK_INPUT="$(cat 2>/dev/null || true)"
fi

if [ -n "$HOOK_INPUT" ]; then
  "$SPOOL_BIN" hook stop \
    --config "$SPOOL_CONFIG" \
    --cwd "$CWD" \
    --hook-input "$HOOK_INPUT" \
    >/dev/null 2>&1 || true
else
  "$SPOOL_BIN" hook stop \
    --config "$SPOOL_CONFIG" \
    --cwd "$CWD" \
    >/dev/null 2>&1 || true
fi
exit 0
