from cli.infrastructure.output import OutputService
from alloy_runtime_types.dtos.knowledge import BulkReingestFailedDocumentsResponse


def _follow_up_message(response: BulkReingestFailedDocumentsResponse) -> str | None:
    if response.dry_run:
        return None
    if response.status == "accepted":
        return f"Bulk reingest accepted. Poll status with: alloy knowledge documents reingest-failed-status {response.operation_id}"
    if response.queued_count and response.queued_count > 0:
        return "Bulk reingest queued. Watch worker queue depth until processing stabilizes."
    if response.skipped_count and response.skipped_count > 0:
        return "No documents were queued. Review skipped documents before retrying."
    return "No failed documents matched the provided scope."


def present_bulk_reingest_failed_result(
    response: BulkReingestFailedDocumentsResponse,
) -> None:
    output = OutputService.get()
    next_step = _follow_up_message(response)

    extra_fields: dict[str, bool | str | int | None] = {
        "Dry Run": response.dry_run,
        "Message": response.message,
        "Next Step": next_step,
    }

    if response.status == "accepted":
        extra_fields["Status"] = response.status
        extra_fields["Operation ID"] = str(response.operation_id)
    else:
        extra_fields["Matched"] = response.matched_count
        extra_fields["Queued"] = response.queued_count
        extra_fields["Skipped"] = response.skipped_count

    output.result(
        action="reingest",
        resource="knowledge_documents",
        status="dry_run" if response.dry_run else "success",
        identifier=str(response.operation_id) if response.operation_id else None,
        name=None,
        extra_fields=extra_fields,
    )
