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

A search input that uses the ApiClient to fetch tool configs on each keystroke,
displaying results in a static list below. Filters by tool_id to only show
configs for a specific tool.
"""

from typing import Any

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.tool_configs import ToolConfigSummary

from cli.infrastructure.forms.base_picker import SingleSelectPicker


class ToolConfigPicker(SingleSelectPicker[ToolConfigSummary]):
    """Single-select tool config picker with live search.

    Filters tool configs by tool_id to only show configs for the selected tool.

    Usage:
        yield ToolConfigPicker(
            client=server_client,
            tool_id="rag_search",
            id="tool-config-picker"
        )

        # Get selected config
        picker = self.query_one("#tool-config-picker", ToolConfigPicker)
        config = picker.selected_config  # ToolConfigSummary | None

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

    def __init__(
        self,
        client: ApiClient,
        tool_id: str | None = None,
        placeholder: str = "Type to search saved configs...",
        **kwargs: Any,
    ) -> None:
        """Initialize the tool config picker.

        Args:
            client: ApiClient instance for API calls
            tool_id: Filter by tool ID (e.g., 'rag_search')
            placeholder: Placeholder text for search input
        """
        super().__init__(
            client=client,
            placeholder=placeholder,
            empty_message="No saved config selected",
            fetch_on_mount=True,  # Load configs initially
            **kwargs,
        )
        self._tool_id = tool_id

    @property
    def tool_id(self) -> str | None:
        """Get the tool ID filter."""
        return self._tool_id

    @tool_id.setter
    def tool_id(self, value: str | None) -> None:
        """Set the tool ID filter and refresh results."""
        self._tool_id = value
        # Clear current selection if tool changed
        self.clear()
        # Trigger a refresh
        if self._fetch_on_mount:
            self._fetch_initial()

    @property
    def selected_config(self) -> ToolConfigSummary | None:
        """Get the selected tool config."""
        return self.selected_item

    @property
    def selected_config_id(self) -> str | None:
        """Get the ID of the selected tool config as string."""
        if self.selected_item:
            return str(self.selected_item.id)
        return None

    async def _fetch_items(self, query: str) -> list[ToolConfigSummary]:
        """Fetch tool configs matching query from the API."""
        if not self._tool_id:
            # No tool selected yet, return empty list
            return []

        response = await self._client.list_tool_configs(
            search=query if query else None,
            tool_id=self._tool_id,
            limit=50,
        )
        return list(response.tool_configs)

    def _format_item(self, item: ToolConfigSummary) -> str:
        """Format tool config for display in option list."""
        desc = ""
        if item.description:
            desc = f" - {item.description}"
        return f"{item.name}{desc}"

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

    def _get_result_count_message(self, count: int) -> str:
        """Get status message for result count."""
        if count == 0:
            if not self._tool_id:
                return "Select a tool first"
            return "No saved configs found for this tool"
        return f"{count} config{'s' if count != 1 else ''} found - Enter to select"

    def set_initial_config(self, config: ToolConfigSummary) -> None:
        """Pre-populate the picker with an existing config selection.

        Args:
            config: ToolConfigSummary object to pre-select
        """
        self.set_initial_selection(config)
