"""Schema picker component for selecting input/output schemas.

A specialized search picker that uses the ApiClient to fetch schemas
and returns the selected schema's ID.
"""

from typing import Any

from alloy_runtime_sdk.api_client.client import ApiClient

from cli.infrastructure.forms.base_picker import SingleSelectPicker


def _format_schema(schema: dict[str, Any]) -> str:
    """Format a schema for display in the picker."""
    name = schema.get("schema_name", "Unknown")
    version = schema.get("version", "?")
    schema_format = schema.get("schema_format_id", "unknown")

    # Determine scope from ownership fields
    user_id = schema.get("user_id")
    org_id = schema.get("organization_id")
    if user_id:
        scope = "User"
    elif org_id:
        scope = "Org"
    else:
        scope = "Global"

    # Truncate description if present
    description = schema.get("description")
    desc_part = ""
    if description:
        desc_part = f" - {description}"

    return f"{name} (v{version}) [{schema_format}] {scope}{desc_part}"


class SchemaPicker(SingleSelectPicker[dict[str, Any]]):
    """Schema picker for selecting input or output schemas.

    Searches schemas via the ApiClient and returns the selected schema's ID.
    User sees friendly schema names with version and format info, not UUIDs.

    Usage:
        yield SchemaPicker(
            client=server_client,
            id="output-schema",
        )

        # Get selected schema ID
        picker = self.query_one("#output-schema", SchemaPicker)
        schema_id = picker.selected_id  # UUID string or None

        # Optionally filter by format
        yield SchemaPicker(
            client=server_client,
            schema_format="json_schema",  # Only show JSON schemas
            id="output-schema",
        )
    """

    def __init__(
        self,
        client: ApiClient,
        schema_format: str | None = None,
        placeholder: str = "Search schemas (e.g., user profile, json output)...",
        empty_message: str = "No schema selected (optional)",
        **kwargs: Any,
    ) -> None:
        """Initialize the schema picker.

        Args:
            client: ApiClient instance for API calls
            schema_format: Optional filter by schema format (json_schema or regex)
            placeholder: Placeholder text for search input
            empty_message: Message shown when nothing is selected
        """
        super().__init__(
            client=client,
            placeholder=placeholder,
            empty_message=empty_message,
            **kwargs,
        )
        self._schema_format = schema_format

    @property
    def selected_schema_id(self) -> str | None:
        """Alias for selected_id - returns the schema UUID."""
        return self.selected_id

    @property
    def selected_schema_name(self) -> str | None:
        """Get the name of the selected schema."""
        if self._selected_item is None:
            return None
        return self._selected_item.get("schema_name")

    async def _fetch_items(self, query: str) -> list[dict[str, Any]]:
        """Fetch schemas matching query from the API."""
        response = await self._client.list_schemas(
            search=query,
            schema_format=self._schema_format,
            limit=50,
        )
        return [schema.model_dump() for schema in response.schemas]

    def _format_item(self, item: dict[str, Any]) -> str:
        """Format schema for display in option list."""
        return _format_schema(item)

    def _get_item_id(self, item: dict[str, Any]) -> str:
        """Get unique identifier for a schema."""
        return str(item.get("id", ""))

    def set_initial_schema(self, schema: dict[str, Any]) -> None:
        """Pre-populate the picker with an existing schema selection.

        Args:
            schema: Schema dict with at least 'id' and 'schema_name' keys
        """
        self.set_initial_selection(schema)

    def set_initial_schema_by_id(
        self, schema_id: str, name: str = "Selected Schema"
    ) -> None:
        """Pre-populate the picker with a schema by its ID.

        Use this when you only have the schema ID and not the full schema data.

        Args:
            schema_id: The schema UUID
            name: Display name for the schema
        """
        self.set_initial_selection({"id": schema_id, "schema_name": name})
