"""prompt_toolkit based input with history and multiline support."""

from __future__ import annotations

from pathlib import Path

from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.key_binding import KeyBindings


HISTORY_FILE = Path.home() / ".tsumugi" / "history.txt"


def _make_key_bindings() -> KeyBindings:
    """Create key bindings for multiline input.

    - Enter: submit input
    - Alt+Enter: insert newline (multiline mode)
    """
    kb = KeyBindings()

    @kb.add("escape", "enter")  # Alt+Enter
    def _(event):
        event.current_buffer.insert_text("\n")

    return kb


def create_session() -> PromptSession:
    """Create a prompt session with persistent history."""
    HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
    return PromptSession(
        history=FileHistory(str(HISTORY_FILE)),
        multiline=False,
        key_bindings=_make_key_bindings(),
    )


def get_input(session: PromptSession, user_name: str = "user") -> str | None:
    """Read user input. Returns None on EOF/Ctrl+D.

    Enter submits, Alt+Enter inserts a newline.
    """
    try:
        return session.prompt(f"{user_name}先輩 > ")
    except EOFError:
        return None
    except KeyboardInterrupt:
        return None
