"""Knowledge recover command implementation."""

from typing import Optional

import typer

from cli.commands.knowledge.recover.presenter import present_recovery_result
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.knowledge import RecoverDocumentsRequest


def knowledge_recover_command(
    max_retries: Optional[int] = typer.Option(
        None,
        "-r",
        "--max-retries",
        min=1,
        max=10,
        help="Override max retry attempts (default: 3)",
    ),
    restart_queued: bool = typer.Option(
        False,
        "--restart-queued/--no-restart-queued",
        help="Also restart queued backlog documents from scratch (default: no)",
    ),
) -> None:
    """Recover stuck documents.

    Retries or permanently fails documents stuck in 'processing' state after
    their heartbeat goes stale, and logs queued backlog on the server.

    Documents can get stuck when:
    - Processing is interrupted (container crash, API timeout, etc.)
    - Celery never picks up the task (message lost, worker unavailable)

    Examples:
        alloy knowledge recover
        alloy knowledge recover --max-retries 5
        alloy knowledge recover --restart-queued
    """
    _execute_recover(max_retries=max_retries, restart_queued=restart_queued)


@async_command
async def _execute_recover(max_retries: Optional[int], restart_queued: bool) -> None:
    """Execute document recovery operation."""
    request = None
    if max_retries is not None or restart_queued:
        request = RecoverDocumentsRequest(
            max_retries=max_retries,
            restart_queued=restart_queued,
        )

    async with authenticated_client() as (_config, client):
        response = await client.recover_documents(request)

    present_recovery_result(response)
