#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第一百三十九轮：批量落库 5 条半核验详情页（化学/化工/应用物理方向）"""
import re, os, json, sys
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")

# 5 条候选数据（来自云主机预研 batch_137/138）
NEW_ITEMS = [
    {
        "id": "gatech-ms-cheme", "s": "gatech", "n": "化学工程硕士",
        "en": "M.S. in Chemical Engineering", "deg": "MS", "lvl": "m",
        "college": "College of Engineering · School of Chemical & Biomolecular Engineering",
        "stem": 1, "disc": "chem", "dur": "待查",
        "ddl": "2027-01-15（Fall only；PhD 截止 1/4）",
        "lang": "TOEFL iBT 90（小分≥19）/ IELTS 7.0（R/L/S 6.5，W 5.5）",
        "test": "GRE 不接受（系里明确 no longer accepts GRE scores）",
        "tui": "约 $32,116/年（Fall 2026 out-of-country 12+ credits $16,058/semester）",
        "url": "details/gatech-ms-cheme.html",
        "official": "https://www.chbe.gatech.edu/",
        "req": "Fall 2027 申请 2027/1/15；3 封推荐信；申请费国际生 $85",
    },
    {
        "id": "umich-ms-chemistry", "s": "umich", "n": "化学硕士",
        "en": "M.S. in Chemistry", "deg": "MS", "lvl": "m",
        "college": "College of Literature, Science, and the Arts (LSA)",
        "stem": 1, "disc": "chem", "dur": "待查",
        "ddl": "2027-02-15（Fall only；PhD 截止 12/1）",
        "lang": "TOEFL iBT 84（Rackham standard；2026/1/21 后新制 4.5）",
        "test": "GRE 不要求（will NOT be used in admissions）",
        "tui": "学生自付（MS 不提供 funding）；out-of-state 待查精确数字",
        "url": "details/umich-ms-chemistry.html",
        "official": "https://lsa.umich.edu/chem/",
        "req": "分 course-only 与 research-based 两个 track；research track 需至少 1 封直接评价研究能力的推荐信；项目代码 00119",
    },
    {
        "id": "cornell-ms-aep", "s": "cornell", "n": "应用物理硕士",
        "en": "M.S. in Applied Physics", "deg": "MS", "lvl": "m",
        "college": "Duffield College of Engineering · School of Applied and Engineering Physics",
        "stem": 1, "disc": "phys", "dur": "2 年",
        "ddl": "2026-12-15（Fall only，无春季入学）",
        "lang": "TOEFL iBT（Grad School 最低：W 20 / L 15 / R 20 / S 22；物理系要求口语≥23）/ IELTS Academic",
        "test": "GRE 不要求、不考虑（系里明确 does not require, and will not consider, GRE scores）",
        "tui": "待查",
        "url": "details/cornell-ms-aep.html",
        "official": "https://www.duffield.cornell.edu/aep/",
        "req": "2 年制 terminal MS；三大方向：光学/纳米技术/生物技术；2 封推荐信；本科生需物理或工程背景",
    },
    {
        "id": "yale-ms-apphys", "s": "yale", "n": "应用物理硕士",
        "en": "M.S. in Applied Physics", "deg": "MS", "lvl": "m",
        "college": "School of Engineering & Applied Science",
        "stem": 1, "disc": "phys", "dur": "1 年（course-based）",
        "ddl": "2026-12-15 11:59pm ET（Fall only）",
        "lang": "TOEFL iBT 或 IELTS Academic（母语非英语者）",
        "test": "GRE General 与 Physics Subject 均 optional（自 2025 Fall 起不要求）",
        "tui": "1 年学费（MS 不提供 funding，PhD 全奖）",
        "url": "details/yale-ms-apphys.html",
        "official": "https://engineering.yale.edu/academic-study/departments/applied-physics/",
        "req": "1 年制 course-based terminal MS；方向：凝聚态/光学激光/量子科学/量子信息/纳米；决策时间 PhD 早 2 月初、MS 约 2 月中",
    },
    {
        "id": "stanford-ms-apphys", "s": "stanford", "n": "应用物理硕士",
        "en": "M.S. in Applied Physics", "deg": "MS", "lvl": "m",
        "college": "School of Humanities & Sciences · Dept of Applied Physics",
        "stem": 1, "disc": "phys", "dur": "待查（45 units coursework）",
        "ddl": "2026-12-14 11:59pm PST（硬截止，不接受迟交）",
        "lang": "TOEFL iBT（Stanford 研究生院标准，约 100+）",
        "test": "GRE General + Physics Subject 均 required（2026-27 cycle 明确要求；financial hardship 可申诉但不保证）",
        "tui": "terminal MS 无系里/学校 funding；待查精确数字",
        "url": "details/stanford-ms-apphys.html",
        "official": "https://appliedphysics.stanford.edu/",
        "req": "45 units coursework，无 thesis；纯 course-based terminal MS；Knight-Hennessy Scholars 联合申请 10/6 截止；与 coterm MS（仅限 Stanford 本科生）区分开",
    },
]

