#!/bin/bash
# Start all three servers: backend, admin-frontend, and viewer-frontend

set -euo pipefail

cd "$(dirname "$0")"

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

echo -e "${BLUE}🚀 Starting all PunimTag servers...${NC}"
echo ""

# Function to cleanup on exit
cleanup() {
    echo ""
    echo -e "${YELLOW}Shutting down all servers...${NC}"
    kill $WORKER_PID 2>/dev/null || true
    kill $BACKEND_PID 2>/dev/null || true
    kill $ADMIN_PID 2>/dev/null || true
    kill $VIEWER_PID 2>/dev/null || true
    exit
}

trap cleanup SIGINT SIGTERM

# Start backend
echo -e "${GREEN}📦 Starting backend server...${NC}"
# Use explicit Python path to avoid Cursor interception
PYTHON_BIN="/usr/bin/python3"
if [ ! -f "$PYTHON_BIN" ]; then
    if command -v python3 >/dev/null 2>&1; then
        PYTHON_BIN="$(which python3)"
    elif command -v python >/dev/null 2>&1; then
        PYTHON_BIN="$(which python)"
    else
        echo -e "${YELLOW}❌ Python3 not found${NC}"
        exit 1
    fi
fi

if [ -d "venv" ]; then
    source venv/bin/activate
fi
export PYTHONPATH="$(pwd)"

# Check if Redis is running
if ! redis-cli ping > /dev/null 2>&1; then
    echo -e "${YELLOW}⚠️  Redis is not running. Starting Redis...${NC}"
    redis-server --daemonize yes 2>/dev/null || {
        echo -e "${YELLOW}❌ Failed to start Redis. Please start it manually: redis-server${NC}"
        exit 1
    }
    sleep 1
fi

# Start RQ worker in background
echo -e "${GREEN}🚀 Starting RQ worker...${NC}"
env PYTHONPATH="$(pwd)" "$PYTHON_BIN" -m backend.worker > /tmp/worker.log 2>&1 &
WORKER_PID=$!

# Give worker a moment to start
sleep 2

# Start FastAPI server
echo -e "${GREEN}🚀 Starting FastAPI server...${NC}"
"$PYTHON_BIN" -m uvicorn backend.app:app --host 127.0.0.1 --port 8000 --reload > /tmp/backend.log 2>&1 &
BACKEND_PID=$!

# Wait a moment for backend to start
sleep 2

# Start admin-frontend
echo -e "${GREEN}📦 Starting admin-frontend...${NC}"
cd admin-frontend
npm run dev > /tmp/admin-frontend.log 2>&1 &
ADMIN_PID=$!
cd ..

# Start viewer-frontend
echo -e "${GREEN}📦 Starting viewer-frontend...${NC}"
cd viewer-frontend
npm run dev > /tmp/viewer-frontend.log 2>&1 &
VIEWER_PID=$!
cd ..

echo ""
echo -e "${GREEN}✅ All servers started!${NC}"
echo ""
echo -e "${BLUE}📍 Server URLs:${NC}"
echo -e "  Backend API:    ${GREEN}http://127.0.0.1:8000${NC}"
echo -e "  API Docs:       ${GREEN}http://127.0.0.1:8000/docs${NC}"
echo -e "  Admin Frontend: ${GREEN}http://127.0.0.1:3000${NC}"
echo -e "  Viewer Frontend: ${GREEN}http://127.0.0.1:3001${NC}"
echo ""
echo -e "${YELLOW}📋 Logs:${NC}"
echo -e "  Worker:         ${BLUE}/tmp/worker.log${NC}"
echo -e "  Backend:        ${BLUE}/tmp/backend.log${NC}"
echo -e "  Admin:          ${BLUE}/tmp/admin-frontend.log${NC}"
echo -e "  Viewer:         ${BLUE}/tmp/viewer-frontend.log${NC}"
echo ""
echo -e "${YELLOW}Press Ctrl+C to stop all servers${NC}"
echo ""

# Wait for all processes
wait

