#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Round 153: UMich x3 + Duke + CMU, 5 master programs
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
IDX = os.path.join(BASE, 'index_main.html')

projects = [
    {
        "id": "umich-ms-applied-statistics",
        "s": "umich",
        "n": "应用统计学硕士",
        "en": "Applied Statistics (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "3-4 semesters full-time (30 credits, ~10 courses; most students take 2 years/4 semesters, well-prepared may finish in 3)",
        "ddl": "Jan 15 (Fall admission, MS/Bridge)",
        "lang": "TOEFL/IELTS per Rackham Graduate School",
        "test": {"cls": "GRE not required (admission distribution, not minimum threshold); prereqs: calculus + linear algebra + probability + theoretical stats + applied/computational stats or ML"},
        "tui": "TBD (Rackham graduate tuition)",
        "url": "details/umich-ms-applied-statistics.html",
        "fields": ["Probability & Theoretical Statistics", "Statistical Modeling", "Data Analysis", "Computational Statistics", "Machine Learning", "Cognate (Biostat/CS/Econ/IOE/Math/Sociology/SRC)"],
        "school": "University of Michigan-Ann Arbor",
        "official": "https://lsa.umich.edu/stats/masters-students/masters-programs/applied-stats-masters-program.html",
        "note": "LSA Department of Statistics, Rackham Graduate School. Career-oriented applied statistics MS for industry/government/consulting/research. Cross-registerable with Biostat, CS, Economics, IOE, Math, Information, Sociology, Survey Research Center. GPA must stay 3.0+. Separate admissions pool from PhD. Variants: Bridge MS (dual with other Rackham programs) and AMDP (UMich undergrad accelerated). This entry is the main external-applicant MS.",
    },
    {
        "id": "duke-ms-statistical-science",
        "s": "duke",
        "n": "统计科学硕士",
        "en": "Statistical Science (MS, MSS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "2 years full-time (36 credits: >=24 graded STA credits + up to 6 ungraded STA credits; includes year-long capstone project)",
        "ddl": "TBD (Duke Graduate School Fall regular deadline, ~Dec-Jan)",
        "lang": "TOEFL/IELTS per Duke Graduate School",
        "test": {"cls": "GRE per Duke Graduate School (admission distribution, not minimum threshold); prereqs: 2-semester calculus-based probability & math stats + matrix algebra + applied regression + R/Python programming"},
        "tui": "TBD (Duke Graduate School tuition)",
        "url": "details/duke-ms-statistical-science.html",
        "fields": ["Predictive Modeling & Statistical Learning", "Programming for Statistical Science", "Theory of Statistical Inference", "Bayesian & Modern Statistical Data Analysis", "Statistical Computing", "Multilevel & Hierarchical Models", "Year-long Capstone Project"],
        "school": "Duke University",
        "official": "https://stat.duke.edu/ms",
        "note": "Department of Statistical Science, Duke Graduate School. MSS (Master's in Statistical Science) differs from MIDS (Master in Interdisciplinary Data Science, already in DB): MSS focuses on statistical methods depth and theory/computation; MIDS is broader data-science pipeline with 9-month practicum. Duke is a globally recognized Bayesian research center. Offers collaborative research with NISS (National Institute of Statistical Sciences). Graduates go to data scientist/statistician roles in industry/government/research or PhD continuation.",
    },
    {
        "id": "cmu-msppm-pittsburgh",
        "s": "cmu",
        "n": "公共政策与管理硕士（匹兹堡两年制）",
        "en": "Public Policy and Management (MSPPM, Pittsburgh Two-Year)",
        "deg": "MS",
        "lvl": "m", "stem": 0,
        "dur": "2 years full-time (192 units; 4 consecutive semesters + required summer internship; includes Capstone Project)",
        "ddl": "TBD (Heinz College rolling/round deadlines)",
        "lang": "TOEFL/IELTS per CMU Graduate School",
        "test": {"cls": "GRE/GMAT TBD (admission distribution, not minimum threshold); quantitative and policy-analysis background expected"},
        "tui": "TBD (Heinz College tuition)",
        "url": "details/cmu-msppm-pittsburgh-two-year.html",
        "fields": ["Cybersecurity & Management", "Energy Systems & Public Policy", "Environmental Policy", "Health Policy", "International Trade & Development", "Management", "Policy Analysis", "Public & Non-Profit Finance", "Smart Communities", "Urban & Regional Economic Development"],
        "school": "Carnegie Mellon University",
        "official": "https://www.heinz.cmu.edu/programs/public-policy-management-master/pittsburgh-two-year",
        "note": "Heinz College of Information Systems and Public Policy. Flagship MSPPM, full-time professional degree, interdisciplinary policy + technology + management. Core: quantitative management, evidence-based problem-solving, communication and strategic thinking. Four pathways: MSPPM Pittsburgh (this entry), MSPM Data Analytics (STEM), MSPM 3-Semester Fast Track, MSPM Washington DC. 10 optional concentrations. Most students receive merit-based fellowship ($5k to full tuition). Nearly half of graduates in recent 3 years started at $75k+.",
    },
    {
        "id": "umich-mpp-ford",
        "s": "umich",
        "n": "公共政策硕士（福特学院）",
        "en": "Public Policy (MPP, Ford School)",
        "deg": "MPP",
        "lvl": "m", "stem": 0,
        "dur": "2 years full-time (48 credits: 24.5 core + 23.5 electives; required summer internship between year 1 and year 2)",
        "ddl": "Jan 15 (Fall admission, priority for merit fellowship)",
        "lang": "TOEFL/IELTS per Rackham Graduate School",
        "test": {"cls": "GRE optional (may substitute quantitative preparation statement; admission distribution, not minimum threshold); dual-degree with Law/Medicine/Ross may use LSAT/MCAT/GMAT respectively"},
        "tui": "TBD (Ford School tuition; ~2/3 of residential students receive tuition fellowship, $5k to full)",
        "url": "details/umich-mpp-ford.html",
        "fields": ["Public Management", "Integrated Policy Exercise", "Microeconomics for Policy", "Statistics & Data Analysis for Policy", "Political Institutions", "Policy Design & Implementation", "Ethics & Public Policy"],
        "school": "University of Michigan-Ann Arbor",
        "official": "https://fordschool.umich.edu/masters/mpp",
        "note": "Gerald R. Ford School of Public Policy. Top-ranked public policy school. Enrolls ~100 students per year, full-time daytime. Dual master's with 14 U-M schools (Law/Business/Education/Public Health/Social Work, etc.). Graduates go to government at all levels, military/national security, nonprofits, international NGOs, private consulting. Differs from 9-month MPA (mid-career, requires 5+ years policy experience): MPP is for regular entry-level. Online MPA (launched 2026) is for working professionals and excluded; this entry is the in-person full-time MPP.",
    },
    {
        "id": "umich-ross-mban",
        "s": "umich",
        "n": "商业分析硕士（Ross MBAn）",
        "en": "Business Analytics (MBAn, Ross School of Business)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "10 months full-time (Summer start: June to next April; 35.75 credits; includes Business Analytics Consulting Studio)",
        "ddl": "Round-based: R1 9/11/2026, R2 10/23/2026, R4 2/19/2027, R5 4/2/2027, R6 5/14/2027 (Summer entry)",
        "lang": "TOEFL/IELTS per Ross Graduate Admissions",
        "test": {"cls": "GMAT/GRE TBD (admission distribution, not minimum threshold); aimed at high-achieving recent graduates comfortable with complex data"},
        "tui": "TBD (Ross One-Year Master tuition; mean base salary $97,500, 94% job-offer rate within 6 months of graduation)",
        "url": "details/umich-ross-mban.html",
        "fields": ["Data Engineering", "Data Architecture", "Machine Learning", "Business Fundamentals", "Cross-functional Electives (Fintech/Biotech)", "Business Analytics Consulting Studio"],
        "school": "University of Michigan-Ann Arbor",
        "official": "https://michiganross.umich.edu/graduate/master-of-business-analytics",
        "note": "Ross School of Business One-Year Master's program. Full-time residential, takes cross-functional electives alongside MBA students. STEM-designated. Action-based curriculum emphasizing data-driven leadership. Part of Ross one-year master cohort with Master of Accounting, Master of Management, Master of Supply Chain Management. Cannot apply to MBA in same application cycle. Program cannot be extended beyond one academic year.",
    },
]

