#!/bin/bash
# Development setup script

set -e

echo "🚀 Setting up Stiftung development environment..."

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker is not running. Please start Docker first."
    exit 1
fi

# Check if .env exists
if [ ! -f ".env" ]; then
    echo "📝 Creating .env file from template..."
    cp env-template.txt .env
    echo "✅ Please edit .env file with your configuration"
fi

# Start services
echo "🐳 Starting Docker services..."
docker-compose up -d

# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
sleep 10

# Run migrations
echo "🔄 Running database migrations..."
docker-compose exec web python manage.py migrate

# Create superuser if needed
echo "👤 Creating superuser (if needed)..."
docker-compose exec web python manage.py shell << 'EOF'
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(is_superuser=True).exists():
    print("No superuser found. Please create one:")
    exit()
else:
    print("Superuser already exists")
EOF

# Collect static files
echo "📦 Collecting static files..."
docker-compose exec web python manage.py collectstatic --noinput

# Check health
echo "🏥 Checking application health..."
sleep 5
if curl -f -s http://localhost:8000/health/ > /dev/null; then
    echo "✅ Application is healthy!"
else
    echo "❌ Application health check failed"
fi

echo ""
echo "🎉 Development environment is ready!"
echo ""
echo "📊 Services:"
echo "  - Application: http://localhost:8000"
echo "  - Admin: http://localhost:8000/admin/"
echo "  - HelpBox Admin: http://localhost:8000/help-box/admin/"
echo ""
echo "🛠️ Useful commands:"
echo "  - View logs: docker-compose logs -f web"
echo "  - Run tests: docker-compose exec web python manage.py test"
echo "  - Django shell: docker-compose exec web python manage.py shell"
echo "  - Create superuser: docker-compose exec web python manage.py createsuperuser"
