"""
Alembic Migration Environment.

Configured for SwX Framework with async SQLAlchemy support.
"""

import asyncio
from logging.config import fileConfig

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

from alembic import context

# Import models to ensure they are registered with Base.metadata
from swx_core.models.base import Base
from swx_core.utils.model import load_all_models

# Load all models (both core and app)
load_all_models()

# this is the Alembic Config object
config = context.config

# Interpret the config file for Python logging.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Set target metadata
target_metadata = Base.metadata


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode."""
    from swx_core.config.settings import settings

    url = settings.SQLALCHEMY_DATABASE_URI
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

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


def render_item(type_, obj, autogen_context):
    from sqlmodel.sql.sqltypes import AutoString
    from sqlalchemy import String, DateTime, Text, Integer, BigInteger, Float, Boolean

    if type_ == "type":
        if isinstance(obj, AutoString):
            return f"String({obj.length})" if obj.length else "String()"
        if hasattr(obj, "__class__") and obj.__class__.__name__ == "NullType":
            return "DateTime()"
    return False


def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        render_item=render_item,
    )

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


async def run_async_migrations() -> None:
    """Run migrations in 'online' mode with async engine."""
    from swx_core.config.settings import settings

    configuration = {"sqlalchemy.url": settings.ASYNC_SQLALCHEMY_DATABASE_URI}
    connectable = async_engine_from_config(
        configuration,
        prefix="",
        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()
