#!/usr/bin/env bash
# Doctor must contain a stalled drift checker and continue its remaining audit.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOCTOR="$SCRIPT_DIR/../../_scripts/mosaic-doctor"
WORK="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/framework-drift-doctor}"
rm -rf "$WORK"
mkdir -p "$WORK/source/tools/quality/scripts" "$WORK/source/tools/_scripts" "$WORK/home/tools"
cp "$DOCTOR" "$WORK/source/tools/_scripts/mosaic-doctor"
cat > "$WORK/source/tools/quality/scripts/framework-drift-check.py" <<'PY'
import time
time.sleep(30)
PY

start=$(date +%s)
set +e
output=$(MOSAIC_HOME="$WORK/home" MOSAIC_DOCTOR_DRIFT_TIMEOUT_SEC=1 \
  bash "$WORK/source/tools/_scripts/mosaic-doctor" --fail-on-warn 2>&1)
rc=$?
set -e
elapsed=$(( $(date +%s) - start ))

[[ "$rc" -ne 0 ]] || { echo "FAIL: checker timeout became doctor success" >&2; exit 1; }
[[ "$elapsed" -lt 10 ]] || { echo "FAIL: checker hang escaped watchdog (${elapsed}s)" >&2; exit 1; }
[[ "$output" == *"CANNOT_ASSERT framework drift checker timed out"* ]] || {
  echo "FAIL: missing timeout CANNOT_ASSERT diagnostic" >&2; printf '%s\n' "$output" >&2; exit 1;
}
[[ "$output" == *"[mosaic-doctor] warnings="* ]] || {
  echo "FAIL: doctor did not continue after checker timeout" >&2; printf '%s\n' "$output" >&2; exit 1;
}

echo "framework drift doctor watchdog regression passed"
