#!/bin/bash

# 🚀 VEZA V4 - DÉMARRAGE COMPLET
# Lance tous les services pour tests

set -e

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

echo -e "${BLUE}"
echo "██╗   ██╗███████╗███████╗ █████╗     ██╗   ██╗██╗  ██╗"
echo "██║   ██║██╔════╝╚══███╔╝██╔══██╗    ██║   ██║██║  ██║"
echo "██║   ██║█████╗    ███╔╝ ███████║    ██║   ██║███████║"
echo "╚██╗ ██╔╝██╔══╝   ███╔╝  ██╔══██║    ╚██╗ ██╔╝╚════██║"
echo " ╚████╔╝ ███████╗███████╗██║  ██║     ╚████╔╝      ██║"
echo "  ╚═══╝  ╚══════╝╚══════╝╚═╝  ╚═╝      ╚═══╝       ╚═╝"
echo -e "${NC}"
echo -e "${YELLOW}🚀 DÉMARRAGE DE TOUS LES SERVICES${NC}"
echo "========================================"
echo ""

# Logs directory
LOGS_DIR="./logs"
mkdir -p $LOGS_DIR

# 1. PostgreSQL (Docker)
echo -e "${YELLOW}📦 1/5 Démarrage PostgreSQL...${NC}"
if docker ps | grep -q veza-postgres; then
    echo -e "${GREEN}✓ PostgreSQL déjà en cours d'exécution${NC}"
else
    docker-compose up -d postgres
    echo -e "${GREEN}✓ PostgreSQL démarré${NC}"
fi
sleep 2

# 2. Redis (Docker)
echo -e "${YELLOW}📦 2/5 Démarrage Redis...${NC}"
if docker ps | grep -q veza-redis; then
    echo -e "${GREEN}✓ Redis déjà en cours d'exécution${NC}"
else
    docker-compose up -d redis
    echo -e "${GREEN}✓ Redis démarré${NC}"
fi
sleep 2

# 3. Backend Go (Port 8080)
echo -e "${YELLOW}🔵 3/5 Démarrage Backend Go API...${NC}"
cd veza-backend-api
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}⚠ Port 8080 déjà utilisé, arrêt du processus...${NC}"
    kill -9 $(lsof -ti:8080) 2>/dev/null || true
    sleep 2
fi

# Start backend in background
nohup go run main.go > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > ../logs/backend.pid
echo -e "${GREEN}✓ Backend Go démarré (PID: $BACKEND_PID)${NC}"
cd ..
sleep 3

# 4. Chat Server Rust (Port 8081)
echo -e "${YELLOW}🦀 4/5 Démarrage Chat Server Rust...${NC}"
cd veza-chat-server
if lsof -Pi :8081 -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}⚠ Port 8081 déjà utilisé, arrêt du processus...${NC}"
    kill -9 $(lsof -ti:8081) 2>/dev/null || true
    sleep 2
fi

# Build and start chat server
if [ ! -f "./target/release/chat-server" ]; then
    echo -e "${YELLOW}⚠ Compilation du chat server...${NC}"
    SQLX_OFFLINE=true cargo build --release 2>&1 | grep -v "warning" || true
fi
nohup SQLX_OFFLINE=true ./target/release/chat-server > ../logs/chat.log 2>&1 &
CHAT_PID=$!
echo $CHAT_PID > ../logs/chat.pid
echo -e "${GREEN}✓ Chat Server démarré (PID: $CHAT_PID)${NC}"
cd ..
sleep 3

# 5. Stream Server Rust (Port 8082)
echo -e "${YELLOW}🦀 5/5 Démarrage Stream Server Rust...${NC}"
cd veza-stream-server
if lsof -Pi :8082 -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}⚠ Port 8082 déjà utilisé, arrêt du processus...${NC}"
    kill -9 $(lsof -ti:8082) 2>/dev/null || true
    sleep 2
fi

# Build and start stream server
cargo build --release 2>&1 | grep -v "warning" || true
nohup ./target/release/veza-stream-server > ../logs/stream.log 2>&1 &
STREAM_PID=$!
echo $STREAM_PID > ../logs/stream.pid
echo -e "${GREEN}✓ Stream Server démarré (PID: $STREAM_PID)${NC}"
cd ..
sleep 3

