#!/usr/bin/env bash
# Health check: verify backend, frontend, and the scheduler worker are ready
set -euo pipefail

MAX_RETRIES=10
RETRY_INTERVAL=5

echo "Running health checks..."

check_endpoint() {
  local name="$1"
  local url="$2"
  local attempt=1

  while [[ $attempt -le $MAX_RETRIES ]]; do
    if curl -sf --max-time 5 "$url" > /dev/null 2>&1; then
      echo "  [OK] ${name} is healthy"
      return 0
    fi
    echo "  [WAIT] ${name} not ready (attempt ${attempt}/${MAX_RETRIES})..."
    sleep "$RETRY_INTERVAL"
    ((attempt++))
  done

  echo "  [FAIL] ${name} did not become healthy after ${MAX_RETRIES} attempts"
  return 1
}

check_container_health() {
  local name="$1"
  local service="$2"
  local attempt=1
  local container_id=""
  local health=""

  while [[ $attempt -le $MAX_RETRIES ]]; do
    container_id=$(docker compose -f /opt/helix/compose/docker-compose.prod.yml ps -q "$service")
    if [[ -n "$container_id" ]]; then
      health=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container_id" 2>/dev/null || true)
      if [[ "$health" == "healthy" ]]; then
        echo "  [OK] ${name} is healthy"
        return 0
      fi
    fi
    echo "  [WAIT] ${name} not ready (state=${health:-missing}, attempt ${attempt}/${MAX_RETRIES})..."
    sleep "$RETRY_INTERVAL"
    ((attempt++))
  done

  echo "  [FAIL] ${name} did not become healthy after ${MAX_RETRIES} attempts"
  return 1
}

FAILED=0
check_endpoint "Backend readiness" "http://localhost:8000/api/v1/ready" || FAILED=1
check_container_health "Worker scheduler" "worker" || FAILED=1
check_endpoint "Frontend" "http://localhost:80/" || FAILED=1

if [[ $FAILED -eq 0 ]]; then
  echo "All health checks passed."
  exit 0
else
  echo "One or more health checks failed."
  exit 1
fi
