#!/bin/bash

# Start Redis
echo "Starting Redis..."
if sudo service redis-server start; then
    echo "✓ Redis started"
else
    echo "x Failed to start Redis"
    exit 1
fi

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

# Start Celery Worker
echo "Starting Celery Worker..."
# Check for existing celery process
if pgrep -f "celery worker" > /dev/null; then
    echo "! Celery is already running"
else
    nohup celery -A src.worker.app worker --loglevel=info > celery.log 2>&1 &
    echo "✓ Celery worker started"
fi

# Start Backend
echo "Starting Backend API..."
if pgrep -f "uvicorn backend.main:app" > /dev/null; then
    echo "! Backend is already running"
else
    nohup uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000 > backend.log 2>&1 &
    echo "✓ Backend API started"
fi

# Start Frontend
echo "Starting Frontend..."
if pgrep -f "vite" > /dev/null; then
    echo "! Frontend is already running"
else
    cd frontend
    nohup npm run dev > ../frontend.log 2>&1 &
    cd ..
    echo "✓ Frontend started"
fi

echo "-----------------------------------"
echo "All services are running!"
echo "Logs:"
echo "  - Celery:   tail -f celery.log"
echo "  - Backend:  tail -f backend.log"
echo "  - Frontend: tail -f frontend.log"
