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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

echo "=== Phase 26 verification ==="

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

echo "2. Manual API checks (requires running stack)"
BASE_URL="${BASE_URL:-http://localhost:5270}"
ENCOUNTER_ID="${ENCOUNTER_ID:?Set ENCOUNTER_ID to an active encounter UUID}"

post_obs() {
  local code="$1" value="$2"
  curl -sf -X POST "${BASE_URL}/api/v1/encounters/${ENCOUNTER_ID}/observations" \
    -H "Content-Type: application/json" \
    -d "{\"observations\":[{\"observationCode\":\"${code}\",\"value\":${value},\"unit\":\"score\",\"source\":\"Manual\",\"recordedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}]}"
}

wait_for_sofa_baseline() {
  for _ in $(seq 1 30); do
    if curl -sf "${BASE_URL}/api/v1/encounters/${ENCOUNTER_ID}/sofa/history?limit=20" \
      | jq -e '[.data.items[] | select(.isBaseline == true)] | length > 0' >/dev/null; then
      return 0
    fi
    sleep 1
  done
  echo "Timed out waiting for SOFA baseline"
  return 1
}

wait_for_sofa_delta() {
  local min_delta="$1"
  for _ in $(seq 1 30); do
    if curl -sf "${BASE_URL}/api/v1/encounters/${ENCOUNTER_ID}/sofa" \
      | jq -e ".data.deltaFromBaseline >= ${min_delta}" >/dev/null; then
      return 0
    fi
    sleep 1
  done
  echo "Timed out waiting for SOFA delta >= ${min_delta}"
  return 1
}

post_obs PAO2_MMHG 100
post_obs FIO2_PCT 40
post_obs PLATELET_K_UL 180
post_obs BILIRUBIN_MG_DL 1.0
post_obs SYSTOLIC_BP 120
post_obs DIASTOLIC_BP 80
post_obs CREATININE_MG_DL 1.0
post_obs URINE_OUTPUT_ML_H 50
wait_for_sofa_baseline
curl -sf "${BASE_URL}/api/v1/encounters/${ENCOUNTER_ID}/sofa" | jq -e '.data.totalScore >= 0'

post_obs PLATELET_K_UL 20
post_obs CREATININE_MG_DL 4.5
wait_for_sofa_delta 2
echo "Verify SOFA_SEPSIS alert and delta >= 2 in DB/UI"

echo "Phase 26 verification complete."