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

set -euo pipefail

cd "$(dirname "$0")"

# Ensure virtual environment exists and dependencies are installed
PYTHON_BIN="${PYTHON_BIN:-}"
if [ -z "$PYTHON_BIN" ]; then
    if command -v python3 >/dev/null 2>&1; then
        PYTHON_BIN="python3"
    elif command -v python >/dev/null 2>&1; then
        PYTHON_BIN="python"
    else
        echo "❌ Python interpreter not found. Please install Python 3.10+."
        exit 1
    fi
fi

if [ ! -d "venv" ]; then
    echo "📦 Creating virtual environment..."
    "$PYTHON_BIN" -m venv venv
fi

source venv/bin/activate

REQUIREMENTS_STAMP="venv/.requirements_installed"
if [ ! -f "$REQUIREMENTS_STAMP" ] || [ requirements.txt -nt "$REQUIREMENTS_STAMP" ]; then
    echo "📦 Installing backend dependencies..."
    python -m pip install --upgrade pip wheel setuptools
    python -m pip install -r requirements.txt
    touch "$REQUIREMENTS_STAMP"
fi

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

# Ensure database schema exists
echo "🗃  Ensuring database schema is up to date..."
python - <<'PY'
from src.web.db.models import Base
from src.web.db.session import engine

Base.metadata.create_all(bind=engine)
print("✅ Database schema ready")
PY

# 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

