"""Explicit numbered choices in chat and direct-command replies."""

from __future__ import annotations

import re
from collections.abc import Sequence
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from app.services.chat_dashboard import ChatTurnDashboardReporter


_SELECTION_NUMBER = (
    r"[1-9]\d?|[一二三四五六七八九十]|"
    r"one|two|three|four|five|six|seven|eight|nine|ten"
)

_NUMBERED_SELECTION_RE = re.compile(
    r"^(?:"
    rf"(?P<bare>{_SELECTION_NUMBER})(?:\ufe0f?\u20e3)?(?:[^\S\n]*[..、))::])?|"
    rf"(?:我\s*)?(?:就\s*)?(?:选|选择|要)\s*(?:第\s*)?(?P<choice>{_SELECTION_NUMBER})\s*(?:个|项|条|种|号|选项)?|"
    rf"(?:我\s*)?(?:就\s*)?第\s*(?P<ordinal>{_SELECTION_NUMBER})\s*(?:个|项|条|种|号|选项)?"
    r")\s*(?:吧|即可|就行|可以)?[。!!,,\s]*$",
    re.I,
)
_NUMBER_LIKE_SELECTION_RE = re.compile(
    r"(?:[+-]?\d+(?:[..]\d+)?|[零一二三四五六七八九十]+|"
    r"zero|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|"
    r"eighteen|nineteen|twenty|"
    r"(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|"
    r"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|"
    r"eighteen|nineteen|twenty)(?:\s+(?:zero|one|two|three|four|"
    r"five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|"
    r"fifteen|sixteen|seventeen|eighteen|nineteen|twenty|hundred|thousand))+"
    r")(?:\ufe0f?\u20e3)?\s*[..、))::]?",
    re.IGNORECASE,
)

# 普通聊天菜单严格保持原判定口径。
_MENU_OPTION_LINE_RE = re.compile(
    r"^[^\S\n]*(?:[-+*][^\S\n]+)?(?:\*\*)?(?P<num>\d{1,2})(?:\*\*)?"
    r"[^\S\n]*[.、))][^\S\n]*(?P<text>\S.*?)[^\S\n]*$",
    re.M,
)
_HEADING_MENU_OPTION_LINE_RE = re.compile(
    r"^[^\S\n]*#{1,6}[^\S\n]+(?P<num>\d{1,2})[^\S\n]*[.、))]"
    r"[^\S\n]*(?P<text>\S.*?)[^\S\n]*$",
    re.M,
)

# 中文章节序号菜单独立分支:分析回复常用「一、二、」当标题,仅尾部有选择式问句时才算菜单。
_CHINESE_MENU_OPTION_LINE_RE = re.compile(
    r"^[^\S\n]*(?:[-+*][^\S\n]+)?(?:\*\*)?(?P<num>[一二三四五六七八九十])(?:\*\*)?"
    r"[^\S\n]*[、..::][^\S\n]*(?P<text>\S.*?)[^\S\n]*$",
    re.M,
)

_MENU_TAIL_QUESTION_RE = re.compile(
    r"(?:要哪个|选哪个|请选择|请输入编号|说一声|挑一个|任选)",
)

_CHINESE_MENU_OPTION_TEXT_LIMIT = 60

# Direct-command reports may separate explicit numbered headings with detail
# paragraphs.  Plain ``1 text`` / ``1text`` lines remain a consecutive block.
_REPORT_MARKED_OPTION_LINE_RE = re.compile(
    r"^[^\S\n]*(?P<num>[1-9]\d?)(?:\ufe0f?\u20e3|[^\S\n]*[.、))::])"
    r"[^\S\n]*(?P<text>\S.*?)[^\S\n]*$"
)

_REPORT_PLAIN_OPTION_LINE_RE = re.compile(
    r"^[^\S\n]*(?P<num>[1-9]\d?)(?:[^\S\n]+|(?=[^\W\d_]))"
    r"[^\S\n]*(?P<text>\S.*?)[^\S\n]*$"
)

_SELECTION_MARKUP_RE = re.compile(r"[*`]+")

_CHINESE_SELECTION_NUMBERS = {
    "一": "1",
    "二": "2",
    "三": "3",
    "四": "4",
    "五": "5",
    "六": "6",
    "七": "7",
    "八": "8",
    "九": "9",
    "十": "10",
}

_ENGLISH_SELECTION_NUMBERS = {
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
    "five": "5",
    "six": "6",
    "seven": "7",
    "eight": "8",
    "nine": "9",
    "ten": "10",
}


