# -*- coding: utf-8 -*-
import re, io, sys, os, shutil, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
src = 'index_main.html'
shutil.copy(src, 'index_main.html.bak_r321')

h = open(src, encoding='utf-8').read()
p0 = h.index("const PROGRAMS=["); p1 = h.index("const CATD=[")
seg = h[p0:p1]

rename = {
 'col-stat-ma':'统计学硕士（MA）',
 'ucla-ece-ms':'电气与计算机工程硕士（MS）',
 'ucla-aero-ms':'航空航天工程硕士（MS）',
 'usc-aero-ms':'航空航天工程硕士（MS）',
 'gatech-msbinf':'生物信息学硕士（MS）',
 'usc-abe-ms':'应用生物统计与流行病学硕士（MS）',
 'ucla-stats-ms':'统计学硕士（MS）',
 'cmu-mspm':'产品管理硕士（MSPM）',
}

def repl(m):
    pid = m.group(1); body = m.group(2)
    if pid in rename:
        newbody, n = re.subn(r'n:"[^"]*"', f'n:"{rename[pid]}"', body, count=1)
        if n == 0:
            print('WARN n not found:', pid)
        return '{id:"%s"%s' % (pid, newbody)
    return m.group(0)

newseg = re.sub(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|,?\n\];)', repl, seg)
h2 = h[:p0] + newseg + h[p1:]

# 校验替换条数
after = re.findall(r'\{id:"([^"]+)"', newseg)
print('PROGRAMS 条数:', len(after))
for pid, cn in rename.items():
    mm = re.search(r'\{id:"'+re.escape(pid)+r'",[^}]*?n:"([^"]*)"', newseg)
    print(f"  {pid} -> {mm.group(1) if mm else 'MISSING'}")

open(src, 'w', encoding='utf-8').write(h2)
print('written, bytes=', os.path.getsize(src))
