"""r286: add 5 independent PhD — MIT Architecture / UofT MSE / Yale ACM / Cornell ORIE / Harvard Biostatistics."""
import re
from pathlib import Path

ROOT = Path(r"D:\work buddy\2026-11-05-14-15-52")
IDX = ROOT / "index_main.html"
DETAILS = ROOT / "details"

PAGES = {
    "mit-architecture-phd": {
        "id": "mit-architecture-phd",
        "s": "mit",
        "n": "MIT建筑学博士",
        "en": "PhD in Architecture",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years (typical; coursework + general exams + dissertation)",
        "ddl": "Jan 7, 2027 at 11:59pm ET (Fall 2027 entry; application opens Sep 15)",
        "lang": "TOEFL iBT 100 / IELTS Academic 7.0 / DET 135 / Cambridge C1 190 / C2 200 (MIT OGS recommended minimum; Home Version accepted)",
        "test": "GRE General: NOT ACCEPTED (Department of Architecture does not accept GRE scores and will not consider them in evaluation)",
        "tui": "Fully funded (tuition + stipend) via research/teaching assistantships; application fee $90; ETS institution code 3514",
        "url": "details/mit-architecture-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Architecture (School of Architecture and Planning)",
        "website": "https://architecture.mit.edu/graduate-admissions",
        "overview": "The PhD in Architecture at MIT is a research-intensive doctoral program offered by the Department of Architecture within the School of Architecture and Planning. The PhD is offered in three areas: Building Technology, Design and Computation, and History, Theory and Criticism of Architecture and Art. The program sequence consists of required subject work, general examinations, and dissertation research, writing, and defense. Fall admission only. The January 7 deadline is notably later than most MIT departments (Dec 1-15 cluster).",
        "requirements": "Bachelor's or master's degree in architecture or related field; GRE NOT accepted (department explicitly does not consider GRE scores); TOEFL 100 / IELTS 7.0 / DET 135 minimum; application fee $90; statement of objectives, portfolio, letters of recommendation, and writing sample required for relevant tracks; general examination after coursework; doctoral dissertation; students may take subjects at Harvard and across MIT departments.",
        "research": "Research areas include Building Technology (sustainable design, structures, building systems), Design and Computation (design computing, urban simulation, AR/VR), and History, Theory and Criticism (architectural history, urbanism, critical theory). The department hosts the Aga Khan Program for Islamic Architecture and collaborates with the Leventhal Center for Advanced Urbanism."
    },
    "ut-mse-phd": {
        "id": "ut-mse-phd",
        "s": "ut",
        "n": "多伦多大学材料科学与工程博士",
        "en": "PhD in Materials Science and Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-6 years (2.0 FCE coursework + thesis; typical completion 4-5 years)",
        "ddl": "Feb 1, 2027 (Fall 2027 entry; later applications considered only if authorized in writing by a potential MSE supervisor)",
        "lang": "TOEFL iBT 93 (22 on writing and speaking) / IELTS Academic 7.0 (6.5 each component)",
        "test": "GRE: not explicitly required by department (per SGS and MSE graduate admissions page)",
        "tui": "Guaranteed base support funding for up to 4 years; ETS institution code 0982; only full-time study; 2 academic references required",
        "url": "details/ut-mse-phd.html",
        "school": "University of Toronto",
        "dept": "Department of Materials Science and Engineering (Faculty of Applied Science and Engineering)",
        "website": "https://mse.utoronto.ca/future/graduate/phd/",
        "overview": "The PhD in Materials Science and Engineering at the University of Toronto is a research-intensive doctoral program offered by the Department of Materials Science and Engineering. PhD students work under the direction of a supervisor on original research contributing to the field, supplemented by advanced coursework. The program includes a weekly Graduate Research Seminar and Graduate Ethics Seminar. A general Qualifying Examination must be passed within 12 months of initial enrollment. Only full-time study is available.",
        "requirements": "Successful completion of a research master's degree (MASc) in engineering with an overall average of at least B+ (78%+); current MASc students within the department may fast-track into the PhD; TOEFL 93 (22 W/S) / IELTS 7.0 (6.5 each); 2 academic references; thesis-based; 2.0 FCE including Graduate Research Seminar and Graduate Ethics Seminar; Qualifying Examination within 12 months.",
        "research": "Research areas include advanced materials, sustainable energy materials, biomaterials, nanomaterials, structural materials, and materials characterization. Collaborative specializations available in Biomedical Engineering and Neuromodulation. The department is located in the Faculty of Applied Science and Engineering at the St. George campus."
    },
    "yale-acm-phd": {
        "id": "yale-acm-phd",
        "s": "yale",
        "n": "耶鲁大学应用与计算数学博士",
        "en": "PhD in Applied and Computational Mathematics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years (typical; fully supported)",
        "ddl": "Jan 2, 2027 at 11:59pm ET (Fall 2027 entry)",
        "lang": "TOEFL iBT or IELTS Academic required for most applicants whose native language is not English (Yale GSAS minimum)",
        "test": "GRE General: REQUIRED (per Yale GSAS standardized testing table; GRE Mathematics Subject Test NOT required for ACM — that requirement applies to the Mathematics PhD)",
        "tui": "5 years of full support (tuition + stipend); application fee $105; ETS institution code 2174",
        "url": "details/yale-acm-phd.html",
        "school": "Yale University",
        "dept": "Department of Applied and Computational Mathematics (Physical Sciences and Engineering)",
        "website": "https://gsas.yale.edu/programs-of-study/applied-computational-mathematics",
        "overview": "The PhD in Applied and Computational Mathematics at Yale is a research-intensive doctoral program offered by the Department of Applied and Computational Mathematics. The program studies the application of mathematics to problems motivated by a wide range of application domains, including classical and modern applied harmonic analysis, PDEs, inverse problems, quantum optics, imaging, numerical analysis, scientific computing, discrete algorithms, combinatorics, graph algorithms, cryptography, statistical theory, probability, information theory, econometrics, financial mathematics, fluid mechanics, and combustion. The January 2 deadline is distinct from the Yale Mathematics PhD (December 15).",
        "requirements": "Bachelor's degree in mathematics, applied mathematics, engineering, or related quantitative field; GRE General required; TOEFL iBT or IELTS Academic required for non-native English speakers; application fee $105; statement of purpose, personal statement, three letters of recommendation, and transcripts required; dissertation research under faculty supervision.",
        "research": "Research areas span applied harmonic analysis, linear and nonlinear PDEs, inverse problems, imaging, numerical analysis, scientific computing, combinatorics and combinatorial optimization, graph algorithms, discrete mathematics, cryptography, statistical theory, probability, information theory, econometrics, financial mathematics, and applications to fluid mechanics and combustion."
    },
    "cornell-or-phd": {
        "id": "cornell-or-phd",
        "s": "cornell",
        "n": "康奈尔大学运筹学博士",
        "en": "PhD in Operations Research",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years (qualifying exam in 3rd term; dissertation research)",
        "ddl": "Jan 4, 2027 (Fall 2027 entry only; no spring admission; decisions by April 15)",
        "lang": "TOEFL iBT or IELTS Academic required (English language proficiency requirement for all applicants; average admitted TOEFL ~110 per dept FAQ)",
        "test": "GRE General: scores reviewed (dept FAQ reports average admitted GRE V162 / Q168 / AW4.28; no explicit waiver posted; ETS institution code 2098)",
        "tui": "Fully funded (tuition + stipend) via assistantships and fellowships; 3 recommendations required; ORCID required; Ithaca, NY campus",
        "url": "details/cornell-or-phd.html",
        "school": "Cornell University",
        "dept": "School of Operations Research and Information Engineering (Duffield College of Engineering)",
        "website": "https://www.orie.cornell.edu/",
        "overview": "The PhD in Operations Research at Cornell is a research-intensive doctoral program offered by the School of Operations Research and Information Engineering (ORIE) in the Duffield College of Engineering. Doctoral students majoring in operations research concentrate in one of three areas: applied probability and statistics, manufacturing systems engineering, or mathematical programming. The program requires a qualifying examination normally taken in the third term of graduate study. Fall admission only. In-person delivery at the Ithaca campus.",
        "requirements": "Strong background in engineering, mathematics, or related quantitative field; undergraduate calculus-based probability course recommended; GRE General scores reviewed (average admitted V162/Q168/AW4.28 per dept FAQ); TOEFL/IELTS required; 3 letters of recommendation; statement of purpose; ORCID required; qualifying exam in 3rd term; one minor outside the field; dissertation.",
        "research": "Research areas include applied probability and statistics (stochastic processes, queueing theory, mathematical finance, reliability theory, statistical decision theory), manufacturing systems engineering (inventory control, production planning, scheduling), and mathematical programming (linear, nonlinear, integer, combinatorial programming, network flows, discrete and computational geometry)."
    },
    "harvard-biostat-phd": {
        "id": "harvard-biostat-phd",
        "s": "harvard",
        "n": "哈佛大学生物统计学博士",
        "en": "PhD in Biostatistics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years (coursework + oral qualifying exam + dissertation)",
        "ddl": "Dec 1, 2026 at 5pm Boston time (Fall 2027 entry; application through SOPHAS and Harvard GSAS)",
        "lang": "TOEFL iBT 80 minimum (Harvard GSAS baseline; higher recommended for competitive review) / IELTS Academic 7.0",
        "test": "GRE General: REQUIRED (no minimum score; competitive review; contrast with Harvard Chan SM programs which are GRE optional)",
        "tui": "Fully funded (tuition + stipend + health fees) for 5 years; ETS institution code 3401 (Harvard GSAS); SOPHAS application required",
        "url": "details/harvard-biostat-phd.html",
        "school": "Harvard University",
        "dept": "Department of Biostatistics (Harvard T.H. Chan School of Public Health / Harvard Kenneth C. Griffin Graduate School of Arts and Sciences)",
        "website": "https://www.hsph.harvard.edu/biostatistics/graduate-programs/phd-in-biostatistics/",
        "overview": "The PhD in Biostatistics at Harvard is a research-intensive doctoral program offered jointly by the Harvard T.H. Chan School of Public Health and the Harvard Kenneth C. Griffin Graduate School of Arts and Sciences. The program trains researchers in the development and application of statistical methods to biomedical and public health problems. The PhD is part of the Harvard Integrated Life Sciences (HILS) consortium. The GRE is required for the PhD, in contrast to the Harvard Chan SM programs which are GRE optional. Fall admission only.",
        "requirements": "Bachelor's degree in mathematics, statistics, or related quantitative field; GRE General required; TOEFL iBT 80 / IELTS 7.0 minimum; application through SOPHAS and Harvard GSAS; three letters of recommendation; statement of purpose; transcripts; oral qualifying examination; dissertation research under faculty supervision; 5-year funding package.",
        "research": "Research areas include statistical genetics, high-dimensional data analysis, causal inference, survival analysis, longitudinal data analysis, Bayesian methods, machine learning for biology, environmental statistics, and clinical trials. The department collaborates closely with the Dana-Farber Cancer Institute, Broad Institute, and Harvard teaching hospitals."
    },
}

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{title} — {school}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6;}}
h1{{color:#1a3a6c;border-bottom:2px solid #1a3a6c;padding-bottom:8px;}}
h2{{color:#1a3a6c;margin-top:28px;}}
.badge{{display:inline-block;background:#1a3a6c;color:#fff;padding:2px 10px;border-radius:12px;font-size:13px;margin-right:6px;}}
.card{{background:#f7f9fc;border-left:4px solid #1a3a6c;padding:14px 18px;margin:12px 0;border-radius:4px;}}
a{{color:#1a6fc4;}}
</style>
</head>
<body>
<h1>{title}</h1>
<p><span class="badge">{deg}</span><span class="badge">{stem_label}</span><span class="badge">{lvl_label}</span></p>
<div class="card"><strong>School:</strong> {school}<br>
<strong>Department:</strong> {dept}<br>
<strong>Website:</strong> <a href="{website}" target="_blank">{website}</a></div>

<h2>Overview</h2>
<p>{overview}</p>

<h2>Degree Requirements</h2>
<div class="card">
<strong>Duration:</strong> {duration}<br>
<strong>Application Deadline:</strong> {ddl}<br>
<strong>English Language:</strong> {lang}<br>
<strong>Standardized Tests:</strong> {test_cls}<br>
<strong>Tuition &amp; Funding:</strong> {tui}
</div>
<p>{requirements}</p>

<h2>Research Areas</h2>
<p>{research}</p>

<p style="color:#888;font-size:12px;margin-top:32px;">Verified against official department / graduate school source. Not a minimum-threshold guarantee; admitted class distributions reflect competitive review.</p>
</body>
</html>
"""


def render(p):
    stem_label = "STEM" if p["stem"] == 1 else "Non-STEM"
    lvl_label = "Doctoral" if p["lvl"] == "d" else "Master"
    return TEMPLATE.format(
        title=p["n"], school=p["school"], deg=p["deg"],
        stem_label=stem_label, lvl_label=lvl_label,
        dept=p["dept"], website=p["website"], overview=p["overview"],
        duration=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"], tui=p["tui"],
        requirements=p["requirements"], research=p["research"],
    )


def append_program(html, entry):
    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
        elif c == "[" and depth == 1:
            depth += 1
        elif c == "]" and depth == 1:
            break
        i += 1
    else:
        raise RuntimeError("PROGRAMS end not found")
    insert_at = i
    j = insert_at - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[insert_at:]
    if not prefix.endswith(","):
        prefix += ","
    block = ('{{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(
        id=entry["id"], s=entry["s"], n=entry["n"], en=entry["en"], deg=entry["deg"],
        lvl=entry["lvl"], stem=entry["stem"], dur=entry["dur"], ddl=entry["ddl"],
        lang=entry["lang"], test=entry["test"], tui=entry["tui"], url=entry["url"])
    return prefix + "\n" + block + "\n" + suffix


def append_vd(html, urls):
    m = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\[", html)
    if not m:
        raise RuntimeError("VERIFIED_DETAILS 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:
                break
        i += 1
    else:
        raise RuntimeError("VD end not found")
    j = i - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[i:]
    if not prefix.endswith(",") and not prefix.endswith("["):
        prefix += ","
    additions = ",".join('"{}"'.format(u) for u in urls)
    return prefix + "\n" + additions + "\n" + suffix


def main():
    html = IDX.read_text(encoding="utf-8")
    before = len(html.encode("utf-8"))
    new_urls = []
    for pid, p in PAGES.items():
        out = DETAILS / (pid + ".html")
        out.write_text(render(p), encoding="utf-8")
        print("wrote", out)
        html = append_program(html, p)
        new_urls.append(p["url"])
    html = append_vd(html, new_urls)
    after = len(html.encode("utf-8"))
    IDX.write_text(html, encoding="utf-8")
    print(f"index_main.html: {before} -> {after} bytes (delta +{after - before})")
    print("done.")


if __name__ == "__main__":
    main()
