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

CENTRAL="${CENTRAL_URL:-http://localhost:5270}"
GATEWAY="${GATEWAY_URL:-http://localhost:5081}"
JWT="${ADMIN_JWT:?Set ADMIN_JWT to a valid admin bearer token}"
GATEWAY_JWT="${GATEWAY_JWT:?Set GATEWAY_JWT to a valid gateway dashboard JWT}"

echo "=== VigilCare climate resilience demo ==="

echo "==> 1. Full stack up"
docker compose --profile full --profile ward-gateway up -d
sleep 30

echo "==> 2. Baseline — gateway ONLINE"
curl -sf "$CENTRAL/api/v1/operations/gateways" \
  -H "Authorization: Bearer $JWT" \
  | jq '.data[] | {code: .gatewayCode, status, buffer: .reportedBufferDepth}'

echo "==> 3. Partition — disconnect gateway from central network"
GATEWAY_CONTAINER=$(docker ps -qf name=ward-gateway-api)
NETWORK=$(docker network ls --format '{{.Name}}' | grep vigilcare | head -1)
docker network disconnect "$NETWORK" "$GATEWAY_CONTAINER" 2>/dev/null || true

echo "Partition active — posting observation to gateway..."
ENCOUNTER_ID=$(curl -sf "$GATEWAY/api/v1/encounters?status=ACTIVE&department=ICU" \
  -H "Authorization: Bearer $GATEWAY_JWT" | jq -r '.data.items[0].encounterId')

curl -sf -X POST "$GATEWAY/api/v1/encounters/$ENCOUNTER_ID/observations" \
  -H "Authorization: Bearer $GATEWAY_JWT" \
  -H "Content-Type: application/json" \
  -d "{\"observationCode\":\"HEART_RATE\",\"value\":165,\"unit\":\"bpm\",\"source\":\"DEVICE\",\"recordedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"idempotencyKey\":\"partition-demo-$(date +%s)\"}"

sleep 15

echo "==> 4. Fleet status during partition"
curl -sf "$CENTRAL/api/v1/operations/gateways" \
  -H "Authorization: Bearer $JWT" \
  | jq '.data[] | {code: .gatewayCode, status, buffer: .reportedBufferDepth, minutes: .minutesSinceHeartbeat}'

echo "==> 5. Heal partition"
docker network connect "$NETWORK" "$GATEWAY_CONTAINER"
echo "Waiting for sync (60s)..."
sleep 60

echo "==> 6. Recovery — ONLINE + buffer 0"
curl -sf "$CENTRAL/api/v1/operations/gateways" \
  -H "Authorization: Bearer $JWT" \
  | jq '.data[] | {code: .gatewayCode, status, buffer: .reportedBufferDepth}'

echo "=== Demo complete ==="