"""Pipeline execution rerun command implementation."""

from uuid import UUID

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.execute.presenter import present_execution_result
from cli.infrastructure.command import async_command, authenticated_client


def pipelines_executions_rerun_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    execution_id: str = typer.Argument(
        ...,
        help="Execution UUID to rerun",
    ),
) -> None:
    """Re-run a failed or paused pipeline execution.

    Completed steps are automatically skipped via idempotent cache-hits.
    Use after approving a checkpoint to resume pipeline execution.

    Examples:
        alloy pipelines executions rerun 123e4567... 456e7890...
    """
    p_uuid = validate_uuid(pipeline_id, "pipeline")
    e_uuid = validate_uuid(execution_id, "execution")
    _execute_rerun(pipeline_id=p_uuid, execution_id=e_uuid)


@async_command
async def _execute_rerun(pipeline_id: UUID, execution_id: UUID) -> None:
    """Execute rerun pipeline operation."""
    async with authenticated_client() as (_config, client):
        response = await client.rerun_pipeline_execution(pipeline_id, execution_id)

    present_execution_result(response)
