"""
Alembic async environment configuration.

Uses asyncpg (via sqlalchemy[asyncio]) so migrations run through the same
async engine as the FastAPI application — no sync/async mismatch.

Usage:
    alembic upgrade head
    alembic downgrade base
    alembic revision --autogenerate -m "add foo_table"
"""

import asyncio
import os
from logging.config import fileConfig

# Load .env before reading any os.environ values — must happen before
# get_database_url() and before importing app modules that call get_settings().
try:
    from dotenv import load_dotenv
    load_dotenv(override=False)   # override=False: real env vars win over .env
except ImportError:
    pass  # python-dotenv not installed; rely on env vars already being set

from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config

from alembic import context

# ---------------------------------------------------------------------------
# Alembic Config object — gives access to values in alembic.ini
# ---------------------------------------------------------------------------
config = context.config

# Wire up Python logging from the alembic.ini [loggers] section
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# ---------------------------------------------------------------------------
# Import all SQLAlchemy models so autogenerate can see every table
# ---------------------------------------------------------------------------
from app.db.models import Base  # noqa: E402  (import after sys.path is set)

target_metadata = Base.metadata

# ---------------------------------------------------------------------------
# Read DATABASE_URL from environment — never from alembic.ini plain text
# ---------------------------------------------------------------------------
def get_database_url() -> str:
    url = os.environ.get("DATABASE_URL")
    if not url:
        raise RuntimeError(
            "DATABASE_URL environment variable is not set. "
            "Export it before running alembic:\n"
            "  export DATABASE_URL=postgresql+asyncpg://user:pass@host/db"
        )
    # Alembic autogenerate sometimes receives a sync URL; ensure async driver
    if url.startswith("postgresql://"):
        url = url.replace("postgresql://", "postgresql+asyncpg://", 1)
    if url.startswith("postgres://"):
        # Heroku-style URL
        url = url.replace("postgres://", "postgresql+asyncpg://", 1)
    return url


# ---------------------------------------------------------------------------
# OFFLINE mode — generates SQL script without a live DB connection
# ---------------------------------------------------------------------------
def run_migrations_offline() -> None:
    """
    Emit migration SQL to stdout (useful for DBAs / CI preview).
    Call with: alembic upgrade head --sql
    """
    url = get_database_url()
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        # Include schemas if you use PostgreSQL schemas other than 'public'
        include_schemas=False,
        compare_type=True,
        compare_server_default=True,
    )
    with context.begin_transaction():
        context.run_migrations()


# ---------------------------------------------------------------------------
# ONLINE mode — runs migrations against a live async PostgreSQL connection
# ---------------------------------------------------------------------------
def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True,
        compare_server_default=True,
        # Render as batch for SQLite compatibility if ever needed; no-op on PG
        render_as_batch=False,
        include_schemas=False,
    )
    with context.begin_transaction():
        context.run_migrations()


async def run_async_migrations() -> None:
    """Create async engine, obtain a connection, delegate to sync runner."""
    configuration = config.get_section(config.config_ini_section, {})
    configuration["sqlalchemy.url"] = get_database_url()

    connectable = async_engine_from_config(
        configuration,
        prefix="sqlalchemy.",
        # NullPool so Alembic never leaves idle connections after finishing
        poolclass=pool.NullPool,
    )

    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)

    await connectable.dispose()


def run_migrations_online() -> None:
    asyncio.run(run_async_migrations())


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
