"""Presenter for schema get command output."""

import json

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 GetSchemaResponse


def _derive_scope(response: GetSchemaResponse) -> str:
    """Derive scope string from organization_id and user_id fields.

    Args:
        response: Schema response from server

    Returns:
        Scope string: user, organization, or global
    """
    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 _format_definition_for_display(
    schema_format_id: str, schema_definition: str
) -> str:
    """Format schema definition for display.

    JSON schemas are pretty-printed, regex patterns shown as-is.

    Args:
        schema_format_id: Format type (json_schema, regex)
        schema_definition: The schema definition string

    Returns:
        Formatted definition string
    """
    if schema_format_id == "json_schema":
        try:
            # Parse and pretty-print JSON
            parsed = json.loads(schema_definition)
            return json.dumps(parsed, indent=2, ensure_ascii=False)
        except (json.JSONDecodeError, TypeError):
            # If parsing fails, return as-is
            return schema_definition
    else:
        # Regex or other formats - return as-is
        return schema_definition


def present_schema_details(response: GetSchemaResponse) -> None:
    output = OutputService.get()

    metadata_fields = [
        FieldConfig("id", "ID", lambda value: format_uuid(value, short=False)),
        FieldConfig("schema_name", "Name"),
        FieldConfig("schema_format_id", "Format"),
        FieldConfig("version", "Version", str),
        FieldConfig("description", "Description", format_optional),
        FieldConfig("id", "Scope", lambda _: _derive_scope(response)),
        FieldConfig("is_latest", "Is Latest", lambda value: "Yes" if value else "No"),
        FieldConfig(
            "organization_id",
            "Organization ID",
            lambda value: format_optional(
                value, lambda item: format_uuid(item, short=True)
            ),
        ),
        FieldConfig(
            "user_id",
            "User ID",
            lambda value: format_optional(
                value, lambda item: format_uuid(item, short=True)
            ),
        ),
        FieldConfig("created_at", "Created At", format_datetime),
    ]
    output.entity(
        response,
        f"Schema: {response.schema_name}",
        metadata_fields,
        raw_payload=response,
    )

    definition_fields = [
        FieldConfig(
            "schema_definition",
            "Definition",
            lambda value: _format_definition_for_display(
                response.schema_format_id, value
            ),
        )
    ]
    output.entity(
        response, f"Schema Definition: {response.schema_name}", definition_fields
    )
