"""
Module: repl.completer
Description: Tab-completion provider for the REPL using prompt_toolkit.

Implements:
    - docs/cli/reference.md#interactive-repl
    - docs/cli/reference.md#huitzo-pack-dev

See Also:
    - docs/cli/reference.md#repl-features
"""

from __future__ import annotations

from prompt_toolkit.completion import CompleteEvent, Completer, Completion
from prompt_toolkit.document import Document


# Meta-commands that the REPL understands
META_COMMANDS = [
    "help",
    "list",
    "describe",
    "exec",
    "upload",
    "files",
    "clear-files",
    "exit",
    "quit",
]


class CommandCompleter(Completer):
    """Provides tab-completion for REPL meta-commands and pack commands.

    Completes:
    - Meta-commands (help, list, describe, exec, exit, quit, etc.)
    - Pack command names (fetched from the sandbox)
    - After 'describe' or 'exec', completes with pack command names
    """

    def __init__(self, pack_commands: list[str] | None = None) -> None:
        """Initialize the completer.

        Args:
            pack_commands: List of available pack command names for completion.
                           Can be updated later via update_commands().
        """
        self._pack_commands: list[str] = pack_commands or []

    def update_commands(self, commands: list[str]) -> None:
        """Update the list of available pack commands.

        Called when the REPL refreshes its command list from the sandbox.

        Args:
            commands: Updated list of pack command names
        """
        self._pack_commands = list(commands)

    def get_completions(
        self, document: Document, complete_event: CompleteEvent
    ) -> list[Completion]:
        """Generate completions for the current input.

        Args:
            document: The current document/input state
            complete_event: The completion event

        Returns:
            List of possible completions
        """
        text = document.text_before_cursor
        parts = text.split()

        # Complete the first word: meta-commands + pack commands
        if len(parts) <= 1:
            word = parts[0] if parts else ""
            candidates = META_COMMANDS + self._pack_commands
            return [
                Completion(c, start_position=-len(word)) for c in candidates if c.startswith(word)
            ]

        # After 'describe' or 'exec', complete with pack command names
        first = parts[0]
        if first in ("describe", "exec") and len(parts) == 2:
            word = parts[1]
            return [
                Completion(c, start_position=-len(word))
                for c in self._pack_commands
                if c.startswith(word)
            ]

        return []
