"""
Enhanced Input Prompts

Advanced input prompts with history and completion using prompt_toolkit.
"""

from pathlib import Path
from typing import Callable

from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.history import FileHistory
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.filters import has_suggestion


class CommandCompleter(Completer):
    """
    Auto-completer for special commands.

    Provides tab completion for:
    - Special commands (/help, /clear, /export, etc.)
    - Session IDs
    - Configuration keys
    """

    def __init__(self, commands: list[str] | None = None):
        """
        Initialize completer with available commands.

        Args:
            commands: List of command strings to complete
        """
        self.commands = commands or []

    def get_completions(self, document, complete_event):
        """Get completions for the current input."""
        text = document.text_before_cursor

        # Only complete commands that start with /
        if text.startswith("/"):
            for command in self.commands:
                if command.startswith(text):
                    yield Completion(
                        command,
                        start_position=-len(text),
                        display=command,
                        display_meta=self._get_command_description(command)
                    )

    def _get_command_description(self, command: str) -> str:
        """Get description for a command."""
        descriptions = {
            "/help": "Show help message",
            "/clear": "Clear screen",
            "/exit": "Exit chat",
            "/quit": "Exit chat",
            "/new": "Start new session",
            "/save": "Save current session",
            "/load": "Load a session",
            "/list": "List all sessions",
            "/delete": "Delete a session",
            "/export": "Export session",
            "/config": "Show configuration",
            "/reload-config": "Reload configuration",
            "/history": "Show message history",
            "/model": "View/change current model",
            "/provider": "Change provider",
        }
        return descriptions.get(command, "")

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


class EnhancedPrompt:
    """
    Enhanced input prompt with history and completion.

    Features:
    - Command history (persistent across sessions)
    - Auto-suggestions from history (accept with Tab or Right Arrow)
    - Tab completion for commands
    - Multi-line input support (future)
    """

    def __init__(
        self,
        history_file: Path,
        commands: list[str] | None = None,
        enable_history: bool = True,
        enable_completion: bool = True,
    ):
        """
        Initialize enhanced prompt.

        Args:
            history_file: Path to history file
            commands: List of commands for completion
            enable_history: Whether to enable command history
            enable_completion: Whether to enable tab completion
        """
        # Ensure history directory exists
        history_file.parent.mkdir(parents=True, exist_ok=True)

        # Create key bindings for Tab to accept suggestions
        kb = KeyBindings()

        @kb.add('tab', filter=has_suggestion)
        def _(event):
            """Accept suggestion with Tab key."""
            buffer = event.current_buffer
            suggestion = buffer.suggestion
            if suggestion:
                buffer.insert_text(suggestion.text)

        # Create prompt session with features
        kwargs = {
            'key_bindings': kb,
        }

        if enable_history:
            kwargs['history'] = FileHistory(str(history_file))
            kwargs['auto_suggest'] = AutoSuggestFromHistory()

        if enable_completion and commands:
            kwargs['completer'] = CommandCompleter(commands)

        self.session = PromptSession(**kwargs)
        self.completer = kwargs.get('completer')

    def prompt(self, message: str = "> ") -> str:
        """
        Prompt for user input with history and completion.

        Args:
            message: Prompt message

        Returns:
            User input
        """
        try:
            return self.session.prompt(message)
        except (KeyboardInterrupt, EOFError):
            return ""

    async def prompt_async(self, message: str = "> ") -> str:
        """
        Async prompt for user input with history and completion.

        Args:
            message: Prompt message

        Returns:
            User input
        """
        try:
            return await self.session.prompt_async(message)
        except (KeyboardInterrupt, EOFError):
            return ""

    def update_commands(self, commands: list[str]) -> None:
        """
        Update available commands for completion.

        Args:
            commands: List of command strings
        """
        if self.completer:
            self.completer.update_commands(commands)


def create_chat_prompt(history_file: Path) -> EnhancedPrompt:
    """
    Create a chat input prompt with standard commands.

    Args:
        history_file: Path to history file

    Returns:
        EnhancedPrompt instance
    """
    commands = [
        "/help",
        "/clear",
        "/exit",
        "/quit",
        "/new",
        "/save",
        "/load",
        "/list",
        "/delete",
        "/export",
        "/config",
        "/reload-config",
        "/history",
        "/model",
        "/provider",
    ]

    return EnhancedPrompt(
        history_file=history_file,
        commands=commands,
        enable_history=True,
        enable_completion=True,
    )
