#!/bin/bash

# SACAP FAQ App - Consolidated Startup Script for Staging/Production
# This script starts all services in the proper order for staging deployment

set -e

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

print_header() {
    echo -e "${PURPLE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║                    SACAP FAQ App - Staging                   ║${NC}"
    echo -e "${PURPLE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_status() {
    echo -e "${BLUE}[STARTUP]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

print_service() {
    echo -e "${PURPLE}[SERVICE]${NC} $1"
}

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR"

print_header
print_status "Starting SACAP FAQ App for staging deployment..."
print_status "Project root: $PROJECT_ROOT"

# Check if we're in a DDEV environment
if [ -f ".ddev/config.yaml" ]; then
    print_status "DDEV environment detected"
    IN_DDEV=true
else
    print_status "Standard environment detected"
    IN_DDEV=false
fi

# Function to check if a service is running
check_service() {
    local service_name=$1
    local port=$2
    local path=${3:-"/"}

    if curl -s "http://localhost:$port$path" > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# Function to wait for service
wait_for_service() {
    local service_name=$1
    local port=$2
    local path=${3:-"/"}
    local max_attempts=30
    local attempt=1

    print_status "Waiting for $service_name to be ready..."

    while [ $attempt -le $max_attempts ]; do
        if check_service "$service_name" "$port" "$path"; then
            print_success "$service_name is ready!"
            return 0
        fi

        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done

    print_error "$service_name failed to start within expected time"
    return 1
}

# Start services
print_service "Starting services in order..."

# 1. Start RAG Service
print_status "Starting RAG Service..."
cd "$PROJECT_ROOT/services/rag-service"

# Check if virtual environment exists, if not create it
if [ ! -d "venv" ]; then
    print_status "Creating Python virtual environment..."
    python3 -m venv venv
    print_success "Virtual environment created"
fi

# Activate virtual environment
source venv/bin/activate

# Check if requirements are installed
if [ ! -f "venv/lib/python3.*/site-packages/flask/__init__.py" ]; then
    print_status "Installing Python dependencies..."
    pip3 install -r requirements.txt
    print_success "Python dependencies installed"
fi

if [ -f "rag_service.pid" ]; then
    PID=$(cat rag_service.pid)
    if kill -0 "$PID" 2>/dev/null; then
        print_warning "RAG Service is already running (PID: $PID)"
    else
        print_status "Removing stale PID file"
        rm -f rag_service.pid
    fi
fi

# Start RAG service in background
./start.sh background

# Wait for RAG service to be ready
wait_for_service "RAG Service" "5002" "/rag-service/health"

# Deactivate virtual environment
deactivate

cd "$PROJECT_ROOT"

# 2. Start Laravel development server (if not using external web server)
print_status "Starting Laravel application..."

# Check if Laravel dependencies are installed
if [ ! -d "vendor" ]; then
    print_status "Installing Laravel dependencies..."
    composer install --no-dev --optimize-autoloader
    print_success "Laravel dependencies installed"
fi

# Run Laravel migrations
print_status "Running database migrations..."
php artisan migrate --force
print_success "Database migrations completed"

# Clear and cache Laravel configuration
print_status "Optimizing Laravel configuration..."
php artisan config:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
print_success "Laravel optimization completed"

# Start Laravel server
LARAVEL_PORT=${LARAVEL_PORT:-8000}
print_status "Starting Laravel development server on port $LARAVEL_PORT..."

if check_service "Laravel" "$LARAVEL_PORT"; then
    print_warning "Laravel server is already running on port $LARAVEL_PORT"
else
    # Start Laravel in background
    nohup php artisan serve --host=0.0.0.0 --port="$LARAVEL_PORT" > laravel.log 2>&1 &
    echo $! > laravel.pid

    # Wait for Laravel to be ready
    wait_for_service "Laravel" "$LARAVEL_PORT" "/api/content/status"
fi

# 3. Start frontend build process (if in development)
if [ "${NODE_ENV:-development}" = "development" ]; then
    print_status "Starting frontend development server..."

    # Check if node_modules exists
    if [ ! -d "node_modules" ]; then
        print_status "Installing Node.js dependencies..."
        npm install
        print_success "Node.js dependencies installed"
    fi

    # Start Vite dev server
    nohup npm run dev > vite.log 2>&1 &
    echo $! > vite.pid
    print_success "Frontend development server started"
fi

# Display service status
print_header
print_success "All services started successfully!"
echo ""
print_service "Service Status:"
echo "  • RAG Service:    http://localhost:5002/rag-service/"
echo "  • Laravel API:    http://localhost:$LARAVEL_PORT/api/"
echo "  • Application:    http://localhost:$LARAVEL_PORT/"
echo ""
print_status "Process IDs:"
if [ -f "services/rag-service/rag_service.pid" ]; then
    echo "  • RAG Service:    $(cat services/rag-service/rag_service.pid)"
fi
if [ -f "laravel.pid" ]; then
    echo "  • Laravel:        $(cat laravel.pid)"
fi
if [ -f "vite.pid" ]; then
    echo "  • Vite:           $(cat vite.pid)"
fi
echo ""
print_status "Logs:"
echo "  • RAG Service:    tail -f services/rag-service/rag_service.log"
echo "  • Laravel:        tail -f laravel.log"
if [ -f "vite.pid" ]; then
    echo "  • Vite:           tail -f vite.log"
fi
echo ""
print_success "Startup complete! 🚀"
