import re, os, sys

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

# id -> (old n 断言, 新规范中文名)
rename = {
    "harvard-bus-eco-phd": ("Business Economics (PhD)", "商业经济学博士（PhD）"),
    "brown-scm-cs": ("Computer Science ScM", "计算机科学硕士（ScM）"),
    "umich-ece-ms": ("Electrical and Computer Engineering MS", "电气与计算机工程硕士（MSE）"),
    "usc-stats-ms": ("Statistics MS", "统计学硕士（MS）"),
    "berkeley-maiml": ("Master of AI and Machine Learning (MAIML)", "人工智能与机器学习硕士（MAIML）"),
    "umich-hds-ms": ("Health Data Science MS", "健康数据科学硕士（MS）"),
    "umich-msi": ("Information MS", "信息学硕士（MSI）"),
    "umich-biostat-ms": ("Biostatistics MS", "生物统计学硕士（MS）"),
}

# 声明行无空格断言（历史坑：不得写成 const PROGRAMS = [）
assert "const PROGRAMS=[" in html, "PROGRAMS 声明行缺失"
assert "const PROGRAMS =[" not in html and "const PROGRAMS= [" not in html, "PROGRAMS 声明行被加空格"

changed = []
for pid, (old, new) in rename.items():
    pat = r'(\{id:"' + re.escape(pid) + r'",[\s\S]*?n:")([^"]*)(")'
    m = re.search(pat, html)
    if not m:
        print(f"[MISS] {pid} 块未找到")
        sys.exit(1)
    if m.group(2) != old:
        print(f"[ASSERT FAIL] {pid} n='{m.group(2)}' != 预期 '{old}'")
        sys.exit(1)
    html = html[:m.start()] + m.group(1) + new + m.group(3) + html[m.end():]
    changed.append((pid, new))

# 缺逗号自检：} { 紧贴无逗号
missing = re.findall(r'\}\{', html)
print(f"缺逗号 }}  {{ 计数: {len(missing)}")
if missing:
    sys.exit(1)

# 声明行复核
assert "const PROGRAMS=[" in html
assert "const PROGRAMS =[" not in html and "const PROGRAMS= [" not in html

open(p, "w", encoding="utf-8").write(html)
print(f"written, bytes={len(html.encode('utf-8'))}")
for pid, new in changed:
    print(f"  {pid} -> {new}")
