"""Interactive agent selection and agent-id utilities."""

from typing import Any, Dict, List, Optional, Tuple

import questionary

from cli_logging.cli_logger import emit_structured_log
from cli_logging.logging_utils import Operation


def normalize_agent_id(agent_id):
    """Append '.declarativeAgent' if agent_id has no '.', else return unchanged.

    Returns the input unchanged when it is None/empty or already contains a dot.
    """
    if not agent_id:
        return agent_id
    return agent_id if '.' in agent_id else f"{agent_id}.declarativeAgent"


def select_agent_interactively(agents: List[Dict[str, Any]]) -> Tuple[Optional[str], Optional[str]]:
    """
    Display an interactive agent selector using questionary.

    Args:
        agents: List of agent dictionaries.

    Returns:
        Tuple of (agent_id, agent_name) or (None, None) if cancelled/skipped
    """
    if not agents:
        return None, None

    # Build id→name lookup and choices
    id_to_name: Dict[str, str] = {}
    choices = []
    sorted_agents = sorted(agents, key=lambda a: a.get("name", ""))
    for agent in sorted_agents:
        agent_name = agent.get("name", "Unknown")
        agent_id = (agent.get("gptId") or "").strip()
        if not agent_id:
            emit_structured_log("warning", f"Skipping agent '{agent_name}': missing or empty gptId.", operation=Operation.FETCH_AGENTS)
            continue
        agent_description = agent.get("description")
        agent_is_owner = agent.get('isOwner')
        agent_provider = agent.get("provider")
        id_to_name[agent_id] = agent_name

        # Format the display text
        if agent_provider:
            title = f"{agent_name} - {agent_provider} ({agent_id})"
        else:
            title = f"{agent_name} ({agent_id})"
        segments = [title]
        if agent_is_owner:
            segments.append(f"IsOwner: {agent_is_owner}")
        if agent_description:
            segments.append(agent_description)
        display_text = " - ".join(segments)

        choices.append(questionary.Choice(title=display_text, value=agent_id))

    if not choices:
        return None, None

    # Display the selection prompt
    selected_agent = questionary.select(
        "Select an agent to evaluate:",
        choices=choices,
        use_shortcuts=len(choices) <= 35,
        use_arrow_keys=True
    ).ask()

    return selected_agent, id_to_name.get(selected_agent) if selected_agent else None
