"""
Alembic migration environment for Munal LMS.

Architecture & Execution Design
────────────────────────────────
1. Async Engine Integration:
   Munal LMS uses SQLAlchemy 2.0 with the asyncpg driver (postgresql+asyncpg).
   Alembic's default env.py is synchronous and fails when given an async URL.
   To support asyncpg without requiring a separate sync driver, this file:
     - Uses `async_engine_from_config` to instantiate an AsyncEngine
     - Runs migrations inside an async event loop via `asyncio.run()`
     - Bridges the async connection to Alembic's sync visitor via `connection.run_sync()`

2. Target Metadata & Model Discovery:
   `from app.models import Base` imports all 25 models via app/models/__init__.py.
   Every table, constraint, index, and enum attached to `Base.metadata` is visible
   to Alembic's autogenerate engine.

3. Deterministic Naming Conventions:
   `Base.metadata` carries the `NAMING_CONVENTION` defined in `app/models/base.py`.
   All generated constraints have deterministic names (ix_, uq_, ck_, fk_, pk_),
   preventing anonymous constraints that fail on PostgreSQL drop operations.

4. Comparison Flags:
   `compare_type=True`           → detects column type/length changes (e.g. String(50) -> String(100))
   `compare_server_default=True`  → detects server_default modifications
"""

import asyncio
from logging.config import fileConfig

from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config

from app.config import settings
from app.models import Base

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Ensure sqlalchemy.url is set to the application's configured DATABASE_URL
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)

# Model MetaData for autogenerate support
target_metadata = Base.metadata

# These four migration-owned snapshots are required for the staff-role rollback.
# They are intentionally outside ORM metadata and must never be proposed for deletion.
ROLE_MIGRATION_BACKUPS = {
    "_role_merge_general_user_backup",
    "_role_merge_permissions_backup",
    "_role_merge_phlebotomist_report_write_backup",
    "_role_merge_role_backup",
}


def include_object(
    object_: object, name: str | None, type_: str, reflected: bool, compare_to: object | None
) -> bool:
    return not (type_ == "table" and name in ROLE_MIGRATION_BACKUPS)


def run_migrations_offline() -> None:
    """
    Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.
    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_type=True,
        compare_server_default=True,
        include_object=include_object,
    )

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


def do_run_migrations(connection: Connection) -> None:
    """
    Run actual sync migration directives on a connection provided by the async runner.
    """
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True,
        compare_server_default=True,
        include_object=include_object,
    )

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


async def run_async_migrations() -> None:
    """
    Create an AsyncEngine and associate a connection with the context.
    """
    configuration = config.get_section(config.config_ini_section) or {}
    configuration["sqlalchemy.url"] = settings.DATABASE_URL

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

    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)

    await connectable.dispose()


def run_migrations_online() -> None:
    """
    Run migrations in 'online' mode.
    """
    asyncio.run(run_async_migrations())


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