"""Alembic migration environment with async and environment variable support.

Supports:
- SQLite for development (sqlite+aiosqlite:///path)
- PostgreSQL for production (postgresql+asyncpg://host/db)
- Environment variable DATABASE_URL for configuration
- Async operations for SQLAlchemy 2.0+
"""

import os
from logging.config import fileConfig

from sqlalchemy import pool
from sqlalchemy.ext.asyncio import create_async_engine

from alembic import context

# 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.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None

# Read database URL from environment or config
database_url = os.getenv(
    "DATABASE_URL",
    config.get_main_option("sqlalchemy.url")
)

# Ensure we have the correct async driver
if database_url and not database_url.startswith(("sqlite+aiosqlite", "postgresql+asyncpg")):
    # Convert to async versions
    if database_url.startswith("sqlite://"):
        database_url = database_url.replace("sqlite://", "sqlite+aiosqlite:///")
    elif database_url.startswith("postgresql://"):
        database_url = database_url.replace("postgresql://", "postgresql+asyncpg://")


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.

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

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


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

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    # Determine pool class based on database type
    if "postgresql" in database_url:
        # PostgreSQL with async support
        engine = create_async_engine(
            database_url,
            poolclass=pool.NullPool,
            future=True,
        )
    else:
        # SQLite - use synchronous connection for migrations
        # Alembic doesn't support async migrations well with SQLite
        from sqlalchemy import create_engine
        db_url = database_url.replace("sqlite+aiosqlite://", "sqlite:///")
        engine = create_engine(
            db_url,
            poolclass=pool.NullPool,
        )

    with engine.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata
        )

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

    if "postgresql" in database_url:
        # Cleanup async engine
        import asyncio
        asyncio.run(engine.dispose())


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