#!/bin/bash
set -e

HEALTH_URL="${HEALTH_URL:-http://localhost:1999/health}"
MAX_RETRIES=30
RETRY_DELAY=2

echo "🏥 Running health check on $HEALTH_URL"

for i in $(seq 1 $MAX_RETRIES); do
    if curl -sf "$HEALTH_URL" > /dev/null 2>&1; then
        echo "✅ Health check passed (attempt $i/$MAX_RETRIES)"

        # Show health response
        RESPONSE=$(curl -s "$HEALTH_URL")
        echo ""
        echo "📊 Health Status:"
        echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

        exit 0
    fi

    echo "⏳ Waiting for service... (attempt $i/$MAX_RETRIES)"
    sleep $RETRY_DELAY
done

echo "❌ Health check failed after $MAX_RETRIES attempts"
exit 1