# 学校中文名映射
SCHOOL_CN = {
    "gatech":"佐治亚理工", "umich":"密歇根安娜堡", "cornell":"康奈尔",
    "yale":"耶鲁", "stanford":"斯坦福",
}

# 生成详情页 HTML（基于 col-cs.html 模板，半核验页）
def gen_detail_html(item):
    sc = item["s"]
    cn = SCHOOL_CN.get(sc, sc)
    stem_badge = "STEM · OPT 36 个月" if item["stem"] else "非 STEM"
    return f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{item["n"]} · {cn} · 项目详情 | 美加硕士项目查询系统</title>
<style>
:root{{--navy1:#0b2447;--navy2:#19376d;--navy3:#2b5ba8;--gold:#f0a500;--bg:#f5f7fa;--card:#fff;--line:#e3e8f0;--text:#1f2937;--muted:#6b7280;--green:#1e8449;--blue:#2563eb}}
*{{margin:0;padding:0;box-sizing:border-box}}
body{{font-family:"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;background:var(--bg);color:var(--text);font-size:14px}}
a{{color:var(--blue)}}
.hero{{background:linear-gradient(135deg,var(--navy1) 0%,var(--navy2) 55%,var(--navy3) 100%);color:#fff;padding:24px 30px 20px}}
.hero h1{{font-size:21px}}
.hero .en{{font-size:13px;opacity:.85;margin-top:4px}}
.hero .school{{margin-top:8px;font-size:14px;font-weight:600;color:#ffd77a}}
.badges{{margin-top:12px;display:flex;gap:8px;flex-wrap:wrap}}
.badge{{font-size:12px;border-radius:5px;padding:3px 10px;font-weight:700;background:rgba(240,165,0,.25);color:#ffe1a1}}
.wrap{{max-width:900px;margin:20px auto 60px;padding:0 16px}}
.card{{background:var(--card);border-radius:12px;box-shadow:0 2px 10px rgba(15,35,80,.08);border:1px solid var(--line);padding:20px 24px;margin-bottom:16px}}
.card h2{{font-size:16px;color:var(--navy2);border-left:4px solid var(--gold);padding-left:10px;margin-bottom:14px}}
table.kv{{width:100%;border-collapse:collapse;font-size:13px}}
table.kv td{{border:1px solid var(--line);padding:10px 12px;vertical-align:top}}
table.kv td.k{{width:130px;background:#f0f4fa;color:var(--muted);font-weight:600;white-space:nowrap}}
table.kv td.v{{line-height:1.8}}
.note{{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.7}}
.clinks{{margin-top:14px;padding-top:12px;border-top:1px dashed var(--line);display:flex;gap:8px;flex-wrap:wrap}}
.clinks a{{font-size:12px;padding:6px 12px;background:#eef3fb;color:var(--navy2);border:1px solid #cfdcef;border-radius:7px;text-decoration:none;font-weight:600}}
.links a{{display:inline-block;margin:4px 8px 4px 0;padding:8px 14px;background:var(--navy2);color:#fff;border-radius:8px;font-size:13px;text-decoration:none;font-weight:600}}
.foot{{max-width:900px;margin:0 auto 40px;padding:0 16px}}
.yellow{{background:#fff8e1;border-left:4px solid var(--gold);border-radius:8px;padding:12px 16px;font-size:12px;line-height:1.8}}
.back{{display:inline-block;margin-bottom:14px;color:var(--navy2);text-decoration:none;font-size:13px;font-weight:600}}
</style>
</head>
<body>
<div class="hero">
  <h1>{item["n"]}</h1>
  <div class="en">{item["en"]}</div>
  <div class="school">{cn} {item["college"]}（STEM）</div>
  <div class="badges"><span class="badge">{stem_badge}</span><span class="badge">半核验页</span></div>
</div>
<div class="wrap">
  <a class="back" href="../index_main.html">← 返回项目库</a>
<div class="card"><h2>申请要求（2027 申请季 · 官网口径）</h2><table class="kv">
<tr><td class="k">申请截止（2027 学年）</td><td class="v"><b>{item["ddl"]}</b> <a href="{item["official"]}" target="_blank">官网原文 ↗</a></td></tr>
<tr><td class="k">语言要求</td><td class="v">{item["lang"]} <a href="{item["official"]}" target="_blank">官网原文 ↗</a></td></tr>
<tr><td class="k">标化要求</td><td class="v">{item["test"]} <a href="{item["official"]}" target="_blank">官网原文 ↗</a></td></tr>
<tr><td class="k">学术背景</td><td class="v">{item["req"]}</td></tr>
<tr><td class="k">申请材料</td><td class="v">系站不可达、待补（从 bulletin/研究生院总站获取的可达字段已填入上方；精确材料清单待系站恢复后补全）</td></tr>
</table></div>
<div class="card"><h2>费用（学费 · 官网口径）</h2><table class="kv">
<tr><td class="k">学费</td><td class="v">{item["tui"]} <a href="{item["official"]}" target="_blank">官网 ↗</a></td></tr>
<tr><td class="k">生活成本</td><td class="v">系站不可达、待补（按学校所在城市估算：见院校速览卡）</td></tr>
</table></div>
<div class="card"><h2>课程设置</h2><table class="kv">
<tr><td class="k">时长</td><td class="v">{item["dur"]}</td></tr>
<tr><td class="k">方向</td><td class="v">系站不可达、待补（从官网简介获取的方向信息已在上方培养方案中列出）</td></tr>
<tr><td class="k">学位要求</td><td class="v">系站不可达、待补（学分/论文/广度课要求待系站恢复后补全）</td></tr>
</table></div>
<div class="card"><h2>培养方案与项目要点（官网口径）</h2><div style="font-size:13px;line-height:1.9">本页为半核验页：申请截止、语言、标化、学费等可达字段已从学校官网 bulletin/研究生院总站获取；课程设置、精确学分、完整材料清单等待系站恢复后补全。<div class="note">来源：<a href="{item["official"]}" target="_blank">项目官方页</a>（抓取日期 2026-11-24，云主机预研 batch_137/138）。</div></div></div>
<div class="card"><h2>院校与城市速览（编辑整理，供沟通参考）</h2><table class="kv">
<tr><td class="k">📍 城市</td><td class="v">系站不可达、待补（按学校所在城市常规整理：见学校官网）</td></tr>
<tr><td class="k">💼 就业环境</td><td class="v">系站不可达、待补</td></tr>
</table><div class="note">ℹ️ 本卡为编辑整理内容，待系站恢复后补全。</div></div>
<div class="card links"><h2>官方链接</h2><a href="{item["official"]}" target="_blank">🔗 项目官方页面</a></div>
</div>
<div class="foot">
  <div class="yellow">📋 数据说明：本页为<b>半核验页</b>，可达字段已填入官网口径；系站不可达字段已明确标注"待补"，不做估算填充。待系站恢复后升级为完整核验页。</div>
</div>
</body>
</html>'''

# 1. 生成详情页
for item in NEW_ITEMS:
    html_path = item["url"]
    if os.path.exists(html_path):
        print(f"[SKIP] 已存在: {html_path}")
        continue
    html = gen_detail_html(item)
    with open(html_path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] 生成: {html_path} ({len(html)} bytes)")

# 2. 追加 PROGRAMS（括号深度匹配）
html = open("index_main.html", encoding="utf-8").read()

# 找到 PROGRAMS 数组结束位置
m = re.search(r"const PROGRAMS\s*=\s*\[", html)
if not m:
    print("[ERR] 未找到 PROGRAMS 数组"); sys.exit(1)
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    if html[i] == '[': depth += 1
    elif html[i] == ']': depth -= 1
    i += 1
# i 现在指向 ] 的下一个字符
end_pos = i - 1  # ] 的位置

# 构造新记录
new_records = []
for item in NEW_ITEMS:
    # 检查是否已存在
    if f'id:"{item["id"]}"' in html:
        print(f"[SKIP] PROGRAMS 已存在: {item['id']}")
        continue
    rec = f'{{id:"{item["id"]}",s:"{item["s"]}",n:"{item["n"]}",en:"{item["en"]}",deg:"{item["deg"]}",lvl:"{item["lvl"]}",stem:{item["stem"]},dur:"{item["dur"]}",ddl:"{item["ddl"]}",lang:"{item["lang"]}",test:{{cls:"{item["test"]}"}},tui:"{item["tui"]}",url:"{item["url"]}"}}'
    new_records.append(rec)

if new_records:
    # 在 ] 前插入新记录（前面加逗号）
    insert_text = ",\n" + ",\n".join(new_records)
    new_html = html[:end_pos] + insert_text + "\n" + html[end_pos:]
    print(f"[OK] PROGRAMS 追加 {len(new_records)} 条: {[r[:r.index(',')] for r in new_records]}")
else:
    new_html = html
    print("[INFO] PROGRAMS 无需追加")

# 3. 追加 VD 集合（括号深度匹配）
vd_added = []
for item in NEW_ITEMS:
    if f'"{item["url"]}"' in new_html and "VERIFIED_DETAILS" in new_html:
        # 检查是否已在 VD 集合
        vd_m = re.search(r"const VERIFIED_DETAILS\s*=\s*new Set\(\[", new_html)
        if vd_m:
            vd_start = vd_m.end()
            vd_depth = 1
            j = vd_start
            while j < len(new_html) and vd_depth > 0:
                if new_html[j] == '[': vd_depth += 1
                elif new_html[j] == ']': vd_depth -= 1
                j += 1
            vd_end = j - 1
            vd_content = new_html[vd_start:vd_end]
            if f'"{item["url"]}"' not in vd_content:
                # 追加
                new_vd = f'"{item["url"]}",'
                new_html = new_html[:vd_end] + new_vd + new_html[vd_end:]
                vd_added.append(item["url"])
                print(f"[OK] VD 追加: {item['url']}")

# 4. 写回 index_main.html
with open("index_main.html", "w", encoding="utf-8") as f:
    f.write(new_html)
print(f"\n[DONE] index_main.html 已写回 ({len(new_html)} bytes)")
print(f"本轮新增 PROGRAMS: {len(new_records)} 条")
print(f"本轮新增 VD: {len(vd_added)} 条")
