# -*- coding: utf-8 -*-
"""r387: 页面体检 + PROGRAMS 回填（8 条）。"""
import io, os, re, shutil, urllib.request

BASE = r"D:\work buddy\2026-11-05-14-15-52"
FILES = {
 'ucsd-ece-phd': 'ucsd-ece-phd.html',
 'ucsd-mae-phd': 'ucsd-mae-phd.html',
 'ucsd-cse-phd': 'ucsd-cse-phd.html',
 'ucsd-biosci-phd': 'ucsd-biosci-phd.html',
 'uchicago-cs-phd': 'uchicago-cs-phd.html',
 'uchicago-stats': 'uchicago-stats.html',
 'uchicago-econ-phd': 'uchicago-econ-phd.html',
 'uchicago-booth-fin-phd': 'uchicago-booth-fin-phd.html',
}
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, fn in FILES.items():
    p = os.path.join(BASE, 'details', fn)
    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/' + fn, timeout=8) as r:
            code = r.status
            ln = len(r.read())
    except Exception as e:
        code = 'ERR:%s' % e
        ln = -1
    print('%-24s bytes=%6d chars=%5d bad=%s http=%s len=%s' % (i, len(t.encode('utf-8')), len(txt), bad, code, ln))

UPD = {
 'ucsd-ece-phd': {
   'ddl': '2026-12-16 23:59 PT（Fall 2027；网申 2026-09-02 开放）；仅秋季入学',
   'lang': 'TOEFL iBT 4.5（新制）/85（旧制），码 4836；IELTS 7.0；Duolingo 120；PTE 65；英语学位可豁免（WHED）',
   'tui': '2026-27：$4,574/quarter + $448 SSF，州内约 $22,985/年；非居民另加 $5,034/quarter，约 $38,087/年；博士 Fellowship/TA/GSR 覆盖学费+杂费',
   'dur': '48 units（12 门 quarter 课，≥36 研究生课）；2 年内修完；第 2 年预考、第 4 年前 UQE；规范 6 年',
   'test': 'opt（Fall 2027 GRE 不要求）',
 },
 'ucsd-mae-phd': {
   'ddl': 'Fall 2027：PhD 已关闭（官网 Applications for Fall 2027 are closed）；MS 2026-09-02–2027-01-13；仅秋季',
   'lang': 'TOEFL iBT 4.5（新制）/85（旧制），纸笔 64；IELTS 7.0；DET 120；PTE 65；码 4836',
   'tui': '2026-27：州内约 $22,985/年、非居民约 $38,087/年；PhD 典型约 $3,600/月 + 学费杂费；MS 基本无资助',
   'dur': '以博士论文研究为核心；核心课 MAE 200–210 系列；项目页未列年限（官网未披露）',
   'test': 'opt（GRE Optional，无最低分；录取者 quant 多 85–90 percentile）',
 },
 'ucsd-cse-phd': {
   'ddl': '2026-09-02–2026-12-16 23:59 PST（Fall 2027）；仅秋季入学',
   'lang': 'GRE 不要求；英语按 UCSD 统一门槛：TOEFL iBT 4.5（新制）/85、IELTS 7.0、DET 120、PTE 65',
   'tui': '2026-27：$4,574/quarter + $448 SSF，州内约 $22,985/年、非居民约 $38,087/年；资助为 fellowship/TA/assistantship',
   'dur': '37 units（breadth 4/10 领域各 1 门 + CSE 292 + 5 门 elective）；breadth GPA 3.3；candidacy 4 年内',
   'test': 'opt（Fall 2027 GRE 不要求，可自愿提交；码 4836）',
 },
 'ucsd-biosci-phd': {
   'ddl': '2026-09-02–2026-12-02 23:59 PST；Zoom 面试 2027-01-14/15、01-19–22、01-25；线下招募 2027-03-04',
   'lang': '官网未披露（项目页未列 GRE/语言最低分；按 UCSD 研究生院统一口径）',
   'tui': '资助包含 tuition + required fees（含医保）+ monthly support；非居民学费付 3 年或至 candidacy；标准费率州内约 $22,985/年、非居民约 $38,087/年',
   'dur': '第一年核心课程 + rotation 选导师；每年 committee meeting + annual report + IDP；Salk 联合博士项目',
   'test': '官网未披露（招生页未列 GRE 要求）',
 },
 'uchicago-cs-phd': {
   'ddl': '2026-12-10（全部材料）；Key Dates 的通知/访校/接受日期年份仍写 2026，官网未更新',
   'lang': '只接受 TOEFL iBT / IELTS Academic（不接受 Duolingo、ITP Plus、Indicator）；TOEFL 码 1832；2 年有效；项目级分线官网未披露',
   'tui': '申请费 $90；博士资助覆盖 tuition + 医保 + stipend（UChicagoGRAD 口径）；CS 项目级 stipend/学费数额官网未披露',
   'dur': '三阶段（Qualifying/Candidacy/Dissertation）约 6 年；Qualifying Exam → Candidacy Exam → Dissertation Defense',
   'test': 'opt（本轮 PhD 不要求 GRE，optional）',
 },
 'uchicago-stats': {
   'ddl': '2027-01-04（全部材料，含分数与推荐信）；仅秋季 autumn 入学，不接受 late',
   'lang': 'TOEFL 90 overall 或新制 4.5；IELTS 7.0；无单项要求；码 1832/59；不提供条件录取',
   'tui': '申请费 $90；UChicagoGRAD 博士资助覆盖学费+医保+stipend；项目级数额官网未披露',
   'dur': '核心 5 领域 + 交叉方向；入学分配 faculty advisor；课程序列自 autumn 开始',
   'test': 'opt（GRE 强烈建议 + 数学 Subject 建议；无最低分，quant 多 90th+；码 1832/0705）',
 },
 'uchicago-econ-phd': {
   'ddl': '2026-12-01 23:59 CT（Autumn 2027）',
   'lang': '只接受 TOEFL iBT / IELTS Academic（UChicagoGRAD）；项目级最低分官网未披露',
   'tui': '六年全程 full funding：学费全免 + 学生医保 + Graduate Student Services Fee + living stipend（金额官网未披露）',
   'dur': '6 年：前两年课程（1 年 core、2 年 fields），第 3 年起独立研究；须完成 5 次教学任务',
   'test': '官网未披露（申请页未列 GRE；联合 Financial Economics 要求 GRE）',
 },
 'uchicago-booth-fin-phd': {
   'ddl': '2026-12-15（Fall 2027 已开放）；面试 1 月–3 月初',
   'lang': 'TOEFL 100（2026-01-21 前）/ 新制 5 且单项 5；IELTS 7.0 且单项 7.0；不接受 Duolingo/Indicator；2 年有效',
   'tui': '申请费 $80；UChicagoGRAD 博士资助覆盖学费+医保+stipend；Booth 项目级数额官网未披露',
   'dur': '全日制；前两年课程 + general exams，第 3 年起论文；最多转 3 门课',
   'test': 'req（GRE 或 GMAT 必交；Finance 方向 GRE 优先、GMAT 可接受；GRE 码 1501）',
 },
}

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