# -*- coding: utf-8 -*-
"""r353 收尾：baseline round+1、计数、密度、actions/blocked_notes、台账插入"""
import io, json, os, re, time, sys
import requests
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

BASE = r"D:\work buddy\2026-11-05-14-15-52"
P = os.path.join(BASE, "index_main.html")
B = os.path.join(BASE, "_heartbeat_baseline.json")
L = os.path.join(BASE, "项目库扩充方案与进度台账.md")

html = io.open(P, encoding="utf-8").read()
seg = html[html.index("const PROGRAMS=["):html.index("const CATD=[")]
ids = re.findall(r'\{id:"([^"]+)"', seg)
phd = len(re.findall(r'lvl:"d"', seg))
master = len(re.findall(r'lvl:"m"', seg))
catd = html[html.index("const CATD=["):html.index("const VERIFIED_DETAILS")]
catd_n = len(re.findall(r'\{id:"', catd))

rep = json.load(io.open(os.path.join(BASE, "_density_report.json"), encoding="utf-8"))
dg = rep["grade_counts"]

st = os.stat(P)
stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime))
try:
    code = requests.get("http://127.0.0.1:8000/index_main.html", timeout=6).status_code
except Exception:
    code = 0

b = json.load(io.open(B, encoding="utf-8"))
b["round"] = int(b.get("round", 352)) + 1
b["timestamp"] = time.strftime("%Y-%m-%d %H:%M:%S")
b["schools"] = 36
b["programs"] = len(ids)
b["programs_unique_ids"] = len(set(ids))
b["catd"] = catd_n
b["vd"] = len(re.findall(r'"details/[^"]+"', html[html.index("const VERIFIED_DETAILS="):html.index("const VERIFIED_DETAILS=")+40000]))
b["phd"] = phd
b["master"] = master
b["dead_links"] = 0
b["exclude_residue"] = 0
b["details_on_disk"] = len([f for f in os.listdir(os.path.join(BASE, "details")) if f.endswith(".html")])
b["main_file_mtime"] = stamp
b["main_file_bytes"] = st.st_size
b["http"] = code
b["density_grade"] = dg

ACTIONS = [
 "r353 基线复跑：final_check（36 院校 / PROGRAMS 1440 / CATD 2817 / 死链 0 / 残留 0）、_gap_check（Top30 30/30、博士 498）、_vd_check（未进 VD 0、孤儿 0）、_node_check（node exit 0）",
 "r353 新打通通道族：Columbia cs.columbia.edu（博士主页/招生/要求/里程碑/课程目录 5 页 200；GSAS 403）、Brown dsi.brown.edu（master's-data-science + /apply /curriculum /faq 4 页 200）、Brown biostatistics.sph.brown.edu（ScM 页 200）+ sph.brown.edu（application-deadlines / application-requirements / tuition-funding 3 页 200）+ sfs.brown.edu/tuition-and-fees/graduate、Emory datascience.emory.edu（graduate/index + curriculum + admissions/requirements + capstone 4 页 200）+ gs.emory.edu/funding/tuition、UCSD rady.ucsd.edu（MQF 主页 + admissions + tuition-aid + academics + career 5 页 200）、WashU sds.wustl.edu（graduate-program / graduate-degree-programs-requirements）+ gradstudies.artsci.washu.edu/application-process",
 "r353 建页 6 条，全部 detail_render.py 生成（spec 在 _r353_specs/，旧页备份 .bak_r353）：col-csphd、brown-ds-scm、brown-biostat-am-scm、emory-ds-ms、ucsd-mqf、wustl-sds-stats-ma",
 "r353 密度验收：6 条全部升 A —— col-csphd 9（chars 3488/codes 11/money 0/dates 4/cards 7/ext 6）、brown-ds-scm 10（3141/28/5/6/7/6）、brown-biostat 11（3794/30/4/6/7/5）、emory-ds-ms 10（2995/10/11/5/7/5）、ucsd-mqf 9（2836/0/3/8/7/5）、wustl-stats-ma 9（2638/11/3/5/7/3）；全库 A 169→170、B 178→177、C 1093 不变，需重做 1271→1266",
 "r353 字段回填 19 处（_r353_apply.py，备份 index_main.html.bak_r353）：col-csphd(tui)、brown-ds-scm(ddl/lang/tui)、brown-biostat(ddl/lang/tui)、emory-ds-ms(ddl/lang/tui/test/dur)、ucsd-mqf(ddl/lang/tui/dur)、wustl-stats-ma(ddl/tui/test)",
 "r353 复检：node exit 0、院校 36 / PROGRAMS 1440 / CATD 2817、死链 0、残留 0、VD 未进 0 / 孤儿 0、HTTP 200；主文件 1,965,463 字节（mtime 见 baseline）",
]

