"""
Configuration Alembic pour PriceWatch.

Recupere l'URL DB depuis AppConfig pour garantir un setup coherent.
"""

from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

from pricewatch.app.core.config import get_config
from pricewatch.app.db.models import Base

# Alembic Config object
config = context.config

# Configure logging
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Metadata SQLAlchemy pour autogenerate
target_metadata = Base.metadata


def _get_database_url() -> str:
    """Construit l'URL DB depuis la config applicative."""
    app_config = get_config()
    return app_config.db.url


def run_migrations_offline() -> None:
    """
    Execute les migrations en mode offline.

    Configure le contexte avec l'URL DB sans creer d'engine.
    """
    url = _get_database_url()
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_type=True,
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """
    Execute les migrations en mode online.

    Cree un engine SQLAlchemy et etablit la connexion.
    """
    configuration = config.get_section(config.config_ini_section) or {}
    configuration["sqlalchemy.url"] = _get_database_url()

    connectable = engine_from_config(
        configuration,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
        )

        with context.begin_transaction():
            context.run_migrations()


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