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

console = Console()

def command(
    steps: int = typer.Option(1, "--step", help="Number of batches to roll back"),
    path: str = typer.Option("database/migrations", "--path"),
) -> None:
    """Roll back the last database migration batch."""
    async def _run():
        from migrate_cmd import _load_app
        _load_app()
        from caprail.orm.model import _engine
        from caprail.orm.migrations import Migrator
        migrator = Migrator(_engine)
        rolled = await migrator.rollback(Path(path), steps)
        if not rolled:
            console.print("[yellow]Nothing to roll back.[/]")
        for name in rolled:
            console.print(f"[red]Rolled back:[/] {name}")
    asyncio.run(_run())
