# -*- 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 = {
    "brown-cs-phd":       "计算机科学博士（PhD）",
    "dartmouth-cs-phd":   "计算机科学博士（PhD）",
    "duke-cs-phd":        "计算机科学博士（PhD）",
    "jhu-cs-phd":         "计算机科学博士（PhD）",
    "usc-cs-phd":         "计算机科学博士（PhD）",
    "yale-cs-phd":        "计算机科学博士（PhD）",
    "princeton-cs-phd":   "计算机科学博士（PhD）",
    "vanderbilt-cs-phd":  "计算机科学博士（PhD）",
}

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)

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)