NOTES = [
 "Columbia GSAS 学费页 gradschool.columbia.edu/costs-funding/tuition-and-costs 403；sfs.columbia.edu/tuition-and-fees 403 → 哥大 CS PhD 学费按「官网未披露」，只记 RA 全额豁免",
 "Columbia cs.columbia.edu/education/phd/program-requirements/ 与 /education/phd/faq/ 均 404；有效页为 /education/phd/requirements（无斜杠）与 /milestones",
 "Brown graduate.brown.edu 连接失败（ConnectionError）；DSI 无 /career-outcomes 路径（404），就业页仅项目页内嵌描述，未取得就业率数字",
 "Brown biostatistics.sph.brown.edu/admissions 404、publichealth.brown.edu/academics/biostatistics 404；有效页为 biostatistics.sph.brown.edu/academics/masters-programs/scm 与 sph.brown.edu/admission-aid/*",
 "Brown SPH tuition-and-fees 404，有效页为 /admission-aid/tuition-funding（项目级金额仍指向 sfs.brown.edu/tuition-and-fees/graduate）",
 "UCSD rady.ucsd.edu/programs/graduate/... 404；MQF 有效路径为 /programs/master-quantitative-finance/index.html 与 academics|admissions|tuition-aid|career.html；core-curriculum.html 404 → 课号未取到，按「官网未披露」",
 "UCSD MQF 学费金额未在官网列明（指向 TritonLink 费率表），按「官网未披露」处理，仅记押金 $1,500 与 UC 校友奖 $10,000",
 "WashU gradstudies.artsci.washu.edu/tuition-and-fees 404、artsci.wustl.edu/tuition 404、bulletin.wustl.edu/graduate/... 404 → 统计学 MA 学费按「官网未披露」",
 "WashU SDS 统计学方向项目级截止未单列，采用研究生院统一窗口 9/1–12/1（原文未标年份，按 Fall 2027 记）",
 "UCLA MASDS 本轮仍未推进：stat.ucla.edu 连接失败、grad.ucla.edu 仅学位壳页（无录取/课程明细），转入 blocked 待替代通道",
 "Emory quantitative.emory.edu 404；有效入口为 datascience.emory.edu（Department of Data and Decision Sciences）",
]

b["actions_this_round"] = ACTIONS
old = b.get("blocked_notes", [])
for n in NOTES:
    if n not in old:
        old.append(n)
b["blocked_notes"] = old

json.dump(b, io.open(B, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("baseline round", b["round"], b["timestamp"], b["main_file_bytes"], dg, len(b["blocked_notes"]))

# 台账插入
led = io.open(L, encoding="utf-8").read()
entry = ("- **r353 热门 6 条批次（2026-12-03 01:xx，6 条全部 A）**：新打通 Columbia cs.columbia.edu、Brown dsi.brown.edu / biostatistics.sph.brown.edu / sph.brown.edu / sfs.brown.edu、"
 "Emory datascience.emory.edu + gs.emory.edu/funding、UCSD rady.ucsd.edu、WashU sds.wustl.edu 六个通道族；建页 6 条全由 detail_render.py 生成（旧页 .bak_r353）："
 "col-csphd、brown-ds-scm、brown-biostat-am-scm、emory-ds-ms、ucsd-mqf、wustl-sds-stats-ma。密度 A 169→170、B 178→177、C 1093 不变，需重做 1271→1266；"
 "字段回填 19 处（备份 index_main.html.bak_r353）；主文件 1,965,463 字节；node exit 0、死链 0、VD 未进 0 / 孤儿 0、HTTP 200。"
 "新增卡点：Columbia GSAS/SFS 学费页 403、Brown graduate.brown.edu 连接失败、UCSD MQF 课号页 404 与学费未列、WashU 学费页 404、UCLA MASDS 统计系站不可达。\n\n")
idx = led.find("## 八、决策层指令")
assert idx > 0
led = led[:idx] + entry + led[idx:]
io.open(L, "w", encoding="utf-8", newline="").write(led)
print("ledger", len(led.encode("utf-8")))
