"""Async generation cancel command implementation."""

import typer

from cli.commands.generate.cancel.presenter import present_generation_cancel
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.console import Confirm


def generate_cancel_command(
    execution_id: str = typer.Argument(
        ...,
        help="Execution UUID of the async generation to cancel",
    ),
    yes: bool = typer.Option(
        False,
        "-y",
        "--yes",
        help="Skip confirmation",
    ),
) -> None:
    """Cancel a pending or running async generation.

    Only generations in non-terminal states (pending, running) can be cancelled.

    Examples:
        alloy generate cancel 123e4567-89ab-cdef-0123-456789abcdef
        alloy generate cancel 123e4567-... -y
    """
    if not yes:
        confirmed = Confirm.ask(f"Cancel generation {execution_id}?")
        if not confirmed:
            raise typer.Abort()

    _execute_cancel(execution_id=execution_id)


@async_command
async def _execute_cancel(execution_id: str) -> None:
    """Execute cancel operation."""
    async with authenticated_client() as (_config, client):
        response = await client.cancel_generation(execution_id)

    present_generation_cancel(response)
