"""Template picker component for selecting system instruction templates.

A specialized search picker that uses the ApiClient to fetch templates
and returns the selected template's latest version ID.
"""

from typing import Any

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.enums.template_enums import TemplateContentType

from cli.infrastructure.forms.base_picker import SingleSelectPicker


def _format_template(template: dict[str, Any]) -> str:
    """Format a template for display in the picker."""
    name = template.get("name", "Unknown")
    version = template.get("latest_version_number", "?")
    visibility = template.get("visibility_id", "organization")
    content_type = template.get("content_type_id", "")

    # Short visibility label
    vis_label = {"private": "Private", "organization": "Org", "public": "Public"}.get(
        visibility, visibility
    )

    # Include content type if not system_instruction (since that's the default filter)
    type_label = ""
    if content_type and content_type != "system_instruction":
        type_label = f" [{content_type}]"

    return f"{name} (v{version}) - {vis_label}{type_label}"


class TemplatePicker(SingleSelectPicker[dict[str, Any]]):
    """Template picker for selecting system instruction templates.

    Searches templates via the ApiClient and returns the selected template's
    latest version ID. User sees friendly template names, not UUIDs.

    Usage:
        yield TemplatePicker(
            client=server_client,
            id="system-template",
        )

        # Get selected version ID
        picker = self.query_one("#system-template", TemplatePicker)
        version_id = picker.selected_id  # UUID string or None
    """

    def __init__(
        self,
        client: ApiClient,
        content_type: TemplateContentType
        | None = TemplateContentType.SYSTEM_INSTRUCTION,
        placeholder: str = "Search templates (e.g., system prompt default)...",
        empty_message: str = "No template selected (optional)",
        **kwargs: Any,
    ) -> None:
        """Initialize the template picker.

        Args:
            client: ApiClient instance for API calls
            content_type: Filter by template content type (default: system_instruction)
            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._content_type = content_type

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

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

    async def _fetch_items(self, query: str) -> list[dict[str, Any]]:
        """Fetch templates matching query from the API."""
        response = await self._client.list_templates(
            search=query,
            content_type=self._content_type,
            limit=50,
        )
        return [template.model_dump() for template in response.templates]

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

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

    def _is_item_selected(self, item: dict[str, Any]) -> bool:
        """Check if an item is currently selected (by latest_version_id)."""
        if self._selected_item is None:
            return False
        return self._get_item_id(item) == self._get_item_id(self._selected_item)

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

        Args:
            template: Template dict with at least 'latest_version_id' and 'name' keys
        """
        self.set_initial_selection(template)

    def set_initial_template_by_version_id(
        self, version_id: str, name: str = "Selected Template"
    ) -> None:
        """Pre-populate the picker with a template by its version ID.

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

        Args:
            version_id: The template version UUID
            name: Display name for the template
        """
        self.set_initial_selection({"latest_version_id": version_id, "name": name})
