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

UPLOAD_DIR="/app/static/uploads"
mkdir -p "$UPLOAD_DIR"
chown -R 1000:998 "$UPLOAD_DIR"
chmod -R 775 "$UPLOAD_DIR"

DB_HOST=${DB_HOST:-db}
DB_PORT=${DB_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"

# Initialize Alembic if not present
if [ ! -d "./migrations" ]; then
  echo "[🆕] No migrations directory found; initializing Alembic"
  flask db init
  echo "[🆕] Generating initial migration"
  flask db migrate -m "initial" || echo "[ℹ️] Nothing to migrate"
fi

# Autogenerate new migration if needed
echo "[🛠️] Checking for new schema changes"
if ! flask db migrate -m "auto-migrate" --compare-type --render-as-batch; then
  echo "[ℹ️] No schema changes detected"
fi

# Apply migrations
echo "[▶️] Applying database migrations"
flask db upgrade

# Create any missing tables (edge case fallback)
echo "[🔧] Running db.create_all() to ensure full sync"
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"
exec "$@"
