# -*- coding: utf-8 -*-
"""Round 248: batch add 5 Mathematics PhD (first batch of basic-science PhD sweep)
- MIT Mathematics PhD (Dec 1 EST; GRE optional; TOEFL 100 iBT / IELTS 7.0; 3 LOR; all admitted students supported)
- Princeton Mathematics PhD (Dec 15 EST; GRE NOT accepted - both General and Subject; 4-year; 3 LOR; no minimum TOEFL)
- Stanford Mathematics PhD (Dec 1 11:59pm PT; GRE Math Subject expected with waiver option; most admitted >800 on Subject; 27 units; qual exams algebra/analysis/geo-topology)
- UC Berkeley Mathematics PhD (Dec 1 8:59pm PT; GRE Math Subject REQUIRED for Fall 2027; below 70th percentile considered low; GPA 3.0; ETS 4833; 5-6 years)
- UChicago Mathematics PhD (Dec 3 11:59pm CST; GRE optional but strongly encouraged Math Subject; ETS 1832 / dept 0703; $90 fee; 3 LOR; first-year 9-course core)
Key finding: Math PhD GRE policy diverges from engineering PhD - Berkeley still requires Math Subject, Stanford still expects Math Subject, while MIT/Princeton/UChicago are optional/not-accepted.
"""
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": "mit-math-phd",
        "s": "mit",
        "n": "数学博士",
        "en": "PhD in Mathematics (Massachusetts Institute of Technology, School of Science, Department of Mathematics; offers Doctor of Philosophy (PhD) and Doctor of Science (ScD) interchangeably; research across pure mathematics, applied mathematics, probability, combinatorics, logic, geometry, analysis, algebra; Fall admission only; all admitted students offered support without separate application)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; first-year coursework and preparatory exams; thesis advisor selection; original research; dissertation defense; on-campus residential (Cambridge, MA); Fall admission only",
        "ddl": "Fall 2027 (September): application opens September 1, 2026. **Deadline December 1, 2026, 23:59 Eastern Time (EST)**. No rolling admissions. Fee waiver application deadline November 20, 2026. All letters of recommendation and supporting documents due by December 1.",
        "lang": "TOEFL iBT minimum 100 (MIT OGE); IELTS minimum 7.0 (Department of Mathematics); Duolingo also accepted by MIT; required for non-native English speakers; prefer scores from this year",
        "test": {"cls": "GRE OPTIONAL (MIT Mathematics: 'Submitting GRE scores is entirely optional: We will accept scores if submitted (and are most interested in the Math Subject test result, if any) but it will not hurt your application if not included.' ETS institution code 3514; scores must be less than 5 years old. 3 LOR; statement of objectives; transcripts; no separate financial support application - all admitted students offered support.)"},
        "tui": "All admitted PhD students are offered financial support without separate application (MIT OGE: 'There is no separate application for financial support; all admitted students are offered support.' Support typically includes full tuition, stipend, and health insurance through Teaching Assistantships, Research Assistantships, and fellowships (NSF GRFP, MIT Sloan Fellows, etc.).",
        "url": "details/mit-math-phd.html",
    },
    {
        "id": "princeton-math-phd",
        "s": "princeton",
        "n": "数学博士",
        "en": "PhD in Mathematics (Princeton University, Department of Mathematics; emphasizes independent research from the start; general exam based on algebra, real/complex analysis, and two advanced topics; thesis expected in four years with optional fifth year; language requirement in French, German, or Russian; applied and computational mathematics applicants apply separately to PACM)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Program length 4 years (a fifth year is usually granted if approved in advance); first-year general exam; thesis advisor selection by end of general exam; dissertation in 2-3 years; Final Public Oral Exam (FPOE); on-campus residential (Princeton, NJ)",
        "ddl": "Fall 2027: application opens September 2026. **Deadline December 15, 2026, 11:59 p.m. Eastern Standard Time (EST)**. Fee $75. No rolling admissions. Note: applicants interested in applied and computational mathematics must apply directly to the Program in Applied and Computational Mathematics (PACM), not to the Department of Mathematics.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (Princeton Graduate School minimums); no minimum score posted by Department of Mathematics; waivers for English-instructed degree",
        "test": {"cls": "GRE NOT ACCEPTED (Princeton Mathematics: 'GREs, both general and subject test scores, will not be accepted for Fall 2023 admissions and subsequent cycles.' If scores are submitted they will not be reviewed. 3 LOR; statement of academic purpose; resume/CV; transcripts; TOEFL/IELTS required. No minimum score requirement.)"},
        "tui": "Princeton guarantees fully-funded PhD support for all admitted students typically for 5 years, including full tuition, stipend, and health insurance, through a combination of Research Assistantships, Teaching Assistantships, and fellowship awards (Princeton Graduate School funding package).",
        "url": "details/princeton-math-phd.html",
    },
    {
        "id": "stanford-math-phd",
        "s": "stanford",
        "n": "数学博士",
        "en": "PhD in Mathematics (Stanford University, School of Humanities and Sciences, Department of Mathematics; offers BS, MS, and PhD in Mathematics and participates in MCS; 27 units of 200-297 level math graduate courses for candidacy; qualifying exams from autumn 2027: choose 2 of algebra / real analysis / geometry-topology; area exam by end of Year 3 winter; dissertation defense by Year 4-5)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; first-year coursework and qualifying exams; candidacy by end of Spring Quarter Year 2; area exam by end of Winter Quarter Year 3; dissertation defended by Year 4-5; on-campus residential (Stanford, CA); Autumn admission only",
        "ddl": "Autumn 2027: application is open. **Deadline Tuesday, December 1, 2026, 11:59 pm Pacific Time (PT)**. Applications accepted for Autumn quarter only; no late applications. ETS Stanford institution code 4704 (department code irrelevant).",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (Stanford Graduate Admissions); waivers for two or more years of full-time professional/educational experience in English in the past 4 years; scores valid 2 years",
        "test": {"cls": "GRE MATH SUBJECT TEST EXPECTED (Stanford Mathematics: 'Applicants are expected to submit their GRE Mathematics Subject Test score. If it is not practical for you to take the GRE Mathematics Subject Test you will be able to submit a waiver form as part of your application.' Most admitted applicants score above 800 on Subject test (admission distribution, not minimum threshold). GRE General not listed as required. ETS 4704. TOEFL/IELTS required for non-native speakers.)"},
        "tui": "Stanford guarantees fully-funded PhD support for all admitted students typically for 5 years, including full tuition, stipend, and health insurance, through a combination of Research Assistantships, Teaching Assistantships, and fellowship awards (NSF GRFP, Stanford Graduate Fellowship, etc.).",
        "url": "details/stanford-math-phd.html",
    },
    {
        "id": "berkeley-math-phd",
        "s": "berkeley",
        "n": "数学博士",
        "en": "PhD in Mathematics (University of California Berkeley, College of Letters and Science, Department of Mathematics; offers both PhD in Mathematics and PhD in Applied Mathematics as separate programs; 5-6 years typical; transfers between programs routine but must be before qualifying exam; ETS institution code 4833)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Graduate students typically take 5-6 years to complete the doctorate; coursework; qualifying exam; dissertation research; on-campus residential (Berkeley, CA); Fall admission only",
        "ddl": "Fall 2027: application opens September 24, 2026 at 12:00 pm Pacific Time. **Deadline Tuesday, December 1, 2026, 8:59 pm Pacific Time (PT)**. ETS institution code 4833 (no department code required).",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (Berkeley Graduate Division); Duolingo, TOEFL ITP, MyBest Scores, IELTS Indicator, and IELTS One Test Retake are NOT accepted; waivers for English-instructed degree",
        "test": {"cls": "GRE MATH SUBJECT TEST REQUIRED (Berkeley Mathematics: 'The GRE Subject exam in Mathematics will be required for the Fall 2027 graduate admissions application. You may still submit other GRE results, such as the General exam; however, only the subject test in Mathematics is required.' Score below 70th percentile considered low (admission distribution, not minimum threshold). Minimum GPA 3.0 on 4-point scale. ETS institution 4833.)"},
        "tui": "UC Berkeley guarantees fully-funded PhD support for all admitted students typically for 5-6 years, including full tuition, stipend, and health insurance, through a combination of Research Assistantships, Teaching Assistantships, and fellowship awards (NSF GRFP, Berkeley Fellowship, etc.).",
        "url": "details/berkeley-math-phd.html",
    },
    {
        "id": "uchicago-math-phd",
        "s": "uchicago",
        "n": "数学博士",
        "en": "PhD in Mathematics (University of Chicago, Department of Mathematics; first-year program of 9 courses with at least 6 core first-year courses; thesis advisor by end of first year; oral topic presentation by end of Winter Quarter Year 2; dissertation defense; no mid-year admission; separate Committee on Computational and Applied Mathematics (CAM) PhD program with January 7 deadline)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; first-year core program (9 courses); thesis advisor by end of Year 1; oral topic presentation by Winter Quarter Year 2; Year 5 progress review; dissertation defense; on-campus residential (Chicago, IL); Fall admission only (no mid-year)",
        "ddl": "Autumn 2027: application is open. **Deadline Thursday, December 3, 2026, 11:59 p.m. Central Standard Time (CST)**. Fee $90. Decisions typically issued by March 31. Note: separate Committee on Computational and Applied Mathematics (CAM) PhD has deadline January 7, 2027.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (UChicago Graduate Division); UChicago has no minimum test scores or GPAs (holistic admissions); ETS institution code 1832",
        "test": {"cls": "GRE OPTIONAL BUT MATH SUBJECT STRONGLY ENCOURAGED (UChicago Mathematics: 'GRE test scores are optional, but applicants are strongly encouraged to submit the Mathematics Subject Test scores. Applicants may submit both General and Subject Test scores. Those who do not submit Mathematics Subject Test scores should briefly explain their reason in the application.' ETS institution 1832; department code for Mathematics 0703, Applied Mathematics 0702. 3 LOR; SOP; CV; transcripts.)"},
        "tui": "UChicago guarantees fully-funded PhD support for all admitted students typically for 5-6 years, including full tuition, stipend, and health insurance, through a combination of Research Assistantships, Teaching Assistantships, and fellowship awards (NSF GRFP, UChicago McCormick Fellowship, etc.).",
        "url": "details/uchicago-math-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> First batch of basic-science PhD sweep (MIT, Princeton, Stanford, UC Berkeley, UChicago Mathematics PhD). Key finding: Math PhD GRE policy diverges sharply from engineering PhD GRE-free trend. Berkeley still requires GRE Math Subject Test for Fall 2027, Stanford still expects GRE Math Subject Test (with waiver option), while MIT is optional and Princeton does not accept either General or Subject GRE. UChicago is optional but strongly encourages Math Subject. Deadlines: Dec 1 (MIT EST / Stanford PT / Berkeley PT), Dec 3 (UChicago CST), Dec 15 (Princeton EST). All 5 programs are STEM-designated, fully-funded, on-campus residential, and Fall admission only. Princeton has a separate PACM program for applied and computational mathematics applicants. UChicago has a separate CAM (Computational and Applied Mathematics) PhD with January 7 deadline. Berkeley offers both PhD in Mathematics and PhD in Applied Mathematics as separate programs; transfers are routine but must be before qualifying exam.
</div>
</body>
</html>
"""

PAGES = {
    "mit-math-phd": {
        "school": "Massachusetts Institute of Technology, School of Science, Department of Mathematics",
        "en": "PhD in Mathematics",
        "deg": "Doctor of Philosophy (PhD) / Doctor of Science (ScD) (interchangeable)",
        "stem_label": "STEM-designated (Mathematical Sciences / CIP 27.0101)",
        "dur": "Typically 5-6 years; first-year coursework and preparatory exams; thesis advisor selection; original research; dissertation defense; on-campus residential (Cambridge, MA); Fall admission only",
        "ddl": "Fall 2027 (September): opens September 1, 2026. **Deadline December 1, 2026, 23:59 EST**. No rolling admissions. Fee waiver deadline November 20, 2026. All LOR and supporting documents due by December 1.",
        "lang": "TOEFL iBT minimum 100 (MIT OGE); IELTS minimum 7.0 (Department of Mathematics); Duolingo also accepted; prefer scores from this year",
        "test_cls": "GRE OPTIONAL (MIT Mathematics: 'entirely optional: We will accept scores if submitted (and are most interested in the Math Subject test result, if any) but it will not hurt your application if not included.' ETS 3514; scores < 5 years old. 3 LOR; statement of objectives.)",
        "tui": "All admitted PhD students offered financial support without separate application. Support typically includes full tuition, stipend, and health insurance through TA, RA, and fellowships (NSF GRFP, MIT fellowships).",
        "overview": "The MIT Department of Mathematics offers the Doctor of Philosophy (PhD) and Doctor of Science (ScD) degrees interchangeably in the School of Science. Research spans pure mathematics (algebra, analysis, geometry, topology, logic, number theory), applied mathematics (applied mathematics, combinatorics, computational biology, probability, theoretical physics), and mathematics with applications across science and engineering. The application opens September 1, with a deadline of December 1 at 23:59 Eastern Time for matriculation in the following September. MIT admits students starting in the Fall term only; there is no rolling admissions. The application fee is $90, with fee waiver requests due by November 20, 2026. GRE scores are entirely optional: MIT will accept scores if submitted (and is most interested in the Math Subject test result if any) but it will not hurt an application if not included. Non-native English speakers must submit IELTS or TOEFL iBT (preferably from this year). Three or more letters of recommendation are required along with a statement of objectives. Critically, there is no separate application for financial support: all admitted students are offered support. ETS institution code is 3514.",
        "requirements": "<ul><li>Bachelor's degree in mathematics or related quantitative field</li><li>GRE OPTIONAL (General and Math Subject; accepted if submitted; absence not penalized)</li><li>TOEFL iBT minimum 100 / IELTS minimum 7.0</li><li>Prefer English scores from this year</li><li>MIT OGE online application (opens September 1)</li><li>3 or more letters of recommendation</li><li>Statement of objectives</li><li>CV/resume (educational and work history)</li><li>Transcripts</li><li>Field(s) of interest</li><li>Grades in math/science/engineering courses and overall</li><li>Honors and awards</li><li>Credit/debit card payment of $90</li><li>Fee waiver requests due November 20, 2026</li><li>**Deadline December 1, 2026, 23:59 EST**</li><li>Fall admission only (no Spring/Summer entry)</li><li>On-campus residential (Cambridge, MA)</li></ul>",
        "research": "<ul><li>Pure mathematics (algebra, analysis, geometry, topology, logic, number theory)</li><li>Applied mathematics</li><li>Combinatorics</li><li>Probability and statistics</li><li>Theoretical computer science</li><li>Mathematical physics</li><li>Computational biology</li><li>Financial mathematics</li></ul>",
        "source": '<a href="https://math.mit.edu/academics/grad/phd/admission/" target="_blank">MIT Mathematics PhD Admission (Dec 1, 23:59 EST; Fall only; $90 fee; fee waiver Nov 20; 3+ LOR; GRE optional; TOEFL/IELTS required; all admitted students supported)</a> | <a href="https://math.mit.edu/academics/grad/phd/admission/faq" target="_blank">MIT Mathematics PhD FAQ (no rolling; fee waiver Nov 20; GRE optional; IELTS minimum 7.0; all LOR and docs due Dec 1)</a> | <a href="https://oge.mit.edu/programs/mathematics/" target="_blank">MIT OGE: Mathematics (Dec 1 11:59pm ET; $90; STEM eligible; PhD/ScD; 5th-year MAppSc for current MIT students only; TOEFL iBT minimum 100; ETS 3514; scores < 5 years old)</a>',
    },
    "princeton-math-phd": {
        "school": "Princeton University, Department of Mathematics",
        "en": "PhD in Mathematics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Mathematical Sciences / CIP 27.0101)",
        "dur": "Program length 4 years (5th year usually granted if approved in advance); first-year general exam; thesis advisor; dissertation in 2-3 years; Final Public Oral Exam (FPOE); on-campus (Princeton, NJ)",
        "ddl": "Fall 2027: application opens September 2026. **Deadline December 15, 2026, 11:59 p.m. EST**. Fee $75. Note: applied and computational mathematics applicants apply separately to PACM.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (Princeton Graduate School); no minimum score posted by Mathematics; waivers for English-instructed degree",
        "test_cls": "GRE NOT ACCEPTED (Princeton Mathematics: 'GREs, both general and subject test scores, will not be accepted for Fall 2023 admissions and subsequent cycles.' Submitted scores will not be reviewed. 3 LOR; statement of academic purpose; CV; transcripts. No minimum TOEFL.)",
        "tui": "Princeton guarantees fully-funded PhD support for all admitted students typically for 5 years: full tuition, stipend, and health insurance through RA, TA, and fellowships.",
        "overview": "The Princeton University Department of Mathematics offers a PhD program that, in contrast to other top mathematics institutions, emphasizes independent research from the start. The curriculum is deliberately minimal in requirements and maximal in research and educational opportunities. Students are expected to write a dissertation in four years, with an additional year provided if deemed necessary. Beyond a strong knowledge of three general subjects (algebra, real analysis, and complex analysis), first-year students take the fast track of research by choosing two advanced research topics from distinct major areas of mathematics, subject to department approval, as part of their general exam. After the general exam, the student chooses a thesis advisor and typically takes 2-3 years to complete the dissertation. The PhD is awarded after the candidate's doctoral dissertation and Final Public Oral Exam (FPOE). A language requirement in French, German, or Russian must be satisfied by demonstrating reasonable ability to read ordinary mathematical texts. The application deadline is December 15 at 11:59 p.m. Eastern Standard Time, with a fee of $75. Critically, Princeton does not accept GRE General Test or GRE Mathematics Subject Test scores; submitted scores will not be reviewed. Three letters of recommendation, a statement of academic purpose, a resume/CV, and transcripts are required. TOEFL/IELTS are required for non-native English speakers; there is no minimum score. Note: applicants interested in applied and computational mathematics must apply directly to the Program in Applied and Computational Mathematics (PACM), not the Department of Mathematics.",
        "requirements": "<ul><li>Bachelor's degree in mathematics or related field</li><li>Solid background in undergraduate mathematics; stronger emphasis on recommender testimony of research potential than specific course palette</li><li>**GRE NOT ACCEPTED** (General and Subject; submitted scores not reviewed)</li><li>TOEFL iBT / IELTS Academic required (no minimum score posted)</li><li>Princeton Graduate School online application</li><li>Statement of academic purpose</li><li>Resume/CV</li><li>3 letters of recommendation</li><li>Transcripts (one from every college/university where degree earned or expected; uploaded electronically; not mailed)</li><li>**Deadline December 15, 2026, 11:59 p.m. EST**</li><li>Fee $75</li><li>Program length 4 years (5th year approved in advance)</li><li>Language requirement: French, German, or Russian</li><li>General exam: algebra + real/complex analysis + 2 advanced topics</li><li>FPOE: Final Public Oral Exam</li><li>On-campus residential (Princeton, NJ)</li><li>Applied and computational mathematics applicants must apply to PACM separately</li></ul>",
        "research": "<ul><li>Pure mathematics (algebra, analysis, geometry, topology, number theory, logic)</li><li>Mathematical physics</li><li>Combinatorics</li><li>Probability</li><li>Partial differential equations</li><li>Representation theory</li><li>Number theory</li><li>Geometric analysis</li></ul>",
        "source": '<a href="https://www.math.princeton.edu/graduate/admissions" target="_blank">Princeton Mathematics Graduate Admissions (Dec 15 deadline; fee $75; 3 LOR; SOP; CV; transcripts; TOEFL/IELTS; GRE both general and subject not accepted; 4-year program; applied math applicants apply to PACM)</a> | <a href="https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/mathematics" target="_blank">Princeton Graduate School: Mathematics (Dec 15, 11:59pm EST; fee $75; GRE General not accepted; Subject in Mathematics not accepted; program length 4 years; general exam; language requirement in French/German/Russian; FPOE)</a> | <a href="https://web.math.princeton.edu/graduate/newindex.htm" target="_blank">Princeton Math Graduate Program (required materials; program requirements; language exams; dissertation and FPOE; contacts)</a>',
    },
    "stanford-math-phd": {
        "school": "Stanford University, School of Humanities and Sciences, Department of Mathematics",
        "en": "PhD in Mathematics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Mathematical Sciences / CIP 27.0101)",
        "dur": "Typically 5-6 years; first-year coursework and qualifying exams; candidacy by Spring Quarter Year 2; area exam by Winter Quarter Year 3; dissertation defense Year 4-5; on-campus (Stanford, CA); Autumn admission only",
        "ddl": "Autumn 2027: application is open. **Deadline Tuesday, December 1, 2026, 11:59 pm Pacific Time (PT)**. Autumn quarter only; no late applications. ETS Stanford institution code 4704.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers (Stanford Graduate Admissions); waivers for 2+ years of full-time professional/educational experience in English in past 4 years; scores valid 2 years",
        "test_cls": "GRE MATH SUBJECT EXPECTED (Stanford Mathematics: 'Applicants are expected to submit their GRE Mathematics Subject Test score. If it is not practical... waiver form available.' Most admitted >800 on Subject (admission distribution, not minimum). GRE General not listed as required. ETS 4704.)",
        "tui": "Stanford guarantees fully-funded PhD support for all admitted students typically for 5 years: full tuition, stipend, and health insurance through RA, TA, and fellowships (NSF GRFP, Stanford Graduate Fellowship).",
        "overview": "The Stanford University Department of Mathematics offers BS, MS, and PhD degrees in Mathematics, and also participates in the BS in Mathematical and Computational Science (MCS) and the MS and PhD programs offered through the Institute for Computational and Mathematical Engineering (ICME). The PhD program requires completion of 27 units of Mathematics graduate courses numbered 200-297 for a letter grade to qualify for candidacy. By university requirements, PhD students must complete 135 course units beyond the bachelor's degree, with a GPA of 3.0 (B) or better. By the end of Spring Quarter of their second year, students must have a dissertation advisor and apply for candidacy. Starting in Autumn 2027, qualifying exams require students to choose 2 out of 3 topics: algebra, real analysis, or geometry and topology. During their third year, students take their Area Examination, which must be completed by the end of Winter Quarter. Typically during the latter part of Year 4 or early part of Year 5, students finish their dissertation research, defend it at the University Oral Examination, and submit the final dissertation to their reading committee. The application for Autumn 2027 is open, with a deadline of Tuesday, December 1, 2026, at 11:59 pm Pacific Time. Applications are accepted for Autumn quarter only. GRE Mathematics Subject Test is expected of applicants; those unable to take it may submit a waiver form explaining why. Most admitted applicants score above 800 on the Subject test (admission distribution, not minimum threshold). ETS institution code is 4704.",
        "requirements": "<ul><li>Bachelor's degree in mathematics or related quantitative field</li><li>GRE Mathematics Subject Test expected (waiver form available if unable to take)</li><li>Most admitted applicants score above 800 on Subject test (admission distribution, not minimum threshold)</li><li>GRE General not listed as required</li><li>TOEFL iBT / IELTS Academic required for non-native English speakers</li><li>Waivers for 2+ years of full-time professional/educational experience in English in past 4 years</li><li>Stanford Graduate Admissions online application</li><li>Statement of purpose</li><li>3 letters of recommendation</li><li>Transcripts</li><li>CV/resume</li><li>ETS Stanford institution code 4704</li><li>**Deadline December 1, 2026, 11:59 pm PT**</li><li>Autumn quarter admission only (no Winter/Spring/Summer entry)</li><li>27 units of Math graduate courses 200-297 for candidacy</li><li>135 course units beyond bachelor's; GPA 3.0 (B) minimum</li><li>Qualifying exams (from Autumn 2027): choose 2 of algebra / real analysis / geometry-topology</li><li>Dissertation advisor by end of Spring Quarter Year 2</li><li>Area exam by end of Winter Quarter Year 3</li><li>On-campus residential (Stanford, CA)</li></ul>",
        "research": "<ul><li>Pure mathematics (algebra, analysis, geometry, topology, number theory, logic)</li><li>Applied mathematics</li><li>Mathematical physics</li><li>Probability</li><li>Combinatorics</li><li>Partial differential equations</li><li>Cross-disciplinary with ICME, CS, Statistics</li></ul>",
        "source": '<a href="https://mathematics.stanford.edu/academics/graduate-admissions" target="_blank">Stanford Mathematics Graduate Admissions (Autumn 2027 open; Dec 1, 2026, 11:59pm PT; Autumn only; GRE Math Subject expected; waiver form available; most admitted >800 on Subject; TOEFL/IELTS required)</a> | <a href="https://mathematics.stanford.edu/academics/graduate-students/phd-program" target="_blank">Stanford Mathematics PhD Program (from Autumn 2027 qual exams choose 2 of algebra/real analysis/geometry-topology; 27 units Math 200-297; candidacy by Spring Year 2; area exam by Winter Year 3; dissertation defense Year 4-5)</a> | <a href="https://23-24.bulletin.stanford.edu/programs/MATH-PHD/overview-aoYks" target="_blank">Stanford Bulletin: MATH-PHD (27 units 200-297; 135 course units beyond bachelor; GPA 3.0 B minimum; candidacy by end of Spring Year 2; dissertation advisor)</a> | <a href="https://gradadmissions.stanford.edu/node/66" target="_blank">Stanford Graduate Admissions: Test Scores (ETS 4704; GRE valid 5 years; TOEFL/IELTS valid 2 years; self-reported accepted for initial review; official scores required if program requires)</a>',
    },
    "berkeley-math-phd": {
        "school": "University of California Berkeley, College of Letters and Science, Department of Mathematics",
        "en": "PhD in Mathematics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Mathematical Sciences / CIP 27.0101)",
        "dur": "Graduate students typically take 5-6 years to complete the doctorate; coursework; qualifying exam; dissertation research; on-campus (Berkeley, CA); Fall admission only",
        "ddl": "Fall 2027: application opens September 24, 2026 at 12:00 pm Pacific Time. **Deadline Tuesday, December 1, 2026, 8:59 pm Pacific Time (PT)**. ETS institution code 4833 (no department code).",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers; Duolingo, TOEFL ITP, MyBest Scores, IELTS Indicator, and IELTS One Test Retake are NOT accepted; waivers for English-instructed degree",
        "test_cls": "GRE MATH SUBJECT REQUIRED (Berkeley Mathematics: 'The GRE Subject exam in Mathematics will be required for the Fall 2027 graduate admissions application. You may still submit other GRE results, such as the General exam; however, only the subject test in Mathematics is required.' Score below 70th percentile considered low (admission distribution, not minimum). Minimum GPA 3.0 on 4-point scale. ETS 4833.)",
        "tui": "UC Berkeley guarantees fully-funded PhD support for all admitted students typically for 5-6 years: full tuition, stipend, and health insurance through RA, TA, and fellowships (NSF GRFP, Berkeley Fellowship).",
        "overview": "The UC Berkeley Department of Mathematics offers both a PhD program in Mathematics and a PhD program in Applied Mathematics. Students are admitted to specific programs (PhD in Mathematics or PhD in Applied Mathematics); requirements differ only in minor respects, and no distinction is made between the two in day-to-day matters. Graduate students typically take 5-6 years to complete the doctorate. Transfers between the two PhD programs are fairly routine but must be done prior to taking the qualifying examination. It is a formal policy that an applicant to the PhD program who has previous graduate work in mathematics must present very strong evidence of capability for mathematical research. The application for Fall 2027 opens September 24, 2026 at 12:00 pm Pacific Time. The deadline is Tuesday, December 1, 2026 at 8:59 pm Pacific Time. Critically, the GRE Subject exam in Mathematics will be required for the Fall 2027 graduate admissions application; applicants may still submit GRE General results, but only the Subject test is required. The Math Subject GRE score will be one factor among many considered by the admissions committee; while there are no rigid rules on weighting, it is very unlikely that an applicant with a low GRE score will be admitted. A score below the 70th percentile would be considered low (admission distribution, not minimum threshold). The department complies with the Graduate Division minimum GPA requirement of 3.0 on a 4-point scale. ETS institution code is 4833, with no department code required. Berkeley does not accept Duolingo, TOEFL ITP, MyBest Scores, IELTS Indicator, or IELTS One Test Retake.",
        "requirements": "<ul><li>Bachelor's degree in mathematics or related quantitative field</li><li>Minimum GPA 3.0 on a 4-point scale (Berkeley Graduate Division minimum)</li><li>**GRE Subject Test in Mathematics REQUIRED for Fall 2027**</li><li>GRE General may also be submitted (optional)</li><li>Score below 70th percentile on Subject test considered low (admission distribution, not minimum threshold)</li><li>TOEFL iBT / IELTS Academic required for non-native English speakers</li><li>Duolingo, TOEFL ITP, MyBest Scores, IELTS Indicator, IELTS One Test Retake NOT accepted</li><li>Waivers for English-instructed degree</li><li>UC Berkeley Graduate Division online application (opens September 24, 2026, 12:00 pm PT)</li><li>Statement of purpose</li><li>3 letters of recommendation</li><li>Transcripts</li><li>Personal history statement</li><li>CV/resume</li><li>ETS institution code 4833 (no department code)</li><li>**Deadline December 1, 2026, 8:59 pm PT**</li><li>Fall admission only</li><li>5-6 years typical completion</li><li>PhD in Mathematics and PhD in Applied Mathematics are separate programs; transfers routine but before qualifying exam</li><li>On-campus residential (Berkeley, CA)</li></ul>",
        "research": "<ul><li>Pure mathematics (algebra, analysis, geometry, topology, number theory, logic)</li><li>Applied mathematics</li><li>Probability and statistics</li><li>Mathematical physics</li><li>Combinatorics</li><li>Partial differential equations</li><li>Logic and methodology of science (Group in Logic and the Methodology of Science)</li></ul>",
        "source": '<a href="https://math.berkeley.edu/graduate/admissions" target="_blank">Berkeley Mathematics Graduate Admissions (Fall 2027 open; Dec 1, 2026, 8:59pm PT; GRE Math Subject REQUIRED for Fall 2027; General optional; below 70th percentile considered low; ETS 4833; recommend taking exams by October for timely score reporting)</a> | <a href="https://math.berkeley.edu/graduate/admissions/frequently-asked-questions" target="_blank">Berkeley Math FAQ (Math Subject required; General optional; below 50th percentile considered low; holistic review; minimum GPA 3.0)</a> | <a href="https://grad.berkeley.edu/program/mathematics-phd/" target="_blank">Berkeley Graduate Division: Mathematics PhD (Dec 1, 2026; Fall admission; GRE Yes, subject test; 970 Evans Hall; PhD in Mathematics and PhD in Applied Mathematics separate programs; 5-6 years typical)</a> | <a href="https://grad.berkeley.edu/admissions/application-process/requirements/" target="_blank">Berkeley Graduate Division: Admissions Requirements (application opens Sept 24, 2026 12:00pm PT; TOEFL/IELTS accepted; Duolingo/TOEFL ITP/MyBest/IELTS Indicator/IELTS One Test Retake NOT accepted)</a>',
    },
    "uchicago-math-phd": {
        "school": "University of Chicago, Department of Mathematics",
        "en": "PhD in Mathematics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Mathematical Sciences / CIP 27.0101)",
        "dur": "Typically 5-6 years; first-year 9-course core program (at least 6 core); thesis advisor by end of Year 1; oral topic presentation by Winter Year 2; Year 5 progress review; dissertation defense; on-campus (Chicago, IL); Fall admission only",
        "ddl": "Autumn 2027: application is open. **Deadline Thursday, December 3, 2026, 11:59 p.m. Central Standard Time (CST)**. Fee $90. Decisions by March 31. Note: separate CAM PhD has deadline January 7, 2027.",
        "lang": "TOEFL iBT / IELTS Academic required for non-native English speakers; UChicago has no minimum test scores or GPAs (holistic admissions); ETS institution code 1832",
        "test_cls": "GRE OPTIONAL BUT MATH SUBJECT STRONGLY ENCOURAGED (UChicago Mathematics: 'GRE test scores are optional, but applicants are strongly encouraged to submit the Mathematics Subject Test scores. Applicants may submit both General and Subject Test scores. Those who do not submit Mathematics Subject Test scores should briefly explain their reason in the application.' ETS 1832; dept 0703 Math / 0702 Applied Math. 3 LOR; SOP; CV; transcripts.)",
        "tui": "UChicago guarantees fully-funded PhD support for all admitted students typically for 5-6 years: full tuition, stipend, and health insurance through RA, TA, and fellowships (NSF GRFP, UChicago McCormick Fellowship).",
        "overview": "The University of Chicago Department of Mathematics offers a PhD program that provides in-depth knowledge and rigorous training across all subject areas of mathematics. A core feature is the first-year program, which helps bring students to the forefront of modern mathematics. Students work closely with faculty and each other, and participate fully in both research and student-run seminars. The firm deadline for applications for Autumn 2027 is Thursday, December 3, 2026, at 11:59 p.m. Central Standard Time. GRE test scores are optional, but applicants are strongly encouraged to submit the Mathematics Subject Test scores; applicants may submit both General and Subject Test scores. Those who do not submit the Mathematics Subject Test scores should briefly explain their reason in the application. ETS institution code is 1832; department code for Mathematics is 0703, and for Applied Mathematics is 0702. The application fee is $90. Required materials include original transcripts and official translations from all undergraduate and graduate institutions attended, at least three letters of recommendation, and TOEFL or IELTS scores if necessary. UChicago does not allow students to begin in the middle of the academic year. The admissions committee generally finishes making decisions by March 31. To obtain the PhD in Pure Mathematics, students must complete a first-year program consisting of nine courses (at least six of which must be core first-year courses), choose a thesis advisor by the end of their first year, make an oral topic presentation with a brief written report usually by the end of the Winter Quarter of their second year, and complete a dissertation under the guidance of a faculty advisor. Note: a separate Committee on Computational and Applied Mathematics (CAM) PhD program has a deadline of January 7, 2027.",
        "requirements": "<ul><li>Bachelor's degree in mathematics or related quantitative field</li><li>GRE OPTIONAL (General and Subject)</li><li>GRE Mathematics Subject Test strongly encouraged; if not submitted, briefly explain reason in application</li><li>TOEFL iBT / IELTS Academic required for non-native English speakers</li><li>UChicago has no minimum test scores or GPAs (holistic admissions)</li><li>ETS institution code 1832; dept 0703 (Math) / 0702 (Applied Math)</li><li>UChicago Graduate Division online application</li><li>$90 nonrefundable application fee</li><li>At least 3 letters of recommendation</li><li>Statement of purpose</li><li>CV/resume</li><li>Original transcripts and official translations from all undergraduate and graduate institutions</li><li>**Deadline December 3, 2026, 11:59 p.m. CST**</li><li>Fall admission only (no mid-year entry)</li><li>Decisions typically by March 31</li><li>First-year 9-course core program (at least 6 core)</li><li>Thesis advisor by end of Year 1</li><li>Oral topic presentation by end of Winter Quarter Year 2</li><li>Year 5 progress review by November 15</li><li>Dissertation defense</li><li>On-campus residential (Chicago, IL)</li><li>Note: separate CAM (Computational and Applied Mathematics) PhD deadline January 7, 2027</li></ul>",
        "research": "<ul><li>Pure mathematics (algebra, analysis, geometry, topology, number theory, logic)</li><li>Applied mathematics</li><li>Mathematical physics</li><li>Probability</li><li>Partial differential equations</li><li>Combinatorics</li><li>Representation theory</li><li>Cross-disciplinary with CAM (Computational and Applied Mathematics), CS, Statistics, Physics</li></ul>",
        "source": '<a href="https://mathematics.uchicago.edu/graduate/mathematics-phd-program/" target="_blank">UChicago Mathematics PhD Program (Dec 3, 2026, 11:59pm CST; GRE optional but Math Subject strongly encouraged; ETS 1832 / dept 0703 Math / 0702 Applied Math; first-year 9-course core; thesis advisor by end Year 1)</a> | <a href="https://mathematics.uchicago.edu/graduate/mathematics-phd-program/how-to-apply/" target="_blank">UChicago Mathematics How to Apply (Dec 3, 2026 deadline; $90 fee; 3 LOR; TOEFL/IELTS; transcripts and translations; decisions by March 31; no mid-year admission)</a> | <a href="https://mathematics.uchicago.edu/graduate/mathematics-phd-program/graduate-student-resources/information-for-current-graduate-students/" target="_blank">UChicago Math: Requirements to Obtain PhD in Pure Mathematics (first-year 9 courses with at least 6 core; thesis advisor by end Year 1; oral topic presentation by Winter Year 2; Year 5 PSD progress review by November 15; dissertation)</a> | <a href="https://cam.uchicago.edu/academics/phd-in-computational-and-applied-mathematics/" target="_blank">UChicago CAM PhD (separate program; deadline January 7, 2027; analytic/physical math and modeling track + computational track; functional analysis, PDE, applied dynamical systems, applied matrix computation, optimization, approximation theory, machine learning)</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)}")
