# -*- 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 = {
    "princeton-ece-phd": "电气与计算机工程博士（PhD）",
    "harvard-ece-phd":   "电气工程博士（PhD）",
    "caltech-cs-phd":    "计算机科学博士（PhD）",
    "berkeley-eecs-phd": "电气工程与计算机科学博士（PhD, EECS）",
    "mit-eecs-phd":      "电气工程与计算机科学博士（PhD, EECS）",
    "cornell-ece-phd":   "电气与计算机工程博士（PhD）",
    "umich-ece-phd":     "电气与计算机工程博士（PhD）",
    "geo-cs-phd":        "计算机科学博士（PhD）",
}

# 定位 PROGRAMS body
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():
    # 块：{id:"pid" ... 到下一个 {id:" 或末尾
    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))

# 写回 PROGRAMS body
html_new = html[:mp.start(1)] + body + html[mp.end(1):]

# CATD 对应行中文名核对（第4元素）
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)
