"""Tests for the command palette modal screen."""

from __future__ import annotations

from textual.widgets import ListItem, Static

from clients.terminal.tui.screens.command_palette import CommandPaletteScreen


def test_select_empty_filtered_does_not_crash() -> None:
    """Selecting the placeholder row when nothing matches must not IndexError.

    Regression guard for the empty-filter path: ``_filtered`` is empty while
    ``_list_items`` holds one "No matching commands" placeholder. A list-select
    event on that row used to index ``_filtered[0]`` and crash.
    """

    class _Evt:
        def __init__(self, item) -> None:
            self.item = item

    screen = CommandPaletteScreen([])
    screen._filtered = []
    screen._list_items = [ListItem(Static("No matching commands"))]

    dismissed: list = []
    screen.dismiss = lambda v: dismissed.append(v)  # type: ignore[method-assign]

    screen.on_list_view_selected(_Evt(screen._list_items[0]))
    assert dismissed == []


def test_select_valid_filtered_dismisses_with_command() -> None:
    """The happy path still dismisses with the selected command."""

    class _Cmd:
        def __init__(self, name: str) -> None:
            from clients.terminal.tui.commands.base import CommandMeta

            self.meta = CommandMeta(name, (), "")

        async def execute(self, ctx, args: str) -> None:  # pragma: no cover
            raise NotImplementedError

    class _Evt:
        def __init__(self, item) -> None:
            self.item = item

    cmd = _Cmd("help")
    screen = CommandPaletteScreen([cmd])
    screen._filtered = [cmd]
    screen._list_items = [ListItem(Static("help"))]

    dismissed: list = []
    screen.dismiss = lambda v: dismissed.append(v)  # type: ignore[method-assign]

    screen.on_list_view_selected(_Evt(screen._list_items[0]))
    assert dismissed == [cmd]