# -*- coding: utf-8 -*-
"""Round 217: batch add 5 PhDs
- mcg-bme-phd (McGill Biological and Biomedical Engineering)
- notre-bme-phd (Notre Dame Bioengineering)
- princeton-orfe-phd (Princeton Operations Research and Financial Engineering)
- stanford-stat-phd (Stanford Statistics)
- uchicago-econ-phd (UChicago Economics)
Note: Stanford Statistics and UChicago Economics still REQUIRE GRE General Test
(rare holdouts against the 2026-27 GRE-free trend).
Reuses r214 VD fix pattern.
"""
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": "mcg-bme-phd",
        "s": "mcg",
        "n": "生物与生物医学工程博士",
        "en": "PhD in Biological and Biomedical Engineering (BBME, interfaculty)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years post-master's (Ph.D. 2); direct bachelor's entry (Ph.D. 1) requires CGPA 3.7/4.0 plus extensive research experience",
        "ddl": "Fall 2027: international deadline January 15, 2027. Winter 2027: international deadline August 1. No summer admission. If primary supervisor is Bioengineering dept, apply by international deadline for Engineering Recruitment awards; if Biomedical Engineering dept, apply by domestic deadline for BME Recruitment awards.",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0. English-language proficiency required.",
        "test": {"cls": "GRE not required. Minimum CGPA 3.0/4.0 university-level; departmental expectation 3.3/4.0 in both Master's and undergraduate. Research-based Master's in Biological/Biomedical Engineering or related field normally required; exceptional bachelor's direct entry (Ph.D. 1) requires CGPA 3.7/4.0 plus Honours thesis or multiple summer research projects and a supervisor attestation letter."},
        "tui": "Admitted students are GUARANTEED funding for 4 years. Interfaculty graduate program jointly run by the Department of Bioengineering (Faculty of Engineering) and the Department of Biomedical Engineering (Faculty of Medicine and Health Sciences). Faculty, hospital and government careers.",
        "url": "details/mcg-bme-phd.html",
    },
    {
        "id": "notre-bme-phd",
        "s": "notre",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering (interdisciplinary, College of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-7 years; minimum 9 graduate-level courses distributed across engineering and the sciences; Qualifying Exam after summer of first year (cumulative GPA 3.3+ required); dissertation defense within 7 years",
        "ddl": "Fall 2027: December 31, 2026. Spring 2027: October 1, 2026. No late applications.",
        "lang": "TOEFL, IELTS, or Duolingo accepted for non-native English speakers.",
        "test": {"cls": "GRE General Test OPTIONAL (considered if submitted; generally advantageous for international applicants and students from smaller engineering colleges; self-reported scores verified before matriculation). Master's degree NOT required - apply directly to PhD. Minimum undergraduate GPA 3.0/4.0; QE requires cumulative GPA 3.3+."},
        "tui": "Fully supported through fellowships and research assistantships; substantially increased stipends available with fellowships. Interdisciplinary program involving faculty from all five engineering departments plus biology and biochemistry. Affiliated with Harper Cancer Research Institute and Institute for Precision Health. Apply through any home department (Aerospace/ME for tissue engineering/mechanobiology; Chemical and Biomolecular Engineering for diagnostics/drug delivery; Electrical Engineering for imaging).",
        "url": "details/notre-bme-phd.html",
    },
    {
        "id": "princeton-orfe-phd",
        "s": "princeton",
        "n": "运筹与金融工程博士",
        "en": "PhD in Operations Research and Financial Engineering (ORFE, SEAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; first year six core courses (ORF 522 Linear/Nonlinear Optimization, 523 Convex/Conic Optimization, 524 Statistical Theory and Methods, 525 Statistical Foundations of Data Science, 526 Probability Theory, 527 Stochastic Calculus); Qualifying Exam end of first summer; General Exam Spring of second year; dissertation 2-3 years after Generals",
        "ddl": "Fall 2027: January 3, 2027 (11:59 PM Eastern). Application fee $75; fee waivers available.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Princeton Graduate School has no minimum score; departments set their own.",
        "test": {"cls": "GRE OPTIONAL / NOT REQUIRED (since Fall 2022). No minimum GRE. Bachelor's degree in engineering, sciences, or mathematics normally required; strong mathematical background expected. Three letters of recommendation; statement of academic purpose; CV; transcripts in English."},
        "tui": "Fully funded via fellowship/RA/TA. ORFE combines Financial Mathematics, Machine Learning, Operations Research, Optimization, Probability and Statistics. Faculty affiliated with Bendheim Center for Finance, Andlinger Center for Energy and Environment, Princeton Environmental Institute, and Center for Statistics and Machine Learning. Research areas: financial engineering, stochastic systems, optimization, statistics and financial econometrics, energy, health, bioinformatics.",
        "url": "details/princeton-orfe-phd.html",
    },
    {
        "id": "stanford-stat-phd",
        "s": "stanford",
        "n": "统计学博士",
        "en": "PhD in Statistics (Department of Statistics)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; PhD students select advisor at end of second year after rotating with faculty; autumn quarter entry only",
        "ddl": "Autumn 2027-28: Wednesday, December 2, 2026 (11:59 PM PST). Application fee $125. Knight-Hennessy Scholars separate deadline October 6, 2026 (1:00 PM PT), with department application moved to December 1 for KHS candidates. Decisions by mid-February.",
        "lang": "TOEFL iBT minimum 4.5 (90 on previous scale); IELTS minimum 7.0. Incoming students scoring below TOEFL 5.5 (109 old scale) or IELTS 8.0 are required to take English coursework.",
        "test": {"cls": "GRE GENERAL TEST REQUIRED (rare holdout against the 2026-27 GRE-free trend - all PhD applicants must submit valid GRE General scores). GRE Math Subject Test OPTIONAL but RECOMMENDED (since May 2024). No separate review process for internal applicants. No deferral of admission. About 175 PhD applications per year, admit 11-12 new students."},
        "tui": "Full financial aid package (departmental support for all PhD students). MS students receive no financial aid. Advisor selected at end of second year after research rotations. May also apply for Knight-Hennessy Scholars fellowship (up to 100 across Stanford's seven graduate schools).",
        "url": "details/stanford-stat-phd.html",
    },
    {
        "id": "uchicago-econ-phd",
        "s": "uchicago",
        "n": "经济学博士",
        "en": "PhD in Economics (Kenneth C. Griffin Department of Economics)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; year-long first-year sequence of courses; autumn quarter entry only; entering class 20-25 students per year",
        "ddl": "Autumn 2027: December 1, 2026 (11:59 PM Central Time). Late-round March 15 deadline for current UChicago MAE/MAPSS-Econ/MACSS-Econ students only (requires 6 graded graduate courses with A- or higher in 3 Economics courses, plus one letter from a tenured-track Economics faculty).",
        "lang": "TOEFL iBT minimum 4.5 on each section (Reading 22, Listening 20, Writing 21, Speaking 23 - for tests taken after January 21, 2026); IELTS minimum 7.0 on each section. Home-administered tests accepted. TOEFL MyBest scores NOT accepted.",
        "test": {"cls": "GRE GENERAL TEST REQUIRED (rare holdout - Social Sciences Division lists Economics as 'Required'. Official scores required; self-reported not sufficient. Institution code 1832. Exams should be taken no later than November 1 for December 1 deadline). Prerequisites: one year college calculus, plus one quarter/semester each of matrix algebra and mathematical statistics; recommended additional real analysis. No arbitrary GPA or test score cut-offs; holistic review."},
        "tui": "Full funding via fellowship/RA/TA. Joint PhD in Financial Economics offered with Chicago Booth PhD Program in Finance. Also accepts UChicago MAE Research Intensive Track and MACSS-Econ students through late-round March 15 entry. Note: applicants already holding a PhD in a closely related field cannot be considered.",
        "url": "details/uchicago-econ-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>Yes</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> This is a research-oriented PhD program. Admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification.
</div>
</body>
</html>
"""

PAGES = {
    "mcg-bme-phd": {
        "school": "McGill University",
        "en": "PhD in Biological and Biomedical Engineering (BBME, interfaculty)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years post-master's (Ph.D. 2); direct bachelor's entry (Ph.D. 1) requires CGPA 3.7/4.0 plus extensive research experience",
        "ddl": "Fall 2027: international deadline January 15, 2027. Winter 2027: international deadline August 1. No summer admission. If primary supervisor is Bioengineering dept, apply by international deadline for Engineering Recruitment awards; if Biomedical Engineering dept, apply by domestic deadline for BME Recruitment awards.",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0. English-language proficiency required.",
        "test_cls": "GRE not required. Minimum CGPA 3.0/4.0 university-level; departmental expectation 3.3/4.0 in both Master's and undergraduate. Research-based Master's in Biological/Biomedical Engineering or related field normally required; exceptional bachelor's direct entry (Ph.D. 1) requires CGPA 3.7/4.0 plus Honours thesis or multiple summer research projects and a supervisor attestation letter.",
        "tui": "Admitted students are GUARANTEED funding for 4 years. Interfaculty graduate program jointly run by the Department of Bioengineering (Faculty of Engineering) and the Department of Biomedical Engineering (Faculty of Medicine and Health Sciences). Faculty, hospital and government careers.",
        "overview": "The Biological and Biomedical Engineering (BBME) PhD is an interfaculty graduate program jointly run by the Department of Bioengineering (Faculty of Engineering) and the Department of Biomedical Engineering (Faculty of Medicine and Health Sciences). It is research-intensive and emphasizes hands-on training. Students normally enter with a research-based master's; exceptional bachelor's applicants may be admitted directly to Ph.D. 1.",
        "requirements": "<ul><li>Eligible bachelor's degree with minimum CGPA 3.0/4.0; departmental expectation 3.3/4.0 in both Master's and undergraduate</li><li>Research-based Master's in Biological/Biomedical Engineering or related field normally required</li><li>Bachelor's direct entry (Ph.D. 1): CGPA 3.7/4.0 + Honours thesis or multiple summer research projects + supervisor attestation letter</li><li>TOEFL iBT 100 / IELTS 7.0</li><li>Identify a supervisor before applying (McGill requires supervisor agreement before admission)</li><li>Letters of recommendation, CV, transcripts</li></ul>",
        "research": "<ul><li>Bioinformatics and computational biology</li><li>Biomaterials and tissue engineering</li><li>Biomedical modelling and signals/systems</li><li>Biomedical sensors and medical diagnostics</li><li>Biomolecular and cellular engineering</li><li>Imaging and microscopy</li><li>Machine learning in medicine</li><li>Therapeutics</li></ul>",
        "source": '<a href="https://www.mcgill.ca/gradapplicants/program/biological-and-biomedical-engineering-phd" target="_blank">McGill BBME PhD Admissions</a> | <a href="https://www.mcgill.ca/bbme/" target="_blank">BBME Department</a> | <a href="https://www.mcgill.ca/bbme/programs/doctoral-program/application-deadlines" target="_blank">Doctoral Deadlines</a>',
    },
    "notre-bme-phd": {
        "school": "University of Notre Dame",
        "en": "PhD in Bioengineering (interdisciplinary, College of Engineering)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-7 years; minimum 9 graduate-level courses distributed across engineering and the sciences; Qualifying Exam after summer of first year (cumulative GPA 3.3+ required); dissertation defense within 7 years",
        "ddl": "Fall 2027: December 31, 2026. Spring 2027: October 1, 2026. No late applications.",
        "lang": "TOEFL, IELTS, or Duolingo accepted for non-native English speakers.",
        "test_cls": "GRE General Test OPTIONAL (considered if submitted; generally advantageous for international applicants and students from smaller engineering colleges; self-reported scores verified before matriculation). Master's degree NOT required - apply directly to PhD. Minimum undergraduate GPA 3.0/4.0; QE requires cumulative GPA 3.3+.",
        "tui": "Fully supported through fellowships and research assistantships; substantially increased stipends available with fellowships. Interdisciplinary program involving faculty from all five engineering departments plus biology and biochemistry. Affiliated with Harper Cancer Research Institute and Institute for Precision Health. Apply through any home department (Aerospace/ME for tissue engineering/mechanobiology; Chemical and Biomolecular Engineering for diagnostics/drug delivery; Electrical Engineering for imaging).",
        "overview": "The Notre Dame Bioengineering PhD is an interdisciplinary program leading to a doctorate. It involves faculty from all five engineering departments, biology, and biochemistry. Students apply through a 'home department' within the College of Engineering; the application is reviewed by all bioengineering faculty regardless of home department. If not admitted to Bioengineering, the home department may consider the student for its own PhD.",
        "requirements": "<ul><li>BS in any engineering field; limited number of science (biology/biochemistry) majors accepted</li><li>Biology/biochemistry applicants must have at least 2 years college math and 1 year physics</li><li>Statement of Intent, CV, Summary of Research Experience</li><li>3 letters of recommendation</li><li>GRE optional (self-reported, verified before matriculation)</li><li>TOEFL/IELTS/Duolingo (international applicants)</li><li>May apply simultaneously to one additional PhD program (e.g., Biophysics)</li></ul>",
        "research": "<ul><li>Mechanobiology and biomechanics</li><li>Engineered tissues and organ/tissue-on-a-chip</li><li>Diagnostics, devices, and instrumentation</li><li>Imaging and photonics</li><li>Biomaterials and materials science</li><li>Drug development and delivery</li><li>Affiliated with Harper Cancer Research Institute and Institute for Precision Health</li></ul>",
        "source": '<a href="https://bioengineering.nd.edu/apply/" target="_blank">Notre Dame Bioengineering Apply</a> | <a href="https://graduateschool.nd.edu/degree-programs/bioengineering-phd---doctoral/" target="_blank">Graduate School Bioengineering PhD</a> | <a href="https://cbe.nd.edu/graduate/phd-in-bioengineering/" target="_blank">CBE PhD in Bioengineering</a>',
    },
    "princeton-orfe-phd": {
        "school": "Princeton University",
        "en": "PhD in Operations Research and Financial Engineering (ORFE, SEAS)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; first year six core courses (ORF 522 Linear/Nonlinear Optimization, 523 Convex/Conic Optimization, 524 Statistical Theory and Methods, 525 Statistical Foundations of Data Science, 526 Probability Theory, 527 Stochastic Calculus); Qualifying Exam end of first summer; General Exam Spring of second year; dissertation 2-3 years after Generals",
        "ddl": "Fall 2027: January 3, 2027 (11:59 PM Eastern). Application fee $75; fee waivers available.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Princeton Graduate School has no minimum score; departments set their own.",
        "test_cls": "GRE OPTIONAL / NOT REQUIRED (since Fall 2022). No minimum GRE. Bachelor's degree in engineering, sciences, or mathematics normally required; strong mathematical background expected. Three letters of recommendation; statement of academic purpose; CV; transcripts in English.",
        "tui": "Fully funded via fellowship/RA/TA. ORFE combines Financial Mathematics, Machine Learning, Operations Research, Optimization, Probability and Statistics. Faculty affiliated with Bendheim Center for Finance, Andlinger Center for Energy and Environment, Princeton Environmental Institute, and Center for Statistics and Machine Learning. Research areas: financial engineering, stochastic systems, optimization, statistics and financial econometrics, energy, health, bioinformatics.",
        "overview": "Princeton ORFE PhD prepares students for research and teaching. The program provides a strong disciplinary background in probability, statistics, optimization, and stochastic processes. The department combines Financial Mathematics, Machine Learning, Operations Research, Optimization, Probability and Statistics under one roof.",
        "requirements": "<ul><li>Bachelor's degree in engineering, sciences, or mathematics</li><li>Strong mathematical background expected</li><li>CV, statement of academic purpose</li><li>Transcripts in English from each institution</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li><li>Application fee $75 (waivers available)</li></ul>",
        "research": "<ul><li>Financial engineering and mathematical finance</li><li>Probability and stochastic processes</li><li>Stochastic analysis and stochastic calculus</li><li>Mathematical and nonlinear optimization</li><li>Convex analysis</li><li>Stochastic networks and queueing theory</li><li>Mathematical and computational finance</li><li>Financial econometrics and risk management</li><li>Applications: finance, energy, health, bioinformatics, engineering</li></ul>",
        "source": '<a href="https://orfe.princeton.edu/graduate" target="_blank">Princeton ORFE Graduate Program</a> | <a href="https://orfe.princeton.edu/graduate/handbook" target="_blank">ORFE Graduate Handbook</a> | <a href="https://gradschool.princeton.edu/admission-onboarding/prepare/deadlines-and-fees" target="_blank">Graduate School Deadlines</a>',
    },
    "stanford-stat-phd": {
        "school": "Stanford University",
        "en": "PhD in Statistics (Department of Statistics)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; PhD students select advisor at end of second year after rotating with faculty; autumn quarter entry only",
        "ddl": "Autumn 2027-28: Wednesday, December 2, 2026 (11:59 PM PST). Application fee $125. Knight-Hennessy Scholars separate deadline October 6, 2026 (1:00 PM PT), with department application moved to December 1 for KHS candidates. Decisions by mid-February.",
        "lang": "TOEFL iBT minimum 4.5 (90 on previous scale); IELTS minimum 7.0. Incoming students scoring below TOEFL 5.5 (109 old scale) or IELTS 8.0 are required to take English coursework.",
        "test_cls": "GRE GENERAL TEST REQUIRED (rare holdout against the 2026-27 GRE-free trend - all PhD applicants must submit valid GRE General scores). GRE Math Subject Test OPTIONAL but RECOMMENDED (since May 2024). No separate review process for internal applicants. No deferral of admission. About 175 PhD applications per year, admit 11-12 new students.",
        "tui": "Full financial aid package (departmental support for all PhD students). MS students receive no financial aid. Advisor selected at end of second year after research rotations. May also apply for Knight-Hennessy Scholars fellowship (up to 100 across Stanford's seven graduate schools).",
        "overview": "Stanford Statistics PhD is a small, highly selective program. About 175 PhD applications are received each year and 11-12 new students are admitted. Students only matriculate in autumn quarter. The PhD allows students to rotate with faculty and select their advisor at the end of the second year.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution (must be conferred before program start)</li><li>GRE General Test REQUIRED (all applicants)</li><li>GRE Math Subject Test optional but recommended</li><li>TOEFL iBT 4.5 (90 old) / IELTS 7.0 minimum</li><li>3 letters of recommendation (up to 4 allowed)</li><li>Statement of Purpose, CV, transcripts</li><li>Application fee $125</li><li>No deferral of admission</li></ul>",
        "research": "<ul><li>Theoretical statistics and probability</li><li>Statistical inference and machine learning</li><li>High-dimensional statistics</li><li>Biostatistics and computational biology</li><li>Data science and statistical foundations of data science</li><li>Time series and stochastic processes</li><li>Applications to genomics, neuroscience, finance, and the social sciences</li></ul>",
        "source": '<a href="https://statistics.stanford.edu/admissions/statistics-phd-admissions/phd-admissions-requirements-and-procedures" target="_blank">Stanford Stats PhD Requirements</a> | <a href="https://statistics.stanford.edu/admissions/graduate-admissions" target="_blank">Graduate Admissions</a> | <a href="https://statistics.stanford.edu/admissions/statistics-phd-admissions/phd-admissions-frequently-asked-questions" target="_blank">PhD FAQ</a>',
    },
    "uchicago-econ-phd": {
        "school": "University of Chicago",
        "en": "PhD in Economics (Kenneth C. Griffin Department of Economics)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; year-long first-year sequence of courses; autumn quarter entry only; entering class 20-25 students per year",
        "ddl": "Autumn 2027: December 1, 2026 (11:59 PM Central Time). Late-round March 15 deadline for current UChicago MAE/MAPSS-Econ/MACSS-Econ students only (requires 6 graded graduate courses with A- or higher in 3 Economics courses, plus one letter from a tenured-track Economics faculty).",
        "lang": "TOEFL iBT minimum 4.5 on each section (Reading 22, Listening 20, Writing 21, Speaking 23 - for tests taken after January 21, 2026); IELTS minimum 7.0 on each section. Home-administered tests accepted. TOEFL MyBest scores NOT accepted.",
        "test_cls": "GRE GENERAL TEST REQUIRED (rare holdout - Social Sciences Division lists Economics as 'Required'. Official scores required; self-reported not sufficient. Institution code 1832. Exams should be taken no later than November 1 for December 1 deadline). Prerequisites: one year college calculus, plus one quarter/semester each of matrix algebra and mathematical statistics; recommended additional real analysis. No arbitrary GPA or test score cut-offs; holistic review.",
        "tui": "Full funding via fellowship/RA/TA. Joint PhD in Financial Economics offered with Chicago Booth PhD Program in Finance. Also accepts UChicago MAE Research Intensive Track and MACSS-Econ students through late-round March 15 entry. Note: applicants already holding a PhD in a closely related field cannot be considered.",
        "overview": "The UChicago Economics PhD is a small, elite program enrolling 20-25 new graduate students each autumn. The department requires a strong mathematical background. The year-long course sequence begins each autumn. A Joint PhD in Financial Economics is offered with the Chicago Booth PhD Program in Finance.",
        "requirements": "<ul><li>Bachelor's degree (or equivalent); need not be in economics, but economics background desirable</li><li>Prerequisites: one year college calculus, one quarter/semester matrix algebra, one quarter/semester mathematical statistics</li><li>Recommended additional: real analysis, graduate-level economics courses, research exposure</li><li>GRE General Test REQUIRED (official scores; institution code 1832)</li><li>TOEFL iBT 4.5 each section / IELTS 7.0 each section</li><li>3 letters of recommendation; writing sample; statement of purpose</li><li>Applicants already holding a PhD in a closely related field cannot be considered</li></ul>",
        "research": "<ul><li>Microeconomic theory</li><li>Macroeconomics</li><li>Econometrics and quantitative methods</li><li>Labor economics</li><li>Industrial organization</li><li>Public economics</li><li>International trade and finance</li><li>Development economics</li><li>Financial economics (joint with Booth)</li><li>Applications to law, history, political science, and business</li></ul>",
        "source": '<a href="https://economics.uchicago.edu/phd-program/apply" target="_blank">UChicago Economics PhD Apply</a> | <a href="https://socialsciences.uchicago.edu/admissions/application-materials/gre-general-test" target="_blank">Social Sciences GRE Requirements</a> | <a href="https://socialsciences.uchicago.edu/admissions/application-materials/english-proficiency-requirements" target="_blank">English Proficiency</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"], 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)}")
