"""
Shared interactive model picker for llmpm CLI commands.
Used by run, serve, info, and uninstall to handle ambiguous model queries.
"""

from __future__ import annotations

import sys

import click

from llmpm import display

_IS_WIN = sys.platform == "win32"


def pick_installed_model(
    matches: list[tuple[str, dict]],
    query: str,
) -> tuple[str, dict] | None:
    """
    Prompt the user to select from multiple matching installed models.

    Returns (model_id, entry) for the chosen model, or None if cancelled.
    """
    display.info(f"Multiple models match \"{query}\":")
    display.blank()

    try:
        if _IS_WIN:
            raise RuntimeError("skip questionary on Windows")
        import questionary  # type: ignore  # pylint: disable=import-outside-toplevel
        from questionary import Choice  # type: ignore  # pylint: disable=import-outside-toplevel

        choices = [
            Choice(
                title=f"{mid}  [{entry.get('model_type', '?')}]",
                value=(mid, entry),
            )
            for mid, entry in matches
        ]
        selected = questionary.select(
            "Select a model:",
            choices=choices,
            style=questionary.Style([
                ("selected", "bold fg:green"),
                ("pointer",  "bold fg:green"),
            ]),
        ).ask()

    except Exception:  # pylint: disable=broad-except
        for idx, (mid, entry) in enumerate(matches, 1):
            click.echo(f"  {idx:>2}.  {mid}  [{entry.get('model_type', '?')}]")
        display.blank()
        raw = click.prompt(
            "  Select (number)",
            type=click.Choice([str(i) for i in range(1, len(matches) + 1)]),
        )
        selected = matches[int(raw) - 1]

    if selected is None:
        display.info("Cancelled.")
        return None

    return selected
