# -*- coding: utf-8 -*-
"""Round 245: batch add 5 Materials Science and Engineering PhD (third-tier U.S. sweep)
- Princeton Materials Institute Joint PhD (not standalone; students apply to MAE/CBE/Chem/CEE/ECE/Geosciences then add joint degree)
- Harvard SEAS Engineering Sciences: Materials Science and Mechanical Engineering PhD (Dec 15, GRE Not Accepted)
- Yale GSAS Materials Science PhD (Dec 15, GRE optional)
- Caltech APHMS Materials Science PhD (Dec 15, GRE recommended not required; no standalone MS)
- Duke MEMS PhD: Mechanical Engineering and Materials Science (Fall Dec 11, GRE optional)
"""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
DET = os.path.join(BASE, "details")
os.makedirs(DET, exist_ok=True)

PROGRAMS = [
    {
        "id": "princeton-mse-joint-phd",
        "s": "princeton",
        "n": "材料科学联合博士（Princeton Materials Institute）",
        "en": "PhD in Materials Science (Joint Degree through Princeton Materials Institute; students apply to and are admitted through a home department - Mechanical and Aerospace Engineering, Chemical and Biological Engineering, Chemistry, Civil and Environmental Engineering, Electrical and Computer Engineering, or Geosciences - then add the PMI joint degree; dissertation must have a clear materials focus)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; minimum 3 courses approved by Princeton Materials Institute; dissertation must have clear materials focus and be approved by PMI program director; students may apply for joint degree any time after matriculation but encouraged to do so in first year",
        "ddl": "Fall 2027 admission: application opens September 2026. Deadline governed by the home department (e.g. MAE/CBE typically December 1; Chemistry typically December 1). No spring admission. Full-time only. One application to one department per year.",
        "lang": "TOEFL iBT / IELTS / Duolingo per Princeton Graduate School; ETS Princeton University 2617 (no department code used); waivers for English-instructed undergraduate degree",
        "test": {"cls": "GRE per home department (Princeton CBE PhD round 241: 'no GRE tests are required, nor are GRE scores accepted'; MAE PhD round 212: GRE not required; Chemistry PhD typically GRE required - verify with home department). PMI itself does not impose separate GRE. 3 LOR; SOP; CV; transcripts; bachelor's degree in engineering/physical science."},
        "tui": "Princeton guarantees full funding for all PhD students for 5 years through fellowship, RA, TA, and assistantship (tuition + stipend + health insurance). PMI provides additional research support, access to Imaging and Analysis Center (IAC) and Micro/Nanofabrication Center (MNFC) shared facilities.",
        "url": "details/princeton-mse-joint-phd.html",
    },
    {
        "id": "harvard-mme-phd",
        "s": "harvard",
        "n": "材料科学与机械工程博士（Engineering Sciences）",
        "en": "PhD in Engineering Sciences: Materials Science and Mechanical Engineering (Harvard John A. Paulson School of Engineering and Applied Sciences, SEAS; administered through Harvard Griffin GSAS; area of study within Engineering and Applied Sciences; interdisciplinary connections to Applied Mathematics, Applied Physics, Earth and Planetary Sciences, Chemistry and Chemical Biology)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; coursework + oral qualifying exam + prospectus + dissertation; PhD students typically receive full funding through SEAS/GSAS fellowships, RA, TA; Harvard Griffin GSAS supplementary form required",
        "ddl": "Fall 2027 admission: GSAS application available September 2026. **PhD deadline December 15, 2026, 5:00 pm ET** (master's S.M./M.E./AB-SM deadline December 1, 2026, 5:00 pm ET). Review begins mid-late December; decisions mid-February; reply date April 15, 2027. No late applications accepted.",
        "lang": "TOEFL iBT / IELTS Academic per Harvard Griffin GSAS; ETS Harvard 3451; waivers for English-instructed degree; PhD students must complete Supplemental SEAS Application Form",
        "test": {"cls": "GRE NOT ACCEPTED (Harvard SEAS: 'SEAS does not accept General GRE scores nor Subject Test GRE scores for applicants to our Ph.D. programs. Applicants should not submit official or unofficial GRE scores to us nor mention them anywhere in their application materials.' Policy in effect since August 2020. 3 LOR; SOP; CV; transcripts; Supplemental SEAS Application Form.)"},
        "tui": "Harvard Griffin GSAS PhD students typically receive full funding for 4-5 years including tuition, stipend, and health insurance through a combination of SEAS fellowships, research assistantships, and teaching fellowships.",
        "url": "details/harvard-mme-phd.html",
    },
    {
        "id": "yale-mse-phd",
        "s": "yale",
        "n": "材料科学博士",
        "en": "PhD in Materials Science (Yale Graduate School of Arts and Sciences, Yale School of Engineering and Applied Science; fields include quantum/low-dimensional materials, energy materials, soft/polymer/bio materials, electronic/optical materials, metals/ceramics/structural materials, computational materials science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; coursework + qualifying exam + prospectus + dissertation; Yale PhD students normally fully funded: 12-month stipend + fellowship covering full tuition + student healthcare",
        "ddl": "Fall 2027 admission: **PhD deadline December 15, 2026, 11:59 pm ET** (no spring admission). Combined programs deadline is earlier of two programs or December 15, whichever is earlier. LOR no specific deadline but must be submitted promptly after deadline for review.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers; waiver for applicants with undergraduate degree from English-primary-language institution with at least 3 years in residence",
        "test": {"cls": "GRE OPTIONAL (Yale GSAS Materials Science: 'GRE is optional.' Self-reported GRE accepted; if self-reported, official scores required for verification. Holistic review; no preference given to submitters or non-submitters. 3 LOR; SOP; CV; transcripts; bachelor's in engineering, physics, chemistry, materials science, or related field.)"},
        "tui": "Yale PhD students normally fully funded for duration: 12-month stipend for living expenses + fellowship covering full cost of tuition + student healthcare. Additional support through research assistantships and university fellowships.",
        "url": "details/yale-mse-phd.html",
    },
    {
        "id": "caltech-mse-phd",
        "s": "caltech",
        "n": "材料科学博士（Applied Physics and Materials Science）",
        "en": "PhD in Materials Science (California Institute of Technology, Department of Applied Physics and Materials Science, APHMS; doctoral program only - no standalone master's; students are admitted directly into the PhD program; minimum 111 units of 100+ level coursework before candidacy; oral candidacy exam + written thesis + final oral defense)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; minimum 111 units of 100+ level coursework before PhD candidacy; at least 18 units of MS 200 research; oral candidacy exam; written thesis; final oral defense; doctoral research adviser required",
        "ddl": "Fall 2027 admission: **Materials Science PhD deadline December 15, 2026** (Caltech conducts admissions once per year for fall entry only; all decisions posted by April 1, 2027). Application through gradoffice.caltech.edu/admissions; applicants may only apply to one academic option per cycle.",
        "lang": "TOEFL iBT / IELTS Academic per Caltech Graduate Studies Office; waivers for English-instructed degree; scores must be sent electronically",
        "test": {"cls": "GRE RECOMMENDED BUT NOT REQUIRED (Caltech APHMS: 'For the 2026-27 admissions cycle, Materials Science recommends but does not require the general GRE.' Absence not penalized; submitted scores considered. No minimum GPA or quantitative metric; holistic review of personal statement, transcripts, LOR. 3 LOR; SOP; CV; transcripts; bachelor's in science or engineering.)"},
        "tui": "All Caltech PhD students are provided with financial support for tuition and living expenses (full tuition + stipend + health insurance) to enable singular focus on research; support through a combination of research assistantships, teaching assistantships, and institute fellowships. No separate application required - all applicants automatically considered for aid.",
        "url": "details/caltech-mse-phd.html",
    },
    {
        "id": "duke-mems-mse-phd",
        "s": "duke",
        "n": "机械工程与材料科学博士",
        "en": "PhD in Mechanical Engineering and Materials Science (Duke University, Thomas Lord Department of Mechanical Engineering and Materials Science, MEMS; concentrations include Materials Science & Biomaterials, Aerodynamics & Aeroelasticity, Biomechanics, Computation & AI, Energy Systems & Materials, Robotics & Autonomy, Soft Matter & Nanoscale Materials; 5 years stipend + 6 years health and dental coverage)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; coursework + qualifying exam + dissertation; Duke provides significant financial support: 5 years of stipend + 6 years of health and dental coverage",
        "ddl": "Fall 2027 admission: **PhD guaranteed review deadline December 11, 2026, 11:59:59 pm ET**. Applications after December 11 but before closing March 8, 2027 reviewed based on space and funding availability. Spring admission deadline October 1.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test required for non-native English speakers; test waiver may apply for some applicants",
        "test": {"cls": "GRE GENERAL OPTIONAL (Duke Graduate School: 'GRE Scores: GRE General (Optional).' No absolute cut-off; averages/ranges of admitted applicants available in program statistics. 3 LOR; SOP per department guidance; résumé; unofficial transcripts; bachelor's GPA on 4.0 scale required.)"},
        "tui": "Duke provides significant financial support to PhD students: 5 years of stipend plus 6 years of health and dental coverage, plus mentorship and career exploration support. Support through research assistantships, teaching assistantships, and fellowships.",
        "url": "details/duke-mems-mse-phd.html",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{school} - {en}</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{{font-size:24px;border-bottom:2px solid #1a73e8;padding-bottom:8px}}
h2{{font-size:18px;color:#1a73e8;margin-top:24px}}
.card{{background:#f8f9fa;border-left:4px solid #1a73e8;padding:12px 16px;margin:12px 0;border-radius:4px}}
.meta{{display:grid;grid-template-columns:120px 1fr;gap:6px 12px;font-size:14px}}
.meta b{{color:#555}}
ul{{margin:6px 0;padding-left:20px}}
.note{{background:#fff3cd;border-left-color:#ffc107;padding:10px 14px;margin-top:16px;font-size:13px}}
a{{color:#1a73e8}}
</style>
</head>
<body>
<h1>{school} - {en}</h1>
<div class="card">
<div class="meta">
<b>Degree</b><span>{deg}</span>
<b>Level</b><span>Research Doctorate (PhD)</span>
<b>STEM</b><span>{stem_label}</span>
<b>Duration</b><span>{dur}</span>
<b>Deadline</b><span>{ddl}</span>
<b>Language</b><span>{lang}</span>
<b>Standardized</b><span>{test_cls}</span>
<b>Funding</b><span>{tui}</span>
</div>
</div>

<h2>Program Overview</h2>
<div class="card">
{overview}
</div>

<h2>Admissions Requirements</h2>
<div class="card">
{requirements}
</div>

<h2>Research Areas</h2>
<div class="card">
{research}
</div>

<h2>Official Source</h2>
<div class="card">
{source}
</div>

<div class="note">
<strong>Note:</strong> Third batch of Materials Science and Engineering PhD sweep (Princeton joint / Harvard SEAS / Yale / Caltech / Duke MEMS). Continuation from round 243 (MIT, Stanford, Berkeley, UIUC, Georgia Tech) and round 244 (CMU, Cornell, Northwestern, UMich, UCSD). GRE policy: Harvard SEAS explicitly does not accept GRE; Yale and Duke GRE optional; Caltech APHMS recommends but does not require GRE; Princeton joint degree follows home department policy (CBE/MAE not required/accepted). Deadlines: December 1 (Princeton via home dept), December 11 (Duke MEMS), December 15 (Harvard, Yale, Caltech). All five programs offer full funding to PhD students. Combined with rounds 243-244, the MSE PhD sweep now covers 15 of the top U.S. programs; remaining top-tier MSE PhD programs to be added in next round include Vanderbilt MSE and the Canadian 4 schools (UofT/UBC/McGill/Waterloo).
</div>
</body>
</html>
"""

PAGES = {
    "princeton-mse-joint-phd": {
        "school": "Princeton University, Princeton Materials Institute (Joint PhD)",
        "en": "PhD in Materials Science (Joint Degree)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.1801)",
        "dur": "Typically 5-6 years; minimum 3 PMI-approved courses; dissertation must have clear materials focus and be approved by PMI program director; students may add joint degree any time after matriculation but encouraged in first year",
        "ddl": "Fall 2027: application opens September 2026. Deadline governed by home department (MAE/CBE/Chemistry/CEE/ECE/Geosciences typically December 1). No spring admission. Full-time only. One application to one department per year. No second PhD in same/similar field.",
        "lang": "TOEFL iBT / IELTS / Duolingo per Princeton Graduate School; ETS Princeton University 2617 (no department codes used by Princeton); waivers for English-instructed undergraduate degree",
        "test_cls": "GRE per home department (CBE PhD: no GRE required nor accepted; MAE PhD: GRE not required; Chemistry PhD typically GRE required - verify with home department). PMI itself does not impose separate GRE. 3 LOR; SOP; CV; transcripts.",
        "tui": "Princeton guarantees full funding for all PhD students for 5 years through fellowship, RA, TA, and assistantship (tuition + stipend + health insurance). PMI provides access to Imaging and Analysis Center (IAC) and Micro/Nanofabrication Center (MNFC) shared facilities.",
        "overview": "The Princeton Materials Institute (PMI) offers a formal undergraduate Certificate in Materials Science and Engineering and a joint PhD degree program with participating academic departments. At the graduate level, PMI does not admit students directly: students must apply to and be admitted to a specific academic department (MAE, CBE, Chemistry, CEE, ECE, or Geosciences), fulfill all departmental requirements, and then add the PMI joint degree. The dissertation must have a clear materials focus and be approved by the PMI program director. Students must take a minimum of three courses approved by PMI. They may apply for the joint degree at any time after matriculating in their home department, but are encouraged to do so in their first year. PMI operates the Imaging and Analysis Center (IAC) and Micro/Nanofabrication Center (MNFC), two large multi-user central research facilities. The Director of Graduate Studies is Alejandro W. Rodriguez; Graduate Program Administrator is Sandra Lam.",
        "requirements": "<ul><li>Bachelor's degree in engineering, physics, chemistry, geosciences, or related field</li><li>Apply to a home department (MAE, CBE, Chemistry, CEE, ECE, or Geosciences) - NOT directly to PMI</li><li>GRE per home department policy (CBE/MAE: not required/accepted; Chemistry: verify)</li><li>TOEFL iBT / IELTS / Duolingo per Princeton Graduate School</li><li>Princeton Graduate School online application (one department per year)</li><li>3 letters of recommendation</li><li>Statement of academic purpose</li><li>Resume/CV</li><li>Transcripts (in English) from each institution</li><li>**Deadline per home department** (typically December 1 for fall entry)</li><li>No spring admission; full-time only</li><li>After matriculation: minimum 3 PMI-approved courses; dissertation with materials focus approved by PMI director</li><li>On-campus residential (Princeton, NJ)</li></ul>",
        "research": "<ul><li>Materials science and engineering (interdisciplinary across 6 affiliated departments)</li><li>Imaging and Analysis Center (IAC) - shared central characterization</li><li>Micro/Nanofabrication Center (MNFC) - shared cleanroom</li><li>Curiosity-driven fundamental research + high-impact innovation with industry, government labs, and academia</li><li>Energy materials, quantum materials, nanomaterials, soft matter, structural materials</li></ul>",
        "source": '<a href="https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/materials-science" target="_blank">Princeton Graduate School: Materials Science (joint degree; affiliated departments MAE/CBE/Chemistry/CEE/ECE/Geosciences; minimum 3 PMI courses; dissertation materials focus; DGS Alejandro W. Rodriguez; GPA Sandra Lam)</a> | <a href="https://materials.princeton.edu/education/graduate" target="_blank">Princeton Materials Institute: Joint PhD Degree Program (students apply to specific academic department; may apply for joint degree after matriculation; encouraged in first year; affiliated departments listed)</a> | <a href="https://materials.princeton.edu/" target="_blank">Princeton Materials Institute homepage (mission; IAC and MNFC shared facilities; undergraduate certificate + joint PhD)</a>',
    },
    "harvard-mme-phd": {
        "school": "Harvard John A. Paulson School of Engineering and Applied Sciences (SEAS)",
        "en": "PhD in Engineering Sciences: Materials Science and Mechanical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.3501)",
        "dur": "Typically 5-6 years; coursework + oral qualifying exam + prospectus + dissertation; full funding through SEAS/GSAS fellowships, RA, TA",
        "ddl": "Fall 2027: GSAS application available September 2026. **PhD deadline December 15, 2026, 5:00 pm ET** (master's S.M./M.E./AB-SM deadline December 1, 2026, 5:00 pm ET). Review begins mid-late December; decisions mid-February; reply date April 15, 2027. No late applications.",
        "lang": "TOEFL iBT / IELTS Academic per Harvard Griffin GSAS; ETS Harvard 3451; waivers for English-instructed degree; PhD students must complete Supplemental SEAS Application Form",
        "test_cls": "GRE NOT ACCEPTED (Harvard SEAS: 'SEAS does not accept General GRE scores nor Subject Test GRE scores for applicants to our Ph.D. programs. Applicants should not submit official or unofficial GRE scores to us nor mention them anywhere in their application materials.' Policy in effect since August 2020. 3 LOR; SOP; CV; transcripts; Supplemental SEAS Form.)",
        "tui": "Harvard Griffin GSAS PhD students typically receive full funding for 4-5 years including tuition, stipend, and health insurance through SEAS/GSAS fellowships, research assistantships, and teaching fellowships.",
        "overview": "The Materials Science and Mechanical Engineering program at Harvard SEAS ranges from fundamental work in solid and fluid mechanics to diverse studies in materials, mechanical systems, and biomechanics. It is a field within the Engineering Sciences area of study at SEAS. Prospective students apply through Harvard Griffin GSAS; in the online application, select 'Engineering and Applied Sciences' as the program choice and select 'PhD Engineering Sciences: Materials Science and Mechanical Engineering' in the area of study menu. Research is strongly interdisciplinary, with many connections to Applied Mathematics, Applied Physics, Earth and Planetary Sciences, and Chemistry and Chemical Biology. The PhD deadline is December 15, 2026 at 5:00 pm ET. Harvard SEAS does not accept General GRE or Subject Test GRE scores for PhD programs; applicants should not submit scores or mention them in application materials. Note: terminal SM degrees are only offered in CSE and DS; MME is PhD-only.",
        "requirements": "<ul><li>Bachelor's degree in natural sciences, mathematics, computer science, or engineering</li><li>GRE NOT ACCEPTED (do not submit; do not mention in application)</li><li>TOEFL iBT / IELTS Academic per GSAS; ETS Harvard 3451</li><li>Harvard Griffin GSAS online application (select 'Engineering and Applied Sciences' program)</li><li>Area of study: 'PhD Engineering Sciences: Materials Science and Mechanical Engineering'</li><li>3 letters of recommendation</li><li>Statement of purpose</li><li>CV/resume</li><li>Transcripts</li><li>Supplemental SEAS Application Form (required for PhD applicants)</li><li>**PhD deadline December 15, 2026, 5:00 pm ET**</li><li>Master's S.M./M.E./AB-SM deadline December 1, 2026, 5:00 pm ET</li><li>Decisions mid-February 2027; reply date April 15, 2027</li><li>On-campus residential (Cambridge, MA)</li></ul>",
        "research": "<ul><li>Solid and fluid mechanics</li><li>Materials science and engineering</li><li>Mechanical systems and biomechanics</li><li>Interdisciplinary connections to Applied Mathematics, Applied Physics, Earth and Planetary Sciences, Chemistry and Chemical Biology</li><li>PhD-only (no terminal SM in MME; terminal SM only in CSE and DS)</li></ul>",
        "source": '<a href="https://gsas.harvard.edu/program/materials-science-and-mechanical-engineering" target="_blank">Harvard GSAS: Materials Science and Mechanical Engineering (PhD; GRE Not Accepted; deadline Dec 15 2025 5:00pm ET; area of study within Engineering and Applied Sciences; interdisciplinary connections)</a> | <a href="https://seas.harvard.edu/prospective-students/prospective-graduate-students/how-apply" target="_blank">Harvard SEAS How to Apply (PhD deadline Dec 15 5pm ET; master deadline Dec 1 5pm ET; GRE not accepted for PhD; review mid-late Dec; decisions mid-Feb; reply date Apr 15)</a> | <a href="https://seas.harvard.edu/prospective-students/prospective-graduate-students/frequently-asked-questions-faqs-graduate" target="_blank">Harvard SEAS Graduate FAQ (GRE not accepted since August 2020; PhD Dec 15; SM/ME/AB-SM Dec 1; MS/MBA and MDE excluded; do not submit GRE scores)</a>',
    },
    "yale-mse-phd": {
        "school": "Yale Graduate School of Arts and Sciences, School of Engineering and Applied Science",
        "en": "PhD in Materials Science",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.1801)",
        "dur": "Typically 5-6 years; coursework + qualifying exam + prospectus + dissertation; Yale PhD students normally fully funded: 12-month stipend + fellowship covering full tuition + student healthcare",
        "ddl": "Fall 2027: **PhD deadline December 15, 2026, 11:59 pm ET** (no spring admission). Combined programs deadline is earlier of two programs or December 15. LOR no specific deadline but must be submitted promptly after deadline for review.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers; waiver for undergraduate degree from English-primary-language institution with at least 3 years in residence",
        "test_cls": "GRE OPTIONAL (Yale GSAS Materials Science: 'GRE is optional.' Self-reported GRE accepted; if self-reported, official scores required for verification. Holistic review. 3 LOR; SOP; CV; transcripts; bachelor's in engineering, physics, chemistry, materials science, or related field.)",
        "tui": "Yale PhD students normally fully funded for duration: 12-month stipend for living expenses + fellowship covering full cost of tuition + student healthcare. Additional support through research assistantships and university fellowships.",
        "overview": "Yale's Materials Science PhD program is administered through the Yale Graduate School of Arts and Sciences and the Yale School of Engineering and Applied Science. Fields of study include quantum and low-dimensional materials; energy materials; soft, polymer, and bio materials; electronic and optical materials; metals, ceramics, and structural materials; and computational materials science. The terminal degree offered is the PhD (no standalone MS in Materials Science at Yale). The program deadline is December 15 at 11:59 pm ET for fall admission; there is no spring admission. The GRE is optional. Yale PhD students are normally fully funded with a 12-month stipend plus a fellowship covering full tuition and student healthcare. The Director of Graduate Studies is Liangbing Hu; the Graduate Registrar is Margaret Walker.",
        "requirements": "<ul><li>Bachelor's degree in engineering, physics, chemistry, materials science, or related field</li><li>GRE OPTIONAL (self-reported accepted; official required if self-reported)</li><li>TOEFL iBT / IELTS Academic required for non-native English speakers</li><li>Waiver for undergraduate degree from English-primary-language institution with at least 3 years in residence</li><li>Yale GSAS online application</li><li>3 letters of recommendation (no specific deadline but submit promptly)</li><li>Statement of purpose</li><li>CV/resume</li><li>Transcripts</li><li>**PhD deadline December 15, 2026, 11:59 pm ET**</li><li>No spring admission</li><li>Terminal degree: PhD only (no standalone MS in Materials Science)</li><li>On-campus residential (New Haven, CT)</li></ul>",
        "research": "<ul><li>Quantum and low-dimensional materials</li><li>Energy materials (batteries, solar, thermoelectrics)</li><li>Soft, polymer, and bio materials</li><li>Electronic and optical materials</li><li>Metals, ceramics, and structural materials</li><li>Computational materials science</li></ul>",
        "source": '<a href="https://gsas.yale.edu/programs-of-study/materials-science" target="_blank">Yale GSAS: Materials Science (PhD terminal; GRE optional; TOEFL/IELTS required; deadline Dec 15 11:59pm ET; PhD fully funded 12-month stipend + tuition + healthcare; DGS Liangbing Hu; registrar Margaret Walker)</a> | <a href="https://gsas.yale.edu/admissions/phdmasters-application-process/dates-deadlines" target="_blank">Yale GSAS Dates & Deadlines (Dec 15 deadlines include Applied Physics, CS PhD, ECE, Materials Science; 11:59pm ET; combined programs earlier of two or Dec 15)</a> | <a href="https://engineering.yale.edu/apply" target="_blank">Yale Engineering Apply (BS or equivalent in engineering/physics/chemistry/CS/math/materials science; Dec 15 fall deadline; no spring; GRE optional; self-reported requires official verification; Materials Science registrar margaret.walker@yale.edu)</a>',
    },
    "caltech-mse-phd": {
        "school": "California Institute of Technology, Department of Applied Physics and Materials Science",
        "en": "PhD in Materials Science",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.1801)",
        "dur": "Typically 5-6 years; minimum 111 units of 100+ level coursework before candidacy; at least 18 units of MS 200 research; oral candidacy exam; written thesis; final oral defense; doctoral research adviser required",
        "ddl": "Fall 2027: **Materials Science PhD deadline December 15, 2026** (Caltech conducts admissions once per year for fall entry only; all decisions posted by April 1, 2027). Application through gradoffice.caltech.edu/admissions; applicants may only apply to one academic option per cycle.",
        "lang": "TOEFL iBT / IELTS Academic per Caltech Graduate Studies Office; waivers for English-instructed degree; scores must be sent electronically",
        "test_cls": "GRE RECOMMENDED BUT NOT REQUIRED (Caltech APHMS: 'For the 2026-27 admissions cycle, Materials Science recommends but does not require the general GRE.' Absence not penalized; submitted scores considered. No minimum GPA; holistic review. 3 LOR; SOP; CV; transcripts; bachelor's in science or engineering.)",
        "tui": "All Caltech PhD students are provided with financial support for tuition and living expenses (full tuition + stipend + health insurance) to enable singular focus on research; through a combination of RA, TA, and institute fellowships. No separate application required - all applicants automatically considered for aid.",
        "overview": "The graduate degree in Materials Science at Caltech is offered through the Department of Applied Physics and Materials Science (APHMS). The doctoral program is designed to be a doctoral program: students are admitted directly into the PhD program, and there is no separate master's program in materials science. The PhD consists of a series of preparatory classes, followed by an oral candidacy exam, a written thesis, and a final oral thesis defense. Students must complete a minimum of 111 units of courses numbered 100 or above before presenting for PhD candidacy, plus at least 18 units of MS 200 research with a doctoral research adviser. For the 2026-27 admissions cycle, Materials Science recommends but does not require the general GRE; the application deadline is December 15, 2026. Caltech conducts admissions once per year for fall entry only; applicants may only apply to one academic option per cycle. All admitted PhD students receive full tuition and living expense support.",
        "requirements": "<ul><li>Bachelor's degree in science or engineering related to Caltech options</li><li>GRE RECOMMENDED BUT NOT REQUIRED (absence not penalized; submitted scores considered)</li><li>No minimum GPA or quantitative metric; holistic review</li><li>TOEFL iBT / IELTS Academic per Caltech Graduate Studies Office</li><li>Caltech online application through gradoffice.caltech.edu/admissions</li><li>3 letters of recommendation</li><li>Statement of purpose / personal statement</li><li>CV/resume</li><li>Transcripts</li><li>**PhD deadline December 15, 2026** (Fall 2027 entry only)</li><li>One application to one option per cycle</li><li>All decisions posted by April 1, 2027</li><li>No standalone MS in Materials Science (PhD only)</li><li>On-campus residential (Pasadena, CA)</li></ul>",
        "research": "<ul><li>Materials science (interdisciplinary with applied physics)</li><li>Condensed matter physics and materials</li><li>Quantum materials, nanomaterials, energy materials</li><li>Biomaterials, soft matter</li><li>Computational materials science</li><li>Collaboration with JPL and other Caltech divisions</li></ul>",
        "source": '<a href="https://www.aphms.caltech.edu/academics/grad/graduate-degree-in-materials-science" target="_blank">Caltech APHMS: Graduate Degree in Materials Science (2026-27 GRE recommended but not required; deadline Dec 15 2026; doctoral program only - no standalone MS; minimum 111 units 100+ before candidacy; at least 18 units MS 200; oral candidacy exam; written thesis; final oral defense; doctoral research adviser required)</a> | <a href="https://gradoffice.caltech.edu/admissions" target="_blank">Caltech Graduate Studies Admissions (admissions once per year for fall; Dec 1 - Jan 15 window; one option per cycle; holistic review; no minimum GPA; financial support automatic consideration)</a> | <a href="https://catalog.caltech.edu/current/information-for-graduate-students/graduate-policies-and-procedures/admission-to-graduate-standing/" target="_blank">Caltech Catalog: Admission to Graduate Standing (bachelor\'s in science/engineering; records and recommendations; fall enrollment only; PhD students provided tuition + living support; nondiscrimination policy)</a>',
    },
    "duke-mems-mse-phd": {
        "school": "Duke University, Thomas Lord Department of Mechanical Engineering and Materials Science (MEMS)",
        "en": "PhD in Mechanical Engineering and Materials Science",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.1801)",
        "dur": "Typically 5-6 years; coursework + qualifying exam + dissertation; Duke provides significant financial support: 5 years of stipend + 6 years of health and dental coverage",
        "ddl": "Fall 2027: **PhD guaranteed review deadline December 11, 2026, 11:59:59 pm ET**. Applications after December 11 but before closing March 8, 2027 reviewed based on space and funding availability. Spring admission deadline October 1.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test required for non-native English speakers; test waiver may apply for some applicants",
        "test_cls": "GRE GENERAL OPTIONAL (Duke Graduate School: 'GRE Scores: GRE General (Optional).' No absolute cut-off; averages/ranges of admitted applicants available in program statistics. 3 LOR; SOP per department guidance; résumé; unofficial transcripts; bachelor's GPA on 4.0 scale required.)",
        "tui": "Duke provides significant financial support to PhD students: 5 years of stipend plus 6 years of health and dental coverage, plus mentorship and career exploration support. Through RA, TA, and fellowships.",
        "overview": "The Duke Thomas Lord Department of Mechanical Engineering and Materials Science (MEMS) offers MS and PhD degrees. The PhD in Mechanical Engineering and Materials Science has concentrations including Materials Science & Biomaterials, Aerodynamics & Aeroelasticity, Biomechanics & Biomaterials, Computation & Artificial Intelligence, Energy Systems & Materials, Robotics & Autonomy, and Soft Matter & Nanoscale Materials. Fall applications submitted by December 11, 2026 are guaranteed review; applications after December 11 but before March 8, 2027 are reviewed based on space and funding. Duke provides significant financial support to PhD students: 5 years of stipend plus 6 years of health and dental coverage, plus mentorship and career exploration support. The GRE General Test is optional. The program requires 3 LOR, SOP per department guidance, résumé, and unofficial transcripts. Undergraduate GPA on a 4.0 scale is required.",
        "requirements": "<ul><li>Bachelor's degree in engineering, physics, chemistry, materials science, or related field</li><li>Undergraduate GPA calculated on 4.0 scale</li><li>GRE GENERAL OPTIONAL (no absolute cut-off)</li><li>TOEFL iBT / IELTS Academic / Duolingo English Test required for non-native English speakers (waiver may apply)</li><li>Duke Graduate School online application</li><li>3 letters of recommendation</li><li>Statement of purpose (per department guidance)</li><li>Résumé</li><li>Unofficial transcripts (official upon admission)</li><li>**PhD guaranteed review deadline December 11, 2026, 11:59:59 pm ET**</li><li>Late applications through March 8, 2027 reviewed on space/funding basis</li><li>Spring admission deadline October 1</li><li>On-campus residential (Durham, NC)</li></ul>",
        "research": "<ul><li>Materials Science & Biomaterials</li><li>Aerodynamics & Aeroelasticity</li><li>Biomechanics & Biomaterials</li><li>Computation & Artificial Intelligence</li><li>Energy Systems & Materials</li><li>Robotics & Autonomy</li><li>Soft Matter & Nanoscale Materials</li></ul>",
        "source": '<a href="https://gradschool.duke.edu/phd-mechanical-engineering-and-materials-science/" target="_blank">Duke Graduate School: PhD in Mechanical Engineering and Materials Science (Fall Dec 11 2026 guaranteed review; late through Mar 8 2027; Spring Oct 1; GRE General optional; TOEFL/IELTS/Duolingo; 3 LOR; SOP; résumé; unofficial transcripts; 4.0 scale GPA; Materials Science & Biomaterials concentration)</a> | <a href="https://mems.duke.edu/admissions/phd/" target="_blank">Duke MEMS PhD Admissions (guaranteed funding; 5 years stipend + 6 years health/dental; areas: Aerodynamics, Biomechanics, Computation & AI, Energy Systems, Robotics, Soft Matter & Nanoscale; apply before first Monday in December)</a> | <a href="https://gradschool.duke.edu/admissions/application-deadlines/" target="_blank">Duke Graduate School Application Deadlines (all deadlines 11:59:59pm ET; Fall 2027; MEMS PhD Dec 11 guaranteed; Materials Science and Engineering MS Nov 3 priority / Jan 31 priority / Mar 15 all applications)</a>',
    },
}

# Write detail pages
for p in PROGRAMS:
    key = p["id"]
    d = PAGES[key]
    html = DETAIL_TEMPLATE.format(
        school=d["school"], en=d["en"], deg=d["deg"], stem_label=d["stem_label"],
        dur=d["dur"], ddl=d["ddl"], lang=d["lang"], test_cls=d["test_cls"], tui=d["tui"],
        overview=d["overview"], requirements=d["requirements"],
        research=d["research"], source=d["source"],
    )
    path = os.path.join(DET, key + ".html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Wrote: {key}.html")

# Append PROGRAMS
idx_path = os.path.join(BASE, "index_main.html")
with open(idx_path, "r", encoding="utf-8") as f:
    html = f.read()

def build_entry(p):
    return ('{{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=p["n"], en=p["en"], deg=p["deg"], lvl=p["lvl"],
        stem=p["stem"], dur=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"].replace('"', "'"),
        tui=p["tui"].replace('"', "'"), url=p["url"],
    )

new_entries = ",\n".join(build_entry(p) for p in PROGRAMS)

m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[': depth += 1
    elif c == ']': depth -= 1
    i += 1
insert_pos = i - 1
prefix = html[:insert_pos].rstrip()
suffix = html[insert_pos:]
if prefix.endswith('{'):
    new_block = prefix + "\n" + new_entries + "\n" + suffix
else:
    new_block = prefix + ",\n" + new_entries + "\n" + suffix

# Append VD on new_block (re-locate to avoid offset)
vd_entries = ",\n".join(f'"{p["url"]}"' for p in PROGRAMS)
m2 = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', new_block)
vstart = m2.end()
vdepth = 1
j = vstart
while j < len(new_block) and vdepth > 0:
    c = new_block[j]
    if c == '[': vdepth += 1
    elif c == ']': vdepth -= 1
    j += 1
vinsert_pos = j - 1
vprefix = new_block[:vinsert_pos].rstrip()
vsuffix = new_block[vinsert_pos:]
if vprefix.endswith(','):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
elif vprefix.endswith('['):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
else:
    new_block = vprefix + ",\n" + vd_entries + "\n" + vsuffix

with open(idx_path, "w", encoding="utf-8") as f:
    f.write(new_block)

print(f"Appended {len(PROGRAMS)} PROGRAMS entries and {len(PROGRAMS)} VD entries")
print(f"Done. File size: {os.path.getsize(idx_path)}")
