#!/bin/bash
# ThrillWiki Development Server
# Runs Django, Celery worker, and Celery beat together
#
# Usage: ./run-dev.sh
# Press Ctrl+C to stop all services

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Find backend directory (script may be run from different locations)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -d "$SCRIPT_DIR/backend" ]; then
    BACKEND_DIR="$SCRIPT_DIR/backend"
elif [ -d "$SCRIPT_DIR/../backend" ]; then
    BACKEND_DIR="$SCRIPT_DIR/../backend"
elif [ -f "$SCRIPT_DIR/manage.py" ]; then
    BACKEND_DIR="$SCRIPT_DIR"
else
    echo -e "${RED}❌ Cannot find backend directory. Run from project root or backend folder.${NC}"
    exit 1
fi

cd "$BACKEND_DIR"

echo -e "${BLUE}🎢 ThrillWiki Development Server${NC}"
echo "=================================="
echo -e "Backend: ${GREEN}$BACKEND_DIR${NC}"
echo ""

# Check Redis is running
if ! redis-cli ping &> /dev/null; then
    echo -e "${YELLOW}⚠️  Redis not running. Starting Redis...${NC}"
    if command -v brew &> /dev/null; then
        brew services start redis 2>/dev/null || true
        sleep 1
    else
        echo -e "${RED}❌ Redis not running. Start with: docker run -d -p 6379:6379 redis:alpine${NC}"
        exit 1
    fi
fi
echo -e "${GREEN}✓ Redis connected${NC}"

# Cleanup function to kill all background processes
cleanup() {
    echo ""
    echo -e "${YELLOW}Shutting down...${NC}"
    kill $PID_DJANGO $PID_CELERY_WORKER $PID_CELERY_BEAT 2>/dev/null
    wait 2>/dev/null
    echo -e "${GREEN}✓ All services stopped${NC}"
    exit 0
}

trap cleanup SIGINT SIGTERM

echo ""
echo -e "${BLUE}Starting services...${NC}"
echo ""

# Start Django
echo -e "${GREEN}▶ Django${NC} (http://localhost:8000)"
uv run python manage.py runserver 2>&1 | sed 's/^/  [Django] /' &
PID_DJANGO=$!

# Start Celery worker
echo -e "${GREEN}▶ Celery Worker${NC}"
uv run celery -A config worker -l info 2>&1 | sed 's/^/  [Worker] /' &
PID_CELERY_WORKER=$!

# Start Celery beat
echo -e "${GREEN}▶ Celery Beat${NC}"
uv run celery -A config beat -l info 2>&1 | sed 's/^/  [Beat]   /' &
PID_CELERY_BEAT=$!

echo ""
echo -e "${GREEN}All services running. Press Ctrl+C to stop.${NC}"
echo ""

# Wait for any process to exit
wait
