#!/bin/bash
# Watchtower SessionEnd hook — spawns Ring 3 close-mode processing.
#
# Runs at session end. Reads session info from Claude Code's stdin JSON
# (transcript_path, session_id, cwd, reason). Spawns the Ring 3 close
# processor via nohup/disown so it survives terminal close.
#
# Skips if:
#   - reason is "resume" (session continuing, not ending)
#   - no transcript file exists
#   - watchtower is not installed (no config.json)
#
# ROLLBACK: Comment out the SessionEnd entry in .claude/settings.json
# to disable this hook immediately.

command -v jq >/dev/null 2>&1 || exit 0

WATCHTOWER_DIR="${HOME}/.claude-cabinet/watchtower"

# No config -> watchtower not installed -> exit silently
if [ ! -f "${WATCHTOWER_DIR}/config.json" ]; then
  exit 0
fi

# Read session info from stdin JSON
SESSION_JSON=$(cat)
if [ -z "${SESSION_JSON}" ]; then
  exit 0
fi

# Parse fields from stdin JSON
REASON=$(echo "${SESSION_JSON}" | jq -r '.reason // empty' 2>/dev/null)
TRANSCRIPT_PATH=$(echo "${SESSION_JSON}" | jq -r '.transcript_path // empty' 2>/dev/null)
SESSION_ID=$(echo "${SESSION_JSON}" | jq -r '.session_id // empty' 2>/dev/null)
CWD=$(echo "${SESSION_JSON}" | jq -r '.cwd // empty' 2>/dev/null)

# Skip on resume — session is continuing, not ending
if [ "${REASON}" = "resume" ]; then
  exit 0
fi

# Skip if no transcript file
if [ -z "${TRANSCRIPT_PATH}" ] || [ ! -f "${TRANSCRIPT_PATH}" ]; then
  exit 0
fi

# Skip if no session ID
if [ -z "${SESSION_ID}" ]; then
  exit 0
fi

# Ensure logs directory exists
mkdir -p "${WATCHTOWER_DIR}/logs"

LOG_FILE="${WATCHTOWER_DIR}/logs/ring3-close-${SESSION_ID}.log"

# Source watchtower environment (API keys, node path, NODE_PATH)
ENV_FILE="${WATCHTOWER_DIR}/env"
if [ -f "${ENV_FILE}" ]; then
  set -a; source "${ENV_FILE}"; set +a
fi

NODE_BIN="${WATCHTOWER_NODE_PATH:-$(command -v node || true)}"

# Spawn Ring 3 close processor via nohup/disown (survives terminal close)
nohup "${NODE_BIN}" "${WATCHTOWER_DIR}/scripts/watchtower-ring3-close.mjs" \
  --session-id "${SESSION_ID}" \
  --transcript "${TRANSCRIPT_PATH}" \
  --cwd "${CWD}" \
  --reason "${REASON}" \
  > "${LOG_FILE}" 2>&1 &
disown

exit 0
