# -*- coding: utf-8 -*-
"""Round 160: 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-msia",
        "s": "nu",
        "n": "分析科学硕士",
        "en": "Master of Science in Analytics (MSiA)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "15 months full-time on-campus (5 consecutive quarters, includes required summer internship)",
        "ddl": "Fall admission (see McCormick MSiA admissions page)",
        "lang": "TOEFL/IELTS required (Northwestern graduate standard)",
        "test": "GRE/GMAT optional (if submitted, no preference between exams; scores must be <= 5 years old)",
        "tui": "2025-26: $22,973/quarter full-time (Analytics MS rate); summer internship quarter no tuition charged",
        "url": "details/nu-msia.html",
        "official": "https://www.mccormick.northwestern.edu/analytics/",
        "summary": "Northwestern MSiA is housed in the Department of Industrial Engineering and Management Sciences (IEMS) within McCormick. Full-time on-campus day program, no online or part-time option. 5 consecutive quarters: 3 on-campus quarters of required coursework + Practicum project, 10-week minimum industry internship in summer (no tuition), 1 final fall quarter for remaining coursework and Capstone. Cohort ~40 students. Covers predictive, prescriptive, and descriptive analytics: statistics, ML, AI, optimization, databases, data engineering. STEM-designated (OPT extension eligible). 2-week bootcamp/orientation before classes start.",
    },
    {
        "id": "nu-msit",
        "s": "nu",
        "n": "信息技术硕士（McCormick 全日制）",
        "en": "Master of Science in Information Technology (MSIT, Full-Time)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "10-13 months full-time on-campus (3-quarter option: 10 months; 4-quarter option: 15 months with optional summer internship)",
        "ddl": "Round 1: March 1; Round 2: June 15 (full-time)",
        "lang": "TOEFL/IELTS required (Northwestern graduate standard)",
        "test": "GRE/GMAT not required",
        "tui": "2025-26: $22,100/quarter full-time (Information Technology MS rate)",
        "url": "details/nu-msit.html",
        "official": "https://www.mccormick.northwestern.edu/information-technology/",
        "summary": "Northwestern McCormick MSIT full-time track at Evanston campus. Distinct from the SPS MS in Information Systems (part-time/online, excluded). Designed for IT professionals with EE/CS/equivalent undergraduate degree; requires at least 2 years of industry experience. Classes weekdays and Saturdays. Cohort 25-30. Blends technology and business strategy coursework. Optional summer industry internship in greater Chicagoland area extends to 15 months. Rolling admissions.",
    },
    {
        "id": "nu-mbp",
        "s": "nu",
        "n": "生物技术硕士",
        "en": "Master of Science in Biotechnology (MBP)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "15-21 months full-time on-campus (includes 6 months full-time lab research; optional 3 or 6-month industry internship extends to 21 months)",
        "ddl": "Round 1 Scholarship (domestic & international): March 1; International Final: May 1; Domestic Final: May 31",
        "lang": "Recommended TOEFL >= 100 / IELTS >= 7.5 (Northwestern institution code 5937)",
        "test": "GRE not required",
        "tui": "Northwestern McCormick graduate tuition (see SFS Cost of Attendance)",
        "url": "details/nu-mbp.html",
        "official": "https://www.mccormick.northwestern.edu/biotechnology/",
        "summary": "Northwestern MBP is an interdisciplinary MS in biotechnology jointly taught by Feinberg School of Medicine, Weinberg College of Arts and Sciences, and McCormick School of Engineering. Evanston campus, access to 100+ research labs (including Robert H. Lurie Comprehensive Cancer Center). 21-unit curriculum: 13 units coursework over 3 quarters + 8 units (6 months) full-time research in a preceptor's lab. Optional minors: Engineering Management, Entrepreneurship, Synthetic Biology; certificate: Nanobiotechnology. Cohort 30-40. Recommended GPA 3.5+. No application fee.",
    },
    {
        "id": "umich-ms-mathematics",
        "s": "umich",
        "n": "数学硕士",
        "en": "Master of Science in Mathematics (Rackham, LSA)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "~2 years full-time on-campus (Rackham)",
        "ddl": "Fall 2027: February 1, 2027 (MS)",
        "lang": "TOEFL/IELTS required (Rackham standard)",
        "test": "GRE required (see Math PhD/MS admissions page)",
        "tui": "Rackham graduate tuition (see Rackham Cost of Attendance)",
        "url": "details/umich-ms-mathematics.html",
        "official": "https://rackham.umich.edu/programs-of-study/",
        "summary": "University of Michigan Mathematics MS (LSA) granted through Rackham Graduate School. Program code 00279 (MS); separate from PhD (00278). Fall admission only. Applied and pure mathematics coursework, preparing students for industry, government, or doctoral study. Note: UMich Applied Statistics MS (already in database) is a separate professional program; this is the Mathematics MS in the Department of Mathematics.",
    },
    {
        "id": "cmu-msp",
        "s": "cmu",
        "n": "统计实务硕士",
        "en": "Master of Statistical Practice (MSP)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "12 months (2 consecutive semesters) full-time on-campus",
        "ddl": "See Dietrich Statistics & Data Science MSP admissions page (rolling/annual cohort)",
        "lang": "Recommended TOEFL >= 105",
        "test": "GRE required (see MSP admissions page)",
        "tui": "CMU Dietrich graduate tuition (see SCS/Dietrich Cost of Attendance)",
        "url": "details/cmu-msp.html",
        "official": "https://www.cmu.edu/dietrich/statistics-datascience/academics/msp/",
        "summary": "CMU Master of Statistical Practice (MSP) is an intensive 1-year, 2-semester professional master's in the Department of Statistics & Data Science (Dietrich College). 99 units minimum, no thesis requirement, no qualifying exam; the final client report and presentation in 36-726 functions in place of a thesis. Three focus areas: Data Analysis, Statistical Computing, Professional Skills. Designed for students seeking immediate industry placement as data scientists, data analysts, or data engineers. Note: a related 9-month MADS (MS in Applied Data Science) also exists; MSP is the 12-month version.",
    },
]

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">本页为半核验页：学位、学制、方向、官方链接、已核实学费（Northwestern McCormick 2025-26 官方费率）、申请轮次（MBP 三轮截止、MSIT 两轮截止）已从学校官网（McCormick/Rackham/Dietrich 公告页）核实；完整课程清单、材料清单、语言最低分具体小分、精确学费每学期金额等待系站恢复后补全。录取分数如后续补充均为"录取分布，非最低门槛"。</div>

</body>
</html>
"""

SCHOOL_ZH = {
    "nu": "西北大学",
    "umich": "密歇根大学安娜堡分校",
    "cmu": "卡内基梅隆大学",
}

# 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)")
