import re, os, sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
base = os.path.dirname(os.path.abspath(__file__))
fp = os.path.join(base, 'index_main.html')
html = open(fp, encoding='utf-8').read()

assert 'const PROGRAMS=[' in html, "PROGRAMS 声明行格式异常"
assert 'const CATD=[' in html, "CATD 声明行格式异常"

REPL = {
    "ubc-meng-ece": "国际生首年 C$27,419.34（每年 3 期，每期 C$9,139.78；本地生 C$6,974.94/年；学费每年或上调 2%–5%，官网未列全程总额）",
    "emory-econ-ms": "Laney 研究生院 2026-27：全日制（≥9 学分/学期）$24,900/学期；非全日制 $2,767/学分；项目 self-funded，学院不提供 fellowship/assistantship",
    "emory-ms-ds": "Laney 研究生院 2026-27：全日制（≥9 学分/学期）$24,900/学期；非全日制 $2,767/学分；另收学杂费与医保（官网费率页）",
}

before_ids = len(re.findall(r'\{id:"', html))
changed = []
for tid, newtui in REPL.items():
    pat = re.compile(r'(\{id:"' + re.escape(tid) + r'"[\s\S]*?)tui:"([^"]*)"')
    mm = pat.search(html)
    if not mm:
        print(f"!! {tid}: 块未定位，跳过"); continue
    old = mm.group(2)
    if old != "待补":
        print(f"!! {tid}: 现有 tui 非待补（{old}），不覆盖"); continue
    new_block = mm.group(1) + f'tui:"{newtui}"'
    html = html[:mm.start()] + new_block + html[mm.end():]
    changed.append((tid, old, newtui))

after_ids = len(re.findall(r'\{id:"', html))
assert before_ids == after_ids, f"id 数变化 {before_ids}->{after_ids}"
nocomma = len(re.findall(r'\}\{', html))
print(f"id 数: {before_ids}->{after_ids}；缺逗号 }} {{ 计数: {nocomma}")
assert nocomma == 0, "存在缺逗号 }{"

open(fp, 'w', encoding='utf-8').write(html)
print("已写盘。变更条目：")
for tid, old, new in changed:
    print(f"  {tid}: tui 「{old}」 -> 「{new[:42]}…」")
print("bytes:", os.path.getsize(fp))
