from alembic import context

from zbt.core.config import Settings
from zbt.infrastructure.mysql.agent_models import AgentBase
from zbt.infrastructure.mysql.sessions import DatabaseName, build_mysql_url

config = context.config
target_metadata = AgentBase.metadata


def run_migrations_offline() -> None:
    context.configure(
        url=build_mysql_url(Settings(), DatabaseName.AGENT),
        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:
    from sqlalchemy import create_engine

    engine = create_engine(build_mysql_url(Settings(), DatabaseName.AGENT))
    with engine.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()
