#!/bin/bash

# ThrillWiki Local CI Start Script
# This script starts the Django development server following project requirements

set -e  # Exit on any error

# Configuration
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_DIR="$PROJECT_DIR/logs"
PID_FILE="$LOG_DIR/django.pid"
LOG_FILE="$LOG_DIR/django.log"

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

# Logging function
log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

# Create logs directory if it doesn't exist
mkdir -p "$LOG_DIR"

# Change to project directory
cd "$PROJECT_DIR"

log "Starting ThrillWiki CI deployment..."

# Check if UV is installed
if ! command -v uv &> /dev/null; then
    log_error "UV is not installed. Please install UV first."
    exit 1
fi

# Stop any existing Django processes on port 8000
log "Stopping any existing Django processes on port 8000..."
if lsof -ti :8000 >/dev/null 2>&1; then
    lsof -ti :8000 | xargs kill -9 2>/dev/null || true
    log_success "Stopped existing processes"
else
    log "No existing processes found on port 8000"
fi

# Clean up Python cache files
log "Cleaning up Python cache files..."
find . -type d -name "__pycache__" -exec rm -r {} + 2>/dev/null || true
log_success "Cache files cleaned"

# Install/update dependencies
log "Installing/updating dependencies with UV..."
uv sync --no-dev || {
    log_error "Failed to sync dependencies"
    exit 1
}

# Run database migrations
log "Running database migrations..."
uv run manage.py migrate || {
    log_error "Database migrations failed"
    exit 1
}

# Collect static files
log "Collecting static files..."
uv run manage.py collectstatic --noinput || {
    log_warning "Static file collection failed, continuing anyway"
}

# Start the development server
log "Starting Django development server with Tailwind..."
log "Server will be available at: http://localhost:8000"
log "Press Ctrl+C to stop the server"

# Start server and capture PID
uv run manage.py tailwind runserver 0.0.0.0:8000 &
SERVER_PID=$!

# Save PID to file
echo $SERVER_PID > "$PID_FILE"

log_success "Django server started with PID: $SERVER_PID"
log "Server logs are being written to: $LOG_FILE"

# Wait for server to start
sleep 3

# Check if server is running
if kill -0 $SERVER_PID 2>/dev/null; then
    log_success "Server is running successfully!"
    
    # Monitor the process
    wait $SERVER_PID
else
    log_error "Server failed to start"
    rm -f "$PID_FILE"
    exit 1
fi

# Cleanup on exit
cleanup() {
    log "Shutting down server..."
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if kill -0 $PID 2>/dev/null; then
            kill $PID
            log_success "Server stopped"
        fi
        rm -f "$PID_FILE"
    fi
}

trap cleanup EXIT INT TERM