"""Presenter for knowledge documents list command output."""

from alloy_runtime_types.dtos.knowledge import (
    DOCUMENT_STATUS_ORDER,
    ListDocumentsResponse,
)
from rich.markup import escape

from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.list_renderer import ColumnConfig


def _format_status(status: str) -> str:
    return status


def present_documents_list(response: ListDocumentsResponse) -> None:
    """Present list of documents with Rich table formatting.

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

    columns = [
        ColumnConfig(
            source_field="id",
            header_label="ID",
            compact_line=1,
            compact_style="cyan",
        ),
        ColumnConfig(
            source_field="processing_status",
            header_label="Status",
            formatter=_format_status,
            compact_line=1,
        ),
        ColumnConfig(
            source_field="filtered_reason",
            header_label="Filtered Reason",
            formatter=lambda value: value or "-",
            compact_line=1,
            compact_style="yellow",
        ),
        ColumnConfig(
            source_field="chunks_count",
            header_label="Chunks",
            align="right",
            compact_line=1,
            compact_style="blue",
        ),
        ColumnConfig(
            source_field="questions_generated",
            header_label="Questions",
            align="right",
            compact_line=1,
            compact_style="magenta",
        ),
        ColumnConfig(
            source_field="updated_at",
            header_label="Updated",
            formatter=lambda x: x.strftime("%Y-%m-%d") if x else "-",
            compact_line=1,
            compact_style="dim",
        ),
        ColumnConfig(
            source_field="title",
            header_label="Title",
            formatter=lambda x: x or "-",
            compact_line=2,
            compact_style="white bold",
        ),
        ColumnConfig(
            source_field="collection_id",
            header_label="Collection",
            formatter=lambda x: str(x) if x else "-",
            compact_line=2,
            compact_style="dim",
        ),
    ]

    output.table(
        items=response.documents,  # type: ignore[arg-type]
        title=f"Documents ({response.total})",
        columns=columns,
        raw_payload=response,
        total_count=response.total,
    )
    breakdown = response.breakdown_by_status.model_dump()
    output.text(
        "By status: "
        + ", ".join(
            f"{escape(status)}={escape(str(breakdown[status]))}"
            for status in DOCUMENT_STATUS_ORDER
        )
    )
