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

# Resolve DB host/port from vars or defaults
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"

# Only the "flask" entrypoint needs uploads + migrations
if [ "$1" = "flask" ]; then

  # Prepare upload dir (web only) — path comes from .env UPLOAD_FOLDER (e.g. "data/uploads")
  UPLOAD_DIR="/app/${UPLOAD_FOLDER:-static/uploads}"
  mkdir -p "$UPLOAD_DIR"
  echo "⏺️  Ensured upload directory exists: $UPLOAD_DIR"

  # Run DB migrations
  echo "[🛠️] Applying database migrations"
  flask db upgrade

  # Ensure any missing tables
  echo "[🛠️] Ensuring tables exist"
  python <<EOF
from app import create_app, db
app = create_app()
with app.app_context():
    db.create_all()
EOF

  # Optional seeding
  if [ "${ENABLE_DB_SEEDING,,}" = "true" ] || [ "${ENABLE_DB_SEEDING}" = "1" ]; then
    echo "[🌱] Seeding Data"
    flask preload-data
  fi

  echo "[🚀] Starting Flask"
fi

# Finally hand off to whatever service was requested (flask or celery)
exec "$@"
