#!/usr/bin/env python3
"""
批量清理 TypeScript / TSX 文件中注释里的加粗样式 `**...**`

策略：
  1. 维护一个状态机：normal / line_comment / block_comment
  2. 遇到 `//` → 进入 line_comment
  3. 遇到 `/*` → 进入 block_comment
  4. 遇到 `*/` → 退出 block_comment
  5. 遇到换行 → 退出 line_comment
  6. 在 comment 状态下，删除所有孤立的 `**` 标记（成对出现或单数都处理）

注意事项：
  - 字符串字面量（"..." / '...' / `...`）不会被识别 —— 不会误删代码里的 `**`
  - 模板字符串（`...`）也不识别 —— 同样安全
  - 只在 comment 状态下删除 `**`
"""
import re
import sys
from pathlib import Path


def strip_bold_from_comments(text: str) -> str:
    """状态机：只在 comment 状态删除 `**`"""
    out: list[str] = []
    i = 0
    n = len(text)
    state = "normal"  # normal | line_comment | block_comment

    while i < n:
        c = text[i]
        c2 = text[i + 1] if i + 1 < n else ""

        if state == "normal":
            if c == "/" and c2 == "/":
                out.append(c)
                out.append(c2)
                i += 2
                state = "line_comment"
                continue
            if c == "/" and c2 == "*":
                out.append(c)
                out.append(c2)
                i += 2
                state = "block_comment"
                continue
            out.append(c)
            i += 1
        elif state == "line_comment":
            if c == "\n":
                out.append(c)
                i += 1
                state = "normal"
                continue
            # 在 line_comment 状态下：跳过 `**`
            if c == "*" and c2 == "*":
                i += 2
                continue
            out.append(c)
            i += 1
        elif state == "block_comment":
            if c == "*" and c2 == "/":
                out.append(c)
                out.append(c2)
                i += 2
                state = "normal"
                continue
            # 在 block_comment 状态下：跳过 `**`
            if c == "*" and c2 == "*":
                i += 2
                continue
            out.append(c)
            i += 1

    return "".join(out)


def main():
    if len(sys.argv) < 2:
        print("Usage: strip-bold-from-comments.py <file> [file...]")
        sys.exit(1)

    for path_str in sys.argv[1:]:
        path = Path(path_str)
        text = path.read_text(encoding="utf-8")
        original = text
        cleaned = strip_bold_from_comments(text)
        if cleaned != original:
            path.write_text(cleaned, encoding="utf-8")
            removed = original.count("**") - cleaned.count("**")
            print(f"  {path_str}: removed {removed} `**` markers")
        else:
            print(f"  {path_str}: no changes")


if __name__ == "__main__":
    main()
