#!/bin/bash

# Start script for development
# Make sure Redis is running before starting

echo "Starting Whisper AI Backend..."

# Load environment variables from .env if it exists
if [ -f .env ]; then
    echo "Loading environment variables from .env..."
    # Unset any existing config variables to ensure .env takes precedence
    unset REDIS_URL CELERY_CONCURRENCY HOST PORT LOG_LEVEL
    export $(grep -v '^#' .env | xargs)
fi

# Check if Redis is running and accessible
echo "Checking Redis connection..."
./check_redis.py

if [ $? -eq 0 ]; then
    echo "Redis check passed. Starting services..."
else
    echo "Redis is not running or not accessible. Please start Redis first:"
    echo "  redis-server"
    echo "  # or"
    echo "  brew services start redis"
    exit 1
fi

# Get configuration from environment (loaded from .env)
CELERY_CONCURRENCY=${CELERY_CONCURRENCY:-4}
HOST=${HOST:-0.0.0.0}
PORT=${PORT:-8000}

# Start the API server in background
echo "Starting FastAPI server on $HOST:$PORT..."
python3 main.py &
API_PID=$!

# Wait a moment for API to start
sleep 2

# Start the Celery worker
echo "Starting Celery worker (concurrency: $CELERY_CONCURRENCY)..."
celery -A celery_app worker --loglevel=info --concurrency=$CELERY_CONCURRENCY -Q whisper &
WORKER_PID=$!

echo ""
echo "✅ Services started successfully!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "API Server:    http://$HOST:$PORT"
echo "API PID:       $API_PID"
echo "Worker PID:    $WORKER_PID"
echo "Concurrency:   $CELERY_CONCURRENCY workers"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "To stop services:"
echo "  kill $API_PID $WORKER_PID"
echo ""
echo "Or press Ctrl+C to stop all services"

# Wait for interrupt
trap "echo 'Stopping services...'; kill $API_PID $WORKER_PID; exit" INT
wait
