"""
Utilities for running Alembic migrations from the CLI.
"""
from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Any, Sequence

from alembic import command
from alembic.config import Config

ALEMBIC_INI = Path(__file__).resolve().parents[3] / "alembic.ini"


def _load_config() -> Config:
    cfg = Config(str(ALEMBIC_INI))
    cfg.set_main_option("script_location", "alembic")
    return cfg


def run_migrations_online() -> None:
    """Run Alembic upgrade head."""
    cfg = _load_config()
    command.upgrade(cfg, "head")


def make_migration(message: str) -> None:
    """Create an autogenerated migration revision."""
    cfg = _load_config()
    command.revision(cfg, autogenerate=True, message=message)


async def migrate_async(message: str | None = None) -> None:
    """Async entrypoint used by CLI."""
    loop = asyncio.get_event_loop()
    if message:
        await loop.run_in_executor(None, make_migration, message)
    await loop.run_in_executor(None, run_migrations_online)


def migrate(message: str | None = None) -> None:
    """Sync helper."""
    asyncio.run(migrate_async(message))


__all__ = ["migrate", "migrate_async", "run_migrations_online", "make_migration"]

