import re, os, sys, io

base = os.path.dirname(os.path.abspath(__file__))
p = os.path.join(base, "index_main.html")
html = open(p, encoding="utf-8").read()

# 声明行无空格断言（r326 踩坑：定位脚本用无空格字面量）
assert 'const PROGRAMS=[' in html, "PROGRAMS 声明行缺失/空格异常"
assert 'const PROGRAMS =[' not in html and 'const PROGRAMS= [' not in html, "PROGRAMS 声明行含空格"
assert 'const CATD=[' in html, "CATD 声明行缺失/空格异常"

rename = {
    "berkeley-biostat-ma": ("Biostatistics MA", "生物统计学文学硕士（MA）"),
    "brown-scm-biostat": ("Biostatistics ScM", "生物统计学硕士（ScM）"),
    "umich-me-mse": ("Mechanical Engineering MSE", "机械工程硕士（MSE）"),
    "ucsd-mae-ms": ("Mechanical and Aerospace Engineering MS", "机械与航空航天工程硕士（MS）"),
    "umich-robotics-ms": ("Robotics MS", "机器人学硕士（MS）"),
    "usc-apmath-ms": ("Applied Mathematics MS", "应用数学硕士（MS）"),
    "umich-bme-ms": ("Biomedical Engineering MSE", "生物医学工程硕士（MSE）"),
    "cornell-mps-aem": ("Applied Economics and Management (MPS)", "应用经济学与管理专业硕士（MPS）"),
}

block_re = re.compile(r'(\{id:"([^"]+)"(?:(?!\{id:").)*?)(?=\{id:"|\n\];)', re.S)

changed = []
def repl(m):
    pid = m.group(2)
    if pid not in rename:
        return m.group(0)
    old, new = rename[pid]
    body = m.group(1)
    # 幂等：已是新名则不动
    if f'n:"{new}"' in body:
        return m.group(0)
    pat = re.compile(r'n:"' + re.escape(old) + r'"')
    nb, cnt = pat.subn(f'n:"{new}"', body, count=1)
    if cnt == 0:
        print(f"[WARN] {pid} 未匹配旧 n: {old}")
        return m.group(0)
    changed.append((pid, old, new))
    return nb

html2 = block_re.sub(repl, html)

# 缺逗号自检
bad = html2.count('}{')
print(f"缺逗号 '{{}}' 计数: {bad}")
if bad:
    sys.stderr.write("缺逗号异常，中止写入\n")
    sys.exit(1)

open(p, "w", encoding="utf-8").write(html2)
print(f"替换条数: {len(changed)}")
for pid, old, new in changed:
    print(f"  {pid}: {old} -> {new}")
