"""Search helpers for registry entries."""

from __future__ import annotations

from revo_module_installer.config.registry import RegistryEntry


def find_registry_entry(
    registry_entries: list[RegistryEntry],
    module_id: str,
) -> RegistryEntry | None:
    """Find a registry entry by ID.

    Args:
        registry_entries: Entries from the registry index.
        module_id: Module identifier to search for.

    Returns:
        Matching registry entry or None.
    """
    for registry_entry in registry_entries:
        if registry_entry.id == module_id:
            return registry_entry
    return None


def find_registry_entry_by_name(
    registry_entries: list[RegistryEntry],
    module_name: str,
) -> RegistryEntry | None:
    """Find a registry entry by name.

    Args:
        registry_entries: Entries from the registry index.
        module_name: Module name to search for.

    Returns:
        Matching registry entry or None.
    """
    normalized_name: str = module_name.casefold()
    for registry_entry in registry_entries:
        if registry_entry.name.casefold() == normalized_name:
            return registry_entry
    return None


def filter_registry_entries(
    registry_entries: list[RegistryEntry],
    search_query: str,
) -> list[RegistryEntry]:
    """Filter registry entries by name or description.

    Args:
        registry_entries: Entries from the registry index.
        search_query: Search text to match.

    Returns:
        Filtered list of registry entries.
    """
    trimmed_query: str = search_query.strip()
    if not trimmed_query:
        return registry_entries
    normalized_query: str = trimmed_query.casefold()
    return [
        registry_entry
        for registry_entry in registry_entries
        if normalized_query in registry_entry.name.casefold()
        or normalized_query in registry_entry.description.casefold()
    ]


def format_search_results(
    registry_entries: list[RegistryEntry],
    *,
    max_results: int = 10,
) -> str:
    """Format registry entries for interactive search display.

    Args:
        registry_entries: Entries from the registry index.
        max_results: Maximum number of entries to display.

    Returns:
        Formatted search results.
    """
    if not registry_entries:
        return "No matches yet."

    limited_entries: list[RegistryEntry] = registry_entries[:max_results]
    lines: list[str] = [
        f"{registry_entry.name} — {registry_entry.description}"
        for registry_entry in limited_entries
    ]
    remaining_count: int = len(registry_entries) - len(limited_entries)
    if remaining_count > 0:
        lines.append(f"... and {remaining_count} more")
    return "\n".join(lines)
