# -*- coding: utf-8 -*-
"""Round 161: add 5 verified master's programs (semi-verified pages)."""
import re, os, json

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

NEW = [
    {
        "id": "nu-ms-ee",
        "s": "nu",
        "n": "电气工程硕士",
        "en": "Master of Science in Electrical Engineering (MS EE)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "9-15 months full-time on-campus (Evanston campus)",
        "ddl": "Fall admission (see TGS ECE MS admissions page)",
        "lang": "TOEFL/IELTS required (Northwestern TGS standard)",
        "test": "GRE required (see ECE graduate admissions)",
        "tui": "Northwestern TGS graduate tuition (see McCormick Cost of Attendance)",
        "url": "details/nu-ms-ee.html",
        "official": "https://www.mccormick.northwestern.edu/electrical-computer/academics/graduate/masters/electrical-engineering/",
        "summary": "Northwestern McCormick MS in Electrical Engineering (ECE department). 12 course units total: 6 core + 6 electives. Three plans: Thesis, Project, or Course-only. Areas of study: Solid-State, Photonic & Quantum Technologies (devices/systems), and Signals & Systems (communications, signal processing, ML, control). 300-level or higher; at least 9 courses from ECE/CS; minimum 3 units at 400-level or above; GPA B (3.0) or higher. Research in quantum devices, nanoelectronics, photonic computing, signal processing, integrated circuits.",
    },
    {
        "id": "nu-ms-cbe",
        "s": "nu",
        "n": "化学与生物工程硕士",
        "en": "Master of Science in Chemical and Biological Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "Coursework MS: 9-15 months; MS with thesis: 21 months (on-campus)",
        "ddl": "Fall 2027: May 1, 2027 (MS; applications open September 15)",
        "lang": "TOEFL/IELTS required (Northwestern TGS standard)",
        "test": "GRE required (see CBE graduate admissions)",
        "tui": "Northwestern TGS graduate tuition (see McCormick Cost of Attendance)",
        "url": "details/nu-ms-cbe.html",
        "official": "https://www.mccormick.northwestern.edu/chemical-biological/academics/graduate/chemical-biological-engineering-ms/",
        "summary": "Northwestern McCormick MS in Chemical and Biological Engineering (CBE). Two tracks: Coursework MS (minimum 10 courses, 9-15 months, industry careers) and MS with thesis (21 months). 4 core courses: Math Methods for ChE, Transport Phenomena, Advanced Thermodynamics, ChE Kinetics & Reactor Design. 6 electives (2 within dept, 4 additional). Research areas: synthetic biology, biotechnology, medicine, complex systems, energy, sustainability, materials. No ChE bachelor's? Additional prerequisites may be required, sometimes after admission.",
    },
    {
        "id": "umich-mse-civil",
        "s": "umich",
        "n": "土木工程工程硕士",
        "en": "Master of Science in Engineering (MSE) in Civil Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "~2 years full-time on-campus (Rackham CEE)",
        "ddl": "Fall 2027: January 15, 2027 (MSE)",
        "lang": "TOEFL/IELTS required (Rackham standard)",
        "test": "GRE required (see CEE graduate admissions)",
        "tui": "Rackham graduate tuition (see Rackham Cost of Attendance)",
        "url": "details/umich-mse-civil.html",
        "official": "https://cee.engin.umich.edu/graduate-studies/masters-programs/mse-in-civil-engineering/",
        "summary": "U-M MSE in Civil Engineering (Rackham CEE). Program code 00122 (MSE). 26 credit hours minimum of approved graduate work; 9 credit hours per semester full-time. US News #4 Civil Engineering. Concentrations: construction engineering & management, geotechnical, hazards & resilience, hydraulic & hydrologic, intelligent systems, materials, structural, transportation systems. In-person format. Distinct from the on-campus MEng track (online MEng excluded). Note: MSE in Construction Engineering & Management, MSE in Environmental Engineering are separate Rackham programs.",
    },
    {
        "id": "umich-mse-ioe",
        "s": "umich",
        "n": "工业与运筹工程硕士",
        "en": "Master of Science in Engineering (MSE) / MS in Industrial and Operations Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "~1.5-2 years full-time on-campus (Rackham IOE)",
        "ddl": "Fall: January 15; Winter: October 1 (MS/MSE; same deadlines regardless of citizenship)",
        "lang": "TOEFL/IELTS required (Rackham standard)",
        "test": "GRE required (see IOE graduate admissions)",
        "tui": "Rackham graduate tuition (see Rackham Cost of Attendance)",
        "url": "details/umich-mse-ioe.html",
        "official": "https://ioe.engin.umich.edu/graduate/masters-programs/industrial-and-operations-engineering-masters/",
        "summary": "U-M IOE MS/MSE residential on-campus only (online MEng is a separate professional program and is distinguished here). 30 credit hours of approved graduate courses, course-based with no thesis. Degree awarded: MSE for engineering bachelor's; MS for physics/math/other backgrounds. US News #2 Industrial Engineering Graduate Program (2025). Average starting salary $96K (2025). Focus: data, optimization, systems engineering, human-centered design. Graduates go to healthcare, finance, tech, manufacturing as business analysts, consultants, data analysts, supply chain analysts, UX researchers. Distinct from on-campus IOE MEng and the separate SED/AI MEng programs.",
    },
    {
        "id": "geo-ms-physics",
        "s": "geo",
        "n": "物理学硕士",
        "en": "Master of Science in Physics (Terminal)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years full-time on-campus (Hilltop campus; 08/17/26-05/20/28)",
        "ddl": "Fall 2027: May 1, 2027 (MS)",
        "lang": "Minimum TOEFL iBT 100 (or new TOEFL iBT 5 on new scale from Jan 21, 2026) / IELTS 7.5",
        "test": "GRE General and Physics Subject GRE waived for 2026-2027 admission cycle",
        "tui": "Total ~$96,000 (2026-27 ISSS estimate; self-funded, no funding component for MS)",
        "url": "details/geo-ms-physics.html",
        "official": "https://physics.georgetown.edu/prospective-students-and-applicants/",
        "summary": "Georgetown CAS Department of Physics terminal MS program. Distinct from funded PhD (which has full tuition + stipend); the MS is a paid program with no funding component. Fall admission only. Bachelor's in Physics or related field; minimum GPA 3.0. Research areas: condensed matter physics, soft matter, magnetism, biophysics, quantum information. Note: unlike PhD (5 years funded), MS students pay out of pocket or secure external funding.",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n_zh} | {en} | {school_zh}</title>
<style>
body{{font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{font-size:22px;border-bottom:3px solid #1a4480;padding-bottom:10px}}
h2{{font-size:16px;color:#1a4480;margin-top:26px;border-left:4px solid #1a4480;padding-left:10px}}
.badge{{display:inline-block;background:#1a4480;color:#fff;padding:2px 10px;border-radius:10px;font-size:12px;margin-right:6px}}
.grid{{display:grid;grid-template-columns:1fr 1fr;gap:10px 24px;margin-top:10px}}
.kv{{background:#f6f8fc;padding:8px 12px;border-radius:6px}}
.kv b{{color:#1a4480}}
a{{color:#1a4480}}
.note{{background:#fff8e1;padding:10px 14px;border-left:4px solid #f0b400;border-radius:4px;margin-top:14px;font-size:14px}}
</style>
</head>
<body>
<h1>{n_zh}</h1>
<div><span class="badge">{deg}</span><span class="badge">{school_zh}</span>{stem_badge}</div>

<h2>项目概述</h2>
<p>{summary}</p>

<h2>核心信息</h2>
<div class="grid">
  <div class="kv"><b>学位：</b>{deg}</div>
  <div class="kv"><b>学制：</b>{dur}</div>
  <div class="kv"><b>申请截止：</b>{ddl}</div>
  <div class="kv"><b>语言要求：</b>{lang}</div>
  <div class="kv"><b>标化要求：</b>{test}</div>
  <div class="kv"><b>学费：</b>{tui}</div>
</div>

<h2>官方链接</h2>
<p>项目官网：<a href="{official}" target="_blank">{official}</a></p>

<div class="note">本页为半核验页：学位、学制、方向、官方链接、申请截止、语言最低分（Georgetown Physics）、已核实总学费（Georgetown Physics ISSS 估算）已从学校官网（McCormick/Rackham/CAS/ISSS 公告页）核实；完整课程清单、材料清单、GRE 具体要求、精确学费每学期金额等待系站恢复后补全。录取分数如后续补充均为"录取分布，非最低门槛"。</div>

</body>
</html>
"""

SCHOOL_ZH = {
    "nu": "西北大学",
    "umich": "密歇根大学安娜堡分校",
    "geo": "乔治城大学",
}

# 1. Generate detail pages
for p in NEW:
    stem_badge = '<span class="badge">STEM</span>' if p["stem"] == 1 else ""
    page = DETAIL_TEMPLATE.format(
        n_zh=p["n"], en=p["en"], deg=p["deg"], school_zh=SCHOOL_ZH[p["s"]],
        stem_badge=stem_badge, summary=p["summary"], dur=p["dur"],
        ddl=p["ddl"], lang=p["lang"], test=p["test"], tui=p["tui"],
        official=p["official"],
    )
    path = os.path.join(ROOT, p["url"].replace("/", os.sep))
    with open(path, "w", encoding="utf-8") as f:
        f.write(page)
    print(f"[OK] generated: {p['url']} ({len(page)} chars)")

# 2. Append PROGRAMS
with open(HTML, "r", encoding="utf-8") as f:
    html = f.read()

def find_array_end(s, start_marker):
    i = s.index(start_marker)
    j = s.index("[", i)
    depth = 0
    k = j
    in_str = False
    str_ch = ""
    while k < len(s):
        c = s[k]
        if in_str:
            if c == "\\":
                k += 2
                continue
            if c == str_ch:
                in_str = False
        else:
            if c in ('"', "'"):
                in_str = True
                str_ch = c
            elif c == "[":
                depth += 1
            elif c == "]":
                depth -= 1
                if depth == 0:
                    return k
        k += 1
    raise RuntimeError("no end bracket")

def fmt_entry(p):
    return ('{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
            'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}').format(**p)

new_entries = ",\n" + ",\n".join(fmt_entry(p) for p in NEW)

end_idx = find_array_end(html, "const PROGRAMS=")
html = html[:end_idx] + new_entries + "\n" + html[end_idx:]
print("[OK] PROGRAMS appended", len(NEW))

# VERIFIED_DETAILS
i = html.index("const VERIFIED_DETAILS=new Set(")
j = html.index("[", i)
depth = 0
k = j
in_str = False
str_ch = ""
while k < len(html):
    c = html[k]
    if in_str:
        if c == "\\":
            k += 2
            continue
        if c == str_ch:
            in_str = False
    else:
        if c in ('"', "'"):
            in_str = True
            str_ch = c
        elif c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
            if depth == 0:
                vd_end = k
                break
    k += 1

new_vd = "," + ",".join('"{}"'.format(p["url"]) for p in NEW)
if html[vd_end-1] == '"':
    html = html[:vd_end] + new_vd + html[vd_end:]
elif html[vd_end-1] == ",":
    html = html[:vd_end-1] + new_vd + html[vd_end:]
else:
    html = html[:vd_end] + new_vd + html[vd_end:]
print("[OK] VERIFIED_DETAILS appended", len(NEW))

with open(HTML, "w", encoding="utf-8") as f:
    f.write(html)
print(f"[DONE] index_main.html written back ({len(html)} chars)")
