"""Presenter for knowledge document get command output."""

import json
from typing import Any, cast

from cli.infrastructure.formatting.fields import (
    format_datetime,
    format_uuid,
)
from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.entity_renderer import FieldConfig
from alloy_runtime_types.dtos.knowledge import GetDocumentResponse


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


def _format_optional_text(value: str | None) -> Any:
    if value is None:
        return cast(str, None)
    return value


def _format_optional_json(value: dict[str, Any] | None) -> Any:
    if value is None:
        return cast(str, None)
    return json.dumps(value, indent=2)


def present_document_details(
    response: GetDocumentResponse, show_content: bool = False
) -> None:
    """Present document details with Rich formatting.

    Args:
        response: GetDocumentResponse from server
        show_content: Whether to show original content panel
    """
    output = OutputService.get()
    output.entity(
        response,
        f"Document: {response.title}",
        [
            FieldConfig("id", "ID", lambda v: format_uuid(v, short=False)),
            FieldConfig(
                "collection_id", "Collection ID", lambda v: format_uuid(v, short=False)
            ),
            FieldConfig("title", "Title"),
            FieldConfig("source_type", "Source Type"),
            FieldConfig("character_count", "Character Count", lambda v: f"{v:,}"),
            FieldConfig(
                "estimated_tokens", "Estimated Tokens", lambda v: f"{v:,}" if v else "-"
            ),
            FieldConfig("processing_status", "Processing Status", _format_status),
            FieldConfig("filtered_reason", "Filtered Reason", _format_optional_text),
            FieldConfig("processing_error", "Processing Error", _format_optional_text),
            FieldConfig("chunks_count", "Chunks Count", str),
            FieldConfig("chunks_failed", "Chunks Failed", str),
            FieldConfig("questions_generated", "Questions Generated", str),
            FieldConfig("metadata", "Metadata", _format_optional_json),
            FieldConfig("created_at", "Created At", format_datetime),
            FieldConfig("updated_at", "Updated At", format_datetime),
        ],
        raw_payload=response,
    )

    if show_content:
        output.entity(
            response,
            "Original Content",
            [
                FieldConfig(
                    "original_content", "Original Content", _format_optional_text
                )
            ],
        )
