# -*- coding: utf-8 -*-
"""Round 158: add 5 in-person half-verified detail pages."""
import re, os

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

PROGRAMS = [
    {
        "id": "umich-ms-data-science",
        "s": "umich",
        "n": "数据科学硕士（跨系联合）",
        "en": "Master of Science in Data Science (MDS)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "~1.5-2 years (residential, Ann Arbor; minimum 25 graduate credits in program)",
        "ddl": "Fall 1/15 (external MS); Fall 4/1 / Winter 12/1 (Rackham dual degree)",
        "lang": "TOEFL/IELTS minimum TBD pending Rackham site recovery",
        "test": {"cls": "GRE required for Rackham graduate applicants; admissions profile, not minimum threshold"},
        "tui": "~$33,467/term nonresident (2026-27 Rackham)",
        "url": "details/umich-ms-data-science.html",
        "school_zh": "密歇根大学安娜堡分校",
        "college": "LSA Dept. of Statistics (joint with CSE / UMSI / Biostatistics), Rackham",
        "website": "https://lsa.umich.edu/stats/masters_students/mastersprograms/data-science-masters-program.html",
        "summary": "Rackham MS in Data Science (MDS, Program code 02279), jointly owned by CSE Division, Dept. of Statistics, School of Information, and Dept. of Biostatistics. Balanced training in statistical skills and computational skills. Minimum 25 graduate-level credits during residency, of which 18 must be at advanced graduate level (500+ LSA/CoE, 600+ UMSI/SPH). Pre-core includes MATH 403 (fulfillable by EECS 203), EECS 402 (by EECS 280), EECS 403 (by EECS 281), plus Expertise in Data Management and Manipulation and Expertise in Data Science Techniques (part 2 fulfillable by EECS 445). Course waivers possible for equivalent prior courses with grade B- or better. Rackham cumulative GPA 3.0+ to graduate. Dual-degree track available for current Rackham students (must enroll 1+ year before degree awarded).",
        "tracks": ["Statistical modeling & inference", "Computational data science", "Data management & systems", "Data science techniques (ML/AI)", "Biostatistics / public health data"],
        "careers": ["Data scientist", "ML engineer", "Quantitative analyst", "Research scientist (industry/nonprofit)", "PhD preparation in stats/CS"],
    },
    {
        "id": "umich-ms-information",
        "s": "umich",
        "n": "信息学硕士（UMSI，在校）",
        "en": "Master of Science in Information (MSI, residential)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years (48 credits, residential on North Campus Leinweber Building)",
        "ddl": "Fall 1/15 (international final deadline)",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE requirement TBD pending site recovery; admissions profile, not minimum threshold"},
        "tui": "~$33,467/term nonresident (2026-27 Rackham)",
        "url": "details/umich-ms-information.html",
        "school_zh": "密歇根大学安娜堡分校",
        "college": "University of Michigan School of Information (UMSI)",
        "website": "https://www.si.umich.edu/programs/master-science-information",
        "summary": "UMSI residential MSI (STEM-designated), distinct from the online MADS (excluded). 48 graduate credits, minimum 39 from UMSI courses. Most students complete in 2 years full-time. Five pathways: Big Data Analytics (Information and Data Analytics), Libraries/Archives/Knowledge Environments in Society (LAKES), Product Management, User-Centered Agile Development (User-Centered Application Development), UX Research and Design. Cohort can switch pathway during first semester. Housed in Leinweber Computer Science and Information Building on North Campus (connected by bridge to CoE; design/AR/VR studios, maker lab). Nearly 100% of MSI students tackle real client projects. Preferred GPA 3.0; admits below 3.0 on holistic basis.",
        "tracks": ["Big Data Analytics", "UX Research & Design", "Product Management", "User-Centered Application Development", "Libraries/Archives/Digital Curation"],
        "careers": ["Data analyst / scientist", "UX researcher / designer", "Product manager", "Information architect", "Digital archivist / librarian"],
    },
    {
        "id": "geo-ms-mathematics-statistics",
        "s": "geo",
        "n": "数学与统计硕士（STEM）",
        "en": "Master of Science in Mathematics and Statistics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "~2 years (30 credits, 10 courses; no thesis; full-time 3 courses/semester)",
        "ddl": "Fall 1/15; Spring 10/1",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE required; admissions profile, not minimum threshold"},
        "tui": "TBD pending site recovery (Graduate School of Arts & Sciences rate)",
        "url": "details/geo-ms-mathematics-statistics.html",
        "school_zh": "乔治城大学",
        "college": "Graduate School of Arts & Sciences, Dept. of Mathematics and Statistics",
        "website": "https://mathstat.georgetown.edu/ms-mathematics-statistics/",
        "summary": "Georgetown MS in Mathematics and Statistics, STEM-certified, professional terminal master's (no thesis, no qualifying/comprehensive exams). 30 credits / 10 courses: 4 required core (MATH 5051 Probability Theory & Applications, MATH 5052 Deterministic Math Models, MATH 5151 Statistical Inference & Modeling, MATH 5152 Numerical Methods for Data Science) + 5 math/stat electives + 1 non-math/stat elective. Elective menu: R/Python, cloud computing, regression, unsupervised learning, financial mathematics, time series, data mining, Bayesian statistics, ML, deep learning, mathematics of climate, operations research, optimization, social network analysis, survey sampling. Non-math electives can be biostatistics, CS, econometrics, public policy surveys, computational neuroscience. Admission expects equivalent of a math minor: 2 semesters single-variable calculus, multivariable vector calculus, linear algebra (grade B or better).",
        "tracks": ["Probability & stochastic processes", "Statistical inference & modeling", "Numerical methods & data science", "Financial mathematics", "Optimization & operations research"],
        "careers": ["Data scientist", "Quantitative analyst", "ML engineer", "Risk analyst (finance)", "Operations research analyst"],
    },
    {
        "id": "duke-meng-photonics",
        "s": "duke",
        "n": "光子学与光学科学工程硕士（Pratt 在校）",
        "en": "Master of Engineering in Photonics and Optical Sciences (On-Campus)",
        "deg": "MEng",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5 years / 3 semesters (30 credits)",
        "ddl": "Rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE optional for 2027 applicants; admissions profile, not minimum threshold"},
        "tui": "~$35,680/semester (2026-27 campus Pratt MEng, ~$107,040 total over 3 semesters)",
        "url": "details/duke-meng-photonics-optical-sciences.html",
        "school_zh": "杜克大学",
        "college": "Pratt School of Engineering, Fitzpatrick Institute for Photonics",
        "website": "https://masters.pratt.duke.edu/photonics/",
        "summary": "Duke Pratt MEng in Photonics and Optical Sciences (Program Code E-EGR-POS). 30 credits: 6 credits Core Industry Preparation (Business Fundamentals for Engineers, Management of High-Tech Industries) + 15 credits Departmental/Cross-Disciplinary Requirements (1 advanced math course + 2 optics/photonics courses + 1 BME technical optics/photonics + 1 ECE technical optics/photonics) + 9 credits Technical Electives in a Concentration Area (3 courses, 2 from similar concentration) + 0-credit required internship/project. Leverages Fitzpatrick Institute for Photonics (FIP) research: scalable quantum computing, cancer imaging, high-throughput imaging systems. Corporate Partnership Program and Carolinas Photonics Consortium. Internship must occur after matriculation at Duke. Independent study (BME 899/790 or ECE 899) up to 3 units allowed.",
        "tracks": ["Optical engineering & imaging", "Biophotonics / medical optics", "Quantum photonics", "Optoelectronics / lasers", "Optical materials"],
        "careers": ["Photonics engineer", "Optical engineer", "Medical imaging engineer", "Laser systems engineer", "Semiconductor/optoelectronics R&D"],
    },
    {
        "id": "duke-meng-risk-engineering",
        "s": "duke",
        "n": "风险工程硕士（Pratt 在校）",
        "en": "Master of Engineering in Risk Engineering (On-Campus)",
        "deg": "MEng",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5 years / 3 semesters (30 credits)",
        "ddl": "Rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE optional for 2027 applicants; admissions profile, not minimum threshold"},
        "tui": "~$35,680/semester (2026-27 campus Pratt MEng, ~$107,040 total over 3 semesters)",
        "url": "details/duke-meng-risk-engineering.html",
        "school_zh": "杜克大学",
        "college": "Pratt School of Engineering, Civil & Environmental Engineering",
        "website": "https://cee.duke.edu/graduate-programs/risk-engineering",
        "summary": "Duke Pratt MEng in Risk Engineering, CEE department. Emphasizes systems approach, decision analysis, and leveraging large data sets to assess risk of extreme events and costs/benefits of consequences. 30 credits over 3 semesters: 2 industry prep core + 4-5 CEE risk/resilience courses + 6-9 credits electives + 0-credit required internship. Designed for practicing engineers/scientists from civil/environmental/other engineering branches wanting expertise in risk analysis plus engineering specialty, risk policy, economics, or law; also open to undergrads in engineering or related mathematical/physical sciences with catch-up courses. Graduates enter engineering/business consulting, insurance/finance, environmental risk assessment, infrastructure engineering. Part of Duke CEE MEng family (Civil / Environmental / Climate & Sustainability / Risk / Computational Mechanics).",
        "tracks": ["Quantitative risk analysis", "Decision analysis", "Infrastructure & resilience engineering", "Environmental / natural catastrophe risk", "Financial / insurance risk modeling"],
        "careers": ["Risk analyst", "Actuarial / insurance consultant", "Infrastructure resilience engineer", "Management consultant (risk practice)", "Environmental risk assessor"],
    },
]

