# -*- coding: utf-8 -*-
import io, json, os, re, sys, datetime
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")
html = io.open(P, encoding="utf-8").read()

seg = html[html.index("const PROGRAMS=["):html.index("const CATD=[")]
blocks = [x for x in re.split(r'(?=\{id:")', seg) if x.lstrip().startswith('{id:"')]
catd = html[html.index("const CATD=["):html.index("const VERIFIED_DETAILS=")]
vseg = html[html.index("const VERIFIED_DETAILS=new Set(["):]
vseg = vseg[:vseg.index("])")]
vd = re.findall(r'"([^"]+)"', vseg)
phd = sum(1 for b in blocks if 'lvl:"d"' in b)

st = os.stat(P)
mt = datetime.datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
d = json.load(io.open(os.path.join(BASE, "_density_report.json"), encoding="utf-8"))
gc = d["grade_counts"]

try:
    import requests
    r = requests.get("http://127.0.0.1:8000/index_main.html", timeout=8)
    http = r.status_code
except Exception as e:
    http = "ERR:%s" % e

b = json.load(io.open(os.path.join(BASE, "_heartbeat_baseline.json"), encoding="utf-8"))
b["round"] = b.get("round", 354) + 1
b["timestamp"] = mt
b["schools"] = 36
b["programs"] = len(blocks)
b["programs_unique_ids"] = len(set(re.findall(r'id:"([^"]+)"', seg)))
b["catd"] = len(re.findall(r'\{id:"', catd))
b["vd"] = len(vd)
b["phd"] = phd
b["master"] = len(blocks) - phd
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"] = mt
b["main_file_bytes"] = st.st_size
b["http"] = http
b["density_grade"] = {"A": gc["A"], "B": gc["B"], "C": gc["C"]}

acts = [
 "r355：Duke MAE 建页（details/duke-c529fb8.html，18,514 B，A9：4602/29/0/1/7/5）——30 学分/≥15 经济/2 门理论/1 门计量/3 学分 capstone、ECON 601–707 全套课号、ECON 673↔671 与 674↔678 互斥、MATH 712/719 需 DGS 预批、Portfolio 毕业 + RCR、STEM CIP 45.0603 / 24 个月 OPT；经济系要求 GRE General（代码 5156）；仅秋季、January 14（官网未标年份）",
 "r355：Rice MSTAT 建页（details/rice-statistics.html，16,106 B，A9：3487/3/4/12/7/5）——30 credit hours（≥24 在 Rice）、5 门核心+2–5 门方向+≤9 选修、STAT 518/613/682、3 学期非论文、5 个 specialization；$85 申请费、GRE 建议不强制、GPA 3.0、3 封推荐信；语言按研究生院口径 TOEFL 4.5（旧 90）/IELTS 7/Duolingo 115、ETS 6609",
 "r355：WUSTL MSME 建页（details/wustl-mems-mechanical-engineering-msme.html，17,842 B，A11：4268/13/18/16/7/8）——论文/课程双选项、30 学分、应用数学 6+方向 15+选修 9、≥15 MEMS、≤6 4000 级、MEMS 5000/501/4000/4320/7998、GPA 2.70、转学分 ≤6",
 "r355：WUSTL MEng 建页（details/wustl-mems-mechanical-engineering-meng.html，17,104 B，A11：3874/9/18/16/7/8）——30 units 4000+、≥9 units MEMS 5000 级、≤6 独立研究、≤6 转学分、入学 GPA 2.75、在读 2.70、1–2 年、MEMS 5804、PE 考试不适用的官网提示",
 "r355：字段回填 rice-mstat-2027 共 6 个字段（n/en/dur/ddl/lang/tui）+ test 改 rec（GRE 建议不强制具象化）；备份 index_main.html.bak_r355",
 "r355：WUSTL 学费/截止按官网 2026-27 口径落页——$34,595/学期（$69,190/年，9–21 units）、>21 units $2,883/unit、兼读 $2,450/unit、健康费 $350/学期、活动费 $15/学期、保险 $2,923；Fall 全日制 2027-03-01、早决 2026-12-31、Spring 2026-10-01",
]
b["actions_this_round"] = acts

