#!/bin/bash
# Shared pi-tmux hook for Claude Code.
#
# Dispatches on the JSON `hook_event_name` field read from stdin:
#   SessionStart → write `.session_id` to $PI_TMUX_READY_FILE
#   Stop        → append lifecycle-end sentinel to $PI_TMUX_END_FILE
#
# The hook is env-gated: it no-ops unless PI_TMUX_READY_FILE / PI_TMUX_END_FILE
# are set, so it is inert for the user's own interactive claude sessions.
# Exit 0 on all paths so Claude Code never retries.

set -e

if [ -z "${PI_TMUX_READY_FILE:-}" ] && [ -z "${PI_TMUX_END_FILE:-}" ]; then
  exit 0
fi

input=$(cat)
event=""

# Both SessionStart and Stop carry transcript_path on stdin JSON, so the
# ready file can hand it to waitForReady directly (no slug reconstruction).
if command -v jq >/dev/null 2>&1; then
  event=$(printf '%s' "$input" | jq -r '.hook_event_name // empty' 2>/dev/null || true)
  session_id=$(printf '%s' "$input" | jq -r '.session_id // empty' 2>/dev/null || true)
  transcript_path=$(printf '%s' "$input" | jq -r '.transcript_path // empty' 2>/dev/null || true)
  stop_hook_active=$(printf '%s' "$input" | jq -r '.stop_hook_active // empty' 2>/dev/null || true)
else
  # jq unavailable — substring probes (good enough for stable field names).
  event=$(printf '%s' "$input" | grep -o '"hook_event_name"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/' | head -n1 || true)
  session_id=$(printf '%s' "$input" | grep -o '"session_id"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/' | head -n1 || true)
  transcript_path=$(printf '%s' "$input" | grep -o '"transcript_path"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/' | head -n1 || true)
  if printf '%s' "$input" | grep -q '"stop_hook_active"[[:space:]]*:[[:space:]]*true'; then
    stop_hook_active="true"
  else
    stop_hook_active=""
  fi
fi

if [ "$event" = "SessionStart" ]; then
  if [ -n "${PI_TMUX_READY_FILE:-}" ] && [ -n "$session_id" ]; then
    # line 1 = session_id, line 2 = transcript_path (handed to waitForReady)
    printf '%s\n%s\n' "$session_id" "$transcript_path" > "$PI_TMUX_READY_FILE"
  fi
  exit 0
fi

if [ "$event" = "Stop" ]; then
  # Belt-and-suspenders loop guard: never block, but skip if this is a retry.
  if [ "$stop_hook_active" = "true" ]; then
    exit 0
  fi
  if [ -n "${PI_TMUX_END_FILE:-}" ]; then
    printf 'end\n' >> "$PI_TMUX_END_FILE"
  fi
  exit 0
fi

exit 0
