#!/bin/bash
set -e

# 1) Wait for the database service to be ready
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 and reachable"

# If there’s no migrations folder yet, initialize Alembic here:
if [ ! -d "./migrations" ]; then
  echo "[🆕] No migrations directory found; initializing Alembic"
  flask db init
fi

# 2) Always apply any already-created migration scripts first
echo "[▶️] Applying existing migrations (upgrade)"
flask db upgrade

# 3) Now attempt to autogenerate a new migration if the models changed
echo "[✨] Autogenerating new migration (if needed)"
flask db migrate -m "auto"

# 4) Apply that new migration (if one was generated)
echo "[▶️] Applying any newly autogenerated migration"
flask db upgrade

# 5) Optionally seed data
if [ "$ENABLE_DB_SEEDING" = "true" ] || [ "$ENABLE_DB_SEEDING" = "1" ]; then
  echo "[🌱] Seeding Data"
  flask preload-data
fi

# 6) Finally, run the Flask application
echo "[🚀] Starting Flask"
exec "$@"
