"""
Module: test_completer
Description: Tests for CommandCompleter tab-completion

Implements:
    - docs/cli/reference.md#interactive-repl
"""

from prompt_toolkit.completion import CompleteEvent
from prompt_toolkit.document import Document

from huitzo_cli.repl.completer import META_COMMANDS, CommandCompleter


def _complete(completer: CommandCompleter, text: str) -> list[str]:
    """Helper: run completion and return sorted list of completion texts."""
    doc = Document(text, len(text))
    event = CompleteEvent()
    return sorted(c.text for c in completer.get_completions(doc, event))


def test_complete_empty_input() -> None:
    """Empty input returns all meta-commands + pack commands."""
    completer = CommandCompleter(pack_commands=["greet", "summarize"])
    result = _complete(completer, "")
    expected = sorted(META_COMMANDS + ["greet", "summarize"])
    assert result == expected


def test_complete_partial_first_word() -> None:
    """Partial first word narrows to matching meta-commands."""
    completer = CommandCompleter(pack_commands=["hello-world"])
    result = _complete(completer, "he")
    assert result == sorted(["help", "hello-world"])


def test_complete_after_describe() -> None:
    """After 'describe', complete with pack command names."""
    completer = CommandCompleter(pack_commands=["hello", "help-me", "goodbye"])
    result = _complete(completer, "describe he")
    assert result == sorted(["hello", "help-me"])


def test_complete_after_other_verb() -> None:
    """After a verb that isn't describe/exec, no completions."""
    completer = CommandCompleter(pack_commands=["hello"])
    result = _complete(completer, "list foo")
    assert result == []


def test_update_commands() -> None:
    """update_commands() reflects in subsequent completions."""
    completer = CommandCompleter()
    # Initially no pack commands
    result = _complete(completer, "")
    assert result == sorted(META_COMMANDS)

    # After update
    completer.update_commands(["alpha", "beta"])
    result = _complete(completer, "")
    assert result == sorted(META_COMMANDS + ["alpha", "beta"])
