#!/usr/bin/env bash
# Ensures the launch-recall watcher is running. Designed for the Claude Code
# SessionStart hook (.claude/settings.json). Idempotent: silently no-ops if
# recall isn't configured, logs OK if watcher is already alive, spawns a
# detached watcher if it isn't.
#
# Portable across two layouts:
#   - Dev: project has packages/cli/dist/server/recall-entry.js (e.g.
#     launchsecure-v2 itself) → spawn via `node`.
#   - Customer: project doesn't ship launch-kit → spawn via
#     `npx -y -p @launchsecure/launch-kit launch-recall watch`. First run
#     downloads from npm (slow); subsequent runs use the npx cache.
#
# Exits 0 in all cases — recall failing should never block Claude Code startup.

set -u

REPO_ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}"
RECALL_DIR="$REPO_ROOT/.recall"
PIDFILE="$RECALL_DIR/watch.pid"
LOCAL_RECALL_BIN="$REPO_ROOT/packages/cli/dist/server/recall-entry.js"

# No recall configured here — exit quietly. Hook is safe to ship in any repo;
# it only acts when there's a shadow-git to protect.
if [[ ! -d "$RECALL_DIR/repo.git" ]]; then
  exit 0
fi

# Watcher already alive?
if [[ -f "$PIDFILE" ]]; then
  pid="$(cat "$PIDFILE" 2>/dev/null || true)"
  if [[ -n "${pid:-}" ]] && kill -0 "$pid" 2>/dev/null; then
    echo "[recall] watcher alive (pid $pid)" >&2
    exit 0
  fi
fi

# Pick spawn command. Prefer the local dev build (instant) over npx (slow on
# first run because of the npm download).
if [[ -f "$LOCAL_RECALL_BIN" ]]; then
  SPAWN_CMD=(node "$LOCAL_RECALL_BIN" watch)
  via="local dev build"
else
  SPAWN_CMD=(npx -y -p @launchsecure/launch-kit launch-recall watch)
  via="npx (initial download may take a moment)"
fi

echo "[recall] starting watcher via $via" >&2

# Spawn detached. nohup + redirected fds + & keeps the watcher alive past this
# script's exit. disown removes it from the shell's job table.
nohup "${SPAWN_CMD[@]}" >/dev/null 2>&1 &
disown 2>/dev/null || true

# Brief check — long enough for the local-dev path, not long enough to block
# session start when npx is downloading.
sleep 0.5

if [[ -f "$PIDFILE" ]]; then
  newpid="$(cat "$PIDFILE" 2>/dev/null || true)"
  if [[ -n "${newpid:-}" ]] && kill -0 "$newpid" 2>/dev/null; then
    echo "[recall] watcher started (pid $newpid)" >&2
    exit 0
  fi
fi

# Spawn is still in flight (likely npx download). Don't block session start.
echo "[recall] watcher spawn initiated — check with /ls:show-mcp-status in a moment" >&2
exit 0