def _is_numbered_reply_selection(value: str, reply: str) -> bool:
    """Keep concise numeric responses with the topic that offered a menu."""
    return _numbered_reply_selection(value, reply) is not None


def _report_menu_options(reply: str) -> dict[str, str]:
    """Extract explicit headings plus a consecutive plain 1..N report block."""
    options: dict[str, str] = {}
    for line in (reply or "").splitlines():
        match = _REPORT_MARKED_OPTION_LINE_RE.fullmatch(line)
        if match:
            options.setdefault(match.group("num"), match.group("text"))

    best: dict[str, str] = {}
    current: dict[str, str] = {}
    expected = 1
    for line in (reply or "").splitlines():
        match = _REPORT_PLAIN_OPTION_LINE_RE.fullmatch(line)
        number = int(match.group("num")) if match else 0
        if match and number == expected:
            current[str(number)] = match.group("text")
            expected += 1
            continue
        if len(current) > len(best):
            best = current
        current = {}
        expected = 1
        if match and number == 1:
            current["1"] = match.group("text")
            expected = 2
    if len(current) > len(best):
        best = current
    if len(best) >= 2:
        for number, text in best.items():
            options.setdefault(number, text)
    # Requiring a real 1..N menu prevents timestamp/log lines such as
    # ``18:34:29 Bash ...`` from turning a bare numeric message into a choice.
    return options if "1" in options and len(options) >= 2 else {}


def _reply_offers_menu(reply: str) -> bool:
    """中文序号菜单资格门:无选择问句的章节头不是菜单。"""
    tail = (reply or "")[-120:]
    return bool(_MENU_TAIL_QUESTION_RE.search(tail))


def _menu_options(reply: str, *, report_style: bool = False) -> dict[str, str]:
    options: dict[str, str] = {}
    for match in _MENU_OPTION_LINE_RE.finditer(reply or ""):
        options.setdefault(match.group("num"), match.group("text"))
    if _reply_offers_menu(reply):
        for match in _HEADING_MENU_OPTION_LINE_RE.finditer(reply or ""):
            options.setdefault(match.group("num"), match.group("text"))
    # 中文章节行归一化编号注册(「五、」→"5"),阿拉伯项优先。
    chinese: dict[str, str] = {}
    if _reply_offers_menu(reply):
        for match in _CHINESE_MENU_OPTION_LINE_RE.finditer(reply or ""):
            text = match.group("text")
            if len(text) > _CHINESE_MENU_OPTION_TEXT_LIMIT:
                continue
            chinese.setdefault(
                _CHINESE_SELECTION_NUMBERS.get(match.group("num"), match.group("num")),
                text,
            )
    if len(chinese) >= 2:
        for number, text in chinese.items():
            options.setdefault(number, text)
    if report_style:
        for number, text in _report_menu_options(reply).items():
            options.setdefault(number, text)
    return options


def parse_selection_number(value: str) -> str | None:
    """解析独立的阿拉伯、汉字、英文或键帽数字选择。"""
    match = _NUMBERED_SELECTION_RE.fullmatch(value.strip())
    if not match:
        return None
    selected = next(group for group in match.groups() if group)
    return _CHINESE_SELECTION_NUMBERS.get(
        selected,
        _ENGLISH_SELECTION_NUMBERS.get(selected.casefold(), selected),
    )


def looks_like_numbered_choice(value: str) -> bool:
    """识别编号形态,含不在支持范围内的无效数字。"""
    stripped = value.strip()
    return parse_selection_number(stripped) is not None or bool(
        _NUMBER_LIKE_SELECTION_RE.fullmatch(stripped)
    )


def _option_text_key(value: str) -> str:
    """Normalize plain option text without changing its visible spelling."""
    return " ".join(_SELECTION_MARKUP_RE.sub("", value).split()).casefold()


def match_option_text(value: str, options: Sequence[str]) -> int | None:
    """Return the index of one exact option/title match, never a fuzzy guess."""
    if len(options) < 2 or looks_like_numbered_choice(value):
        return None
    key = _option_text_key(value)
    if not key or value.lstrip().startswith("/") or key in {
        "approve", "reject", "continue", "yes", "继续", "继续回复",
        "确认", "确认执行", "确定", "取消",
    }:
        return None
    matches = [
        index for index, raw in enumerate(options)
        if key in {
            _option_text_key(raw),
            _option_text_key(re.split(r"[((]", raw, maxsplit=1)[0]),
        }
    ]
    return matches[0] if len(matches) == 1 else None


