#!/usr/bin/env bash
# Sehat Sahoolat — one-command dev environment.
#
# What it does:
#   1. Ensures docker-compose services (Postgres + Redis) are up.
#   2. Waits for Postgres to be healthy.
#   3. Applies backend migrations.
#   4. Runs the dev seed.
#   5. Starts the self-hosted Whisper service for AI Scribe (best-effort).
#   6. Prints a banner with URLs + credentials.
#   7. Launches backend + patient/doctor/admin portals in parallel via concurrently.
#
# Ctrl-C cleanly tears everything down. Non-zero exit on any step failure.

set -euo pipefail

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

TOTAL_STEPS=7
step() {
  echo ""
  echo "[step $1/$TOTAL_STEPS] $2"
}

# ---------- Pre-flight ----------
step 1 "Pre-flight checks"
if ! command -v docker >/dev/null 2>&1; then
  echo "  docker not found — install Docker Desktop and retry." >&2
  exit 1
fi
if ! command -v node >/dev/null 2>&1; then
  echo "  node not found." >&2
  exit 1
fi
NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
if [ "$NODE_MAJOR" != "22" ]; then
  echo "  ⚠  Node $(node --version) detected — this project pins Node 22 LTS."
  echo "     Run:  brew link --force --overwrite node@22"
  exit 1
fi
echo "  ✓ docker, node $(node --version)"

# ---------- Docker compose ----------
step 2 "Docker compose (Postgres + Redis)"
if docker ps --format '{{.Names}}' | grep -q '^sehat-postgres$' \
  && docker ps --format '{{.Names}}' | grep -q '^sehat-redis$'; then
  echo "  ✓ already running"
else
  docker compose up -d
fi

# The KB / RAG migration requires the pgvector extension. If the running
# container is on the stock postgres image (pre-pgvector switch), recreate it
# from the current compose file — the named volume persists, so no data loss.
PG_IMAGE="$(docker inspect sehat-postgres --format '{{.Config.Image}}' 2>/dev/null || true)"
if [[ -n "$PG_IMAGE" && "$PG_IMAGE" != *"pgvector"* ]]; then
  echo "  ⚠  postgres container is on $PG_IMAGE (no pgvector)."
  echo "     recreating from compose (volume preserved)…"
  docker compose up -d --force-recreate postgres
fi

# Wait for Postgres to be healthy (up to ~60s).
echo "  waiting for Postgres health…"
for i in $(seq 1 30); do
  status="$(docker inspect -f '{{.State.Health.Status}}' sehat-postgres 2>/dev/null || echo "starting")"
  if [ "$status" = "healthy" ]; then
    echo "  ✓ postgres healthy"
    break
  fi
  sleep 2
  if [ "$i" = "30" ]; then
    echo "  ✗ postgres did not become healthy in 60s" >&2
    exit 1
  fi
done

# ---------- Root dev deps ----------
step 3 "Root dev dependencies"
if [ ! -d node_modules ] || [ ! -d node_modules/concurrently ] || [ ! -d node_modules/tsx ]; then
  echo "  installing root devDependencies…"
  npm install --silent --no-audit --no-fund
else
  echo "  ✓ already installed"
fi

# ---------- Migrations ----------
step 4 "Backend migrations"
( cd backend && npm run db:migrate )

# ---------- Seed ----------
step 5 "Dev seed"
npx --yes tsx "$REPO_ROOT/scripts/dev-seed.ts"

# ---------- Self-hosted Whisper (AI Scribe) ----------
# Best-effort: failure here doesn't abort the rest of the boot. The Scribe
# service falls back to OpenAI Whisper automatically when the local service
# is down (provided an OpenAI key is configured in Admin → AI settings).
step 6 "Self-hosted Whisper (AI Scribe)"
WHISPER_COMPOSE="$REPO_ROOT/services/whisper/docker-compose.whisper.yml"
if [ -f "$WHISPER_COMPOSE" ]; then
  if docker ps --format '{{.Names}}' | grep -q '^sehat-whisper$'; then
    echo "  ✓ sehat-whisper already running"
  else
    if docker compose -f "$WHISPER_COMPOSE" up -d 2>/dev/null; then
      echo "  ✓ sehat-whisper started (http://localhost:8090)"
      echo "    first /transcribe call will download the model (~3 GB for large-v3)"
    else
      echo "  ⚠  failed to start sehat-whisper — Scribe will use OpenAI fallback"
      echo "     debug:  docker compose -f $WHISPER_COMPOSE logs"
    fi
  fi
else
  echo "  ⚠  $WHISPER_COMPOSE missing — skipping"
fi

# ---------- Banner ----------
step 7 "Starting dev servers"

cat <<BANNER

────────────────────────────────────────────────────────────────────
 Sehat Sahoolat — dev environment ready
────────────────────────────────────────────────────────────────────

 URLs
   Backend API ........ http://localhost:3000   (LAN: http://192.168.1.103:3000)
   Patient portal ..... http://localhost:3001
   Doctor portal ...... http://localhost:3002
   Admin portal ....... http://localhost:3003
   Whisper (Scribe) ... http://localhost:8090   (curl /health to probe)

 Test logins (password reset on each ./scripts/dev-start.sh)
   admin@sehat.local       AdminPass1!
   cardio@sehat.local      DoctorPass1!     (Dr. Imran Rashid — cardiology)
   derma@sehat.local       DoctorPass1!     (Dr. Sana Mahmood — dermatology)
   patient1@sehat.local    PatientPass1!    (has a pending appointment)
   patient2@sehat.local    PatientPass1!
   patient3@sehat.local    PatientPass1!

 Stop everything: Ctrl-C
────────────────────────────────────────────────────────────────────

BANNER

# ---------- Run the four processes in parallel ----------
# concurrently handles SIGINT and forwards it so Ctrl-C tears the tree down.
exec npx --yes concurrently \
  --kill-others-on-fail \
  --prefix "[{name}]" \
  --names "backend,patient,doctor,admin" \
  --prefix-colors "cyan,green,magenta,yellow" \
  "cd backend && npm run start" \
  "cd web && npm run dev:patient" \
  "cd web && npm run dev:doctor" \
  "cd web && npm run dev:admin"
