"""Alembic environment configuration.

When called programmatically (from init_db), the sqlalchemy.url is set on
the Config object.  When called via CLI, it falls back to DATABASE_URL env var.
"""

import os

from alembic import context
from sqlalchemy import create_engine, pool


def _get_url() -> str:
    """Get the database URL from config or fall back to DATABASE_URL env."""
    url = context.config.get_main_option("sqlalchemy.url")
    if url:
        return url
    env_url = os.environ.get("DATABASE_URL", "")
    if not env_url:
        raise RuntimeError("DATABASE_URL environment variable is not set")
    # Ensure SQLAlchemy-compatible URL scheme
    if env_url.startswith("postgres://"):
        env_url = "postgresql+psycopg://" + env_url[len("postgres://"):]
    elif env_url.startswith("postgresql://") and "+psycopg" not in env_url:
        env_url = env_url.replace("postgresql://", "postgresql+psycopg://", 1)
    return env_url


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode (emit SQL to stdout)."""
    context.configure(
        url=_get_url(),
        target_metadata=None,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """Run migrations against a live database connection."""
    connectable = create_engine(
        _get_url(),
        poolclass=pool.NullPool,
    )
    with connectable.connect() as connection:
        context.configure(connection=connection, target_metadata=None)
        with context.begin_transaction():
            context.run_migrations()


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