#!/bin/bash
#
# OrbiQuant IA - Start All Services
# Starts all required services for the trading platform
#

set -e

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

# Project root
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

echo -e "${BOLD}"
echo "╔══════════════════════════════════════════════════════════╗"
echo "║          OrbiQuant IA - Service Launcher                 ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Function to check if a port is in use
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# Function to wait for a service
wait_for_service() {
    local name=$1
    local url=$2
    local max_attempts=30

    echo -ne "${BLUE}Waiting for $name...${NC}"

    for i in $(seq 1 $max_attempts); do
        if curl -s "$url" >/dev/null 2>&1; then
            echo -e " ${GREEN}✓${NC}"
            return 0
        fi
        echo -n "."
        sleep 1
    done

    echo -e " ${RED}✗ (timeout)${NC}"
    return 1
}

# Parse arguments
MODE=${1:-"dev"}  # dev or docker

echo -e "${YELLOW}Mode: ${MODE}${NC}\n"

if [ "$MODE" == "docker" ]; then
    # Docker Compose mode
    echo -e "${BLUE}Starting services with Docker Compose...${NC}\n"

    cd "$PROJECT_ROOT"

    # Start infrastructure first
    echo -e "${YELLOW}Starting infrastructure (PostgreSQL, Redis, Ollama)...${NC}"
    docker-compose -f docker-compose.services.yml up -d postgres redis ollama

    sleep 5

    # Start Python services
    echo -e "${YELLOW}Starting Python services...${NC}"
    docker-compose -f docker-compose.services.yml up -d ml-engine llm-agent trading-agents

    sleep 5

    # Start Node.js services
    echo -e "${YELLOW}Starting Node.js services...${NC}"
    docker-compose -f docker-compose.services.yml up -d backend frontend

    echo -e "\n${GREEN}All services started!${NC}"
    docker-compose -f docker-compose.services.yml ps

else
    # Development mode - separate terminals
    echo -e "${BLUE}Development mode - Starting services in background...${NC}\n"

    # Check if tmux is available
    if command -v tmux &> /dev/null; then
        SESSION="orbiquant"

        # Kill existing session if any
        tmux kill-session -t $SESSION 2>/dev/null || true

        # Create new session
        tmux new-session -d -s $SESSION -n "services"

        # Window 1: Infrastructure
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT && docker-compose -f docker-compose.services.yml up postgres redis ollama" C-m

        # Window 2: ML Engine
        tmux new-window -t $SESSION -n "ml-engine"
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT/apps/ml-engine && source venv/bin/activate 2>/dev/null; pip install -r requirements.txt -q && uvicorn src.api.main:app --reload --port 8001" C-m

        # Window 3: LLM Agent
        tmux new-window -t $SESSION -n "llm-agent"
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT/apps/llm-agent && source venv/bin/activate 2>/dev/null; pip install -r requirements.txt -q && uvicorn src.main:app --reload --port 8003" C-m

        # Window 4: Trading Agents
        tmux new-window -t $SESSION -n "trading-agents"
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT/apps/trading-agents && source venv/bin/activate 2>/dev/null; pip install -r requirements.txt -q && uvicorn src.api.main:app --reload --port 8004" C-m

        # Window 5: Backend
        tmux new-window -t $SESSION -n "backend"
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT/apps/backend && npm install && npm run dev" C-m

        # Window 6: Frontend
        tmux new-window -t $SESSION -n "frontend"
        tmux send-keys -t $SESSION "cd $PROJECT_ROOT/apps/frontend && npm install && npm run dev" C-m

        echo -e "${GREEN}Services started in tmux session: $SESSION${NC}"
        echo -e "${YELLOW}To attach: tmux attach -t $SESSION${NC}"
        echo -e "${YELLOW}To switch windows: Ctrl+B then number (0-5)${NC}"

    else
        # No tmux - print manual instructions
        echo -e "${YELLOW}tmux not found. Please start services manually:${NC}\n"

        echo -e "${BOLD}Terminal 1 - Infrastructure:${NC}"
        echo "  docker-compose -f docker-compose.services.yml up postgres redis ollama"

        echo -e "\n${BOLD}Terminal 2 - ML Engine:${NC}"
        echo "  cd apps/ml-engine && uvicorn src.api.main:app --reload --port 8001"

        echo -e "\n${BOLD}Terminal 3 - LLM Agent:${NC}"
        echo "  cd apps/llm-agent && uvicorn src.main:app --reload --port 8003"

        echo -e "\n${BOLD}Terminal 4 - Trading Agents:${NC}"
        echo "  cd apps/trading-agents && uvicorn src.api.main:app --reload --port 8004"

        echo -e "\n${BOLD}Terminal 5 - Backend:${NC}"
        echo "  cd apps/backend && npm run dev"

        echo -e "\n${BOLD}Terminal 6 - Frontend:${NC}"
        echo "  cd apps/frontend && npm run dev"
    fi
fi

echo -e "\n${BOLD}Service URLs:${NC}"
echo "  Frontend:        http://localhost:5173"
echo "  Backend API:     http://localhost:3000"
echo "  ML Engine:       http://localhost:8001"
echo "  LLM Agent:       http://localhost:8003"
echo "  Trading Agents:  http://localhost:8004"
echo "  Ollama:          http://localhost:11434"

echo -e "\n${BOLD}Quick Commands:${NC}"
echo "  Test integration: python scripts/test_integration.py"
echo "  Pull Llama 3:     docker exec orbiquant-ollama ollama pull llama3:8b"
echo "  View logs:        docker-compose -f docker-compose.services.yml logs -f [service]"

echo -e "\n${GREEN}Ready!${NC}"
