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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
ALEMBIC="${PROJECT_ROOT}/venv/bin/alembic"
CONFIG="${PROJECT_ROOT}/bridge_platform/migrations/alembic.ini"

if [[ ! -x "${ALEMBIC}" ]]; then
    echo "error: Alembic not found at ${ALEMBIC}" >&2
    exit 2
fi

command="${1:-}"
case "${command}" in
    check)
        "${PROJECT_ROOT}/venv/bin/python" -c \
            "from bridge_platform.runtime.app_factory import create_app; print('imports: ok')"
        heads_output="$("${ALEMBIC}" -c "${CONFIG}" heads)"
        printf '%s\n' "${heads_output}"
        head_count="$(printf '%s\n' "${heads_output}" | sed '/^[[:space:]]*$/d' | wc -l)"
        if [[ "${head_count}" -ne 1 ]]; then
            echo "error: expected one Alembic head, found ${head_count}" >&2
            exit 1
        fi
        if [[ -n "${BRIDGE_MIGRATION_DATABASE_URL:-}" ]]; then
            "${ALEMBIC}" -c "${CONFIG}" current
            echo "database: reachable via BRIDGE_MIGRATION_DATABASE_URL"
        else
            echo "database: not checked (BRIDGE_MIGRATION_DATABASE_URL is unset)"
            echo "safety: upgrade/downgrade/current require an explicit database URL"
        fi
        ;;
    current|upgrade|downgrade)
        if [[ -z "${BRIDGE_MIGRATION_DATABASE_URL:-}" ]]; then
            echo "error: BRIDGE_MIGRATION_DATABASE_URL is required for ${command}" >&2
            echo "The V1 migration graph mixes legacy tenant and control-plane history." >&2
            exit 2
        fi
        shift
        exec "${ALEMBIC}" -c "${CONFIG}" "${command}" "$@"
        ;;
    heads|history|show|branches)
        shift
        exec "${ALEMBIC}" -c "${CONFIG}" "${command}" "$@"
        ;;
    *)
        echo "usage: scripts/db {check|current|heads|history|show|branches|upgrade|downgrade} [args...]" >&2
        exit 2
        ;;
esac
