#!/bin/sh
set -e

# Extrai host/porta/usuário/senha/banco de DATABASE_URL (mysql+pymysql://...).
_parse_db_url() {
  _url="${DATABASE_URL#*://}"
  _creds="${_url%%@*}"
  _rest="${_url#*@}"
  DB_USER="${_creds%%:*}"
  DB_PASS="${_creds#*:}"
  _hostport="${_rest%%/*}"
  DB_NAME="${_rest#*/}"
  DB_NAME="${DB_NAME%%\?*}"
  DB_HOST="${_hostport%%:*}"
  DB_PORT="${_hostport#*:}"
  if [ "$DB_PORT" = "$DB_HOST" ]; then
    DB_PORT=3306
  fi
}

wait_for_mysql() {
  if [ -z "${DATABASE_URL:-}" ]; then
    echo "DATABASE_URL não definida" >&2
    exit 1
  fi
  _parse_db_url
  echo "Aguardando MySQL em ${DB_HOST}:${DB_PORT}..."
  i=0
  while [ "$i" -lt 60 ]; do
    if mysqladmin ping -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" --silent 2>/dev/null; then
      echo "MySQL pronto."
      return 0
    fi
    i=$((i + 1))
    sleep 2
  done
  echo "Timeout aguardando MySQL" >&2
  exit 1
}

run_migrations() {
  if [ "${SKIP_MIGRATIONS:-0}" = "1" ]; then
    echo "SKIP_MIGRATIONS=1 — pulando Alembic."
    return 0
  fi
  echo "Rodando alembic upgrade head..."
  alembic upgrade head
}

run_seed() {
  if [ "${RUN_SEED:-0}" != "1" ]; then
    return 0
  fi
  echo "Rodando seed (RUN_SEED=1)..."
  python -m app.seed
}

wait_for_mysql
run_migrations
run_seed

exec "$@"
