# -*- coding: utf-8 -*-
import re, io, sys, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

P = "index_main.html"
html = open(P, encoding="utf-8").read()

rename = {
    "uchicago-cs-phd":       "计算机科学博士（PhD）",
    "harvard-cs-phd":        "计算机科学博士（PhD, SEAS）",
    "rice-cs-phd":           "计算机科学博士（PhD）",
    "cornell-cs-phd":        "计算机科学博士（PhD）",
    "emory-cs-phd":          "计算机科学与信息学博士（PhD, CS & BMI tracks）",
    "notre-cse-phd":         "计算机科学与工程博士（PhD）",
    "uva-cpe-phd":           "计算机工程博士（PhD）",
    "wustl-cse-cpe-phd":     "计算机工程博士（PhD, CSE）",
}

mp = re.search(r'const PROGRAMS\s*=\s*\[(.*?)\];', html, re.S)
body = mp.group(1)

changed, skipped, missing = [], [], []
for pid, new_n in rename.items():
    blk_re = re.compile(r'(\{id:"' + re.escape(pid) + r'"[\s\S]*?)(?=\{id:"|$)')
    m = blk_re.search(body)
    if not m:
        missing.append(pid); continue
    blk = m.group(1)
    nm = re.search(r'n:"([^"]*)"', blk)
    if not nm:
        missing.append(pid + " (no n)"); continue
    old_n = nm.group(1)
    if old_n == new_n:
        skipped.append(pid); continue
    new_blk = blk.replace('n:"%s"' % old_n, 'n:"%s"' % new_n, 1)
    body = body.replace(blk, new_blk, 1)
    changed.append((pid, old_n, new_n))

html_new = html[:mp.start(1)] + body + html[mp.end(1):]

catd_m = re.search(r'const CATD\s*=\s*\[(.*?)\];', html_new, re.S)
catd_body = catd_m.group(1)
print("=== CATD 对应条目现状（博士条目通常为空）===")
for pid in rename:
    rows = re.findall(r'\["[^"]+",\s*"[^"]*",\s*"[^"]*",\s*"([^"]*)",\s*"[^"]*",\s*"[^"]*",\s*"[^"]*",\s*"details/' + re.escape(pid) + r'\.html"\]', catd_body)
    print(pid, "->", rows)

# 缺逗号自检
bad = html_new.count('}{')
print("\n'}{' 缺逗号处:", bad)

open(P, "w", encoding="utf-8").write(html_new)
print("\nchanged:", len(changed))
for c in changed: print("  ", c[0], "|", c[1], "=>", c[2])
print("skipped(已是中文):", skipped)
print("missing:", missing)
