"""Presenter for knowledge document update metadata 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 UpdateDocumentMetadataResponse


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


def present_update_metadata_result(
    response: UpdateDocumentMetadataResponse,
) -> None:
    """Present document metadata update result.

    Args:
        response: UpdateDocumentMetadataResponse from server
    """
    output = OutputService.get()
    output.result(
        action="update",
        resource="knowledge_document",
        identifier=str(response.id),
        name=response.title,
    )
    output.entity(
        response,
        "Document Metadata",
        [
            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("metadata", "Metadata", _format_metadata),
            FieldConfig("updated_at", "Updated At", format_datetime),
        ],
        raw_payload=response,
    )
