#!/usr/bin/env bash
set -e

# 1) Wait for MySQL
DB_HOST="${DB_HOST:-${MYSQL_HOST:-db}}"
DB_PORT="${DB_PORT:-${MYSQL_PORT:-3306}}"
echo "[⏳] Waiting for database at $DB_HOST:$DB_PORT..."
until nc -z "$DB_HOST" "$DB_PORT"; do sleep 1; done
echo "[✔] Database is up"

# 2) Ensure uploads dir exists/writable
UPLOAD_DIR="/app/${UPLOAD_FOLDER:-data/uploads}"
mkdir -p "$UPLOAD_DIR"
chown -R appuser:appuser "$UPLOAD_DIR"
chmod -R u+rwX,g+rwX,o+rX "$UPLOAD_DIR"
echo "⏺️  Upload directory ready at $UPLOAD_DIR"

# 3) If launching Flask, handle schema + migrations + seeding
if [ "$1" = "flask" ]; then
  # A) Create any truly missing tables (so FKs won’t break)
  echo "[🛠️] Ensuring tables via create_all()"
  python <<EOF
from app import create_app, db
app = create_app()
with app.app_context():
    db.create_all()
EOF

  # B) If this is the very first run (no revisions), stamp head
  VERSIONS_DIR="/app/migrations/versions"
  if [ ! -d "$VERSIONS_DIR" ] || [ -z "$(ls -A "$VERSIONS_DIR")" ]; then
    mkdir -p "$VERSIONS_DIR"
    echo "[🔖] No Alembic revisions found—stamping head"
    flask db stamp head
  fi

  # C) Always try to auto-generate a new migration (if models changed)
  echo "[🛠️] Auto-generating a new migration (if needed)"
  flask db migrate --message "Auto migration on $(date +%Y-%m-%d_%H-%M-%S)" || true

  # D) Apply all pending migrations
  echo "[🛠️] Applying migrations"
  flask db upgrade

  # E) Seed if configured
  if [ "${ENABLE_DB_SEEDING,,}" = "true" ] || [ "${ENABLE_DB_SEEDING}" = "1" ]; then
    echo "[🌱] Seeding demo data"
    flask preload-data
  fi

  echo "[🚀] Ready to start Flask"
fi

# 4) Drop privileges if root; then exec
if [ "$(id -u)" = "0" ]; then
  exec gosu appuser "$@"
else
  exec "$@"
fi
