"""Presenter for tool config get command output."""

import json
from typing import Any

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.tool_configs import GetToolConfigResponse


class ToolConfigBody(BaseModel):
    configuration: str


def _format_scope(response: GetToolConfigResponse) -> str:
    if response.user_id:
        return "User"
    if response.organization_id:
        return "Organization"
    return "Global"


def _format_config(value: dict[str, Any]) -> Any:
    return json.dumps(value, indent=2)


def present_tool_config_details(response: GetToolConfigResponse) -> None:
    """Present tool config details with Rich formatting.

    Args:
        response: GetToolConfigResponse from server
    """
    output = OutputService.get()
    output.entity(
        response,
        f"Tool Config: {response.name}",
        [
            FieldConfig("id", "ID", lambda v: format_uuid(v, short=False)),
            FieldConfig("slug", "Slug"),
            FieldConfig("name", "Name"),
            FieldConfig("tool_id", "Tool ID"),
            FieldConfig("description", "Description", format_optional),
            FieldConfig("id", "Scope", lambda _: _format_scope(response)),
            FieldConfig(
                "user_id",
                "User ID",
                lambda v: format_optional(v, lambda x: format_uuid(x, short=True)),
            ),
            FieldConfig(
                "organization_id",
                "Organization ID",
                lambda v: format_optional(v, lambda x: format_uuid(x, short=True)),
            ),
            FieldConfig("created_at", "Created At", format_datetime),
            FieldConfig("updated_at", "Updated At", format_datetime),
        ],
        raw_payload=response,
    )
    output.entity(
        ToolConfigBody(configuration=_format_config(response.config)),
        "Configuration",
        [FieldConfig("configuration", "Configuration")],
    )
