#!/usr/bin/env bash
# scripts/setup_demo.sh
# Creates the iilmp_demo database, runs migrations, and seeds it with fake data.
# Run this once on the server after deploying the web_demo service.
#
# Usage:
#   bash scripts/setup_demo.sh              # demo volume (default)
#   bash scripts/setup_demo.sh --volume minimal
#   bash scripts/setup_demo.sh --reseed     # drop & recreate (wipe existing demo data)
set -euo pipefail

COMPOSE="docker compose -f docker-compose.prod.yml"
DEMO_SERVICE="web_demo"
DEMO_DB="iilmp_demo"
VOLUME="demo"
RESEED=false

for arg in "$@"; do
  case $arg in
    --volume) shift; VOLUME="$1"; shift ;;
    --volume=*) VOLUME="${arg#*=}" ;;
    --reseed) RESEED=true ;;
  esac
done

echo "=== IILMP Demo Setup ==="
echo "  Database : $DEMO_DB"
echo "  Volume   : $VOLUME"
echo "  Reseed   : $RESEED"
echo ""

# 1. Create the demo database inside the running postgres container.
echo "--- Creating database '$DEMO_DB' (if not exists) ---"
$COMPOSE exec -T postgres psql \
  -U "${DB_USER:-iilmp}" \
  -c "SELECT 1 FROM pg_database WHERE datname='$DEMO_DB'" \
  | grep -q 1 && echo "  Already exists — skipping create." || \
  $COMPOSE exec -T postgres psql \
    -U "${DB_USER:-iilmp}" \
    -c "CREATE DATABASE $DEMO_DB OWNER ${DB_USER:-iilmp};"

# Enable pgvector extension in the demo DB.
$COMPOSE exec -T postgres psql \
  -U "${DB_USER:-iilmp}" \
  -d "$DEMO_DB" \
  -c "CREATE EXTENSION IF NOT EXISTS vector;" 2>/dev/null || true

# 2. If --reseed, wipe and recreate.
if [ "$RESEED" = true ]; then
  echo "--- Reseed requested: dropping all tables ---"
  $COMPOSE exec -T "$DEMO_SERVICE" python manage.py migrate --run-syncdb --fake-initial 2>/dev/null || true
  $COMPOSE exec -T postgres psql \
    -U "${DB_USER:-iilmp}" \
    -d "$DEMO_DB" \
    -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" || true
fi

# 3. Run migrations against iilmp_demo.
echo "--- Running migrations on $DEMO_DB ---"
$COMPOSE exec -T "$DEMO_SERVICE" python manage.py migrate --noinput

# 4. Collect static (shared volume with production — safe, idempotent).
echo "--- Collecting static files ---"
$COMPOSE exec -T "$DEMO_SERVICE" python manage.py collectstatic --noinput --clear 2>/dev/null || \
$COMPOSE exec -T "$DEMO_SERVICE" python manage.py collectstatic --noinput

# 5. Seed with fake data.
echo "--- Seeding demo data (volume=$VOLUME) ---"
$COMPOSE exec -T "$DEMO_SERVICE" python manage.py seed_all --volume "$VOLUME"

echo ""
echo "✓ Demo environment ready."
echo "  URL: http://$(hostname -I | awk '{print $1}'):8001"
echo "  To reset at any time: bash scripts/setup_demo.sh --reseed"