# ---------- detail page template ----------
TPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{p[n]} - {p[school_zh]}</title>
<style>
body{{font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7}}
h1{{color:#1a3a6c;border-bottom:3px solid #1a3a6c;padding-bottom:10px}}
h2{{color:#1a3a6c;margin-top:32px;border-left:4px solid #1a3a6c;padding-left:10px}}
.meta{{background:#f4f7fb;padding:14px 18px;border-radius:6px;margin:16px 0}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}}
.card{{background:#fafbfd;border:1px solid #dde5ef;border-radius:6px;padding:14px 16px}}
.card h3{{margin:0 0 8px 0;color:#1a3a6c;font-size:15px}}
ul{{margin:6px 0;padding-left:22px}}
.tag{{display:inline-block;background:#e3ecf7;color:#1a3a6c;padding:2px 10px;border-radius:12px;font-size:12px;margin-right:6px}}
a{{color:#1a6dc9}}
.warn{{background:#fff7e6;border-left:4px solid #faad14;padding:10px 14px;border-radius:4px;margin:12px 0;font-size:14px}}
</style>
</head>
<body>
<h1>{p[school_zh]} · {p[n]}</h1>
<div class="meta">
<div><b>英文名称：</b>{p[en]}</div>
<div><b>开设学院：</b>{p[college]}</div>
<div><b>学位：</b>{p[deg]} ｜ <b>学制：</b>{p[dur]} ｜ <b>STEM：</b>{stem_label}</div>
<div><b>截止日期：</b>{p[ddl]}</div>
<div><b>语言要求：</b>{p[lang]}</div>
<div><b>标化考试：</b>{p[test][cls]}</div>
<div><b>学费：</b>{p[tui]}</div>
<div><b>官网：</b><a href="{p[website]}" target="_blank">{p[website]}</a></div>
</div>
<div class="warn">⚠ 本页为半核验页：学位/学制/方向/官方链接/已核实学费已核对；精确课程清单、完整材料清单、语言最低分、GRE 分项、学费杂费明细待系站恢复后补全。录取分数若出现均为录取分布，非最低门槛。</div>
<h2>项目概览</h2>
<p>{p[summary]}</p>
<h2>方向 / 模块</h2>
<div class="grid">
{tracks_html}
</div>
<h2>就业方向</h2>
<div class="grid">
{careers_html}
</div>
<h2>备注</h2>
<ul>
<li>口径：2027 USNews 前30含并列 + 加拿大4校；排除线上/远程/在职、MBA、纯临床执业类。</li>
<li>本页信息来自学校官方 bulletin / catalog / 系站（2026-2027 学年），未公布字段整项不展示、不臆造。</li>
</ul>
</body>
</html>
"""

def render(p):
    tracks = "".join(f'<div class="card"><h3>◆</h3>{t}</div>' for t in p["tracks"])
    careers = "".join(f'<div class="card"><h3>●</h3>{c}</div>' for c in p["careers"])
    stem_label = "是" if p["stem"] else "否"
    return TPL.format(p=p, tracks_html=tracks, careers_html=careers, stem_label=stem_label)

# ---------- write detail pages ----------
for p in PROGRAMS:
    out = os.path.join(ROOT, p["url"])
    os.makedirs(os.path.dirname(out), exist_ok=True)
    html = render(p)
    with open(out, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] generated: {p['url']} ({len(html)} chars)")

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

def find_array_end(html, start_marker):
    idx = html.index(start_marker)
    depth = 0
    i = idx
    while i < len(html):
        c = html[i]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
            if depth == 0:
                return i
        i += 1
    raise RuntimeError("no end")

def prog_to_js(p):
    return (
        '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
        'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{cls}"}},tui:"{tui}",url:"{url}"}}'
    ).format(
        id=p["id"], s=p["s"], n=p["n"].replace('"',''), en=p["en"].replace('"',''),
        deg=p["deg"], lvl=p["lvl"], stem=p["stem"],
        dur=p["dur"].replace('"','\\"'), ddl=p["ddl"].replace('"','\\"'),
        lang=p["lang"].replace('"','\\"'), cls=p["test"]["cls"].replace('"','\\"'),
        tui=p["tui"].replace('"','\\"'), url=p["url"],
    )

# PROGRAMS
end = find_array_end(html, "const PROGRAMS=[")
existing = html[:end]
stripped = existing.rstrip()
if not stripped.endswith(","):
    existing = existing + ","
new_block = ",".join(prog_to_js(p) for p in PROGRAMS)
html = existing + new_block + html[end:]
print(f"[OK] PROGRAMS appended {len(PROGRAMS)}")

# VERIFIED_DETAILS
vd_start = html.index("const VERIFIED_DETAILS=new Set([")
i = vd_start + len("const VERIFIED_DETAILS=new Set(")
depth = 0
j = i
while j < len(html):
    c = html[j]
    if c == "[":
        depth += 1
    elif c == "]":
        depth -= 1
        if depth == 0:
            break
    j += 1
k = j - 1
while k >= i and html[k] in " \n\r\t":
    k -= 1
last_char = html[k]
if last_char in (",", '"'):
    insert = "," + ",".join(f'"{p["url"]}"' for p in PROGRAMS)
    html = html[:k+1] + insert + html[k+1:]
else:
    insert = ",".join(f'"{p["url"]}"' for p in PROGRAMS)
    html = html[:k+1] + "," + insert + html[k+1:]
print(f"[OK] VERIFIED_DETAILS appended {len(PROGRAMS)}")

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