#!/usr/bin/env bash
set -euo pipefail

ROOT="${APP_ROOT:-/app}"
PYTHON_BIN="${PYTHON_BIN:-python}"

if [[ ! -d "${ROOT}" ]]; then
  echo "⚠️  Application root ${ROOT} not found; skipping migrations." >&2
  exit 0
fi

cd "${ROOT}"

if [[ ! -f "${ROOT}/alembic.ini" ]]; then
  echo "⚠️  alembic.ini not present in ${ROOT}; skipping migrations." >&2
  exit 0
fi

if [[ "${ALEMBIC_SKIP_ON_START:-0}" == "1" ]]; then
  echo "ℹ️  ALEMBIC_SKIP_ON_START=1; skipping migrations."
  exit 0
fi

ROLE="${ALEMBIC_RUN_ON_START_ROLE:-primary}"

if [[ "${ROLE}" == "primary" ]]; then
  echo "🏃 Applying database migrations..."
else
  echo "ℹ️  ALEMBIC_RUN_ON_START_ROLE=${ROLE}; verifying schema without applying upgrades."
fi

normalize_revisions() {
  matches="$(printf '%s\n' "$1" | grep -Eo '[0-9a-f]{12,}' | sort -u | paste -sd ',' -)"
  if [[ -n "${matches}" ]]; then
    printf '%s' "${matches}"
  fi
}

restore_database_url() {
  if [[ "${ORIGINAL_DATABASE_URL}" != "__unset__" ]]; then
    export DATABASE_URL="${ORIGINAL_DATABASE_URL}"
  else
    unset DATABASE_URL
  fi
}

assert_single_head() {
  local heads_raw heads
  heads_raw="$("${PYTHON_BIN}" -m alembic heads || true)"
  heads="$(normalize_revisions "${heads_raw:-}")"
  if [[ -n "${heads}" && "${heads}" == *","* ]]; then
    echo "❌ Multiple Alembic heads detected (${heads})." >&2
    echo "   HINT: Align migration down_revision values or create a merge revision to restore a single head." >&2
    restore_database_url
    exit 1
  fi
}

# Get sync (non-async) database URL from SPAPS settings
SYNC_URL="$("${PYTHON_BIN}" - <<'PY'
from spaps_server_quickstart.spaps_settings import get_spaps_settings
print(get_spaps_settings().sync_database_url, end="")
PY
)"

ORIGINAL_DATABASE_URL="${DATABASE_URL-__unset__}"
if [[ -n "${SYNC_URL}" ]]; then
  export DATABASE_URL="${SYNC_URL}"
fi

assert_single_head

if [[ "${ROLE}" == "primary" ]]; then
  "${PYTHON_BIN}" -m alembic upgrade head
else
  echo "ℹ️  Skipping alembic upgrade (role=${ROLE})."
fi

current_raw="$("${PYTHON_BIN}" -m alembic current || true)"
heads_raw="$("${PYTHON_BIN}" -m alembic heads || true)"

current="$(normalize_revisions "${current_raw:-}")"
heads="$(normalize_revisions "${heads_raw:-}")"

if [[ -n "${heads}" && "${current}" != "${heads}" ]]; then
  echo "❌ Alembic drift detected (current=${current:-none} expected=${heads:-none})." >&2
  if [[ "${ROLE}" != "primary" ]]; then
    echo "   HINT: Ensure the primary migration runner has applied upgrades." >&2
  fi
  restore_database_url
  exit 1
fi

restore_database_url

echo "✅ Alembic migrations current (${current:-none})."
