"""caprail migrate run"""
from __future__ import annotations
import asyncio
from pathlib import Path
import typer
from rich.console import Console

console = Console()

def command(
    path: str = typer.Option("database/migrations", "--path", help="Path to migrations directory"),
) -> None:
    """Run pending database migrations."""
    _run_migrations(path)

def _run_migrations(path: str) -> None:
    async def _run():
        from caprail.orm.model import _engine
        from caprail.orm.migrations import Migrator
        if _engine is None:
            _bootstrap()
        from caprail.orm.model import _engine as engine
        migrator = Migrator(engine)
        applied = await migrator.run(Path(path))
        if not applied:
            console.print("[yellow]Nothing to migrate.[/]")
        else:
            for name in applied:
                console.print(f"[green]Migrated:[/] {name}")
    asyncio.run(_run())

def _bootstrap() -> None:
    _load_app()

def _load_app() -> None:
    import sys, importlib
    sys.path.insert(0, str(Path.cwd()))
    try:
        importlib.import_module("bootstrap.app")
    except ImportError:
        try:
            importlib.import_module("app")
        except ImportError:
            pass
