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

REN = {
  "mcg-ece-phd":  ("Electrical and Computer Engineering (PhD)", "电气与计算机工程博士（PhD）"),
  "uw-ece-phd":   ("Electrical and Computer Engineering (PhD)", "电气与计算机工程博士（PhD）"),
  "nu-ece-phd":   ("Electrical and Computer Engineering (PhD)", "电气与计算机工程博士（PhD）"),
  "rice-ece-phd": ("Electrical and Computer Engineering (PhD)", "电气与计算机工程博士（PhD）"),
  "vanderbilt-ece-phd": ("Electrical and Computer Engineering (PhD)", "电气与计算机工程博士（PhD）"),
  "wustl-ee-phd": ("Electrical Engineering (PhD)", "电气工程博士（PhD）"),
  "notre-ee-phd": ("Electrical Engineering (PhD)", "电气工程博士（PhD）"),
  "ucsd-cse-bioinfo-phd": ("Computer Science (PhD, Bioinformatics Specialization)", "计算机科学博士（PhD，生物信息学方向）"),
}

h = open('index_main.html', encoding='utf-8').read()
mp = re.search(r'const PROGRAMS\s*=\s*\[(.*?)\];', h, re.S)
head, body, tail = h[:mp.start()], mp.group(1), h[mp.end():]

changed = []
for i, (old, new) in REN.items():
    blk = re.search(r'\{id:"'+re.escape(i)+r'"[\s\S]*?(?=\{id:"|$)', body)
    if not blk:
        print(i, "*** block not found ***"); continue
    b = blk.group(0)
    if f'n:"{new}"' in b:
        print(i, "already renamed"); continue
    m = re.search(r'n:"([^"]*)"', b)
    if not m or m.group(1) != old:
        print(i, "*** n mismatch, skip ***", repr(m.group(1) if m else None)); continue
    nb = b.replace(f'n:"{old}"', f'n:"{new}"', 1)
    body = body.replace(b, nb, 1)
    changed.append(i)

out = head + "const PROGRAMS = [" + body + "];" + tail if not head.rstrip().endswith('[') else None
# 原样拼接：保留 const PROGRAMS = [ ... ]; 格式
out = h[:mp.start()] + "const PROGRAMS = [" + body + "];" + h[mp.end():]

# 缺逗号自检
bad = len(re.findall(r'\}\{', out))
print("changed:", changed)
print("}{ 缺逗号:", bad)
if bad == 0:
    open('index_main.html','w',encoding='utf-8').write(out)
    print("written")
else:
    print("NOT written, 缺逗号异常")
