# -*- coding: utf-8 -*-
"""r381 收尾：baseline（round=381）+ 台账条目。"""
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'] = 381
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 = [
    'r381 新通道（Georgia Tech 四件套，全部 200）：① https://catalog.gatech.edu/programs/{slug}/ 是 2026-2027 Edition 学位页，正文给「Course List Code Title Hours」学分表与考核条款（PhD/MS 同页可查），slug 形如 electrical-computer-engineering-phd / mechanical-engineering-phd / bioinformatics-ms / master-biomedical-innovation-development / building-construction-facility-management-ms / master-sustainable-energy-environmental-management / chemical-engineering-phd；项目总索引 https://catalog.gatech.edu/programs/ 可抽全部 slug；② https://grad.gatech.edu/english-proficiency 给 GT 机构线（TOEFL 旧制 90/各项 19、2026-01-21 起新制 4.5（R/L/W ≥4、S ≥3.5）；IELTS 7.0（R/L/S ≥6.5、W ≥5.5）；机构码 5248；不收 Duolingo/PTE/Essentials/MyBest；IELTS One Skill Retake 可用），并明确 **2027 秋季起公民身份不再豁免语言**；③ https://www.usg.edu/fiscal-affairs/tuition-and-fees/ 挂 FY2027 Appendix IIB 研究生学费 PDF（Georgia Tech：每学期 $7,280 州内 / $16,073 州外 / $16,540 境外；不足 12 学分按学分 $607 / $1,341 / $1,379），是 bursar 被 403 时的官方替代；④ https://grad.gatech.edu/theses-dissertations-deadlines 给逐学期 ISO 论文节点（2026 秋 2026-12-11 12:00、2027 春 2027-04-30 12:00、2027 秋 2027-12-10 12:00）',
    'r381 不可达（勿重复踩）：bursar.gatech.edu 与 www.bursar.gatech.edu 全 403（78 字节裸页）；osfa.gatech.edu 403（Red Hat test page）；coe.gatech.edu、chbe.gatech.edu、www.chbe.gatech.edu、bme.gatech.edu 均 403 78 字节；gradadmissions.gatech.edu 直接 ConnectionError；ece.gatech.edu/graduate、/academics/graduate、/graduate-programs 均 404（正确入口 ece.gatech.edu/future-students/graduate-admissions）；me.gatech.edu/graduate、/academics/graduate、/graduate-admissions、/deadlines 均 404（正确入口 me.gatech.edu/graduate-program → /admissions-1、/masters-degree-program、/phd-degree-program）；grad.gatech.edu/programs、/admissions/checklist、/paying-grad-school 均 404；mseem.gatech.edu 域名 ConnectionError（MSEEM 内容在 spp.gatech.edu/masters/mseem）',
    'r381 口径（GT ECE PhD）：Atlanta 秋季 2026-12-16 23:59 ET（全部 ECE PhD/MS）、MS Robotics 2027-02-01、GT-Europe 秋 MS 2027-03-01 / 春 MS 2026-10-01、Distance Learning 秋 2027-05-01 / 春 2026-09-01；GRE Optional（提交才看，机构码 R5248 dept 1203，5 年有效）；43 学分 = Group I 9 + II 9 + III 辅修 9（ECE 外单一学科，管理类不批）+ IV 选修 14（可用 ≤12 学分 MS thesis 充抵）+ ECE 8022 1 + PHIL 6000 1；两学期全日制驻校、GT 内 ≥9 学分字母成绩、GPA 3.0 且辅修 3.0、candidacy 后 7 年；综合考 = Coursework Qualifier（TIG 清单 4 门取 3.5 GPA，第二年末前）+ Proposal（第 7 学期末前，不含暑期）',
    'r381 口径（GT ME PhD/MS）：ME 系站不列申请截止（官网未披露，旧块「Jan 10 / Oct 1」无依据已删）；博士 36 学期学分 + ≥6 学分字母成绩辅修，GPA 3.3（资格考报名亦需 3.3），ME 6753/6789/6799 不能算辅修，硕士论文同领域可抵 9 学分；Seminar 8014（2 学分、22 场/学分、不计入 36）+ Teaching Practicum ME/NRE 7757（3 学分、毕业学期不得修）+ PHIL 6000；资格考 1 小时口试（3 篇指定论文、rubric 三档、可重考一次），持硕士 1 年内 / 本科直博 2 年内；提案后 ≥6 个月才能答辩；硕士 30 学分（非论文 Major 21 + Minor 6 + Math 3；论文 12 + 9 thesis + 6 + 3），仅 6 学分可为 4000 级，Math 只认 School of Mathematics；BS/MS 需 COE 2001 且 GT GPA ≥3.5、12–24 学分在 GT',
    'r381 口径（GT 职业硕士 4 条）：Bioinformatics 2027-03-01 截止（仅秋季，2026-12-01 前齐料进早申）、36 学分三学期（BIOL 6150/7200/7210 + CS 4400 + CX 4803 + 统计 BIOS 4401 或 MATH 3215 + Capstone 3 + 选修 15）、含暑期全职实习、录取 GPA 3.3–4.0、GRE optional 但建议 V>154/Q>165/AW≥4.0；MBID 2027-01-15（仅秋季，2 月底放榜、4-15 答复、候补 4-7 答复）、GPA 3.0/专业 3.25、GRE 不要求、TOEFL 100（各项 19）/IELTS 7.0（6.5×3+5.5）、36 学分 = BMED 6501–6508 各 3 + 6509 6 + 选修 6、12 个月连续；MSBCFM 秋早 2027-01-15 / 国际生晚 2027-04-01 / 美国晚 2027-05-01、春早 2026-07-15 / 国际生晚 2026-09-01 / 美国晚 2026-10-01、GRE 优先不强制、30 学分双轨（核心 BC 6650/6550/6250/6300/6685 + 论文 BC 7100 3 + thesis 6 + 选修 6；非论文 concentration 12 + 选修 3）、晚间授课；MSEEM 优先 2027-02-15（含资助）/最终 2027-03-15、仅秋季、放榜 ≤2027-05-01、GRE strongly recommended、30 学分 = PUBP 6312 + 6360 + 6801(6) + 定量 6 + 方向 9 + 政策管理 3、全日制 1 年（4-4-2）或在职 2 年（2-2-1）、班额约 30、Byers Fellowship $90,000 stipend 每届 ≤5 人',
    'r381 口径（GT ChBE PhD）：五门 3 学分核心 CHBE 6100/6200/6260/6300/6500 须 GPA ≥3.2、累计 GPA ≥3.0；CHBE 6001 1 + CHBE 6003 1 + 选修 3 + 辅修 9；Professional Preparation 10 单元、3 学期教学（每周 5 小时）、第四年 Colloquium；QE 第二学期（可再考一次）、提案第二学年春、predoctoral review 答辩前 ≥6 个月、答辩公开并全校公告；**系站 403，申请截止与 GRE 政策官网未披露**',
    'r381 坑（old 数据与官网冲突，已改写）：gatech-ece-phd 旧 test.cls 塞整段英文（徽章/筛选双失效）；gatech-me-phd 旧 ddl「Fall 2027: January 10, 2027 / Spring: October 1, 2026」、旧 test「GRE TEMPORARILY WAIVED for 2023」均无现页依据，已改「官网未披露」；gatech-msbinf 旧 ddl「Fall: Feb 1 (year TBD)」实为 2027-03-01；gatech-mbid 旧 ddl「catalog 页未列具体轮次（待补）」实为 2027-01-15；gatech-msbcfm 旧 tui「待补」、旧 dur「1-2 年」已按 30 学分双轨重写；gatech-mseem 旧 test 写「GRE general required」错（官网为 strongly recommended），旧 tui「申请费 $75/$85」未获官网证据已删；gatech-chbe-phd 旧 test 长英文已清',
    'r381 新登记卡点：① ME PhD/MS 与 ChBE PhD 的申请截止官网均未披露（ME 系站无截止页、ChBE 系站 403），已在页面写「官网未披露」并以研究生院论文节点补日期；② 上述两条 GRE 政策亦未披露，PROGRAMS test.cls 先记 opt（可选未强制），待系站可达后核实；③ GT 申请费金额未在已抓页面披露（官方只列免除条件，不含金额）',
]

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、榜外保留 nyu/illinois/ut/ubc/mcg/uw；vd_check url 去重 1439 / VD 1547 / 磁盘 3775 / 未进 0 / 孤儿 0 / 缺失 0；node_check 1 块 exit 0；开工主文件 1,982,646 字节 mtime 2026-12-04 04:06:12',
    '候选：gatech 热门非 A 共 7 条，全部纳入 —— ece-phd(C)、me-phd(B)、chbe-phd(C)、msbinf(C)、mbid(C)、msbcfm(C)、mseem(C)；gatech-me-ms 已为 A，不重做',
    '新通道：catalog.gatech.edu 学位页（2026-2027 Edition，课程代码+学分表+考核条款）+ grad.gatech.edu/english-proficiency（机构语言线 + 2027 秋公民身份不再豁免）+ usg.edu FY2027 Appendix IIB（每学期 $7,280/$16,073/$16,540，学分 $607/$1,341/$1,379）+ grad.gatech.edu 论文节点四件套',
    '逐条实抓并建 7 spec（_r381_specs/），每页 10 卡（申请要求/截止/标化/课程/培养/毕业/费用/录取就业/城市/官方链接），每页 6 条官方外链；全部 detail_render 生成',
    '密度验收：7 条首版全 A、全部 11 分 —— ece-phd（5,678 字/14 课号/18 金额/15 日期）、me-phd（4,360/20/16/8）、msbinf（3,915/17/10/11）、mbid（3,599/15/10/6）、msbcfm（4,153/9/10/16）、mseem（5,069/51/11/14）、chbe-phd（4,103/18/12/8）；无重做',
    'PROGRAMS 回填 35 处（_r381_apply.py，备份 index_main.html.bak_r381）：ddl/lang/tui/dur/test 各 7；test.cls = ece-phd opt、me-phd opt、chbe-phd opt、msbinf rec、mbid notreq、msbcfm rec、mseem rec；同时清掉 ece-phd / chbe-phd 塞在 test.cls 里的长英文',
    '回填后校验：node exit 0、36/1439/2817、死链 0、残留 0、VD 1547 未进 0、孤儿 0、缺失 0、details 3775',
    '复跑密度：A 365 → 372、B 99 → 98、C 975 → 969、需重做 1074 → 1067、rows 1439；主文件 1,982,646 → 1,983,354 字节',
    '7 页终检无「编辑整理」「待补」「TBD」；HTTP 200 且长度与磁盘一致',
    '本轮未推送、未贴链接、未输出汇报；结果只写 _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 = '''- **r381 Georgia Tech 热门 7 条（ECE PhD / ME PhD / ChBE PhD / Bioinformatics MS / MBID / MSBCFM / MSEEM）｜2026-12-04**

  - **只读基线**：final_check 36 / 1439 / 2817、死链 0、残留 0；gap_check Top30 30/30、榜外保留 nyu/illinois/ut/ubc/mcg/uw；vd_check url 去重 1439 / VD 1547 / 磁盘 3775 / 未进 0 / 孤儿 0 / 缺失 0；node_check exit 0。开工主文件 1,982,646 字节（mtime 2026-12-04 04:06:12）。
  - **换校理由**：gatech 在库 101 条，热门非 A 恰 7 条全部闭环；`gatech-me-ms` 已为 A（7 卡 / 3,045 字）不再重做。
  - **新通道（第八个可复用口）**：① `catalog.gatech.edu/programs/` 是 2026-2027 Edition 学位页，正文直接给「Course List Code Title Hours」学分表与考核条款（博士/硕士同页可查），项目索引可批量抽 slug；② `grad.gatech.edu/english-proficiency` 给机构语言线（TOEFL 旧制 90/各项 19，2026-01-21 起新制 4.5（R/L/W ≥4、S ≥3.5）；IELTS 7.0（R/L/S ≥6.5、W ≥5.5）；机构码 5248；不收 Duolingo/PTE/Essentials/MyBest），并明确 **2027 秋季起公民身份不再豁免语言**；③ `usg.edu/fiscal-affairs/tuition-and-fees/` 的 FY2027 Appendix IIB 是 bursar 403 时的官方学费替代（GT 每学期 $7,280 州内 / $16,073 州外 / $16,540 境外；学分 $607/$1,341/$1,379）；④ `grad.gatech.edu/theses-dissertations-deadlines` 给逐学期 ISO 论文节点（2026-12-11 / 2027-04-30 / 2027-12-10，均 12:00）。
  - **实抓口径（择要）**：ECE 博士 Atlanta 秋季 2026-12-16 23:59 ET（全部 ECE PhD/MS）、MS Robotics 2027-02-01、GT-Europe 秋 MS 2027-03-01、DL 秋 2027-05-01；GRE Optional；43 学分 = Group I 9 + II 9 + III 辅修 9 + IV 选修 14 + ECE 8022 1 + PHIL 6000 1，两学期驻校、GPA 3.0、candidacy 后 7 年，QE 为 TIG 清单 4 门取 3.5 GPA（第二年末前）+ Proposal（第 7 学期末前）。ME 博士 36 学分 + ≥6 学分辅修、GPA 3.3、Seminar 8014（22 场/学分）+ ME 7757（3 学分）+ PHIL 6000，QE 1 小时口试可重考一次、提案后 ≥6 个月答辩；ME 硕士 30 学分双轨（非论文 21+6+3；论文 12+9+6+3），仅 6 学分可 4000 级、Math 只认数学系；Woodruff 官网列 90% 博士获 GRA/GTA、30% 硕士获资助，月薪 $2,500/$2,400（Fall 2022 档）。ChBE 博士五门 3 学分核心 GPA ≥3.2、累计 3.0，CHBE 6001/6003 + 选修 3 + 辅修 9，QE 第二学期、提案第二学年春、预审答辩前 ≥6 个月。Bioinformatics 2027-03-01 截止、2026-12-01 前齐料进早申，36 学分三学期（BIOL 6150/7200/7210、CS 4400、CX 4803、BIOS 4401 或 MATH 3215、Capstone 3、选修 15），暑期全职实习，录取 GPA 3.3–4.0。MBID 2027-01-15、仅秋季、GPA 3.0/专业 3.25、GRE 不要求、TOEFL 100/IELTS 7.0，36 学分 = BMED 6501–6508 各 3 + 6509 6 + 选修 6，12 个月连续。MSBCFM 秋早 2027-01-15、国际生晚 2027-04-01、美国晚 2027-05-01（春 2026-07-15/09-01/10-01），GRE 优先不强制，30 学分（核心 BC 6650/6550/6250/6300/6685；论文 + BC 7100 3 + thesis 6 + 选修 6；非论文 concentration 12 + 选修 3），晚间授课。MSEEM 优先 2027-02-15（含资助）/最终 2027-03-15、仅秋季、放榜 ≤2027-05-01，GRE strongly recommended，30 学分（PUBP 6312 + 6360 + 6801 6 + 定量 6 + 方向 9 + 政策管理 3），全日制 1 年（4-4-2）或在职 2 年（2-2-1），班额约 30，Byers Fellowship $90,000 stipend 每届 ≤5 人。
  - **建页与验收**：7 页全部 `detail_render.py` + `_tpl_detail.html` 生成（spec 存 `_r381_specs/`），每页 10 卡（申请要求/截止/标化/课程/培养/毕业/费用/录取就业/城市/官方链接），**首版即全 A、全部 11 分**：ece-phd（5,678 字 / 14 课号 / 18 金额 / 15 日期）、me-phd（4,360 / 20 / 16 / 8）、msbinf（3,915 / 17 / 10 / 11）、mbid（3,599 / 15 / 10 / 6）、msbcfm（4,153 / 9 / 10 / 16）、mseem（5,069 / 51 / 11 / 14）、chbe-phd（4,103 / 18 / 12 / 8）。全页无「编辑整理」「待补」「TBD」，HTTP 200 且长度与磁盘一致。
  - **回填与校验**：PROGRAMS 回填 35 处（ddl/lang/tui/dur/test 各 7；test.cls = ece-phd opt、me-phd opt、chbe-phd opt、msbinf rec、mbid notreq、msbcfm rec、mseem rec），备份 `index_main.html.bak_r381`。回填后 node exit 0、36 / 1439 / 2817、死链 0、残留 0、VD 1547 未进 0、孤儿 0、缺失 0、details 3775；主文件 1,982,646 → 1,983,354 字节。
  - **密度**：A 365 → **372**、B 99 → **98**、C 975 → **969**、需重做 1074 → **1067**（rows 1439）。
  - **旧数据冲突（已改写，登记备查）**：`gatech-me-phd` 旧 ddl「January 10, 2027 / October 1, 2026」与旧 test「GRE TEMPORARILY WAIVED for 2023」无现页依据，已改「官网未披露」；`gatech-msbinf` 旧 ddl「Feb 1 (year TBD)」实为 2027-03-01；`gatech-mbid` 旧 ddl「catalog 页未列具体轮次（待补）」实为 2027-01-15；`gatech-msbcfm` 旧 tui「待补」、旧 dur「1-2 年」已按 30 学分双轨重写；`gatech-mseem` 旧 test「GRE general required」错（官网为 strongly recommended）、旧 tui「申请费 $75/$85」无证据已删；`gatech-ece-phd` 与 `gatech-chbe-phd` 旧 test.cls 内长英文已清（会致徽章与筛选双失效）。
  - **新登记卡点**：① ME PhD/MS 与 ChBE PhD 的申请截止官网均未披露（ME 系站无截止页、ChBE 系站 403），页面按「官网未披露」处理并以论文节点补日期；② 上述两条 GRE 政策亦未披露，`test.cls` 先记 opt 待核；③ GT 申请费金额未在已抓页面披露；④ 不可达站点：bursar.gatech.edu、osfa.gatech.edu、coe/chbe/bme.gatech.edu 全 403（78 字节），gradadmissions.gatech.edu ConnectionError，grad.gatech.edu/programs 404。
  - 本轮未推送、未贴链接、未输出汇报。

'''

led = '项目库扩充方案与进度台账.md'
txt = io.open(led, encoding='utf-8').read()
if 'r381 Georgia Tech 热门 7 条' 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')))
for i, l in enumerate(io.open(led, encoding='utf-8').read().split('\n'), 1):
    if l.startswith('## 八、'):
        print('## 八、 line', i)
        break
