"""Prompt helpers for the CLI."""

from __future__ import annotations

from prompt_toolkit import PromptSession
import typer

from revo_module_installer.cli_support.search import (
    filter_registry_entries,
    format_search_results,
)
from revo_module_installer.config.registry import RegistryEntry


def prompt_for_search_query(
    registry_entries: list[RegistryEntry],
) -> str:
    """Prompt for a module search query with live-updating results.

    Args:
        registry_entries: Entries from the registry index.

    Returns:
        Search query string.
    """
    prompt_session: PromptSession[str] = PromptSession()

    def bottom_toolbar() -> str:
        """Render live search results in the prompt toolbar."""
        search_text: str = prompt_session.default_buffer.text
        matched_entries: list[RegistryEntry] = filter_registry_entries(
            registry_entries,
            search_text,
        )
        return format_search_results(matched_entries)

    return prompt_session.prompt(
        "Search modules by name or description (press Enter to show all): ",
        bottom_toolbar=bottom_toolbar,
    )


def confirm_module_installation(registry_entry: RegistryEntry) -> bool:
    """Confirm installation for a single registry entry.

    Args:
        registry_entry: Registry metadata for the module.

    Returns:
        True when the user confirms the install.
    """
    return typer.confirm(
        f"Install {registry_entry.name} ({registry_entry.id})?",
        default=True,
    )


def prompt_for_module_name() -> str:
    """Prompt for a module name to install.

    Returns:
        Module name provided by the user.
    """
    return typer.prompt("Module name to install")


def prompt_for_variant_id(registry_entry: RegistryEntry) -> str | None:
    """Prompt for a module variant when variants are available.

    Args:
        registry_entry: Registry metadata for the module.

    Returns:
        Selected variant id, or None when variants are unavailable.
    """
    if not registry_entry.variants:
        return None

    ordered_variant_ids: list[str] = []
    if registry_entry.default_variant is not None:
        ordered_variant_ids.append(registry_entry.default_variant)
    ordered_variant_ids.extend([variant.id for variant in registry_entry.variants])
    unique_variant_ids: list[str] = list(dict.fromkeys(ordered_variant_ids))

    typer.echo("Select a variant:")
    for option_index, variant_id in enumerate(unique_variant_ids, start=1):
        suffix: str = ""
        if variant_id == registry_entry.default_variant:
            suffix = " (default)"
        typer.echo(f"  {option_index}. {variant_id}{suffix}")

    while True:
        selected_index: int = typer.prompt(
            "Choose variant number",
            default=1,
            type=int,
        )
        if 1 <= selected_index <= len(unique_variant_ids):
            return unique_variant_ids[selected_index - 1]
        typer.echo(f"Please enter a number between 1 and {len(unique_variant_ids)}.")
