"""将助手回复渲染为适合 Textual RichLog 的 Rich 对象（Markdown 表格、标题、粗体等）。"""

from __future__ import annotations

from typing import TYPE_CHECKING

from rich.console import Group
from rich.markdown import Markdown
from rich.text import Text

if TYPE_CHECKING:
    from rich.console import RenderableType


def _looks_like_table_header(line: str) -> bool:
    s = line.strip()
    return "|" in s and s.count("|") >= 2 and not s.startswith("```")


def _is_table_separator_row(line: str) -> bool:
    """GFM 表格第二行：仅由 |、-、:、空白 组成各列。"""
    s = (line or "").strip()
    if "|" not in s:
        return False
    core = s.strip("|").split("|")
    if len(core) < 1:
        return False
    for cell in core:
        c = cell.strip()
        if not c:
            return False
        if not all(ch in "-:" for ch in c):
            return False
    return True


def normalize_markdown_blocks(raw: str) -> str:
    """
    宽松规整：统一换行；在「紧邻上一段文本的 GFM 表格」前插入空行，避免整张表被当成普通段落。
    """
    text = (raw or "").replace("\r\n", "\n").replace("\r", "\n")
    lines = text.split("\n")
    out: list[str] = []
    for i, line in enumerate(lines):
        if (
            i > 0
            and out
            and out[-1].strip() != ""
            and _looks_like_table_header(line)
            and i + 1 < len(lines)
            and _is_table_separator_row(lines[i + 1])
        ):
            out.append("")
        out.append(line)
    return "\n".join(out)


def render_assistant_message(markdown_body: str, *, label: str = "[助手]") -> RenderableType:
    """
    返回可交给 ``RichLog.write`` 的单块渲染结果（标签 + Markdown，含表格框线、列表、代码块高亮）。
    剪贴板 / 持久化请仍使用模型返回的原始字符串。
    """
    body = (markdown_body or "").strip()
    label_t = Text(label, style="bold cyan")
    if not body:
        return Group(label_t, Text("（空回复）", style="dim"))

    normalized = normalize_markdown_blocks(body)
    md = Markdown(
        normalized,
        code_theme="ansi_dark",
        hyperlinks=False,
    )
    return Group(label_t, md)
