#!/bin/bash

# ThrillWiki Development Server Script
# This script sets up the proper environment variables and runs the Django development server

set -e  # Exit on any error

echo "🚀 Starting ThrillWiki Development Server..."

# Change to the project directory (parent of scripts folder)
cd "$(dirname "$0")/.."

# Set Django environment to local development
export DJANGO_SETTINGS_MODULE="config.django.local"

# Core Django settings
export DEBUG="True"
export SECRET_KEY="django-insecure-dev-key-not-for-production-$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)"

# Allowed hosts for development
export ALLOWED_HOSTS="localhost,127.0.0.1,0.0.0.0"

# CSRF trusted origins for development
export CSRF_TRUSTED_ORIGINS="http://localhost:8000,http://127.0.0.1:8000,https://127.0.0.1:8000"

# Database configuration (PostgreSQL with PostGIS)
export DATABASE_URL="postgis://thrillwiki_user:thrillwiki@localhost:5432/thrillwiki_test_db"

# Cache configuration (use locmem for development if Redis not available)
export CACHE_URL="locmemcache://"
export REDIS_URL="redis://127.0.0.1:6379/1"

# CORS settings for API development
export CORS_ALLOW_ALL_ORIGINS="True"
export CORS_ALLOWED_ORIGINS=""

# Email configuration for development (console backend)
export EMAIL_URL="consolemail://"

# GeoDjango library paths for macOS (adjust if needed)
export GDAL_LIBRARY_PATH="/opt/homebrew/lib/libgdal.dylib"
export GEOS_LIBRARY_PATH="/opt/homebrew/lib/libgeos_c.dylib"

# API rate limiting (generous for development)
export API_RATE_LIMIT_PER_MINUTE="1000"
export API_RATE_LIMIT_PER_HOUR="10000"

# Cache settings
export CACHE_MIDDLEWARE_SECONDS="1"  # Very short cache for development
export CACHE_MIDDLEWARE_KEY_PREFIX="thrillwiki_dev"

# Social auth settings (you can set these if you have them)
# export GOOGLE_OAUTH2_CLIENT_ID=""
# export GOOGLE_OAUTH2_CLIENT_SECRET=""
# export DISCORD_CLIENT_ID=""
# export DISCORD_CLIENT_SECRET=""

# Create necessary directories
echo "📁 Creating necessary directories..."
mkdir -p logs
mkdir -p profiles
mkdir -p media
mkdir -p staticfiles
mkdir -p static/css

# Check if virtual environment is activated
if [[ -z "$VIRTUAL_ENV" ]] && [[ -d ".venv" ]]; then
    echo "🔧 Activating virtual environment..."
    source .venv/bin/activate
fi

# Run database migrations if needed
echo "🗄️  Checking database migrations..."
if uv run manage.py migrate --check 2>/dev/null; then
    echo "✅ Database migrations are up to date"
else
    echo "🔄 Running database migrations..."
    uv run manage.py migrate --noinput
fi
echo "Resetting database..."
if uv run manage.py seed_sample_data 2>/dev/null; then
	echo "Seeding complete!"
else
	echo "Seeding test data to database..."
	uv run manage.py seed_sample_data
fi

# Create superuser if it doesn't exist
echo "👤 Checking for superuser..."
if ! uv run manage.py shell -c "from django.contrib.auth import get_user_model; User = get_user_model(); exit(0 if User.objects.filter(is_superuser=True).exists() else 1)" 2>/dev/null; then
    echo "👤 Creating development superuser (admin/admin)..."
    uv run manage.py shell -c "
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@example.com', 'admin')
    print('Created superuser: admin/admin')
else:
    print('Superuser already exists')
"
fi

# Collect static files for development
echo "📦 Collecting static files..."
uv run manage.py collectstatic --noinput --clear

# Build Tailwind CSS
if command -v npm &> /dev/null; then
    echo "🎨 Building Tailwind CSS..."
    uv run manage.py tailwind build
else
    echo "⚠️  npm not found, skipping Tailwind CSS build"
fi

# Run system checks
echo "🔍 Running system checks..."
if uv run manage.py check; then
    echo "✅ System checks passed"
else
    echo "❌ System checks failed, but continuing..."
fi

# Display environment info
echo ""
echo "🌍 Development Environment:"
echo "  - Settings Module: $DJANGO_SETTINGS_MODULE"
echo "  - Debug Mode: $DEBUG"
echo "  - Database: PostgreSQL with PostGIS"
echo "  - Cache: Local memory cache"
echo "  - Admin URL: http://localhost:8000/admin/"
echo "  - Admin User: admin / admin"
echo "  - Silk Profiler: http://localhost:8000/silk/"
echo "  - Debug Toolbar: Available on debug pages"
echo "  - API Documentation: http://localhost:8000/api/docs/"
echo ""

# Start the development server
echo "🌟 Starting Django development server on http://localhost:8000"
echo "Press Ctrl+C to stop the server"
echo ""

# Use runserver_plus if django-extensions is available, otherwise use standard runserver
if uv run python -c "import django_extensions" 2>/dev/null; then
    exec uv run manage.py runserver_plus 0.0.0.0:8000
else
    exec uv run manage.py runserver 0.0.0.0:8000
fi
