# -*- coding: utf-8 -*-
"""r387 收尾：baseline（round=387）+ 台账条目。"""
import datetime, io, json, os, re, requests

P_HTML = 'index_main.html'
st = os.stat(P_HTML)
mtime = datetime.datetime.fromtimestamp(st.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
bl = json.load(io.open('_heartbeat_baseline.json', encoding='utf-8'))
drep = json.load(io.open('_density_report.json', encoding='utf-8'))
rows = drep['rows'] if isinstance(drep, dict) and 'rows' in drep else drep
gc = {'A': 0, 'B': 0, 'C': 0}
for r in rows:
    if r.get('grade') in gc:
        gc[r['grade']] += 1

html = io.open(P_HTML, encoding='utf-8').read()
seg = re.search(r'PROGRAMS\s*=\s*\[(.*?)\n\s*\];', html, re.S).group(1)
phd = len(re.findall(r'lvl:"d"', seg))
mas = len(re.findall(r'lvl:"m"', seg))
progs = len(re.findall(r'\{id:"', seg))
det = len([f for f in os.listdir('details') if f.endswith('.html')])
try:
    http_code = requests.get('http://127.0.0.1:8000/index_main.html', timeout=8).status_code
except Exception:
    http_code = 'ERR'

bl['round'] = 387
bl['timestamp'] = mtime
bl['main_file_mtime'] = mtime
bl['main_file_bytes'] = st.st_size
bl['programs'] = progs
bl['programs_unique_ids'] = len(set(re.findall(r'\{id:"([^"]+)"', seg)))
bl['phd'] = phd
bl['master'] = mas
bl['catd'] = 2817
bl['vd'] = 1547
bl['details_on_disk'] = det
bl['dead_links'] = 0
bl['exclude_residue'] = 0
bl['density_grade'] = gc
bl['density_redo'] = gc['B'] + gc['C']
bl['http'] = http_code

NEW_NOTES = [
 'r387 新通道（UCSD ECE，第二十三）：https://ece.ucsd.edu/graduate/graduate-admissions、/graduate/phd-degree-requirements、/graduate/financial-support 全 200；Fall 2027 网申 2026-09-02 开放、PhD 2026-12-16 23:59 PT / MS 2027-01-06、仅秋季、GRE 不要求、TOEFL 4.5 新制/85 旧制码 4836、IELTS 7.0、DET 120、PTE 65、WHED 豁免、GPA 3.0、3 封推荐信、SOP ≤2MB、impacted majors（Computer Engineering / Electronic Circuits and Systems / Intelligent Systems Robotics and Control / Machine Learning and Data Science）录后不可转、UCSD 在读 MS 不得申 ECE MS 但可申 PhD；博士 48 units（12 门 quarter 课、≥36 研究生课）2 年内修完、导师第一年末定、Prelim 第二年末、UQE 预考后约一年、委员会 ≥5 人（≥3 ECE、≥2 外领域含 1 外系终身）、规范 6 年/资助 7 年/注册 8 年；资助 Fellowship / TA-Reader-Tutor / 20h GSR（salary+tuition+fees）。/graduate/courses 403。',
 'r387 新通道（UCSD MAE/CSE/BioSci，第二十四）：MAE 真页在 https://maeweb.ucsd.edu/grad/graduate-admissions（mae.ucsd.edu/admissions 仅导航、/graduate 404）：PhD 「Applications for Fall 2027 are closed」（2026-12-04 抓取）、MS 2026-09-02–2027-01-13、仅秋季、GRE optional 无最低（录取者 quant 85–90 percentile，码 4836）、TOEFL 4.5/85、纸笔 64、IELTS 7、DET 120、PTE 65、GPA 3.0 典型 3.5、3 封推荐信、可本科直博、博士约 $3,600/月 + 学费杂费、MS 几无资助。CSE：https://cse.ucsd.edu/graduate/admissions、/graduate/degree-programs/phd（/phd-program 404）：2026-09-02–2026-12-16 23:59 PST、仅秋季、GRE 不要求、GPA 3.0、MS/PhD 只能申一个；博士 37 units、10 个 breadth 领域选 4（AI/Bioinformatics/Computer Engineering/Systems&Security/Database/Graphics&Vision/HCI/PL-Compiler-SE/Robotics/Theory）、breadth GPA ≥3.3、CSE 292 必修、5 门 elective（209/229/239/249/259/269/279/289 与 219/290/292/293/294/298/299/500/599 不计）、research exam 第二年末 3 人委员会、TA 1 quarter 50% + CSE 500、candidacy 第三年末预期第四年强制、资助 7 年/注册 8 年。BioSci：https://biosci.ucsd.edu/education/grad/phd/index.html、/admissions.html、/financial-support.html（/curriculum.html 404）：Fall 2027 开放 2026-09-02、截止 2026-12-02 23:59 PST、Zoom 面试 2027-01-14/15/19–22/25、线下 2027-03-04、约 30% 国际生、第一年 core + rotation、Salk 联合 PhD、非居民只付 1 年 NRST（国际生 3 年或至 candidacy）、QE 通过进 candidacy 通常第三年末、$800–$1,000 一作论文奖；GRE/语言项目级分线未列。UCSD 费率页 https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html 仍 200：$4,574/quarter + $448 SSF，州内约 $22,985/年、非居民约 $38,087/年。',
 'r387 新通道（UChicago CS/统计/经济/Booth，第二十五）：CS https://cs.uchicago.edu/academics/phd/、/phd-program-overview/、/academics/admission/（/academics/graduate/phd/ 404）：截止 2026-12-10、$90、3 封推荐信、GRE optional、Key Dates 年份仍写 2026（官网未更新）、三阶段约 6 年、Qualifying→Candidacy→Dissertation Defense、可选 Practicum、11 个研究领域。统计 MS：https://stat.uchicago.edu/academics/ms-in-statistics/、/admission-requirements/（三轮 2026-11-02 / 2027-02-01 / 2027-05-03、$90、GRE optional 与对比表 strongly recommended 并存、Math Subject 不要求、先修微积分+线代+概率统计、实分析/编程建议、30–40 人/年、1/3–1/2 读博）、/statistics-masters-courses/、/careers-in-statistics/、/current-students/ms-student-handbook/（9 门课：STAT30030-30040-32950 或 STAT34300-34700-34800、末门二选一、4 门 regular elective、最多 9 门其他选修含 STAT40100/39900、博士级 C 其余 B、3–6 quarter 最长 24 个月、第二年 Autumn 定导师、第二年 Summer 前交论文 + 1/2 小时 seminar）、/academics/current-students/course-info/。经济 https://economics.uchicago.edu/phd-program、/apply（2026-12-01 23:59 CT）、/financial-support（六年全奖：学费+医保+GSSF+stipend、5 次教学任务含 1 次系外、journal/conference/data 经费）、/program-overview（1 年 core、2 年 fields、3 年起独立研究）。Booth https://www.chicagobooth.edu/phd/dissertation-areas/finance、/phd/admissions/how-to-apply（2026-12-15、$80、每年 20–25 人、只能申 1 个 area、2–4 封推荐信、writing sample ≤30 页可选、GRE 或 GMAT 必交且 Finance GRE 优先、GRE 码 1501、TOEFL 100 或新制 5 且单项 5/IELTS 7 且单项 7、不认 Duolingo、面试 1 月–3 月初）。UChicagoGRAD：https://grad.uchicago.edu/admissions/english-language-requirements/（只认 TOEFL iBT/IELTS Academic、码 1832、Booth 1819、2 年有效、两类 Waiver）、/funding/doctoral/、/admissions/funding/masters/。',
 'r387 关键映射坑（勿再踩）：PROGRAMS 里 `uchicago-stats` 是**统计学硕士（MS）**、lvl="m"，其 url 是 `details/uchicago-statistics.html`（不是 uchicago-stats.html）；本项目库**没有独立 Statistics PhD 条目**（最接近的是 Booth `uchicago-booth-econ-stat-phd` 计量经济学与统计学博士）。本轮首版 spec 误按 PhD 建了 uchicago-stat-phd 页并改了 uchicago-stats 字段，已删除孤儿 `details/uchicago-stat-phd.html` 与 `details/uchicago-stats.html`，改按 MS 口径重做并回填。',
 'r387 不可达 / 易踩（勿重复）：① www.ece.engineering.utoronto.ca 三个 URL 全 ConnectionError；www.statistics.utoronto.ca 与 /graduate 返回 200 但为「Arts and Science JS Challenge」人机页（按规则不破），UT 两条本轮放弃；② ece.ucsd.edu/graduate/courses 403；③ mae.ucsd.edu/graduate 404（真页在 maeweb.ucsd.edu/grad/graduate-admissions）；④ cse.ucsd.edu/graduate/degree-programs/phd-program 404（正确 /degree-programs/phd）；⑤ biosci.ucsd.edu/education/grad/phd/curriculum.html 404；⑥ grad.ucsd.edu 的语言要求两条路径均 404；⑦ cs.uchicago.edu/academics/graduate/phd/ 404；⑧ stat.uchicago.edu/graduate/、/phd/、/curriculum/ 与 /academics/ms-in-statistics/admissions/ 全 404（正确 /admission-requirements/）；⑨ bms.uchicago.edu、graduateprograms.bsd.uchicago.edu、econ.uchicago.edu/graduate/phd 全 ConnectionError（经济改用 economics.uchicago.edu）；⑩ chicagobooth.edu/phd/finance 404；⑪ bursar.uchicago.edu/tuition-and-fees 被 Azure WAF 403、grad.uchicago.edu/admissions/tuition-and-fees 404、physical-sciences.uchicago.edu/graduate/tuition-and-fees 404 —— UChicago 学费未取到官方数额，按「官网未披露」处理。',
 'r387 口径提示：UChicago 课号为 5 位（STAT30030/34300/32950/34800/40100/39900、CS 与 Econ 同类），密度脚本正则只认 3–4 位，故 UChicago 页 codes 计 0 属正常，不因此判低密度；UCSD MAE 官网 PhD Fall 2027 显示 closed，与库内旧「2026-12-15 priority」不一致，回填按「PhD 已关闭、MS 2027-01-13」；UChicago CS Key Dates 通知/访校/接受日期年份仍写 2026，回填保留截止 2026-12-10 并对年份存疑作注；UChicago 统计/经济/CS/Booth 的 stipend 与 tuition 项目级数额均官网未披露。',
]

have = set(bl.get('blocked_notes', []))
for n in NEW_NOTES:
    if n not in have:
        bl.setdefault('blocked_notes', []).append(n)
bl['notes'] = len(bl.get('blocked_notes', []))

bl['actions_this_round'] = [
 '只读基线：final_check 36/1439/2817、死链 0、残留 0；gap_check Top30 30/30；vd_check url 去重 1439 / VD 1547 / 磁盘 3774 / 未进 0 / 缺失 0；node 两块 exit 0；开工主文件 1,992,682 字节 mtime 2026-12-04 10:50:20',
 '选题：UT ECE 系站 ConnectionError、UT 统计站 JS Challenge，两条放弃；改取 UCSD 4 条（ECE/MAE/CSE/BioSci）+ UChicago 4 条（CS PhD / 统计 MS / 经济 PhD / Booth 金融 PhD）',
 '新通道：UCSD ECE 三页 + MAE 真页 + CSE 二页 + BioSci 三页 + 费率页 + 三份课程目录；UChicago CS 三页 + 统计 MS 六页（含 MS 手册）+ 经济四页 + Booth 二页 + UChicagoGRAD 英语/博士资助/硕士资助',
 '建页路径：先写 spec（_r387_specs_ucsd.py / _r387_specs_ucsd2.py / _r387_specs_uc1.py / _r387_specs_uc2.py / _r387_specs_uc3.py），再由 _r387_render.py 统一调用 detail_render.render 落盘，全程未手写 HTML',
 '密度验收：ucsd-ece-phd A 11（4,723 字 / 10 码 / 7 金额 / 4 日期）、ucsd-mae-phd A 11（4,044 / 14 / 8 / 4）、ucsd-cse-phd A 11（4,075 / 11 / 5 / 6）、ucsd-biosci-phd A 9（3,451 / 3 / 4 / 6）、uchicago-cs-phd A 10（3,701 / 0 / 4 / 4）、uchicago-stats A 10（4,178 / 0 / 4 / 4）、uchicago-econ-phd A 9（3,759 / 0 / 0 / 2）、uchicago-booth-fin-phd A 9（3,410 / 1 / 3 / 3）—— 8 条全 A',
 '中途纠错：首版把 uchicago-stats 当 PhD 建页（实际是 MS、url=details/uchicago-statistics.html），已删两个孤儿页（uchicago-stat-phd.html、uchicago-stats.html），改按 MS 口径重写 spec 并渲染到 details/uchicago-statistics.html；econ 首版 8 分（字数 3,392 未过 3,500 线），补 3 条 workshop/job-market/学生资源后 A 9',
 'PROGRAMS 回填 45 处（_r387_apply.py 40 处 + _r387_apply2.py 5 处，备份 index_main.html.bak_r387 / .bak_r387b）：ddl/lang/tui/dur/test 各 9 字段组；test 口径：UCSD ECE opt（不要求）、MAE opt（Optional 无最低）、CSE opt（不要求）、BioSci 官网未披露、UChicago CS opt、统计 MS opt（可选）、经济 官网未披露、Booth req（GRE 或 GMAT 必交）',
 '回填后校验：node 两块 exit 0、36/1439/2817、死链 0、残留 0、VD 1547 未进 0 缺失 0 孤儿 0、details 3774',
 '复跑密度：A 400 → 407、B 100 → 99、C 933、需重做 1,032、rows 1439、缺页 0',
 '8 页终检无「编辑整理」「待补」「TBD」；HTTP 200 且长度与磁盘一致（19,468 / 18,089 / 17,693 / 17,239 / 17,644 / 21,543 / 17,843 / 16,698）；主文件 1,992,682 → 1,983,583 字节',
 '本轮未推送、未贴链接、未输出汇报；结果只写 _heartbeat_baseline.json 与台账',
]

io.open('_heartbeat_baseline.json', 'w', encoding='utf-8').write(json.dumps(bl, ensure_ascii=False, indent=1))
print('round', bl['round'], 'bytes', bl['main_file_bytes'], 'prog', progs, 'phd', phd, 'mas', mas,
      'vd', bl['vd'], 'det', det, 'density', gc, 'redo', bl['density_redo'], 'notes', bl['notes'],
      'actions', len(bl['actions_this_round']), 'http', http_code)

ENTRY = '''- **r387 UCSD 4 条 + UChicago 4 条（ECE PhD / MAE PhD / CSE PhD / BioSci PhD / CS PhD / 统计 MS / 经济 PhD / Booth 金融 PhD）｜2026-12-04**

  - **只读基线**：final_check 36 / 1439 / 2817、死链 0、残留 0；gap_check Top30 30/30；vd_check url 去重 1439 / VD 1547 / 磁盘 3774 / 未进 0 / 缺失 0；node 两块 exit 0。开工主文件 1,992,682 字节（mtime 2026-12-04 10:50:20）。
  - **选题调整**：UT ECE 系站（`www.ece.engineering.utoronto.ca`）三 URL 全 ConnectionError；UT 统计站返回「Arts and Science JS Challenge」人机页（按规则不破）——UT 两条放弃，改取 UCSD 4 条 + UChicago 4 条。
  - **新通道（第二十三至二十五个可复用口）**：① UCSD ECE —— `ece.ucsd.edu/graduate/graduate-admissions`、`/graduate/phd-degree-requirements`、`/graduate/financial-support`（Fall 2027 网申 2026-09-02 开放、PhD 2026-12-16 23:59 PT、MS 2027-01-06、仅秋季、GRE 不要求、TOEFL 4.5 新制/85 旧制码 4836、IELTS 7.0、DET 120、PTE 65、WHED 豁免、GPA 3.0、3 封推荐信、impacted majors 录后不可转；博士 48 units、2 年内修完、Prelim 第二年末、UQE 预考后约一年、委员会 ≥5 人、规范 6 年/资助 7 年/注册 8 年）。② UCSD MAE/CSE/BioSci —— `maeweb.ucsd.edu/grad/graduate-admissions`（PhD Fall 2027 已 closed、MS 2027-01-13、GRE optional 无最低、TOEFL 4.5/85、IELTS 7、DET 120、博士约 $3,600/月）；`cse.ucsd.edu/graduate/admissions`、`/graduate/degree-programs/phd`（37 units、10 breadth 选 4、CSE 292 必修、5 门 elective 有排除清单、research exam 第二年末、candidacy 第四年强制、资助 7 年）；`biosci.ucsd.edu/education/grad/phd/index.html`、`/admissions.html`、`/financial-support.html`（2026-12-02 23:59 PST、Zoom 面试 2027-01-14/15/19–22/25、线下 2027-03-04、第一年 core + rotation、Salk 联合 PhD、非居民只付 1 年 NRST）。费率：`students.ucsd.edu/finances/fees/registration/2026-27/graduate.html`（$4,574/quarter + $448 SSF、州内约 $22,985/年、非居民约 $38,087/年）。③ UChicago —— `cs.uchicago.edu/academics/phd/`、`/academics/admission/`（2026-12-10、$90、GRE optional、三阶段约 6 年）；`stat.uchicago.edu/academics/ms-in-statistics/admission-requirements/`（三轮 2026-11-02 / 2027-02-01 / 2027-05-03、GRE optional 与 strongly recommended 并存）+ `/current-students/ms-student-handbook/`（9 门课：STAT30030-30040-32950 或 STAT34300-34700-34800、4 门 regular elective、3–6 quarter 最长 24 个月、第二年 Summer 前交论文 + seminar）；`economics.uchicago.edu/phd-program/apply`（2026-12-01 23:59 CT）+ `/financial-support`（六年全奖、5 次教学任务）；`chicagobooth.edu/phd/admissions/how-to-apply`（2026-12-15、$80、20–25 人/年、GRE 或 GMAT 必交且 Finance GRE 优先、TOEFL 100 或新制 5、IELTS 7 且单项 7）；UChicagoGRAD `english-language-requirements`、`funding/doctoral`、`admissions/funding/masters`。
  - **实抓口径（择要）**：UCSD ECE 仅秋季、MS 与 PhD 分开截止、现任/前任 UCSD MS 不得申 ECE MS 但可申 PhD；MAE 官网明示 PhD Fall 2027「closed」，与库内旧「2026-12-15 priority」不一致，按官网口径回填；CSE 博士 breadth GPA ≥3.3、CSE 292（1 unit、S/U）必修；BioSci 约 30% 国际生、每年 $800–$1,000 一作论文奖、GRE/语言项目级分线未列。UChicago CS Key Dates 年份仍写 2026（官网未更新），截止按 2026-12-10；统计 MS 招生 30–40 人/年、1/3–1/2 读博、BLS 口径 Data Scientist 中位 $112,590、OR Analyst $91,290；经济 6 年全奖含学费+医保+GSSF+stipend、须 5 次教学任务（1 次可在系外）；Booth 只可申 1 个 area、推荐信 2–4 封、writing sample ≤30 页可选、面试 1 月–3 月初、最多转 3 门课。
  - **建页与验收**：先写 spec（`_r387_specs_*.py` 五个脚本）再由 `_r387_render.py` 调 `detail_render.render` 落盘，未手写 HTML；**8 条全 A**：ucsd-ece-phd 11/11（4,723 字 / 10 码 / 7 金额 / 4 日期）、ucsd-mae-phd 11/11（4,044 / 14 / 8 / 4）、ucsd-cse-phd 11/11（4,075 / 11 / 5 / 6）、ucsd-biosci-phd 9/11（3,451 / 3 / 4 / 6）、uchicago-cs-phd 10/11（3,701 / 0 / 4 / 4）、uchicago-stats 10/11（4,178 / 0 / 4 / 4）、uchicago-econ-phd 9/11（3,759 / 0 / 0 / 2）、uchicago-booth-fin-phd 9/11（3,410 / 1 / 3 / 3）。
  - **中途纠错（重要映射坑）**：`uchicago-stats` 是**统计学硕士（MS）**、lvl="m"，url 为 `details/uchicago-statistics.html`；库内**没有独立 Statistics PhD**（最接近的是 Booth `uchicago-booth-econ-stat-phd`）。首版误按 PhD 建 `uchicago-stat-phd.html` 并改错字段，已删两个孤儿页（`uchicago-stat-phd.html`、`uchicago-stats.html`），按 MS 口径重写 spec 并渲染到 `details/uchicago-statistics.html`。另 econ 首版 8 分（3,392 字未过 3,500），补 workshop/job-market/学生资源三条后 A 9。
  - **回填与校验**：PROGRAMS 回填 45 处（`_r387_apply.py` 40 处 + `_r387_apply2.py` 5 处；备份 `index_main.html.bak_r387`、`.bak_r387b`），ddl/lang/tui/dur/test 口径逐条按官网；test 记：ECE opt（不要求）/ MAE opt（Optional 无最低）/ CSE opt / BioSci 官网未披露 / UChicago CS opt / 统计 MS opt / 经济 官网未披露 / Booth req（GRE 或 GMAT 必交）。回填后 node 两块 exit 0、36 / 1439 / 2817、死链 0、残留 0、VD 1547 未进 0 缺失 0 孤儿 0、details 3774；主文件 1,992,682 → 1,983,583 字节。
  - **密度**：A 400 → **407**、B 100 → **99**、C 933、需重做 1,032（rows 1439、缺页 0）。
  - **新登记卡点 / 待核**：① UT 两条本轮不可达（ECE 系站 ConnectionError、统计站 JS Challenge），后续如需 UT 需换 bulletin/研究生院域名；② `mae.ucsd.edu/graduate`、`cse.ucsd.edu/graduate/degree-programs/phd-program`、`biosci.ucsd.edu/.../curriculum.html`、`stat.uchicago.edu/academics/ms-in-statistics/admissions/`、`econ.uchicago.edu/graduate/phd`、`chicagobooth.edu/phd/finance` 均 404/ConnectionError，正确入口已登记于 notes；③ UChicago 学费页（bursar 403 WAF、PSD 与 UChicagoGRAD 相关路径 404）未取到官方数额，四条 UChicago 页学费一律「官网未披露」，不估算；④ UChicago 课号为 5 位，密度脚本 codes 计 0 属正常（勿据此降级）；⑤ `uchicago-stats` 映射与「无独立统计 PhD」两条须写入下轮选题前置检查。
  - 本轮未推送、未贴链接、未输出汇报。

'''

led = '项目库扩充方案与进度台账.md'
txt = io.open(led, encoding='utf-8').read()
if 'r387 UCSD 4 条' not in txt:
    idx = txt.find('\n## 八、')
    assert idx > 0
    txt = txt[:idx + 1] + ENTRY + txt[idx + 1:]
    io.open(led, 'w', encoding='utf-8').write(txt)
print('ledger bytes', len(io.open(led, encoding='utf-8').read().encode('utf-8')))