# 6. Frontend React (Port 5173)
echo -e "${YELLOW}⚛️  6/6 Démarrage Frontend React...${NC}"
cd apps/web
if lsof -Pi :5173 -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}⚠ Port 5173 déjà utilisé, arrêt du processus...${NC}"
    kill -9 $(lsof -ti:5173) 2>/dev/null || true
    sleep 2
fi

# Start frontend in background
nohup npm run dev > ../../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > ../../logs/frontend.pid
echo -e "${GREEN}✓ Frontend démarré (PID: $FRONTEND_PID)${NC}"
cd ../..

# Wait for all services to be ready
echo ""
echo -e "${YELLOW}⏳ Attente du démarrage complet (15 secondes)...${NC}"
sleep 15

# Health checks
echo ""
echo -e "${BLUE}🏥 VÉRIFICATION DE LA SANTÉ DES SERVICES${NC}"
echo "=========================================="

check_service() {
    local name=$1
    local url=$2
    local port=$3
    
    echo -n "Checking $name (port $port)... "
    if curl -s --max-time 3 "$url" > /dev/null 2>&1; then
        echo -e "${GREEN}✓ OK${NC}"
        return 0
    else
        echo -e "${RED}✗ ERREUR${NC}"
        return 1
    fi
}

SERVICES_OK=0
SERVICES_TOTAL=4

check_service "Backend Go" "http://localhost:8080/health" "8080" && ((SERVICES_OK++)) || true
check_service "Chat Server" "http://localhost:8081/health" "8081" && ((SERVICES_OK++)) || true
check_service "Stream Server" "http://localhost:8082/health" "8082" && ((SERVICES_OK++)) || true
check_service "Frontend" "http://localhost:5173" "5173" && ((SERVICES_OK++)) || true

echo ""
echo "=========================================="
echo -e "${BLUE}📊 RÉSULTAT: $SERVICES_OK/$SERVICES_TOTAL services OK${NC}"

if [ $SERVICES_OK -eq $SERVICES_TOTAL ]; then
    echo -e "${GREEN}✅ TOUS LES SERVICES SONT OPÉRATIONNELS!${NC}"
else
    echo -e "${YELLOW}⚠️  Certains services n'ont pas démarré correctement${NC}"
    echo "Vérifiez les logs dans le dossier ./logs/"
fi

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}🎉 VEZA V4 EST PRÊT POUR LES TESTS!${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${YELLOW}📍 URLs D'ACCÈS:${NC}"
echo "  Frontend:       http://localhost:5173"
echo "  Backend API:    http://localhost:8080"
echo "  Chat Server:    http://localhost:8081"
echo "  Stream Server:  http://localhost:8082"
echo ""
echo -e "${YELLOW}🔑 COMPTE DE TEST:${NC}"
echo "  Email:     test@example.com"
echo "  Password:  Test1234!"
echo ""
echo -e "${YELLOW}📋 PAGES À TESTER:${NC}"
echo "  ✨ /playlists        - Gestion playlists (NOUVEAU)"
echo "  ✨ /transcoding      - Dashboard jobs (NOUVEAU)"
echo "  ✨ /settings         - Paramètres complets (NOUVEAU)"
echo "  ✨ /library          - Avec waveform + edit (AMÉLIORÉ)"
echo "  📚 /dashboard        - Vue d'ensemble"
echo "  💬 /chat             - Chat temps réel"
echo "  📻 /stream           - Player audio"
echo "  👤 /profile          - Profil utilisateur"
echo ""
echo -e "${YELLOW}📝 LOGS:${NC}"
echo "  Backend:   tail -f logs/backend.log"
echo "  Chat:      tail -f logs/chat.log"
echo "  Stream:    tail -f logs/stream.log"
echo "  Frontend:  tail -f logs/frontend.log"
echo ""
echo -e "${YELLOW}🛑 ARRÊTER TOUS LES SERVICES:${NC}"
echo "  ./stop-all-services.sh"
echo ""
echo -e "${GREEN}Bon testing! 🚀${NC}"
echo ""

