"""Custom prompt session for ReplyMarketing CLI."""

from __future__ import annotations

from typing import Iterable, Sequence

from prompt_toolkit import PromptSession
from prompt_toolkit.completion import (
    CompleteEvent,
    Completer,
    Completion,
    FuzzyCompleter,
    WordCompleter,
)
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
from prompt_toolkit.styles import Style

from ..core.skill_registry import SkillRegistry

PROMPT_SYMBOL = "❯"
PROMPT_SYMBOL_THINKING = "✨"


# Custom style for prompt
PROMPT_STYLE = Style.from_dict(
    {
        "prompt": "ansigreen bold",
        "prompt.symbol": "ansiyellow",
    }
)


class CommandCompleter(Completer):
    """Completer for slash commands - shows all commands when typing /"""

    def __init__(self, commands: Sequence[tuple[str, str]]) -> None:
        """Initialize with list of (name, description) tuples."""
        super().__init__()
        # Store commands as (name, description) without the /
        self._commands = [(cmd[0].lstrip("/"), cmd[1]) for cmd in commands]

    def get_completions(
        self, document: Document, complete_event: CompleteEvent
    ) -> Iterable[Completion]:
        text = document.text_before_cursor

        # Only autocomplete when the input buffer has no other content.
        if document.text_after_cursor.strip():
            return

        # Only trigger when typing /
        if not text.startswith("/"):
            return

        # Get what user typed after /
        typed = text[1:]  # Remove the leading /

        # Show all matching commands
        for name, description in self._commands:
            # If user typed something, filter by it
            if typed and typed not in name.lower():
                continue

            yield Completion(
                text=f"/{name}",
                start_position=-len(text),
                display=f"/{name}",
                display_meta=description,
            )


class CustomPromptSession:
    """Custom prompt session with enhanced features."""

    def __init__(
        self,
        skill_registry: SkillRegistry | None = None,
        thinking: bool = False,
    ) -> None:
        self.skill_registry = skill_registry
        self.thinking = thinking
        self._key_bindings = self._create_key_bindings()
        self._completer = self._create_completer()

        self._session = PromptSession(
            message=self._get_prompt_message,
            style=PROMPT_STYLE,
            key_bindings=self._key_bindings,
            completer=self._completer,
            complete_while_typing=True,
            multiline=False,
            enable_history_search=True,
        )

    def _create_key_bindings(self) -> KeyBindings:
        """Create key bindings for the prompt."""
        kb = KeyBindings()

        @kb.add("c-c")
        def _(event: KeyPressEvent) -> None:
            """Handle Ctrl+C - clear current input or raise KeyboardInterrupt."""
            if event.app.current_buffer.text:
                event.app.current_buffer.reset()
            else:
                event.app.exit(exception=KeyboardInterrupt)

        @kb.add("c-d")
        def _(event: KeyPressEvent) -> None:
            """Handle Ctrl+D - exit."""
            event.app.exit(exception=EOFError)

        @kb.add("c-l")
        def _(event: KeyPressEvent) -> None:
            """Handle Ctrl+L - clear screen."""
            import os

            os.system("clear" if os.name != "nt" else "cls")

        return kb

    def _create_completer(self) -> CommandCompleter | None:
        """Create completer for slash commands."""
        commands = [
            ("help", "Show help message"),
            ("skills", "List all skills"),
            ("clear", "Clear the screen"),
            ("exit", "Exit the CLI"),
            ("quit", "Exit the CLI"),
        ]

        if self.skill_registry:
            for skill in self.skill_registry.get_all_skills():
                commands.append((skill.id, skill.description))

        return CommandCompleter(commands)

    def _get_prompt_message(self) -> FormattedText:
        """Get the prompt message."""
        symbol = PROMPT_SYMBOL_THINKING if self.thinking else PROMPT_SYMBOL
        return FormattedText(
            [
                ("class:prompt.symbol", f"{symbol} "),
                ("class:prompt", ""),
            ]
        )

    async def prompt(self) -> str:
        """Show prompt and get user input."""
        try:
            result = await self._session.prompt_async()
            return result.strip()
        except (KeyboardInterrupt, EOFError):
            raise

    def __enter__(self) -> CustomPromptSession:
        return self

    def __exit__(self, *args) -> None:
        pass


def toast(message: str, style: str = "info") -> None:
    """Show a toast message."""
    from .console import console

    styles = {
        "info": "cyan",
        "success": "green",
        "warning": "yellow",
        "error": "red",
    }
    color = styles.get(style, "white")
    console.print(f"[{color}]{message}[/{color}]")
