#!/bin/bash
set -euo pipefail

# Configuration
API_PORT=8080
CHAT_PORT=8081
STREAM_PORT=8082

API_URL="http://localhost:$API_PORT"
CHAT_URL="http://localhost:$CHAT_PORT"
STREAM_URL="http://localhost:$STREAM_PORT"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[HEALTH] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

# 1. Start Stack
log "Starting production stack..."
if [ -f .env.test ]; then
    docker compose --env-file .env.test -f docker-compose.production.yml up -d
else
    docker compose -f docker-compose.production.yml up -d
fi

log "Waiting for services to be ready (10s)..."
sleep 10

# 2. Check Health
check_health() {
    local service_name=$1
    local url=$2
    
    log "Checking $service_name health..."
    
    # Check /healthz
    if curl -sf "$url/healthz" > /dev/null; then
        echo "  ✅ $service_name /healthz OK"
    else
        error "$service_name /healthz FAILED"
    fi

    # Check /readyz
    if curl -sf "$url/readyz" > /dev/null; then
        echo "  ✅ $service_name /readyz OK"
    else
        error "$service_name /readyz FAILED"
    fi
}

check_health "Backend API" "$API_URL"
check_health "Chat Server" "$CHAT_URL"
check_health "Stream Server" "$STREAM_URL"

# 3. Check Metrics
check_metrics() {
    local service_name=$1
    local url=$2
    
    log "Checking $service_name metrics..."
    
    if curl -sf "$url/metrics" > /dev/null; then
        echo "  ✅ $service_name /metrics OK"
    else
        echo -e "${RED}[WARN] $service_name /metrics FAILED (Ignored)${NC}"
    fi
}

check_metrics "Backend API" "$API_URL"
check_metrics "Chat Server" "$CHAT_URL"
check_metrics "Stream Server" "$STREAM_URL"

log "✅ Global health check passed!"
