"""Migrations CLI commands."""

from __future__ import annotations

import typer

migrations_app = typer.Typer(help="Manage database migrations")


@migrations_app.command("list")
def migrations_list(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """List migrations for a team."""
    from appliku.cli import get_client, render_output

    client = get_client()
    result = client.migrations.list(team)
    rows = [
        {"id": m.id, "command": m.command, "status": m.status, "created_at": m.created_at}
        for m in result.results
    ]
    render_output(rows, ["id", "command", "status", "created_at"], output, title="Migrations")


@migrations_app.command("run")
def migrations_run(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="Application ID"),
    command: str = typer.Option(..., "--command", "-c", help="Migration command"),
) -> None:
    """Run a database migration."""
    from appliku.cli import get_client

    client = get_client()
    migration = client.migrations.run(team, app_id, command)
    typer.echo(f"Migration {migration.id} started (status: {migration.status})")


@migrations_app.command("logs")
def migrations_logs(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    migration_id: int = typer.Argument(..., help="Migration ID"),
) -> None:
    """Get migration logs."""
    from appliku.cli import get_client

    client = get_client()
    entries = client.migrations.logs(team, migration_id)
    for entry in entries:
        typer.echo(f"[{entry.timestamp or ''}] {entry.message}")
