#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

cat >"$TMP/ok" <<'SH'
#!/usr/bin/env bash
printf called >>"$OD_LIVE_REPORT_TEST_LOG"
SH
chmod +x "$TMP/ok"
OD_LIVE_REPORT_TEST_LOG="$TMP/log" OD_LIVE_REPORT_CMD="$TMP/ok" \
  bash "$ROOT/modules/workstation/claude/bin/od-live-report-refresh"
[[ $(<"$TMP/log") == called ]]

OD_LIVE_REPORT_CMD="$TMP/missing" \
  bash "$ROOT/modules/workstation/claude/bin/od-live-report-refresh" 2>"$TMP/missing.err"
grep -q 'is not installed' "$TMP/missing.err"

cat >"$TMP/fail" <<'SH'
#!/usr/bin/env bash
exit 7
SH
chmod +x "$TMP/fail"
OD_LIVE_REPORT_CMD="$TMP/fail" \
  bash "$ROOT/modules/workstation/claude/bin/od-live-report-refresh" 2>"$TMP/fail.err"
grep -q 'failed (rc=7)' "$TMP/fail.err"

grep -q 'od-live-report-refresh' "$ROOT/modules/workstation/claude/workflows/lib/finish-branch.sh"
grep -q 'od-live-report-refresh' "$ROOT/packaging/deploy-local.sh"
grep -q 'spawnSync("od-live-report-refresh"' "$ROOT/modules/workstation/claude/bin/run-remote"
grep -q 'spawnSync("od-live-report-refresh"' "$ROOT/modules/workstation/claude/bin/od-incidents"

printf 'live-report transition hooks: ok\n'
