# -*- coding: utf-8 -*-
"""修复教程 md 中中文语境下的 ASCII 直引号为中文弯引号（跳过代码块与行内代码）"""
import re
import glob
import io

def fix_quotes(text):
    lines = text.split("\n")
    out = []
    in_code = False
    for ln in lines:
        if ln.strip().startswith("```"):
            in_code = not in_code
            out.append(ln)
            continue
        if in_code:
            out.append(ln)
            continue
        # 行内代码 `...` 占位保护
        placeholders = {}

        def prot(m):
            key = "\x00%d\x00" % len(placeholders)
            placeholders[key] = m.group(0)
            return key

        ln = re.sub(r"`[^`]*`", prot, ln)

        def repl(m):
            inner = m.group(1)
            if re.search(r"[\u4e00-\u9fff]", inner):
                return "\u201c" + inner + "\u201d"
            return m.group(0)

        ln = re.sub(r"\"([^\"\n]{1,80})\"", repl, ln)
        for k, v in placeholders.items():
            ln = ln.replace(k, v)
        out.append(ln)
    return "\n".join(out)

total = 0
for f in sorted(glob.glob("tutorial/*.md")):
    with io.open(f, encoding="utf-8") as fh:
        t = fh.read()
    fixed = fix_quotes(t)
    before = len(re.findall(r"\"[^\"\n]{1,80}\"", t))
    after = len(re.findall(r"\"[^\"\n]{1,80}\"", fixed))
    if before != after:
        with io.open(f, "w", encoding="utf-8", newline="\n") as fh:
            fh.write(fixed)
        total += before - after
        print("%s: %d 处" % (f, before - after))
print("总计替换 %d 处" % total)
