#!/bin/bash
# Development setup script for Stiftungsmanagement
# Uses compose.dev.yml for isolated development environment

set -e

COMPOSE_FILE="compose.dev.yml"
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_DIR"

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."
    echo ""
    echo "Install Docker: https://docs.docker.com/engine/install/"
    echo "Or install Docker Desktop: https://docs.docker.com/desktop/"
    exit 1
fi

# Start services
echo "Starting Docker services with $COMPOSE_FILE..."
docker compose -f "$COMPOSE_FILE" up -d --build

# Wait for database to be ready
echo "Waiting for database to be ready..."
until docker compose -f "$COMPOSE_FILE" exec -T db pg_isready -U postgres -d stiftung_dev > /dev/null 2>&1; do
    sleep 2
done
echo "Database is ready."

# Run migrations
echo "Running database migrations..."
docker compose -f "$COMPOSE_FILE" exec -T web python manage.py migrate

# Collect static files
echo "Collecting static files..."
docker compose -f "$COMPOSE_FILE" exec -T web python manage.py collectstatic --noinput

# Create superuser if none exists
echo "Checking for superuser..."
docker compose -f "$COMPOSE_FILE" exec -T web python manage.py shell -c "
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. Create one with:')
    print('  docker compose -f $COMPOSE_FILE exec web python manage.py createsuperuser')
else:
    print('Superuser already exists.')
"

echo ""
echo "Development environment is ready!"
echo ""
echo "Services:"
echo "  Django App:   http://localhost:18081"
echo "  Paperless:    http://localhost:8082"
echo "  Gramps Web:   http://localhost:18090"
echo "  PostgreSQL:   localhost:5433 (user: postgres, pass: postgres_dev, db: stiftung_dev)"
echo ""
echo "Useful commands:"
echo "  Logs:           docker compose -f $COMPOSE_FILE logs -f web"
echo "  Tests:          docker compose -f $COMPOSE_FILE exec web python manage.py test"
echo "  Django shell:   docker compose -f $COMPOSE_FILE exec web python manage.py shell"
echo "  Superuser:      docker compose -f $COMPOSE_FILE exec web python manage.py createsuperuser"
echo "  Stop:           docker compose -f $COMPOSE_FILE down"
echo "  Reset (wipe):   docker compose -f $COMPOSE_FILE down -v"
