"""清洗子进程日志再行展示，减轻 ANSI 控制序列与 \\r 进度条对 Textual RichLog 的干扰。"""

from __future__ import annotations

import re

_ANSI_ESC = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
_ANSI_OTHER = re.compile(r"\x1b[\][()#%][0-9A-Za-z~]*")
_CTRL_BAD = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")


def sanitize_shell_log_line(line: str, *, max_len: int = 32000) -> str:
    s = line.replace("\x00", "")
    s = _ANSI_ESC.sub("", s)
    s = _ANSI_OTHER.sub("", s)
    s = _CTRL_BAD.sub("", s)
    if "\r" in s:
        s = s.split("\r")[-1]
    if len(s) > max_len:
        return s[: max_len - 3] + "..."
    return s
