"""Presenter for document recovery output."""

from uuid import UUID

from pydantic import BaseModel

from cli.infrastructure.formatting.fields import format_uuid
from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.entity_renderer import FieldConfig
from alloy_runtime_types.dtos.knowledge import RecoverDocumentsResponse


class DocumentIdsOutput(BaseModel):
    document_ids: str


def present_recovery_result(response: RecoverDocumentsResponse) -> None:
    """Present document recovery results.

    Args:
        response: Recovery response from server
    """
    output = OutputService.get()

    output.result(
        action="recover",
        resource="knowledge_documents",
        identifier=None,
        name=None,
        extra_fields={
            "Documents Recovered": response.recovered_count,
            "Documents Re-queued": response.requeued_count,
            "Queued Restarts": response.queued_restart_count,
            "Queued Restart Skipped": response.queued_restart_skipped_count,
            "Documents Permanently Failed": response.failed_count,
        },
    )

    if response.queued_restart_document_ids:
        _present_document_ids(
            output,
            "Queued backlog restarted",
            response.queued_restart_document_ids,
        )

    if response.queued_restart_skipped_document_ids:
        _present_document_ids(
            output,
            "Queued backlog skipped",
            response.queued_restart_skipped_document_ids,
        )

    if response.requeued_document_ids:
        _present_document_ids(
            output, "Re-queued for processing", response.requeued_document_ids
        )

    if response.recovered_document_ids:
        _present_document_ids(
            output, "Reset for retry", response.recovered_document_ids
        )

    if response.failed_document_ids:
        _present_document_ids(
            output, "Permanently failed", response.failed_document_ids
        )


def _present_document_ids(
    output: OutputService,
    title: str,
    doc_ids: list[UUID],
    max_display: int = 10,
) -> None:
    """Present a list of document IDs."""
    if not doc_ids:
        return

    _ = max_display
    output.entity(
        DocumentIdsOutput(
            document_ids="\n".join(
                format_uuid(doc_id, short=False) for doc_id in doc_ids
            )
        ),
        title,
        [FieldConfig("document_ids", "Document IDs")],
    )
