"""Safe Alembic environment for the transitional Bridge Platform V1 graph.

The revision chain contains legacy WP Invoices revisions followed by newer
control-plane revisions. Connection commands therefore require an explicit
BRIDGE_MIGRATION_DATABASE_URL until those histories are split in V2.
"""

from __future__ import annotations

import os
import sys
from logging.config import fileConfig
from pathlib import Path

from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlalchemy.engine import make_url


REPOSITORY_ROOT = Path(__file__).resolve().parents[3]
if str(REPOSITORY_ROOT) not in sys.path:
    # Alembic loads env.py as a script. This single __file__-based path is
    # deterministic and independent of the caller's working directory.
    sys.path.insert(0, str(REPOSITORY_ROOT))

config = context.config
if config.config_file_name:
    fileConfig(config.config_file_name)


def get_target_metadata():
    """Load the explicit V1 control-plane metadata or fail visibly."""
    from config.db import Base
    import bridge_platform.tenants.models  # noqa: F401
    import apps.messaging_service.models  # noqa: F401
    import apps.qr_service.models  # noqa: F401

    if not Base.metadata.tables:
        raise RuntimeError("Bridge control-plane metadata loaded no tables")
    return Base.metadata


target_metadata = get_target_metadata()


def configured_database_url() -> str:
    url = os.getenv("BRIDGE_MIGRATION_DATABASE_URL", "").strip()
    if not url:
        raise RuntimeError(
            "BRIDGE_MIGRATION_DATABASE_URL is required for database commands; "
            "the V1 Alembic graph is mixed and has no safe implicit target"
        )
    make_url(url)
    return url


def run_migrations_offline() -> None:
    context.configure(
        url=configured_database_url(),
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_type=True,
        compare_server_default=True,
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    section = config.get_section(config.config_ini_section) or {}
    section["sqlalchemy.url"] = configured_database_url()
    connectable = engine_from_config(section, prefix="sqlalchemy.", poolclass=pool.NullPool)
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
            compare_server_default=True,
        )
        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
