#!/usr/bin/env bash
# Tests dead-advisor-remind.mjs in a sandboxed HOME — no real state touched.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
HOOK="${HERE}/dead-advisor-remind.mjs"
pass=0; fail=0
ok()  { pass=$((pass+1)); echo "ok   - $*"; }
bad() { fail=$((fail+1)); echo "FAIL - $*"; }

SANDBOX="$(mktemp -d)"; trap 'rm -rf "$SANDBOX"' EXIT
mkdir -p "${SANDBOX}/.claude/dead-advisor-state"
printf 'a-agent-xyz\n' > "${SANDBOX}/.claude/dead-advisor-state/sess-1.id"

run() { HOME="$SANDBOX" node "$HOOK"; }  # reads payload on stdin

# 1. compact + sidecar present -> reminder with agentId
out=$(echo '{"source":"compact","session_id":"sess-1"}' | run) || true
echo "$out" | grep -q "a-agent-xyz" && ok "compact+sidecar -> reminder names agentId" || bad "expected reminder: [$out]"
echo "$out" | grep -q "additionalContext" && ok "emits SessionStart additionalContext" || bad "missing hook output shape: [$out]"

# 2. resume also fires
out=$(echo '{"source":"resume","session_id":"sess-1"}' | run) || true
echo "$out" | grep -q "dead-advisor" && ok "resume also fires" || bad "resume should fire: [$out]"

# 3. no sidecar for this session -> silent (empty)
out=$(echo '{"source":"compact","session_id":"sess-NONE"}' | run) || true
[ -z "$out" ] && ok "no sidecar -> silent" || bad "should be silent: [$out]"

# 4. startup source -> silent (not a context-drop event)
out=$(echo '{"source":"startup","session_id":"sess-1"}' | run) || true
[ -z "$out" ] && ok "startup source -> silent" || bad "startup should be silent: [$out]"

# 5. session id derived from transcript_path when session_id absent
out=$(echo '{"source":"compact","transcript_path":"/x/y/sess-1.jsonl"}' | run) || true
echo "$out" | grep -q "a-agent-xyz" && ok "derives session from transcript_path" || bad "transcript_path derive: [$out]"

# 6. malformed stdin -> exit 0, silent
out=$(echo 'not json' | run) || true
[ -z "$out" ] && ok "malformed stdin -> silent exit 0" || bad "malformed should be silent: [$out]"

echo "----"; echo "pass=$pass fail=$fail"
[ "$fail" -eq 0 ]
