"""Tool picker widget with search and single-select.

A search input that uses the ApiClient to fetch available tools on each keystroke,
displaying results in a static list below. Users can select a single tool.
"""

from typing import Any

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.tools import ToolListItemResponse, ToolResponse

from cli.infrastructure.forms.base_picker import SingleSelectPicker


class ToolPicker(SingleSelectPicker[ToolListItemResponse]):
    """Single-select tool picker with live search.

    Uses the ApiClient to fetch tools on each keystroke. Results appear in a
    static box below the search input.

    Usage:
        yield ToolPicker(
            client=server_client,
            id="tool-picker"
        )

        # Get selected tool
        picker = self.query_one("#tool-picker", ToolPicker)
        tool = picker.selected_tool  # ToolResponse | None

    Keybindings:
        - Type to search (fetches from API)
        - Up/Down to navigate results
        - Enter to select/deselect
    """

    def __init__(
        self,
        client: ApiClient,
        placeholder: str = "Type to search tools (e.g., rag, web, search)...",
        **kwargs: Any,
    ) -> None:
        """Initialize the tool picker.

        Args:
            client: ApiClient instance for API calls
            placeholder: Placeholder text for search input
        """
        super().__init__(
            client=client,
            placeholder=placeholder,
            empty_message="No tool selected",
            fetch_on_mount=True,  # Load all tools initially
            **kwargs,
        )

    @property
    def selected_tool(self) -> ToolListItemResponse | None:
        """Get the selected tool."""
        return self.selected_item

    @property
    def selected_tool_id(self) -> str | None:
        """Get the ID of the selected tool."""
        return self.selected_id

    async def _fetch_items(self, query: str) -> list[ToolListItemResponse]:
        """Fetch tools matching query from the API."""
        response = await self._client.list_tools(
            search=query if query else None,
            limit=50,
        )
        return list(response.tools)

    def _format_item(self, item: ToolListItemResponse) -> str:
        """Format tool for display in option list."""
        has_config = item.parameter_schema is not None
        config_indicator = " [dim][configurable][/]" if has_config else ""
        desc = item.description
        return f"{item.id}{config_indicator} - {desc}"

    def _get_item_id(self, item: ToolListItemResponse) -> str:
        """Get unique identifier for a tool."""
        return item.id

    def _get_result_count_message(self, count: int) -> str:
        """Get status message for result count."""
        if count == 0:
            return "No tools found"
        return f"{count} tool{'s' if count != 1 else ''} found - Enter to select"

    def set_initial_tool(self, tool: ToolResponse | ToolListItemResponse) -> None:
        if isinstance(tool, ToolListItemResponse):
            self.set_initial_selection(tool)
            return

        self.set_initial_selection(
            ToolListItemResponse(
                id=tool.id,
                description=tool.description,
                parameter_schema=tool.parameter_schema,
                credential_configured=True,
            )
        )
