# -*- coding: utf-8 -*-
"""Round 280: add 5 independent PhD programs.
USC Accounting / Waterloo CS / Princeton Biophysics / Harvard Biostatistics / MIT BE
"""
import os, 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 = {
    "usc-accounting-phd": {
        "id": "usc-accounting-phd", "s": "usc",
        "n": "会计学 PhD",
        "en": "PhD in Accounting (Marshall School of Business)",
        "deg": "PhD", "lvl": "d", "stem": 0,
        "dur": "5–6 years full-time",
        "ddl": "Dec 15, 2026 (Fall 2027 admission)",
        "lang": "TOEFL iBT / IELTS required for international applicants (USC Marshall minimums per grad school policy)",
        "test": {"cls": "GRE General or GMAT REQUIRED (no exceptions for all applicants regardless of background; GMAT Focus accepted; scores valid within 5 years)."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students (Marshall funding package); application fee $95.",
        "url": "details/usc-accounting-phd.html",
        "school": "University of Southern California",
        "dept": "Marshall School of Business – Leventhal School of Accounting",
        "website": "https://www.marshall.usc.edu/programs/graduate-programs/phd-program/accounting",
        "overview": "The USC Marshall PhD in Accounting trains researchers for careers in leading business schools and research institutions. The program spans financial accounting, managerial accounting, and auditing/corporate governance research. Students work closely with Marshall faculty on empirical and theoretical research across capital markets, disclosure, taxation, and management control.",
        "requirements": "Bachelor's degree in any field (master's/MBA not required); one year of college calculus is a hard prerequisite; matrix algebra, introductory mathematical statistics, and intermediate microeconomic theory are strongly desirable. Three letters of recommendation; statement of purpose; current CV; transcripts. International applicants: TOEFL/IELTS. Decisions mid-Feb to mid-April.",
        "research": "Financial accounting (capital markets, disclosure, international accounting); managerial accounting (budgeting, control, strategic management accounting); auditing and corporate governance; taxation; accounting information systems."
    },
    "uw-cs-phd": {
        "id": "uw-cs-phd", "s": "uw",
        "n": "计算机科学 PhD",
        "en": "PhD in Computer Science (David R. Cheriton School of Computer Science, Faculty of Mathematics)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "48 months (4 years) full-time",
        "ddl": "Dec 1 for September admission; Jun 1 for January admission; Oct 1 for May admission (rolling intakes)",
        "lang": "TOEFL iBT 100 overall (26 writing, 26 speaking); IELTS Academic 7.5 (7.0 writing, 7.0 speaking) — Cheriton uses higher than faculty-of-math baseline.",
        "test": {"cls": "GRE not listed on current program page; older graduate calendar noted GRE for applicants outside North America, but current admissions page does not require GRE scores."},
        "tui": "Tuition approx. CAD 19,950/year (2026); funded by research/teaching assistantships covering tuition plus stipend for admitted students.",
        "url": "details/uw-cs-phd.html",
        "school": "University of Waterloo",
        "dept": "David R. Cheriton School of Computer Science, Faculty of Mathematics",
        "website": "https://uwaterloo.ca/computer-science/future-graduate-students",
        "overview": "The Cheriton School of Computer Science at Waterloo is Canada's largest and most influential CS department, with strengths in algorithms, AI, machine learning, systems, security, programming languages, quantum computing, and HCI. The PhD is a research thesis degree typically completed in four years.",
        "requirements": "Master's degree in CS with at least 78% average; exceptional BS in CS candidates may apply directly to the PhD. Three references (at least two academic); statement of interest (max 500 words); transcripts; CV. On-campus, full-time or part-time thesis option. Faculty of Math ELP exemption applies for 3+ years at English-instruction institutions.",
        "research": "Algorithms and complexity; artificial intelligence; bioinformatics; computer graphics; cryptography/security/privacy; databases; formal methods; HCI; information retrieval; machine learning; programming languages; quantum computing; scientific computing; software engineering; systems and networking."
    },
    "princeton-biophysics-phd": {
        "id": "princeton-biophysics-phd", "s": "princeton",
        "n": "生物物理 PhD",
        "en": "PhD in Biophysics (Lewis-Sigler Institute for Integrative Genomics)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 11:59 PM ET (Fall 2027 admission)",
        "lang": "TOEFL / IELTS / Duolingo required for international applicants (Princeton Graduate School minimums).",
        "test": {"cls": "GRE General Test NOT ACCEPTED. Subject tests not required. Test scores are not part of the review."},
        "tui": "Full tuition + stipend + health coverage for all admitted PhD students for 5 years; application fee $90 (fee waivers available).",
        "url": "details/princeton-biophysics-phd.html",
        "school": "Princeton University",
        "dept": "Lewis-Sigler Institute for Integrative Genomics — Program in Biophysics (BPY)",
        "website": "https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/biophysics",
        "overview": "The Princeton Biophysics PhD (BPY) is an interdisciplinary degree-granting program administered by the Lewis-Sigler Institute, linking physical science and life science faculty across Chemistry, Chemical and Biological Engineering, Computer Science, Ecology and Evolutionary Biology, Mechanical Engineering, Molecular Biology, Neuroscience, and Physics. Research spans molecules to cells to ecosystems in both experiment and theory.",
        "requirements": "Strong undergraduate background in physical sciences, life sciences, or engineering; admission to one degree program per year only; Princeton does not offer admission to candidates seeking a second PhD in the same or similar field. Three letters of recommendation; statement of purpose; transcripts. Dissertation and Final Public Oral (FPO) required.",
        "research": "Single-molecule biophysics; systems biology; quantitative cell biology; biophysics of development; theoretical and computational biophysics; biophysics of ecosystems and behavior; genomics and integrative biology."
    },
    "harvard-biostatistics-phd": {
        "id": "harvard-biostatistics-phd", "s": "harvard",
        "n": "生物统计 PhD",
        "en": "PhD in Biostatistics (Harvard Kenneth C. Griffin GSAS / Harvard T.H. Chan School of Public Health)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 5:00 PM ET (Fall 2027 admission)",
        "lang": "TOEFL iBT / IELTS / Duolingo required; Harvard GSAS minimums (TOEFL iBT 80+ typical, competitive pool higher).",
        "test": {"cls": "GRE General REQUIRED (Harvard GSAS Biostatistics program page explicitly lists GRE General as Required; scores within 5 years)."},
        "tui": "Full tuition + stipend + health fees covered by departmental/GSAS funding for all admitted PhD students; application fee $105.",
        "url": "details/harvard-biostatistics-phd.html",
        "school": "Harvard University",
        "dept": "Department of Biostatistics, Harvard T.H. Chan School of Public Health (GSAS)",
        "website": "https://gsas.harvard.edu/program/biostatistics",
        "overview": "The Harvard Biostatistics PhD is a research degree housed in the Chan School of Public Health and awarded by the Kenneth C. Griffin Graduate School of Arts and Sciences. It trains students to develop statistical methods and theory for applications in public health, medicine, biology, and the social sciences.",
        "requirements": "Required undergraduate preparation: multivariable calculus through integration; one semester of linear algebra; two semesters of probability / statistics / mathematical statistics; programming in R, Python, SAS, or Stata. Strongly encouraged: advanced calculus or real analysis, numerical analysis. For bioinformatics interest: biology, computational biology, genetics coursework and scripting. Three recommendations; statement of purpose; personal statement required.",
        "research": "Statistical theory and methodology; high-dimensional inference; causal inference; missing data and measurement error; genomic and transcriptomic data analysis; clinical trials; environmental statistics; statistical computing and reproducible research."
    },
    "mit-be-phd": {
        "id": "mit-be-phd", "s": "mit",
        "n": "生物工程 PhD",
        "en": "PhD in Biological Engineering (MIT Department of Biological Engineering)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 11:59 PM ET (Fall 2027 admission)",
        "lang": "IELTS Academic 7.0+; TOEFL iBT 100+; Duolingo English Test accepted. Electronic scores to MIT Graduate.",
        "test": {"cls": "GRE NOT ACCEPTED — department explicitly states it will not view or consider GRE scores during review, even if submitted."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students (no separate financial aid application); application fee $90.",
        "url": "details/mit-be-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Biological Engineering (School of Engineering / School of Science)",
        "website": "https://be.mit.edu/graduate-program/phd-program/",
        "overview": "MIT Biological Engineering is an engineering department built around the quantitative and molecular understanding of living systems. The PhD integrates biology, engineering, computation, and physics to train researchers for academic and industry leadership in biotechnology, synthetic biology, biomedical engineering, and quantitative biology.",
        "requirements": "Strong undergraduate background in engineering, physics, chemistry, or biology; no minimum GPA but admitted pool averages 3.8–3.9 / 4.0. Three letters of recommendation (research-supervisor letters especially impactful); statement of objectives; transcripts; CV. STEM-designated degree. No separate application for funding — all admitted students receive a support package.",
        "research": "Synthetic biology; systems biology; quantitative and computational biology; molecular and cellular bioengineering; biomaterials and drug delivery; biophotonics and imaging; neuroengineering; biomechanics; bioinformatics and machine learning for biology."
    },
}

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):
    # locate PROGRAMS array end via bracket depth
    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):
    # locate VERIFIED_DETAILS=new Set([ ... ])
    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")
    # insert before ]
    existing = html[start:end]
    # strip trailing comma/whitespace
    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()
