# -*- coding: utf-8 -*-
"""r383：页面体检（禁词/长度/HTTP）+ PROGRAMS 回填（6 条）。"""
import io, os, re, json, shutil, urllib.request

BASE = r"D:\work buddy\2026-11-05-14-15-52"
IDS = ['nu-ms-ee', 'nu-ece-phd', 'nu-ms-bme', 'nu-kellogg-mecs-phd', 'nu-kellogg-om-phd', 'nu-kellogg-acct-phd']
BAD = ['编辑整理', '待补', 'TBD', 'TODO']

def strip_tags(s):
    s = re.sub(r'<script.*?</script>', '', s, flags=re.S)
    s = re.sub(r'<style.*?</style>', '', s, flags=re.S)
    s = re.sub(r'<[^>]+>', ' ', s)
    return re.sub(r'\s+', ' ', s)

for i in IDS:
    p = os.path.join(BASE, 'details', i + '.html')
    t = io.open(p, encoding='utf-8').read()
    txt = strip_tags(t)
    bad = [b for b in BAD if b in txt]
    try:
        with urllib.request.urlopen('http://127.0.0.1:8000/' + 'details/' + i + '.html', timeout=8) as r:
            code = r.status
            ln = len(r.read())
    except Exception as e:
        code = 'ERR:%s' % e
        ln = -1
    print('%-22s bytes=%6d chars=%5d bad=%s http=%s len=%s' % (i, len(t.encode('utf-8')), len(txt), bad, code, ln))

# ---------- 回填 ----------
# (id, {field: new_value})
UPD = {
 'nu-ms-ee': {
   'ddl': '仅秋季入学；MS 具体截止日期官网未披露（学系写明名额有限、鼓励尽早提交，招满可能提前关闭申请通道）；同系 PhD Fall 2027 截止 2026-12-15（参照）',
   'lang': 'TOEFL iBT 90（2026-01-21 前考试）/ 新制 iBT 4.5（2026-01-21 后考试）；CBT 233 / PBT 577；IELTS 按 TGS 标准，本项目页未列具体分数线',
   'tui': '官网未披露（McCormick 各系 tuition 子页与 SFS 研究生明细页不可达）；申请费官方页未列金额',
   'dur': '仅秋季入学；EE / CE 两条 MS track，12 个 specialization；官网未披露 MS 修读月数与总学分',
   'test': 'notreq',
 },
 'nu-ece-phd': {
   'ddl': '2026-12-15（Fall 2027，官网原文日期）；多数录取 3 月底前定案，个别晚至 4 月 15 日；仅秋季入学',
   'lang': 'TOEFL iBT 90（2026-01-21 前考试）/ 新制 iBT 4.5（之后考试）；CBT 233 / PBT 577；IELTS 按 TGS 标准，具体分数官网未披露',
   'tui': '官网未披露具体金额；博士资助按 TGS 统一政策，系页未列资助包结构',
   'dur': '仅秋季入学；EE / CE 两条博士 track；官网未披露年限与学分总量；研究课 ELEC_ENG 590-0',
   'test': 'notreq',
 },
 'nu-ms-bme': {
   'ddl': '官网未披露 MS 具体截止日期（BME 项目页与系研究生页均未列）；按 TGS 常规为秋季入学',
   'lang': '按 TGS 统一语言标准；BME 硕士项目页未列最低分（官网未披露具体分数线）',
   'tui': '官网未披露（BME 项目页无费率；McCormick/SFS 学费明细页不可达）；申请费金额官网未披露',
   'dur': '有论文轨 9 门课 + 论文（7 个 quarter）；无论文轨 12 门课 + 可选研究项目（3 个 quarter）；通常 1–2 年',
 },
 'nu-kellogg-mecs-phd': {
   'ddl': 'Fall 2027：2026-12-15（每年仅秋季招生）；申请费 $95，与经济学博士双申请 $175',
   'lang': 'TOEFL 或 IELTS 必需（非英语母语），最低分官网未披露；GRE 代码 1565、TOEFL 代码 1565 系代码 01',
   'tui': '5 年全额资助：学费奖学金 + 津贴 + 学生医保单人年费 + 搬迁补助；电脑补贴 $2,000、会议差旅 $4,000',
   'dur': '5–6 年；前两年课程，第三至第五年研究/论文；全日制 Evanston，仅秋季入学',
   'test': 'req',
 },
 'nu-kellogg-om-phd': {
   'ddl': 'Fall 2027：2026-12-15（每年仅秋季招生）；申请费 $95，与经济学博士双申请 $175',
   'lang': 'TOEFL 或 IELTS 必需（非英语母语），最低分官网未披露；TOEFL 代码 1565 系代码 01',
   'tui': '5 年全额资助：学费奖学金 + 津贴 + 医保 + 搬迁补助；电脑补贴 $2,000、会议差旅 $4,000',
   'dur': '5–6 年；前两年课程（OPNS 510/516/521-525 系列），第三至第五年研究/论文；仅秋季',
   'test': 'notreq',
 },
 'nu-kellogg-acct-phd': {
   'ddl': 'Fall 2027：2026-12-15（每年仅秋季招生）；申请费 $95，与经济学博士双申请 $175',
   'lang': 'TOEFL 或 IELTS 必需（非英语母语），最低分官网未披露；TOEFL 代码 1565 系代码 01',
   'tui': '5 年全额资助：学费奖学金 + 津贴 + 医保 + 搬迁补助；电脑补贴 $2,000、会议差旅 $4,000',
   'dur': '5–6 年；前两年课程，第三至第五年研究/论文；全日制 Evanston，仅秋季',
   'test': 'req',
 },
}

main = os.path.join(BASE, 'index_main.html')
shutil.copy2(main, main + '.bak_r383')
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('"', '\\"')

cnt = 0
for pid, fields in UPD.items():
    st, en = block_span(s, pid)
    seg = s[st:en]
    for k, v in fields.items():
        if k == 'test':
            new = 'test:{cls:"%s"},' % 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, (pid, 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 fields', cnt, 'bytes', os.path.getsize(main))
