# -*- coding: utf-8 -*-
"""r387: 修正 uchicago-stats（MS）—— 渲染到正确 url 并回填 MS 口径字段。"""
import io, os, json, re, sys, shutil
sys.path.insert(0, r"D:\work buddy\2026-11-05-14-15-52")
import detail_render as dr

BASE = r"D:\work buddy\2026-11-05-14-15-52"
spec = json.load(io.open(os.path.join(BASE, "_r387_specs", "uchicago-stats.json"), encoding="utf-8"))
spec["out"] = "details/uchicago-statistics.html"
io.open(os.path.join(BASE, "_r387_specs", "uchicago-stats.json"), "w", encoding="utf-8").write(
    json.dumps(spec, ensure_ascii=False, indent=1))
io.open(os.path.join(BASE, "details", "uchicago-statistics.html"), "w", encoding="utf-8").write(dr.render(spec))
print("rendered details/uchicago-statistics.html", os.path.getsize(os.path.join(BASE, "details", "uchicago-statistics.html")))

UPD = {
 'ddl': '2026-11-02 / 2027-02-01 / 2027-05-03 三轮（决定发布后邮件通知，登录系统查看）',
 'lang': 'TOEFL iBT / IELTS Academic（UChicagoGRAD 只接受这两类）；项目页未列最低分（官网未披露）；TOEFL 码 1832；2 年有效',
 'tui': '申请费 $90；全部申请人自动纳入 merit-based 部分学费奖学金评审；2026-27 学费/每 course 费率官网未披露（以 PSD 与 Bursar 费率为准）',
 'dur': '至少 9 门课：理论 STAT30030-30040-32950 或应用 STAT34300-34700-34800 + 4 门 regular elective；3–6 quarter，最长 24 个月；硕士论文 + 公开 seminar',
 'test': 'opt（GRE 可选，不要求；提交可增强竞争力；数学 Subject 不要求）',
}

main = os.path.join(BASE, 'index_main.html')
shutil.copy2(main, main + '.bak_r387b')
s = io.open(main, encoding='utf-8').read()

def block_span(text, pid):
    st = text.find('{id:"%s"' % pid)
    if st < 0:
        raise SystemExit('missing id ' + pid)
    nx = text.find('{id:"', st + 6)
    en = nx if nx > 0 else text.find('];', st)
    return st, en

def esc(v):
    return v.replace('\\', '\\\\').replace('"', '\\"')

st, en = block_span(s, 'uchicago-stats')
seg = s[st:en]
cnt = 0
for k, v in UPD.items():
    if k == 'test':
        new = 'test:{cls:"%s"},' % esc(v)
        seg2, n = re.subn(r'test:\{cls:"[^"]*"\},', new, seg)
    else:
        new = '%s:"%s",' % (k, esc(v))
        seg2, n = re.subn(r'\b%s:"[^"]*",' % k, new, seg, count=1)
    assert n == 1, (k, n)
    seg = seg2
    cnt += 1
s = s[:st] + seg + s[en:]
io.open(main, 'w', encoding='utf-8', newline='\n').write(s)
print('backfill', cnt, 'bytes', os.path.getsize(main))
