#!/bin/bash
set -euo pipefail

# scripts/lab/start_all_services.sh

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'


export VEZA_LAB_DSN="${VEZA_LAB_DSN:-postgres://veza:veza_password@localhost:5432/veza_lab?sslmode=disable}"

echo -e "${GREEN}🚀 Starting all services...${NC}"

# We want services to keep running appropriately.
# The user requirement was: "Laisser les commandes dans le script sous une forme claire... Démarrer en parallèle (ou dans des tmux/panes, ou via & + logs)"
# "Laisser les processus en tâche de fond pour la session courante (ne pas tuer à la fin du script)."
# -> This suggests we should NOT trap exit to kill them if we want them to persist? 
# BUT usually "make services-up" is a blocking call or detached.
# The user said: "Laisser les processus en tâche de fond pour la session courante (ne pas tuer à la fin du script)."
# If I run "make services-up" and the script exits, background jobs might be killed depending on shell.
# I will use nohup or just & and expect the environment to handle it.
# Actually, the user's example in the prompt used `( ) &`.
# I will output logs to temporary files or stdout.

# To keep them running after script exit, we need to disown them or use nohup.
# However, standard `&` inside a script often terminates when script terminates if we don't wait.
# The user workflow `make dev-lab` implies a sequence. If `services-up` returns immediately, then `check-health` runs.
# So the services MUST be running in background.

LOG_DIR="logs/lab"
mkdir -p "$LOG_DIR"

echo -e "${BLUE}Logs will be written to $LOG_DIR${NC}"

# 1. veza-backend-api (8080)
echo -e "${YELLOW}Starting veza-backend-api (8080)...${NC}"
(
    cd veza-backend-api || exit 1
    export DATABASE_URL="$VEZA_LAB_DSN"
    # Ensure other env vars are set if needed, e.g. RabbitMQ/Redis
    # Assuming defaults in code or .env handling
    # We can rely on defaults or export generic ones
    export REDIS_URL="redis://localhost:6379"
    export RABBITMQ_URL="amqp://veza:veza_password@localhost:5672/"
    export JWT_SECRET="dev-secret-key-change-in-production"
    
    if [ -x scripts/start_lab.sh ]; then
        nohup ./scripts/start_lab.sh > "../$LOG_DIR/backend.log" 2>&1 &
    else
        nohup go run ./cmd/modern-server/main.go > "../$LOG_DIR/backend.log" 2>&1 &
    fi
)

# 2. veza-stream-server (8082)
echo -e "${YELLOW}Starting veza-stream-server (8082)...${NC}"
(
    cd veza-stream-server || exit 1
    export DATABASE_URL="$VEZA_LAB_DSN"
    export REDIS_URL="redis://localhost:6379"
    export STREAM_PORT=8082
    export RUST_LOG=info
    
    if [ -x scripts/start_lab.sh ]; then
        nohup ./scripts/start_lab.sh > "../$LOG_DIR/stream.log" 2>&1 &
    else
        nohup cargo run --release > "../$LOG_DIR/stream.log" 2>&1 &
    fi
)

# 3. veza-chat-server (8081)
echo -e "${YELLOW}Starting veza-chat-server (8081)...${NC}"
(
    cd veza-chat-server || exit 1
    export DATABASE_URL="${VEZA_LAB_DSN/veza_lab/veza_chat}"
    export REDIS_URL="redis://localhost:6379"
    export RABBITMQ_URL="amqp://veza:veza_password@localhost:5672/"
    export CHAT_SERVER_PORT=8081
    
    if [ -x scripts/start_lab.sh ]; then
        export VEZA_LAB_DSN="$DATABASE_URL"
        export CHAT_DATABASE_URL="$DATABASE_URL"
        nohup ./scripts/start_lab.sh > "../$LOG_DIR/chat.log" 2>&1 &
    else
        nohup cargo run --release > "../$LOG_DIR/chat.log" 2>&1 &
    fi
)

# 4. apps/web (3000)
echo -e "${YELLOW}Starting apps/web (3000)...${NC}"
(
    cd apps/web || exit 1
    
    # We might need environment variables for the frontend to talk to backend
    export VITE_API_BASE_URL="http://localhost:8080/api/v1"
    
    # apps/web is 2 levels deep? No, apps/web.
    # root -> apps -> web. So ../../.
    # $LOG_DIR = logs/lab.
    # If I am in apps/web, logs is at ../../logs/lab.
    
    if [ -x scripts/start_lab.sh ]; then
        nohup ./scripts/start_lab.sh > "../../$LOG_DIR/web.log" 2>&1 &
    else
        npm install > /dev/null 2>&1
        nohup npm run dev -- --host --port 3000 > "../../$LOG_DIR/web.log" 2>&1 &
    fi
)

echo -e "${GREEN}✅ All services started in background!${NC}"
echo -e "${BLUE}Check logs in $LOG_DIR/${NC}"
echo ""
echo "Endpoints:"
echo "- veza-backend-api : http://localhost:8080"
echo "- veza-chat-server : http://localhost:8081"
echo "- veza-stream-server : http://localhost:8082"
echo "- apps/web         : http://localhost:3000"

# Wait a bit to let them initialize before returning, helpful for immediate health check
sleep 5
