"""Terminal UI - banner, input, completions.

Uses prompt_toolkit for input (history, multiline paste, slash command completion).
Uses rich for all output (streaming, panels, colors).
"""

from __future__ import annotations

from rich.console import Console
from rich.panel import Panel

from krim import __version__

console = Console()

# -- banner --
MASCOT = [
   "                    ",
   "      ●      ●      ",
   "                    ",
   "    ▄████◣◢████▄    ",
   " ◥▄████▀▀  ▀▀████▄◤ ",
   "    ▀▀        ▀▀    ",
]

LOGO = [
    " ██╗  ██╗██████╗ ██╗███╗   ███╗",
    " ██║ ██╔╝██╔══██╗██║████╗ ████║",
    " █████╔╝ ██████╔╝██║██╔████╔██║",
    " ██╔═██╗ ██╔══██╗██║██║╚██╔╝██║",
    " ██║  ██╗██║  ██║██║██║ ╚═╝ ██║",
    " ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝     ╚═╝",
]

TAGLINE = "trust the model, keep the harness light."

SLASH_COMMANDS = ["/help", "/tokens", "/compact", "/config", "/undo", "/verbose"]

PROVIDERS = [
    ("claude", "Anthropic Claude"),
    ("openai", "OpenAI"),
    ("vertex_ai", "Google Vertex AI"),
]


def select_provider() -> str:
    """Interactive provider selection menu. Returns provider name."""
    console.print("\n[bold cyan]Select provider:[/]\n")
    for i, (name, desc) in enumerate(PROVIDERS, 1):
        console.print(f"  [bold white][{i}][/] {name} [dim]({desc})[/]")
    console.print()

    while True:
        try:
            choice = console.input("[bold green]Enter number (1-3): [/]").strip()
            if choice in ("1", "2", "3"):
                selected = PROVIDERS[int(choice) - 1][0]
                console.print(f"[dim]→ {selected}[/]\n")
                return selected
            console.print("[red]Invalid choice. Enter 1, 2, or 3.[/]")
        except (EOFError, KeyboardInterrupt):
            console.print("\n[dim]cancelled[/]")
            import sys
            sys.exit(0)


def print_banner(provider: str, model_name: str, max_turns: int, project_dir: str | None = None):
    """Print the welcome banner with config info."""
    lines = [f"{mascot}  {logo}" for mascot, logo in zip(MASCOT, LOGO)]
    lines.append("")
    lines.append(f"  {TAGLINE}")
    lines.append("")
    lines.append(f"  {provider}/{model_name}  max_turns={max_turns}")
    if project_dir:
        lines.append(f"  config: {project_dir}")
    lines.append("  type /help for commands, 'exit' to quit")

    console.print(Panel("\n".join(lines), title=f"v{__version__}", title_align="left", border_style="white", style="white"))
    console.print()


def print_banner_oneliner(provider: str, model_name: str, max_turns: int):
    """Compact one-line header for single-prompt mode."""
    console.print(f"[bold cyan]krim[/] v{__version__}  [dim]{provider}/{model_name}  max_turns={max_turns}[/]")


# -- input with prompt_toolkit --

def create_session():
    """Create a prompt_toolkit session with history and completions."""
    try:
        from prompt_toolkit import PromptSession
        from prompt_toolkit.history import InMemoryHistory
        from prompt_toolkit.completion import WordCompleter
        from prompt_toolkit.styles import Style

        style = Style.from_dict({
            "prompt": "bold green",
        })

        completer = WordCompleter(
            SLASH_COMMANDS + ["exit", "quit"],
            sentence=True,  # complete full words
        )

        session = PromptSession(
            history=InMemoryHistory(),
            completer=completer,
            style=style,
            complete_while_typing=False,
            enable_history_search=True,
            multiline=False,
        )
        return session
    except ImportError:
        return None


def prompt_input(session=None) -> str | None:
    """Get user input. Returns None on EOF/interrupt."""
    if session:
        try:
            from prompt_toolkit.formatted_text import HTML
            text = session.prompt(HTML("<prompt>&gt; </prompt>"))
            return text
        except (EOFError, KeyboardInterrupt):
            return None
    else:
        # fallback to rich
        try:
            return console.input("[bold green]> [/]")
        except (EOFError, KeyboardInterrupt):
            return None
