# -*- coding: utf-8 -*-
"""Round 159: 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")

# (id, s, n_zh, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official_url)
NEW = [
    {
        "id": "duke-meng-cmsc",
        "s": "duke",
        "n": "计算力学与科学计算工程硕士",
        "en": "Master of Engineering in Computational Mechanics and Scientific Computing",
        "deg": "MEng",
        "lvl": "m",
        "stem": 1,
        "dur": "1 year (3 semesters) on-campus",
        "ddl": "Fall 2027: see Pratt Professional Programs page",
        "lang": "TOEFL/IELTS required (see Pratt Graduate Admissions)",
        "test": "GRE optional (per Pratt general policy)",
        "tui": "2026-27: $35,680/semester (Pratt MEng standard); total ~$107,040",
        "url": "details/duke-meng-cmsc.html",
        "official": "https://prattprofessional.bulletins.duke.edu/allprograms/e-egr/cmsc",
        "summary": "Duke Pratt MEng in Computational Mechanics & Scientific Computing, housed in CEE with Engineering Management Program oversight. Applied, non-thesis professional master's emphasizing finite element methods, uncertainty quantification, solid/fluid mechanics modeling, and data-driven simulation. 4 concentration courses (1 fluid mechanics, 1 mechanics of materials, 1 optimization/data analytics, 1 additional), plus required business/leadership core and a 0-credit internship/project.",
    },
    {
        "id": "umich-ms-bme",
        "s": "umich",
        "n": "生物医学工程硕士",
        "en": "Master of Science in Biomedical Engineering (MS/MSE)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "~2 years full-time on-campus (Rackham)",
        "ddl": "Fall 2027: January 15, 2027 (MS)",
        "lang": "TOEFL/IELTS required (Rackham standard)",
        "test": "General GRE neither required nor accepted",
        "tui": "Rackham graduate tuition (see Rackham Cost of Attendance)",
        "url": "details/umich-ms-bme.html",
        "official": "https://bme.umich.edu/academics/graduate/masters/masters-ms-and-mse/",
        "summary": "U-M Biomedical Engineering (joint Michigan Engineering + U-M Medical School) offers Rackham MS/MSE. On-campus, fall admission only. Five concentrations: Biomechanics & Biotransport; Bioelectrics & Neural Engineering; Biomaterials & Regenerative Medicine; Biomedical Imaging & Ultrasonics; Biotechnology. Recommended minimum GPA 3.2/4.0; strong applicants from engineering, math, physics, chemistry, or biology. Program code 00095 (MS).",
    },
    {
        "id": "cmu-msr",
        "s": "cmu",
        "n": "机器人学硕士（研究型）",
        "en": "Master of Science in Robotics (MSR)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "24 months full-time on-campus (Aug graduation)",
        "ddl": "Fall admission (see RI MSR admissions page)",
        "lang": "TOEFL/IELTS required (CMU CID standard)",
        "test": "GRE required (see RI MSR admissions)",
        "tui": "CMU graduate tuition (see SCS/Robotronics cost of attendance)",
        "url": "details/cmu-msr.html",
        "official": "https://www.ri.cmu.edu/education/academic-programs/master-of-science-robotics/",
        "summary": "Carnegie Mellon Robotics Institute MSR is a 24-month research-oriented terminal master's. 168 units minimum, four core courses + three electives + supervised research under a faculty advisor, culminating in a public thesis talk and Master's Thesis document. Designed to mimic first two years of PhD; prepares students for research careers at industry labs, government agencies, or PhD programs. Note: a separate professional 21-month MRSD track exists for systems development; MSR is the research track.",
    },
    {
        "id": "col-ma-economics",
        "s": "col",
        "n": "经济学文学硕士",
        "en": "Master of Arts in Economics (Free-Standing MA)",
        "deg": "MA",
        "lvl": "m",
        "stem": 1,
        "dur": "3 semesters full-time on-campus (Columbia GSAS)",
        "ddl": "Fall 2027: January 21, 2027",
        "lang": "TOEFL/IELTS required (GSAS standard)",
        "test": "GRE General required",
        "tui": "GSAS graduate tuition per point (see GSAS Cost of Attendance)",
        "url": "details/col-ma-economics.html",
        "official": "https://www.gsas.columbia.edu/content/economics-ma",
        "summary": "Columbia Economics free-standing MA through GSAS. Technical, rigorous approach to economic theory. 8 core courses (Math Methods, Micro I/II, Macro I/II, Econometrics I/II + second-fall core) plus at least 9 credits of field electives, and a required research paper capstone. STEM-designated: F-1 holders eligible for 24-month OPT STEM extension. 3 letters of recommendation (at least 2 academic).",
    },
    {
        "id": "umich-ms-bioinformatics",
        "s": "umich",
        "n": "生物信息学硕士",
        "en": "Master of Science in Bioinformatics (DCMB)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "~1.5 years (3 terms) full-time on-campus",
        "ddl": "Fall 2027: March 1, 2027 (all applicants, international & domestic)",
        "lang": "TOEFL/IELTS required (Rackham standard)",
        "test": "No GRE required",
        "tui": "Rackham graduate tuition (see Rackham Cost of Attendance)",
        "url": "details/umich-ms-bioinformatics.html",
        "official": "https://medicine.umich.edu/dept/dcmb/education/graduate-admissions",
        "summary": "U-M Bioinformatics MS housed in Department of Computational Medicine & Bioinformatics (DCMB, Michigan Medicine) and granted through Rackham. Minimum 30 credit hours + required research experience + research presentation. 1.5 years (3 terms) typical. Apply through Rackham; program code 01638 (MS). Recommended background: at least two of molecular biology, biochemistry, mathematics, statistics, computer science. Minimum GPA 3.2/4.0; 3 letters of recommendation. Note: separate AMDP (5th-year UM undergrad only) and PhD/MS dual-degree tracks also exist.",
    },
]

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">本页为半核验页：学位、学制、方向、官方链接已从学校官网（Rackham/GSAS/Pratt/Robotics Institute 公告页）核实；完整课程清单、材料清单、语言最低分、GRE 分项分数、精确学费每学期金额等待系站恢复后补全。录取分数如后续补充均为"录取分布，非最低门槛"。</div>

</body>
</html>
"""

SCHOOL_ZH = {
    "duke": "杜克大学",
    "umich": "密歇根大学安娜堡分校",
    "cmu": "卡内基梅隆大学",
    "col": "哥伦比亚大学",
}

# 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):
    """Locate the matching ] for const XXX=[, tracking bracket depth."""
    i = s.index(start_marker)
    # find first [
    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")

# Build new PROGRAMS entries
def fmt_entry(p):
    cls = "STEM" if p["stem"] == 1 else ""
    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)

# PROGRAMS
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: const VERIFIED_DETAILS=new Set([...])
# find the Set([ ... ]) end
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)
# Check char before vd_end: if it's " (no trailing comma) add leading comma
if html[vd_end-1] == '"':
    html = html[:vd_end] + new_vd + html[vd_end:]
else:
    # ends with comma, just insert urls (no leading comma needed if we already have it; safer: if comma already, insert after)
    # strip existing trailing comma then add
    if 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)")
