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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
SIM_DIR="${ROOT_DIR}/VigilCare.Simulator"
BASE_URL="${BASE_URL:-http://localhost:5270}"

echo "=== Phase 29 — Clinical Refactor Validation ==="

echo "1. Validate all scenario JSON files"
for scenario in "${SIM_DIR}"/Scenarios/List/*.json; do
  dotnet run --project "${SIM_DIR}" -- validate "${scenario}"
done

echo "2. Integration tests"
dotnet test "${ROOT_DIR}/VigilCareClinicalAPI.Tests" \
  --filter "FullyQualifiedName~ClinicalRefactorEndToEnd" \
  --no-restore

echo "3. Replay new scenarios (requires running API at ${BASE_URL})"
cd "${SIM_DIR}"
dotnet run -- replay Scenarios/List/sepsis-sofa-progression-01.json --speed 0 --poll --base-url "${BASE_URL}"
dotnet run -- replay Scenarios/List/neurological-decline-gcs-01.json --speed 0 --poll --base-url "${BASE_URL}"
dotnet run -- replay Scenarios/List/sofa-partial-spo2-fallback-01.json --speed 0 --poll --base-url "${BASE_URL}"

echo "4. Replay-all backward compat"
dotnet run -- replay-all Scenarios/List --speed 0 --base-url "${BASE_URL}"

echo "5. Dashboard tests (Phase 28 UI)"
cd "${ROOT_DIR}/vigilcare-dashboard"
npm test

echo "Phase 29 verification complete."
echo "Manual: open patient detail after sepsis-sofa-progression replay — verify GCS/SOFA panels and SOFA-triggered bundle."