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

set -euo pipefail

cd "$(dirname "$0")"

# Use explicit Python path to avoid Cursor interception
PYTHON_BIN="${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 "❌ 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

# Activate venv but keep using explicit Python path
source venv/bin/activate

# Override python command to use explicit path (venv activation might change it)
export PYTHON_BIN="${PYTHON_BIN:-/usr/bin/python3}"

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

# Set Python path - must be set before any Python commands
PROJECT_ROOT="$(pwd)"
export PYTHONPATH="$PROJECT_ROOT"

# Ensure database schema exists
echo "🗃  Ensuring database schema is up to date..."
"$PYTHON_BIN" - <<PY
import sys
import os
sys.path.insert(0, '$PROJECT_ROOT')
from backend.db.models import Base
from backend.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..."
# Ensure PYTHONPATH is set and run from project root
# Use env to ensure PYTHONPATH is passed to the worker process
env PYTHONPATH="$PROJECT_ROOT" "$PYTHON_BIN" -m backend.worker > /tmp/worker.log 2>&1 &
WORKER_PID=$!

# Give worker a moment to start
sleep 3

# Check if worker started successfully
if ! ps -p $WORKER_PID > /dev/null 2>&1; then
    echo "❌ Worker process exited immediately with code 1"
    echo "   Check worker errors above or in /tmp/worker.log"
    cat /tmp/worker.log 2>/dev/null | tail -10 || true
    exit 1
fi

# Start FastAPI server
echo "🚀 Starting FastAPI server..."
"$PYTHON_BIN" -m uvicorn backend.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

