#!/bin/bash
# scripts/check_backend.sh
# Vérifie la disponibilité des services backend nécessaires pour le frontend Veza.
# Usage: ./scripts/check_backend.sh

set -euo pipefail

# Couleurs
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Ports par défaut (peuvent être surchargés par les vars d'env si besoin, 
# mais ici on hardcode ou on utilise des vars explicites si définies)
API_URL="${VITE_API_URL:-http://localhost:8080/api/v1}"
WS_URL="${VITE_WS_URL:-ws://localhost:8081}"
STREAM_URL="${VITE_STREAM_URL:-http://localhost:8082}"

# Fonction de check HTTP avec retry
wait_for_url() {
    local url="$1"
    local name="$2"
    local required="$3" # 1 = critical, 0 = optional
    local max_attempts=30
    local attempt=1

    echo -n "⏳ Waiting for $name ($url)... "
    while [ $attempt -le $max_attempts ]; do
        if curl -s -f -m 1 "$url" > /dev/null 2>&1; then
            echo -e "${GREEN}OK${NC}"
            return 0
        fi
        echo -n "."
        sleep 1
        attempt=$((attempt + 1))
    done

    echo -e " ${RED}Timeout${NC}"
    if [ "$required" -eq 1 ]; then
        echo -e "${RED}❌ $name failed to start after ${max_attempts}s [CRITIQUE]${NC}"
        return 1
    else
        echo -e "${YELLOW}⚠️  $name failed to start ($url) [MODE DÉGRADÉ]${NC}"
        return 0
    fi
}

echo -e "${YELLOW}🔍 Vérification des services backend (Timeout: 30s)...${NC}"

EXIT_CODE=0

# 1. Backend API (Critique)
API_HOST_PORT=$(echo "$API_URL" | sed -E 's|/api/v1/?$||')
# Check both /health (root) or /api/v1/health depending on implementation
# We try the one derived from config first
if ! wait_for_url "$API_HOST_PORT/health" "Backend API" 1; then
    EXIT_CODE=1
fi

# 2. Chat Server (Optionnel)
CHAT_HTTP_URL=$(echo "$WS_URL" | sed 's/^ws/http/') 
wait_for_url "$CHAT_HTTP_URL/health" "Chat Server" 0 || true

# 3. Stream Server (Optionnel)
wait_for_url "$STREAM_URL/health" "Stream Server" 0 || true

echo ""
if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}🚀 Tous les services critiques sont opérationnels.${NC}"
else
    echo -e "${RED}🛑 Impossible de démarrer : services critiques manquants.${NC}"
fi

exit $EXIT_CODE
