"""TUI 底部输入框：以 `/` 开头的本地命令自动补全（Textual Suggester）。"""

from __future__ import annotations

from textual.binding import Binding
from textual.suggester import Suggester
from textual.widgets import Input


# 列表顺序 = 同前缀时 Tab/→ 采纳的优先级（不再按字符串总长最短，避免误优先 /task ai）
_COMPLETIONS: list[str] = [
    "/?",
    "/q",
    "/exit",
    "/quit",
    "/help",
    "/work ",
    "/chat ",
    "/chat stop",
    "/doc ",
    "/llm ",
    "/agent ",
    "/history ",
    "/history list",
    "/history clear",
    "/history copy ",
    "/history help",
    "/task ",
    "/task stop",
    "/task list",
    "/task clear",
    "/task help",
    "/task shell ",
    "/task ai ",
    "/task dummy ",
]

_POS: dict[str, int] = {c: i for i, c in enumerate(_COMPLETIONS)}


def pick_slash_completion(value: str) -> str | None:
    """
    返回比当前输入更长、且以前缀匹配的第一条补全（最短总长优先，其次列表顺序）。
    非 `/` 开头返回 None。
    """
    if not value.startswith("/"):
        return None
    vn = value.casefold()
    matches: list[str] = []
    for c in _COMPLETIONS:
        if len(c) <= len(vn):
            continue
        if c.casefold().startswith(vn):
            matches.append(c)
    if not matches:
        return None
    return min(matches, key=lambda c: _POS[c])


class SlashCommandSuggester(Suggester):
    """仅对以 ``/`` 开头的行给出幽灵补全；普通聊天不提示。"""

    def __init__(self) -> None:
        super().__init__(case_sensitive=False, use_cache=True)

    async def get_suggestion(self, value: str) -> str | None:
        # case_sensitive=False 时 value 已为 casefold
        if not value.startswith("/"):
            return None
        return pick_slash_completion(value)


class ChatInput(Input):
    """在 Textual 默认「→ 接受补全」之外，增加 Tab 接受补全。"""

    BINDINGS = [
        *Input.BINDINGS,
        Binding("tab", "accept_suggestion_tab", "补全", show=False),
    ]

    def action_accept_suggestion_tab(self) -> None:
        if self.cursor_at_end and self._suggestion:
            self.action_cursor_right()
