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

SCRIPT="/workspace/digest/run-digest-orchestrator.sh"
TMP_ROOT="$(mktemp -d)"
trap 'rm -rf "$TMP_ROOT"' EXIT

WORKDIR="${TMP_ROOT}/work"
mkdir -p "${WORKDIR}"
cp /workspace/digest/CLAUDE.md "${WORKDIR}/CLAUDE.md"
touch "${WORKDIR}/COMPLETED-DAYS.md"

cat > "${TMP_ROOT}/fail-health.sh" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
echo "forced vpn failure"
exit 1
EOF
chmod +x "${TMP_ROOT}/fail-health.sh"

set +e
"$SCRIPT" \
  --workdir "$WORKDIR" \
  --max-attempts 1 \
  --attempt-timeout-seconds 1 \
  --poll-seconds 1 \
  --simulate \
  --ignore-ack \
  --date-iso 2030-01-01 \
  --vpn-health-script "${TMP_ROOT}/fail-health.sh" \
  --vpn-health-failure-wait 0
status=$?
set -e

if [[ "$status" -ne 1 ]]; then
  echo "Expected orchestrator to fail when VPN preflight fails" >&2
  exit 1
fi

REPORT_FILE="${WORKDIR}/logs/past-logs/2030-01-01.md"
if ! grep -Fq "VPN health preflight" "$REPORT_FILE"; then
  echo "Expected VPN health preflight entry in report" >&2
  exit 1
fi

if grep -Fq "PID/PGID" "$REPORT_FILE"; then
  echo "Worker should not start after failed VPN preflight" >&2
  exit 1
fi

echo "test-run-digest-orchestrator.sh: PASS"
