#!/bin/bash
# Start FastAPI server with RQ worker in background

cd "$(dirname "$0")"

# Activate virtual environment if it exists
if [ -d "venv" ]; then
    source venv/bin/activate
fi

# Set Python path
export PYTHONPATH="$(pwd)"

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

# Function to cleanup on exit
cleanup() {
    echo "Shutting down..."
    kill $WORKER_PID 2>/dev/null
    kill $API_PID 2>/dev/null
    exit
}

trap cleanup SIGINT SIGTERM

# Start RQ worker in background
echo "🚀 Starting RQ worker..."
python -m src.web.worker &
WORKER_PID=$!

# Give worker a moment to start
sleep 2

# Start FastAPI server
echo "🚀 Starting FastAPI server..."
uvicorn src.web.app:app --host 127.0.0.1 --port 8000 &
API_PID=$!

echo ""
echo "✅ Server running on http://127.0.0.1:8000"
echo "✅ Worker running (PID: $WORKER_PID)"
echo "✅ API running (PID: $API_PID)"
echo ""
echo "Press Ctrl+C to stop both services"
echo ""

# Wait for both processes
wait