DETAIL_TPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} {n} - Project Detail</title>
<style>
body{{font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7;}}
h1{{font-size:24px;border-bottom:3px solid #1a5fb4;padding-bottom:8px;}}
h2{{font-size:18px;color:#1a5fb4;margin-top:28px;}}
.meta{{background:#f5f7fa;padding:14px 18px;border-radius:8px;margin:16px 0;}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:10px 24px;}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a5fb4;padding:2px 10px;border-radius:12px;font-size:13px;margin:2px 4px 2px 0;}}
a{{color:#1a5fb4;}}
.note{{background:#fff8e1;padding:12px 16px;border-left:4px solid #f9a825;margin:16px 0;font-size:14px;}}
</style>
</head>
<body>
<h1>{school} · {n}</h1>
<div class="meta">
<div class="grid">
<div><b>English name:</b> {en}</div>
<div><b>Degree:</b> {deg}</div>
<div><b>Duration:</b> {dur}</div>
<div><b>STEM:</b> {stem_yn}</div>
<div><b>Deadline:</b> {ddl}</div>
<div><b>Language:</b> {lang}</div>
<div><b>Tests:</b> {test_cls}</div>
<div><b>Tuition:</b> {tui}</div>
</div>
</div>
<h2>Concentrations / Fields</h2>
{fields_html}
<h2>Program Notes</h2>
<div class="note">{note}</div>
<h2>Official Link</h2>
<p><a href="{official}" target="_blank">{official}</a></p>
<p><a href="index_main.html">Back to project library</a></p>
</body>
</html>
"""

for p in projects:
    fields_html = "\n".join(f'<span class="tag">{f}</span>' for f in p["fields"])
    html = DETAIL_TPL.format(
        school=p["school"], n=p["n"], en=p["en"], deg=p["deg"],
        dur=p["dur"], stem_yn="Yes" if p["stem"] else "No",
        ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"], tui=p["tui"],
        fields_html=fields_html, note=p["note"], official=p["official"]
    )
    with open(os.path.join(BASE, p["url"]), "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] generated: {p['url']} ({len(html)} chars)")

with open(IDX, "r", encoding="utf-8") as f:
    idx = f.read()

def esc(s):
    return s.replace("\\", "\\\\").replace('"', '\\"')

prog_records = []
for p in projects:
    rec = (
        '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
        'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},tui:"{tui}",'
        'url:"{url}"}}'
    ).format(
        id=p["id"], s=p["s"], n=esc(p["n"]), en=esc(p["en"]), deg=p["deg"],
        lvl=p["lvl"], stem=p["stem"], dur=esc(p["dur"]), ddl=esc(p["ddl"]),
        lang=esc(p["lang"]), test_cls=esc(p["test"]["cls"]), tui=esc(p["tui"]),
        url=p["url"]
    )
    prog_records.append(rec)

m = re.search(r'(const PROGRAMS\s*=\s*\[)', idx)
start = m.end()
depth = 1; i = start
while i < len(idx) and depth > 0:
    if idx[i] == '[': depth += 1
    elif idx[i] == ']': depth -= 1
    i += 1
insert_pos = i - 1
j = insert_pos - 1
while j >= 0 and idx[j] in ' \t\n\r': j -= 1
if j >= 0 and idx[j] not in ',[':
    insert_text = "," + ",".join(prog_records)
else:
    insert_text = ",".join(prog_records)
idx = idx[:insert_pos] + insert_text + idx[insert_pos:]
print(f"[OK] PROGRAMS appended {len(prog_records)}")

m2 = re.search(r'(VERIFIED_DETAILS\s*=\s*new Set\(\[)', idx)
vd_start = m2.end()
depth = 1; i = vd_start
while i < len(idx) and depth > 0:
    if idx[i] == '[': depth += 1
    elif idx[i] == ']': depth -= 1
    i += 1
vd_insert = i - 1
j = vd_insert - 1
while j >= 0 and idx[j] in ' \t\n\r': j -= 1
last_char = idx[j] if j >= 0 else ''
new_vd = ",".join(f'"{p["url"]}"' for p in projects)
if last_char == ',':
    vd_text = new_vd
elif last_char == '"':
    vd_text = "," + new_vd
else:
    vd_text = "," + new_vd
idx = idx[:vd_insert] + vd_text + idx[vd_insert:]
print(f"[OK] VERIFIED_DETAILS appended {len(projects)}")

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