"""Presenter for schema update output."""

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.schemas import UpdateSchemaResponse


def _derive_scope(response: UpdateSchemaResponse) -> str:
    """Derive scope string from organization_id and user_id fields."""
    if response.organization_id is not None and response.user_id is None:
        return "organization"
    elif response.user_id is not None:
        return "user"
    else:
        return "global"


def present_schema_update_success(response: UpdateSchemaResponse) -> None:
    """Present successful schema update.

    Args:
        response: Schema update response from server
    """
    output = OutputService.get()
    output.result(
        action="update",
        resource="schema",
        identifier=str(response.id),
        name=response.schema_name,
    )

    fields = [
        FieldConfig("id", "ID", lambda v: format_uuid(v, short=False)),
        FieldConfig("schema_name", "Name"),
        FieldConfig("schema_format_id", "Format"),
        FieldConfig("version", "Version", str),
        FieldConfig("description", "Description", format_optional),
        FieldConfig("scope", "Scope", lambda _: _derive_scope(response)),
        FieldConfig(
            "organization_id",
            "Organization ID",
            lambda v: format_optional(v, lambda x: format_uuid(x, short=True)),
        ),
        FieldConfig(
            "user_id",
            "User ID",
            lambda v: format_optional(v, lambda x: format_uuid(x, short=True)),
        ),
        FieldConfig("is_latest", "Is Latest", str),
        FieldConfig("created_at", "Created At", format_datetime),
    ]

    output.entity(
        response, f"Schema: {response.schema_name}", fields, raw_payload=response
    )