def _matching_text_option(value: str, options: dict[str, str]) -> str | None:
    items = list(options.items())
    index = match_option_text(value, [raw for _, raw in items])
    return items[index][0] if index is not None else None


def _numbered_reply_selection(
    value: str,
    reply: str,
    *,
    report_style: bool = False,
) -> str | None:
    """匹配编号或唯一纯文字选项,返回阿拉伯数字编号。"""
    normalized = parse_selection_number(value)
    if not reply:
        return None
    options = _menu_options(reply, report_style=report_style)
    if normalized is not None:
        return normalized if normalized in options else None
    return _matching_text_option(value, options)


def _menu_option_text(reply: str, number: str, *, report_style: bool = False) -> str:
    """提取菜单第 number 项文本;取不到返回空串。"""
    raw = _menu_options(reply, report_style=report_style).get(number, "")
    text = _SELECTION_MARKUP_RE.sub("", raw).strip()
    if text and any(c.isalnum() for c in text):
        return text
    return ""


def _menu_option_display_text(reply: str, number: str, *, report_style: bool = False) -> str:
    """Return the selected option with its original number and punctuation."""
    patterns = []
    if report_style:
        patterns.extend((_REPORT_MARKED_OPTION_LINE_RE, _REPORT_PLAIN_OPTION_LINE_RE))
    patterns.append(_MENU_OPTION_LINE_RE)
    if _reply_offers_menu(reply):
        patterns.append(_HEADING_MENU_OPTION_LINE_RE)
    for line in (reply or "").splitlines():
        for pattern in patterns:
            match = pattern.fullmatch(line)
            if match and match.group("num") == number:
                return _SELECTION_MARKUP_RE.sub(
                    "",
                    line[match.start("num") :],
                ).strip()
    # 中文章节行独立重扫:归一化编号比对,保留「五、」原格式。
    if _reply_offers_menu(reply):
        for line in (reply or "").splitlines():
            match = _CHINESE_MENU_OPTION_LINE_RE.fullmatch(line)
            if not match:
                continue
            text = match.group("text")
            if len(text) > _CHINESE_MENU_OPTION_TEXT_LIMIT:
                continue
            normalized = _CHINESE_SELECTION_NUMBERS.get(match.group("num"), match.group("num"))
            if normalized == number:
                return _SELECTION_MARKUP_RE.sub(
                    "",
                    line[match.start("num") :],
                ).strip()
    return _menu_option_text(reply, number, report_style=report_style)


def _selection_reply(host: "ChatTurnDashboardReporter") -> tuple[str, bool]:
    """Return chat memory first, or a narrowly scoped restored command reply."""
    last_reply = str(getattr(host, "_last_reply", "") or "")
    if last_reply:
        return last_reply, False
    direct_reply = str(getattr(host, "_direct_command_reply", "") or "")
    return direct_reply, bool(direct_reply)


def numbered_reply_context(
    host: "ChatTurnDashboardReporter" | None,
    value: str,
) -> tuple[str, str] | None:
    """Return the selected number and text only when both are explicit."""
    if host is None:
        return None
    reply, report_style = _selection_reply(host)
    selected = _numbered_reply_selection(value, reply, report_style=report_style)
    if selected is None:
        return None
    option = _menu_option_text(reply, selected, report_style=report_style)
    return (selected, option) if option else None


def numbered_selection_context(
    value: str,
    reply: str,
    *,
    report_style: bool = False,
) -> tuple[str, str] | None:
    """Resolve an explicit selection against one concrete reply only."""
    selected = _numbered_reply_selection(value, reply, report_style=report_style)
    if selected is None:
        return None
    option = _menu_option_text(reply, selected, report_style=report_style)
    return (selected, option) if option else None


def numbered_reply_display_context(
    host: "ChatTurnDashboardReporter" | None,
    value: str,
) -> tuple[str, str] | None:
    """Resolve a selection for display while preserving the menu's option format."""
    if host is None:
        return None
    reply, report_style = _selection_reply(host)
    selected = _numbered_reply_selection(value, reply, report_style=report_style)
    if selected is None:
        return None
    option = _menu_option_display_text(reply, selected, report_style=report_style)
    return (selected, option) if option else None


def numbered_selection_display_context(
    value: str,
    reply: str,
    *,
    report_style: bool = False,
) -> tuple[str, str] | None:
    """Resolve a concrete reply selection and preserve its original option format."""
    selected = _numbered_reply_selection(value, reply, report_style=report_style)
    if selected is None:
        return None
    option = _menu_option_display_text(reply, selected, report_style=report_style)
    return (selected, option) if option else None