# -*- coding: utf-8 -*-
"""Round 162 batch: add 5 half-verified MS pages."""
import os, re, json

ROOT = r"D:\work buddy\2026-11-05-14-15-52"
IDX = os.path.join(ROOT, "index_main.html")

# (id, school_code, chinese_name, english_name, deg, lvl, stem, dur, ddl, lang, test_label, tui, url, official_url)
PROGRAMS = [
    ("nu-ms-matsci", "nu", "材料科学与工程硕士",
     "Materials Science and Engineering MS", "MS", "m", 1,
     "Course-track 9-15 months (3-4 quarters); Thesis-track 21 months (6 quarters incl. 3 quarters research)",
     "Fall only; application deadline待补 (McCormick MS cycle)",
     "TOEFL/IELTS per TGS minimum",
     "GRE: required (TGS standard); see department page",
     "Tuition待补 (TGS graduate per-quarter rate)",
     "details/nu-ms-matsci.html",
     "https://www.mccormick.northwestern.edu/materials-science/academics/graduate/masters/"),
    ("nu-ms-cee", "nu", "土木与环境工程硕士",
     "Civil and Environmental Engineering MS", "MS", "m", 1,
     "9 months / 3 quarters (12 courses); thesis option available",
     "Fall only; application deadline待补",
     "TOEFL/IELTS per TGS minimum",
     "GRE: required (TGS standard)",
     "Tuition待补 (TGS graduate per-quarter rate)",
     "details/nu-ms-cee.html",
     "https://www.mccormick.northwestern.edu/civil-environmental/academics/masters/"),
    ("umich-mse-enve", "umich", "环境工程工程硕士（MSE）",
     "MSE in Environmental Engineering", "MSE", "m", 1,
     "33 credit hours (18 EWRE core + 15 major); in-person; Rackham",
     "Fall: January 15 (MSE); Winter: October 7",
     "TOEFL 84 / IELTS 6.5 (Rackham minimum)",
     "GRE: not required (CEE Rackham standard)",
     "Tuition待补 (Rackham per-term rate)",
     "details/umich-mse-enve.html",
     "https://cee.engin.umich.edu/graduate-studies/masters-programs/mse-in-environmental-engineering/"),
    ("umich-ms-clasp", "umich", "气候与空间科学工程硕士",
     "MS in Climate and Space Sciences and Engineering (CLaSP)", "MS", "m", 1,
     "30 credit hours (15 CLaSP + 3 cognate outside dept); similar to first 2 years of PhD; Fall only",
     "Fall: January 15 (MS 02219); Winter: not offered for MS",
     "TOEFL 84 / IELTS 6.5 (Rackham minimum)",
     "GRE: required (Rackham CLaSP); GPA 3.5/4.0",
     "Tuition待补 (Rackham per-term rate)",
     "details/umich-ms-clasp.html",
     "https://clasp.engin.umich.edu/academics/graduate-studies/masters-program/masters-atmospheric-and-space-sciences/"),
    ("geo-ms-bmb", "geo", "生物化学与分子生物学硕士",
     "MS in Biochemistry and Molecular Biology", "MS", "m", 1,
     "30 graduate credits; full-time or part-time; 4-credit internship in GUMC/NIH/FDA/biotech corridor",
     "Fall only; application deadline待补 (Grad School CAS)",
     "TOEFL 100 / IELTS 7.5 (CAS Science)",
     "GRE: required per program; GPA 3.0",
     "Tuition待补 (Grad School per-credit rate)",
     "details/geo-ms-bmb.html",
     "https://bmcb.georgetown.edu/msbiochem_/"),
]

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} | {en} | {s_name}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{color:#1a3a6c;border-bottom:3px solid #1a3a6c;padding-bottom:10px}}
h2{{color:#1a3a6c;margin-top:28px;border-left:4px solid #1a3a6c;padding-left:10px}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-top:12px}}
.card{{background:#f5f8fc;border-radius:8px;padding:14px 16px;border-left:3px solid #4a7bb7}}
.card b{{color:#1a3a6c}}
a{{color:#1a6fc2}}
.tag{{display:inline-block;background:#e8f0fb;color:#1a3a6c;padding:2px 8px;border-radius:10px;font-size:12px;margin-right:6px}}
.note{{background:#fff8e6;border-left:3px solid #e0a800;padding:10px 14px;border-radius:4px;margin-top:14px;font-size:14px}}
</style>
</head>
<body>
<h1>{s_name} · {n}</h1>
<p><b>English:</b> {en}<br><b>学位：</b>{deg}　<span class="tag">STEM</span><br><b>官方页面：</b><a href="{official}" target="_blank">{official}</a></p>

<h2>① 项目概览</h2>
<div class="grid">
<div class="card"><b>时长：</b>{dur}</div>
<div class="card"><b>学位类型：</b>{deg}（{lvl_cn}）</div>
<div class="card"><b>授课形式：</b>In-person（全日制在校）</div>
<div class="card"><b>STEM：</b>是</div>
</div>

<h2>② 申请截止与语言</h2>
<div class="grid">
<div class="card"><b>截止日期：</b>{ddl}</div>
<div class="card"><b>语言要求：</b>{lang}</div>
<div class="card"><b>标化要求：</b>{test}</div>
<div class="card"><b>学费：</b>{tui}</div>
</div>

<h2>③ 课程与方向</h2>
<div class="card">{courses}</div>

<h2>④ 申请材料</h2>
<div class="card">{materials}</div>

<h2>⑤ 录取分布</h2>
<div class="card"><i>录取分布，非最低门槛。</i> 官方未公布具体录取 GPA / GRE 中位数值，待系站恢复后补全。</div>

<h2>⑥ 备注</h2>
<div class="note">本页为半核验页：学位、学制、官方链接、申请截止、语言最低分已从学校官网核实；完整课程清单、材料清单、GRE 具体要求、精确学费等待系站恢复后补全。</div>

<p style="margin-top:24px"><a href="../index_main.html">← 返回项目库主页</a></p>
</body>
</html>
"""

S_NAME = {
    "nu": "Northwestern University",
    "umich": "University of Michigan, Ann Arbor",
    "geo": "Georgetown University",
}
COURSES = {
    "nu-ms-matsci": "Course-track MS: 12 courses (8 MSE core incl. at least 5 at 400-level, 4 electives). Thesis-track MS: 10 courses (7 MSE, 3 graduate core, 1 MatSci 496 research prep, 3 electives). Research areas: nanomaterials, biomaterials, electronic materials, metals, ceramics, polymers, energy, sustainability, additive manufacturing. Collaborates with Argonne National Lab and Feinberg School of Medicine.",
    "nu-ms-cee": "12 courses (core + electives) across mechanics, analysis, design, computer methods, modeling. Five MS specializations: Environmental Engineering & Science; Underground Science & Engineering; Structural Engineering; Transportation Systems Analysis & Planning; Architectural Engineering & Sustainable Design. Optional certificate in Global and Ecological Health Engineering (4-quarter).",
    "umich-mse-enve": "18 hours in Environmental & Water Resources Engineering (EWRE) core + 15 hours in one of majors: Environmental Process Engineering; Energy, Climate, and Air Quality; Environmental Data Systems and Finance; Ecohydrology and Environmental Fluid Dynamics. US News #2 environmental engineering. 5:1 student-faculty ratio, ~100% employed or further study.",
    "umich-ms-clasp": "30 credit hours (15 in CLaSP + 3 cognate outside dept, non-seminar). Similar to first two years of PhD; MS students work with advisor on custom schedule. Research areas: atmospheric & climate sciences; space & planetary sciences; theory & computational methods; instrumentation & observational methods. Participates in NASA Parker Solar Probe and other missions.",
    "geo-ms-bmb": "At least 30 graduate credits with GPA 3.0+; required core sequence in biochemistry, molecular biology, cell biology; advanced electives and special topics. 4-credit hands-on internship in GUMC labs, NIH, FDA, or MD biotech corridor, culminating in tri-annual poster presentations. ~40 matriculants/year; most transition to PhD/MD/DDS/JD/MBA or biotech research careers.",
}
MATERIALS = {
    "nu-ms-matsci": "Online application (TGS); transcripts; 3 letters of recommendation; statement of purpose; CV; TOEFL/IELTS; GRE (TGS standard). 完整材料清单待系站恢复后补全。",
    "nu-ms-cee": "Online application (TGS); transcripts; 3 letters of recommendation; statement of purpose; CV; TOEFL/IELTS; GRE. 完整材料清单待系站恢复后补全。",
    "umich-mse-enve": "Rackham online application; transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; no GRE required. 完整材料清单待补全。",
    "umich-ms-clasp": "Rackham online application (Program code 02219); transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; GRE required. 完整材料清单待补全。",
    "geo-ms-bmb": "Grad School CAS online application; transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; GRE per program; application fee. 完整材料清单待补全。",
}
LVL_CN = {"m": "硕士（研究/职业导向）"}

html = open(IDX, encoding="utf-8").read()
orig_len = len(html)

# 1. Append 5 detail pages
for (pid, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official) in PROGRAMS:
    page = TEMPLATE.format(
        s_name=S_NAME[s], n=n, en=en, deg=deg, lvl_cn=LVL_CN[lvl],
        dur=dur, ddl=ddl, lang=lang, test=test, tui=tui,
        courses=COURSES[pid], materials=MATERIALS[pid], official=official,
    )
    p = os.path.join(ROOT, url)
    open(p, "w", encoding="utf-8").write(page)
    print(f"[OK] generated: {url} ({len(page)} chars)")

# 2. Append to PROGRAMS array (brace-depth match end of ])
def find_array_end(html, start_marker):
    i = html.find(start_marker)
    if i < 0:
        raise RuntimeError("marker not found: " + start_marker)
    # find opening [
    j = html.find("[", i)
    depth = 1
    k = j + 1
    while k < len(html) and depth > 0:
        c = html[k]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
        k += 1
    return k - 1  # position of closing ]

# Build new PROGRAMS entries (compact)
new_entries = []
for (pid, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official) in PROGRAMS:
    entry = (f'{{id:"{pid}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
             f'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}')
    new_entries.append(entry)

# Locate PROGRAMS array end
end = find_array_end(html, "const PROGRAMS=")
# Insert before closing ]; if preceding char is newline, prepend ",\n"
# Look backwards to see if last char before ] is , or }
prefix = html[:end].rstrip()
if prefix.endswith("}"):
    insert_text = ",\n" + ",\n".join(new_entries) + "\n"
elif prefix.endswith(","):
    insert_text = "\n" + ",\n".join(new_entries) + "\n"
else:
    insert_text = ",\n" + ",\n".join(new_entries) + "\n"
html = html[:end] + insert_text + html[end:]
print(f"[OK] PROGRAMS appended {len(new_entries)}")

# 3. Append to VERIFIED_DETAILS set (no spaces)
vd_new = [p[7] for p in [x[7] for x in PROGRAMS]]  # urls
vd_marker = "const VERIFIED_DETAILS=new Set("
i = html.find(vd_marker)
if i < 0:
    raise RuntimeError("VD marker not found")
j = html.find("(", i)
depth = 1
k = j + 1
while k < len(html) and depth > 0:
    c = html[k]
    if c == "(":
        depth += 1
    elif c == ")":
        depth -= 1
    k += 1
end = k - 1
# VD contents are ["...","..."]
# Insert before closing ); if preceding is , no need; if preceding is " need comma
prefix = html[:end].rstrip()
if prefix.endswith('"'):
    insert_text = "," + ",".join(f'"{u}"' for u in vd_new)
elif prefix.endswith(","):
    insert_text = ",".join(f'"{u}"' for u in vd_new)
else:
    insert_text = ",".join(f'"{u}"' for u in vd_new)
html = html[:end] + insert_text + html[end:]
print(f"[OK] VERIFIED_DETAILS appended {len(vd_new)}")

open(IDX, "w", encoding="utf-8").write(html)
print(f"[DONE] index_main.html written back ({len(html)} chars, was {orig_len})")
