"""Presenter for schemas list command output."""

from pydantic import BaseModel, Field
from alloy_runtime_types.dtos.schemas import ListSchemasResponse, SchemaSummary

from cli.infrastructure.scope_utils import format_scope_label
from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.list_renderer import ColumnConfig


class SchemaDisplay(BaseModel):
    name: str = Field(..., description="Schema name")
    id: str = Field(..., description="Schema ID")
    version: int = Field(..., description="Version number")
    format: str = Field(..., description="Format type")
    scope: str = Field(..., description="Ownership scope")
    created: str | None = Field(None, description="Creation date")
    description: str | None = Field(None, description="Description")


def _transform_schema_for_display(schema: SchemaSummary) -> SchemaDisplay:
    return SchemaDisplay(
        name=schema.schema_name,
        id=str(schema.id),
        version=schema.version,
        format=schema.schema_format_id,
        scope=format_scope_label(
            str(schema.organization_id) if schema.organization_id else None,
            str(schema.user_id) if schema.user_id else None,
        ),
        created=schema.created_at.strftime("%Y-%m-%d") if schema.created_at else None,
        description=schema.description,
    )


def present_schemas_list(response: ListSchemasResponse) -> None:
    output = OutputService.get()
    display_items = [_transform_schema_for_display(s) for s in response.schemas]
    columns = [
        ColumnConfig(
            source_field="name",
            header_label="Name",
        ),
        ColumnConfig(
            source_field="id",
            header_label="ID",
        ),
        ColumnConfig(
            source_field="version",
            header_label="Version",
        ),
        ColumnConfig(
            source_field="format",
            header_label="Format",
        ),
        ColumnConfig(
            source_field="scope",
            header_label="Scope",
        ),
        ColumnConfig(
            source_field="created",
            header_label="Created",
        ),
        ColumnConfig(
            source_field="description",
            header_label="Description",
        ),
    ]

    output.table(
        items=display_items,  # type: ignore[arg-type]
        title="Schemas",
        columns=columns,
        raw_payload=response,
    )