notes = [
 "r355：UCLA stat.ucla.edu 连续两次 ConnectionError（MASDS 详情页仅能从 grad.ucla.edu 拿到项目壳信息，无课程/学费）→ ucla-masds 本轮未推进",
 "r355：Cornell BEE 系站 bee.cornell.edu / www.bee.cornell.edu 均 ConnectionError，cals.cornell.edu/academics/graduate/fields 404 → cornell-bee-meng 本轮未推进",
 "r355：UNC stat.unc.edu ConnectionError → unc-stats-ds 本轮未推进",
 "r355：Duke gradschool.duke.edu 全路径 404（返回 376KB 反爬页），学费/截止/语言最低分无法从研究生院侧取到；econ.duke.edu 侧仅给 January 14（无年份）与“见 Graduate School”",
 "r355：Duke econ.duke.edu/graduate、/ma、/masters/degrees/ma-economics、/academics/graduate-programs、/masters-programs/for-prospective-applicants 均 404，可用路径为 /masters-programs/degree-programs/ma-econ 与 /masters-program/for-prospective-applicants",
 "r355：Rice 学费页 statistics.rice.edu/.../tuition、graduate.rice.edu/tuition-fees、registrar.rice.edu 均 406（疑似 UA/WAF 拦截）→ MSTAT 学费按「官网未披露」终态",
 "r355：WUSTL MEMS 研究领域页 faculty-research/research-areas 403 / .html 404，改用系内导航与研究生项目页表述",
 "r355：Duke econ.duke.edu/courses/all-courses 404，改用 econ.duke.edu/courses（200，2.2 万字，含 ECON 101–201 课号）",
 "r355：Rice MSTAT 截止表版式粘连（internal/domestic/4+1 三列混排），页面按原文分项照录并在正文提示以官网当期为准",
]
for n in notes:
    if n not in b["blocked_notes"]:
        b["blocked_notes"].append(n)
b["blocked_notes"] = list(dict.fromkeys(b["blocked_notes"]))

json.dump(b, io.open(os.path.join(BASE, "_heartbeat_baseline.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

LE = os.path.join(BASE, "项目库扩充方案与进度台账.md")
s = io.open(LE, encoding="utf-8").read()
entry = ("- **r355 热门 4 条批次（2026-12-03，4 条全部 A）**：新打通 Duke econ.duke.edu 硕士通道（/masters-programs/degree-programs/ma-econ、/masters-program/for-prospective-applicants）、"
 "Rice statistics.rice.edu（MSTAT 项目页）+ graduate.rice.edu 语言口径、WUSTL mems.wustl.edu（MS/MEng 项目页）+ engineering.washu.edu 截止/学费两页。"
 "建页 4 条全由 detail_render.py 生成（旧页 .bak_r355）：duke-ma-econ（30 学分/≥15 经济/2 理论+1 计量+capstone、ECON 601–707 全套、ECON 673↔671 与 674↔678 互斥、Portfolio+RCR、STEM CIP 45.0603、GRE General 必交代码 5156、仅秋季 January 14）／"
 "rice-mstat-2027（30 credit hours≥24 在 Rice、5 核心+方向+≤9 选修、STAT 518/613/682、3 学期非论文、$85、GRE 建议不强制、TOEFL 4.5 旧 90/IELTS 7/Duolingo 115、ETS 6609）／"
 "wustl-mems-msme（论文/课程双选项、30 学分 6+15+9、≥15 MEMS、≤6 4000 级、MEMS 5000/501/4000/4320/7998、GPA 2.70）／"
 "wustl-mems-meng（30 units 4000+、≥9 units MEMS 5000、≤6 独立研究/转学分、入学 2.75 在读 2.70、1–2 年、MEMS 5804、PE 提示）。"
 "密度 A 179→183、B 170→166、C 1091 不变，需重做 1261→1257；rice-mstat-2027 回填 6 字段 + test rec；WUSTL 学费按官网 2026-27：$34,595/学期（$69,190/年）、>21 units $2,883/unit、兼读 $2,450/unit、健康费 $350/学期、活动费 $15/学期、保险 $2,923；"
 "截止 Fall 全日制 2027-03-01、早决 2026-12-31、Spring 2026-10-01。校验：node exit 0、院校 36 / PROGRAMS 1440 / CATD 2817、死链 0、残留 0、VD 未进 0 / 孤儿 0、details 3775、HTTP 200。"
 "新增卡点：UCLA stat.ucla.edu 双次连接失败、Cornell BEE 双域名连接失败、UNC stat.unc.edu 连接失败、Duke gradschool 全路径 404、Rice 学费页 406、WUSTL research-areas 403、Duke courses/all-courses 404。\n\n")
i = s.index("## 八、")
s = s[:i] + entry + s[i:]
io.open(LE, "w", encoding="utf-8", newline="").write(s)

print("round", b["round"], "progs", b["programs"], "vd", b["vd"], "catd", b["catd"], "A", gc["A"], "B", gc["B"], "C", gc["C"], "bytes", st.st_size, "http", http, "notes", len(b["blocked_notes"]), "ledger", os.path.getsize(LE))
