"""Alembic environment — the DB URL comes from the environment, never a file.

Container: WITH_DB_URL (compose env_file; migrations run on startup).
Host:      WITH_DB_URL_HOST (read from .env via app.config when invoked
           from the repo root) — the sidecar's 127.0.0.1:54317 binding.
"""

import os
from logging.config import fileConfig

from sqlalchemy import create_engine

from alembic import context

config = context.config

if config.config_file_name is not None:
    fileConfig(config.config_file_name)

from app.models import Base  # noqa: E402  (alembic template puts config first)

target_metadata = Base.metadata


def _db_url() -> str:
    url = os.environ.get("WITH_DB_URL")
    if not url:
        from app.config import settings

        url = settings.with_db_url_host or settings.with_db_url
    if not url:
        raise RuntimeError(
            "Set WITH_DB_URL (container) or WITH_DB_URL_HOST (host) — see .env"
        )
    return url


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


def run_migrations_online() -> None:
    engine = create_engine(_db_url(), pool_pre_ping=True)
    with engine.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)
        with context.begin_transaction():
            context.run_migrations()
    engine.dispose()


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