# -*- coding: utf-8 -*-
"""Round 281: add 5 independent PhD programs.
MIT CEE / MIT NSE / Princeton EEB / Harvard Biomedical Informatics / Waterloo Statistics
"""
import re, pathlib

ROOT = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52")
INDEX = ROOT / "index_main.html"
DET = ROOT / "details"
DET.mkdir(exist_ok=True)

PAGES = {
    "mit-cee-phd": {
        "id": "mit-cee-phd", "s": "mit",
        "n": "土木与环境工程 PhD",
        "en": "PhD / ScD in Civil and Environmental Engineering (MIT Department of CEE)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5–6 years full-time",
        "ddl": "Dec 15, 11:59 PM ET (Fall 2027 admission)",
        "lang": "IELTS / TOEFL iBT / Cambridge English / Duolingo accepted; MIT ELP minimums.",
        "test": {"cls": "GRE General OPTIONAL (institute code 3514, dept 1102; scores within 5 years; no minimum score; Transportation interdepartmental program prefers 80th percentile in all three sections)."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; application fee $90.",
        "url": "details/mit-cee-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Civil and Environmental Engineering (School of Engineering)",
        "website": "https://cee.mit.edu/education/graduate/",
        "overview": "MIT CEE is one of the top-ranked civil and environmental engineering departments in the world. The PhD/ScD program integrates engineering science, data science, and environmental systems across three broad themes: environmental science and engineering, infrastructure systems, and mechanics of materials. Affiliated programs include Computational Science and Engineering (CSE), WHOI Joint Program, Leaders for Global Operations (LGO), and Transportation.",
        "requirements": "Bachelor's or master's degree in engineering, physical sciences, or related quantitative field. Three letters of recommendation; statement of objectives; transcripts; CV. GRE optional — submit only if it strengthens application. Decisions released throughout March; admitted student open house mid-March; CGS April 15 decision deadline.",
        "research": "Environmental chemistry and microbiology; hydrology and climate; coastal and ocean engineering; mechanics of materials and structures; transportation systems; urban science; data-driven engineering; sustainable energy and water systems."
    },
    "mit-nse-phd": {
        "id": "mit-nse-phd", "s": "mit",
        "n": "核科学与工程 PhD",
        "en": "PhD / ScD in Nuclear Science and Engineering (MIT Department of NSE)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5–6 years full-time",
        "ddl": "Dec 15, 11:59 PM ET (Fall 2027 admission; no off-cycle applications)",
        "lang": "TOEFL iBT / IELTS / Cambridge English / Duolingo required; NSE does not offer English exam waivers.",
        "test": {"cls": "GRE General OPTIONAL (institute code 3514; scores within 5 years; included if provided)."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; application fee $90.",
        "url": "details/mit-nse-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Nuclear Science and Engineering (School of Engineering)",
        "website": "https://nse.mit.edu/education/graduate/",
        "overview": "MIT NSE is the leading nuclear science and engineering department in the United States. The PhD program trains researchers in nuclear fission and fusion engineering, plasma physics, radiation applications, nuclear materials, policy and energy systems, and nuclear security. The department also offers an interdisciplinary CSE-NSE doctoral program in computational nuclear science.",
        "requirements": "Strong undergraduate background in physics, engineering, mathematics, or related quantitative field. Exactly three letters of recommendation (no more than 3); statement of objectives; transcripts; CV. Unofficial transcripts acceptable at application; official required before enrollment. Oral exam by end of fourth graduate term; overall graduate GPA 4.0 required to take oral.",
        "research": "Fission reactor engineering and fuel cycles; fusion plasma physics; nuclear materials; radiation detection and medical applications; nuclear policy and energy systems; nonproliferation and security; computational nuclear science; waste management."
    },
    "princeton-eeb-phd": {
        "id": "princeton-eeb-phd", "s": "princeton",
        "n": "生态与演化生物学 PhD",
        "en": "PhD in Ecology and Evolutionary Biology (Princeton Department of EEB)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 11:59 PM ET (Fall 2027 admission)",
        "lang": "TOEFL iBT / IELTS required for non-native English speakers who did not complete undergraduate education at a US institution (ETS code 2672, no department code).",
        "test": {"cls": "GRE General NOT REQUIRED (optional to submit); Biology Subject Test NOT REQUIRED (optional to submit)."},
        "tui": "Full tuition + stipend + student health plan coverage for all admitted PhD students for 5 years; application fee $90 (fee waivers available).",
        "url": "details/princeton-eeb-phd.html",
        "school": "Princeton University",
        "dept": "Department of Ecology and Evolutionary Biology",
        "website": "https://eeb.princeton.edu/graduate",
        "overview": "Princeton EEB is a top-tier ecology and evolutionary biology department with strengths in evolution and genomics, ecology and the environment, behavior and organismal biology, conservation biology, and infectious disease. The program is departmentally reviewed (not by individual faculty group), but it is customary for applicants to have at least one faculty member willing to support their application.",
        "requirements": "Strong undergraduate background in biology with quantitative preparation. Three letters of recommendation; statement of purpose; transcripts. Applicants select a subplan when applying. First-year students take six core courses (EEB 502, 504, 506, 507, 521, 522 colloquium). One graduate program application per year; no second PhD in the same field.",
        "research": "Evolutionary and quantitative genetics; genomics; theoretical and empirical ecology; organismal and behavioral biology; conservation and biodiversity; infectious disease dynamics; tropical ecology; global change biology."
    },
    "harvard-biomedical-informatics-phd": {
        "id": "harvard-biomedical-informatics-phd", "s": "harvard",
        "n": "生物医学信息学 PhD",
        "en": "PhD in Biomedical Informatics (Harvard Integrated Life Sciences / Harvard Medical School)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 5:00 PM ET (Fall 2027 admission)",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0.",
        "test": {"cls": "GRE General OPTIONAL; GRE Subject OPTIONAL. Interviews conducted late December through early January."},
        "tui": "Full tuition + stipend + health fees covered by departmental/HGSAS funding for all admitted PhD students; application fee $105.",
        "url": "details/harvard-biomedical-informatics-phd.html",
        "school": "Harvard University",
        "dept": "Biomedical Informatics (part of Harvard Integrated Life Sciences, HILS)",
        "website": "https://gsas.harvard.edu/program/biomedical-informatics",
        "overview": "The Harvard Biomedical Informatics PhD is a cross-school program within Harvard Integrated Life Sciences (HILS), jointly administered by Harvard Medical School and Harvard T.H. Chan School of Public Health. It trains researchers at the intersection of data science, medicine, and biology. The Bioinformatics and Integrative Genomics (BIG) track admits students with quantitative backgrounds and biological interest.",
        "requirements": "Strong quantitative preparation (CS, math, statistics, physics, bioengineering) OR biological sciences with strong programming/quantitative aptitude. Three letters of recommendation; statement of purpose; personal statement; transcripts. Interviews are part of the process. HILS programs share a common admissions curriculum.",
        "research": "Computational biology and bioinformatics; machine learning for medicine; clinical informatics; biomedical data science; genomics and multi-omics; health natural language processing; imaging informatics; population health informatics."
    },
    "uw-statistics-phd": {
        "id": "uw-statistics-phd", "s": "uw",
        "n": "统计学 PhD",
        "en": "PhD in Statistics (Department of Statistics and Actuarial Science, Faculty of Mathematics)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "48 months (4 years) full-time",
        "ddl": "Jan 15 (for September Fall admission; apply 2–4 weeks earlier for best consideration)",
        "lang": "TOEFL iBT 90 overall (25 writing, 25 speaking); IELTS Academic 7.0 overall (6.5 writing, 6.5 speaking); Cambridge C1/C2 185.",
        "test": {"cls": "GRE not listed on current admissions requirements page; Canadian graduate admissions typically do not require GRE for statistics PhD."},
        "tui": "Fully funded by graduate awards, Teaching Assistantships, and Research Assistantships covering tuition plus stipend for all admitted PhD students.",
        "url": "details/uw-statistics-phd.html",
        "school": "University of Waterloo",
        "dept": "Department of Statistics and Actuarial Science, Faculty of Mathematics",
        "website": "https://uwaterloo.ca/statistics-and-actuarial-science/graduate-students/graduate-programs/doctor-philosophy-phd-statistics",
        "overview": "The Waterloo Statistics PhD is an internationally respected research degree designed to train independent researchers in statistical theory, methodology, and applications. The program builds on a master's-level background and emphasizes scientific methods, computational statistics, and communication. Students may also pursue a related field in actuarial science or biostatistics.",
        "requirements": "Master's degree in statistics, actuarial science, mathematics, or a related quantitative field (commerce, economics, engineering, finance, physical sciences) with at least 78% average. Three references (normally academic); statement of interest; transcripts; CV. On-campus thesis option; full-time or part-time registration. International applicants should apply at least 2 months early for visa processing.",
        "research": "Computational statistics; statistical theory and methods; probability; industrial statistics; statistics in finance; biostatistics and bioinformatics; statistical learning; data science; environmental and actuarial applications."
    },
}

PAGE_TMPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} · {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI','PingFang SC',sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{font-size:24px;margin-bottom:4px}}
h2{{font-size:18px;color:#1a4480;border-bottom:1px solid #d8dde6;padding-bottom:6px;margin-top:28px}}
.meta{{background:#f4f7fb;border-left:4px solid #1a4480;padding:12px 16px;border-radius:4px;margin:14px 0}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:10px 24px}}
.kv{{font-size:14px}}
.kv b{{color:#1a4480}}
.badge{{display:inline-block;background:#e6efff;color:#1a4480;padding:2px 8px;border-radius:10px;font-size:12px;margin-right:6px}}
ul{{margin:6px 0 6px 22px}}
</style>
</head>
<body>
<h1>{n}</h1>
<div style="color:#666;margin-bottom:14px">{en}</div>
<div class="meta">
<div><span class="badge">{school}</span><span class="badge">{dept}</span><span class="badge">stem_label</span></div>
<div class="grid" style="margin-top:10px">
<div class="kv"><b>学位</b>：{deg}</div>
<div class="kv"><b>学制</b>：{duration}</div>
<div class="kv"><b>截止</b>：{ddl}</div>
<div class="kv"><b>语言</b>：{lang}</div>
<div class="kv"><b>标化</b>：{test_cls}</div>
<div class="kv"><b>学费/资助</b>：{tui}</div>
</div>
</div>
<h2>项目概览</h2><p>{overview}</p>
<h2>申请要求</h2><p>{requirements}</p>
<h2>研究方向</h2><p>{research}</p>
<p style="margin-top:24px;color:#888;font-size:12px">官网：<a href="{website}">{website}</a></p>
</body></html>"""


def render(p):
    p = dict(p)
    p["lvl_label"] = "Doctoral" if p["lvl"] == "d" else "Master's"
    p["duration"] = p["dur"]
    p["test_cls"] = p["test"]["cls"]
    return PAGE_TMPL.format(**p)


def append_program(html, rec):
    m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                end = i
                break
        i += 1
    else:
        raise RuntimeError("PROGRAMS end not found")
    block = (
        f',{{id:"{rec["id"]}",s:"{rec["s"]}",n:"{rec["n"]}",en:"{rec["en"]}",'
        f'deg:"{rec["deg"]}",lvl:"{rec["lvl"]}",stem:{rec["stem"]},dur:"{rec["dur"]}",'
        f'ddl:"{rec["ddl"]}",lang:"{rec["lang"]}",test:{{cls:"{rec["test"]["cls"]}"}},'
        f'tui:"{rec["tui"]}",url:"{rec["url"]}"}}'
    )
    return html[:end] + block + html[end:]


def append_vd(html, det_path):
    m = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[', html)
    if not m:
        raise RuntimeError("VD Set not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                end = i
                break
        i += 1
    else:
        raise RuntimeError("VD end not found")
    existing = html[start:end]
    stripped = existing.rstrip()
    if not stripped.endswith(','):
        stripped = stripped + ','
    new_block = stripped + f'"{det_path}"'
    return html[:start] + new_block + html[end:]


def main():
    html = INDEX.read_text(encoding="utf-8")
    size_before = len(html.encode("utf-8"))
    for key, p in PAGES.items():
        out = DET / (key + ".html")
        out.write_text(render(p), encoding="utf-8")
        print(f"wrote {out.relative_to(ROOT)}")
        html = append_program(html, p)
        html = append_vd(html, p["url"])
    size_after = len(html.encode("utf-8"))
    INDEX.write_text(html, encoding="utf-8")
    print(f"index_main.html: {size_before} -> {size_after} bytes (delta +{size_after-size_before})")
    print("done.")


if __name__ == "__main__":
    main()
