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

import json
from typing import Any, cast

from pydantic import BaseModel

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


def _format_optional_json(value: Any) -> Any:
    if value is None:
        return cast(str, None)
    if isinstance(value, BaseModel):
        value = value.model_dump(mode="json")
    return json.dumps(value, indent=2, sort_keys=True)


def present_collection_details(response: GetCollectionResponse) -> None:
    """Present collection details with Rich formatting.

    Args:
        response: GetCollectionResponse from server
    """
    output = OutputService.get()
    output.entity(
        response,
        f"Collection: {response.name}",
        [
            FieldConfig("id", "ID", lambda v: format_uuid(v, short=False)),
            FieldConfig("name", "Name"),
            FieldConfig("description", "Description", format_optional),
            FieldConfig("embedding_model", "Embedding Model"),
            FieldConfig("embedding_dimensions", "Embedding Dimensions", str),
            FieldConfig("chunk_size_tokens", "Chunk Size", lambda v: f"{v} tokens"),
            FieldConfig(
                "chunk_overlap_tokens", "Chunk Overlap", lambda v: f"{v} tokens"
            ),
            FieldConfig("section_strategy", "Section Strategy"),
            FieldConfig(
                "semantic_routing_profile",
                "Semantic Routing Profile",
                _format_optional_json,
            ),
            FieldConfig("document_count", "Document Count", str),
            FieldConfig("created_at", "Created At", format_datetime),
            FieldConfig("updated_at", "Updated At", format_datetime),
        ],
        raw_payload=response,
    )
