"""Alembic env.

Bootstrap (AZ-263) ships the minimal `env.py` so `alembic check` resolves
`0001_initial.sql` as head. Concrete metadata wiring is added by AZ-304.
"""

from __future__ import annotations

import os

from alembic import context
from sqlalchemy import engine_from_config, pool

config = context.config

if "sqlalchemy.url" not in config.get_section(config.config_ini_section, {}):
    db_url = os.environ.get("DB_URL")
    if db_url:
        config.set_main_option(
            "sqlalchemy.url", db_url.replace("postgresql://", "postgresql+psycopg://", 1)
        )


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


def run_migrations_online() -> None:
    connectable = engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    with connectable.connect() as connection:
        context.configure(connection=connection)
        with context.begin_transaction():
            context.run_migrations()


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