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

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

# (id, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official)
PROGRAMS = [
    ("nu-ms-bme", "nu", "生物医学工程硕士",
     "Biomedical Engineering MS", "MS", "m", 1,
     "Coursework-only 12 courses / 3 quarters; with-thesis 9 courses + thesis / 7 quarters (~2 years)",
     "Fall admission; application deadline待补 (TGS standard)",
     "TOEFL/IELTS per TGS minimum",
     "GRE: required (TGS standard)",
     "Tuition待补 (TGS graduate per-quarter rate)",
     "details/nu-ms-bme.html",
     "https://www.mccormick.northwestern.edu/biomedical/academics/graduate/masters/"),
    ("umich-mse-cem", "umich", "建筑工程与管理工程硕士（MSE）",
     "MSE in Construction Engineering and Management", "MSE", "m", 1,
     "26 credit hours; residential on-campus (flagship residential; separate from online MEng); as little as 2 semesters / 8 months",
     "Fall: January 15 (Rackham 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-cem.html",
     "https://cee.engin.umich.edu/graduate-studies/masters-programs/mse-in-construction-engineering-and-management/"),
    ("nu-msr", "nu", "机器人学硕士",
     "Master of Science in Robotics (MSR)", "MS", "m", 1,
     "12-15 months full-time (4 quarters x 4 courses; 15 months with optional summer internship)",
     "Recommended Feb 1; Final Apr 30; application opens Sep 15",
     "TOEFL/IELTS per McCormick graduate minimum",
     "GRE: not required (MSR professional track)",
     "Tuition待补 (TGS graduate per-quarter rate)",
     "details/nu-msr.html",
     "https://www.mccormick.northwestern.edu/robotics/overview/"),
    ("geo-ma-applied-econ", "geo", "应用经济学文学硕士",
     "MA in Applied Economics", "MA", "m", 1,
     "30 credit hours; full-time on-campus; full-time students can complete in 1 calendar year; part-time option available",
     "Fall: January 15 priority / April 1 final",
     "TOEFL 100 / IELTS 7.0 (CAS master's)",
     "GRE: required (MA program); GMAT not accepted",
     "Tuition待补 (Grad School per-credit rate); merit partial-tuition scholarships available",
     "details/geo-ma-applied-econ.html",
     "https://econ.georgetown.edu/ma-applied-economics/"),
    ("geo-ms-dsan", "geo", "数据科学与分析硕士",
     "MS in Data Science & Analytics (DSAN)", "MS", "m", 1,
     "30 credit hours (15 core + 15 elective); full-time as few as 16 months (3 semesters + summer bootcamp); part-time up to 3 years",
     "Fall admission; application deadline待补",
     "TOEFL 100 / IELTS 7.5 (CAS Science)",
     "GRE: not required (DSAN); GPA 3.0 minimum",
     "Tuition待补 (Grad School per-credit rate)",
     "details/geo-ms-dsan.html",
     "https://analytics.georgetown.edu/academics/"),
]

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"}
LVL_CN = {"m": "硕士（研究/职业导向）"}

COURSES = {
    "nu-ms-bme": "9 300-level+ courses (no more than 1 unit of 499); core includes at least 2 of BMD_ENG 304/305/306 (systems physiology sequence); 5 of 9 must be engineering courses. Research groups: Falk Center for Molecular Therapeutics, MRI Research Center, Northwestern Institute for Neuroscience, Center for Innovation in Global Health Technologies. Interdisciplinary with Feinberg School of Medicine and Shirley Ryan AbilityLab.",
    "umich-mse-cem": "30 credits: 9 CR required (CEE 531/532/536), 3 CR required research (CEE 530 or 630), 9 CR construction electives, 3 CR math/probability/stats/math programming, 3 CR business/industrial/operations engineering/management, 3 CR program elective. Launched 1954 as world's first graduate program in construction engineering & management. US News Top 10. 5:1 student-faculty ratio, ~100% employed or further study. MSE is residential flagship; MEng is online flagship (separate).",
    "nu-msr": "4 quarters x 4 courses = 16 courses; covers automatic control, kinematics and dynamics, machine learning, path planning, embedded systems in robotics, open-ended project experiences. Small cohort 15-20 students. Faculty from CS/ME/EECS/BME/math; research areas ML, haptics, simulation, control, rehabilitation robotics, bio-inspired robotics. Each student completes in-depth independent research project with faculty advisor, plus online project portfolio. Career outcomes: Applied Dexterity, Zoox, Disney Research, Honda Research Institute, Whirlpool, etc.",
    "geo-ma-applied-econ": "30 credits; rigorous economic analysis with quantitative methods. Full-time 1 calendar year. Concentrations in applied economics, data-driven decision making. Merit partial-tuition scholarships for selected Fall 2026 admits. Separate from PhD program (PhD students earn 'MA in passing' after 30 credits GPA 3.0+, not external terminal).",
    "geo-ms-dsan": "30 credits (15 core + 15 elective). Core: DSAN 5000 Data Science & Analytics, DSAN 5100 Probabilistic Modeling & Statistical Computing, DSAN 5200 Advanced Data Visualization, DSAN 5300 Statistical Learning, DSAN 6000+. Five concentrations: AI; NLP; Data Visualization & Communication; Financial; Generalist. Required summer bootcamp (R/Python/command line, 3 credits, free of charge) for non-CS background. Tools: R, Python, SQL.",
}

MATERIALS = {
    "nu-ms-bme": "Online application (TGS); transcripts; 3 letters of recommendation; statement of purpose; CV; TOEFL/IELTS; GRE. 完整材料清单待系站恢复后补全。",
    "umich-mse-cem": "Rackham online application; transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; no GRE required. 完整材料清单待补全。",
    "nu-msr": "McCormick online application; transcripts; 3 letters of recommendation; statement of purpose; CV/resume; TOEFL/IELTS; no GRE required. 完整材料清单待补全。",
    "geo-ma-applied-econ": "Grad School CAS online application; transcripts; 2 letters (master's); statement of purpose; CV; TOEFL/IELTS; GRE required; application fee $90. 完整材料清单待补全。",
    "geo-ms-dsan": "Grad School CAS online application; transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; no GRE; GPA 3.0; prerequisites multivariable calculus + calculus-based stats + computer programming. 完整材料清单待补全。",
}

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

# 1. Generate 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)
    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

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)

end = find_array_end(html, "const PROGRAMS=")
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 — use url field (index 12) directly
vd_new = [prog[12] for prog in PROGRAMS]  # url field
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
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)} urls: {vd_new}")

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