"""Agent picker component for selecting base agents.

A specialized search picker that uses the ApiClient to fetch agents
and returns the selected agent'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_agent(agent: dict[str, Any]) -> str:
    """Format an agent for display in the picker."""
    name = agent.get("name", "Unknown")
    description = agent.get("description")
    model_count = agent.get("model_count", 0)

    parts = [name]
    if model_count:
        parts.append(f"({model_count} model{'s' if model_count != 1 else ''})")
    if description:
        parts.append(f"- {description}")

    return " ".join(parts)


class AgentPicker(SingleSelectPicker[dict[str, Any]]):
    """Agent picker for selecting base agents.

    Searches agents via the ApiClient and returns the selected agent's ID.
    User sees friendly agent names, not UUIDs.

    Usage:
        yield AgentPicker(
            client=server_client,
            id="base-agent",
        )

        # Get selected agent ID
        picker = self.query_one("#base-agent", AgentPicker)
        agent_id = picker.selected_agent_id  # UUID string or None
    """

    def __init__(
        self,
        client: ApiClient,
        placeholder: str = "Search agents (e.g., my writer agent)...",
        empty_message: str = "No base agent selected (optional)",
        fetch_on_mount: bool = True,
        **kwargs: Any,
    ) -> None:
        """Initialize the agent picker.

        Args:
            client: ApiClient instance for API calls
            placeholder: Placeholder text for search input
            empty_message: Message shown when nothing is selected
            fetch_on_mount: If True, show recent agents when picker opens (default True)
        """
        super().__init__(
            client=client,
            placeholder=placeholder,
            empty_message=empty_message,
            fetch_on_mount=fetch_on_mount,
            **kwargs,
        )

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

    @property
    def selected_agent_name(self) -> str | None:
        """Get the name of the selected agent."""
        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 agents matching query from the API.

        When query is empty, returns recent agents sorted by updated_at.
        """
        response = await self._client.list_agents(
            search=query if query else None,
            limit=10 if not query else 50,
        )
        return [agent.model_dump() for agent in response.agents]

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

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

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

        Args:
            agent: Agent dict with at least 'id' and 'name' keys
        """
        self.set_initial_selection(agent)

    def set_initial_agent_by_id(
        self, agent_id: str, name: str = "Selected Agent"
    ) -> None:
        """Pre-populate the picker with an agent by its ID.

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

        Args:
            agent_id: The agent UUID
            name: Display name for the agent
        """
        self.set_initial_selection({"id": agent_id, "name": name})
