# -*- coding: utf-8 -*-
"""Round 232: batch add 5 Public Health School PhD (JHU/UCSD/UT/UBC/McGill)
- jhu-hpm-phd (JHU Bloomberg PhD Health Policy and Management)
- ucsd-hsris-phd (UCSD Herbert Wertheim PhD Public Health, HSRIS concentration)
- ut-phs-phd (UofT Dalla Lana PhD Public Health Sciences)
- ubc-spph-phd (UBC School of Population and Public Health PhD)
- mcg-epi-phd (McGill PhD Epidemiology, Epi-Biostat-Occh)
Key finding: JHU Bloomberg HPM PhD still REQUIRES GRE (no waivers),
while UCSD HSRIS, UofT DLSPH, UBC SPPH, and McGill Epi are all GRE-free.
This continues the divergence: top US schools with quantitative/econ-oriented HPM PhDs
still require GRE; Canadian public health schools have uniformly gone GRE-free.
Deadlines: JHU/McGill Dec 1; UCSD Dec 16; UofT late Nov; UBC Jan 7.
"""
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": "jhu-hpm-phd",
        "s": "jhu",
        "n": "卫生政策与管理博士",
        "en": "PhD in Health Policy and Management (Johns Hopkins Bloomberg School of Public Health; four concentrations: Health Economics & Policy, Health Services Research & Policy, Health & Public Policy, Bioethics & Health Policy)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time residential; fall-only admission; SOPHAS application; prior graduate degree not required but highly recommended",
        "ddl": "Fall 2027: December 1, 2026 (all Bloomberg PhD programs). Decisions early-mid February. Supporting documents due within 2 weeks of deadline.",
        "lang": "TOEFL/IELTS required for international applicants; transcript evaluation as needed.",
        "test": {"cls": "GRE REQUIRED (JHU Bloomberg HPM PhD FAQ: 'Yes, GRE scores are required. The department does not grant GRE waivers or exceptions.'). ETS code for Bloomberg via SOPHAS. No minimum score; holistic review. Note: International Health PhD also requires GRE; many other Bloomberg PhDs are optional/not reviewed."},
        "tui": "Full funding for admitted PhD students (tuition + stipend + health insurance). NIA T32 training grant support available for aging-related research.",
        "url": "details/jhu-hpm-phd.html",
    },
    {
        "id": "ucsd-hsris-phd",
        "s": "ucsd",
        "n": "卫生服务研究与实施科学博士",
        "en": "PhD in Public Health, concentration in Health Services Research and Implementation Science (HSRIS; UC San Diego Herbert Wertheim School of Public Health and Human Longevity Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "72 units coursework (56 units HSRIS content/methods + colloquium + grantwriting); fall-only admission; community-engaged, transdisciplinary, team-based",
        "ddl": "Fall 2027: December 16, 2026 (application opens September 16). Interviews late January/early February; admission nominations mid-March.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (DET) required for non-native English speakers.",
        "test": {"cls": "GRE NOT REQUIRED (UCSD Herbert Wertheim SPH: 'GRE not required' for PhD in Public Health). ETS code 4836 (UCSD) if self-submitted. No minimum score; holistic review. Minimum GPA 3.0. Master's degree in public health or related field recommended but not required."},
        "tui": "Full funding for admitted PhD students (tuition + stipend + benefits). Contact UCSD HSRIS program director for current package details.",
        "url": "details/ucsd-hsris-phd.html",
    },
    {
        "id": "ut-phs-phd",
        "s": "ut",
        "n": "公共卫生科学博士",
        "en": "PhD in Public Health Sciences (University of Toronto Dalla Lana School of Public Health; fields: Biostatistics, Epidemiology, Occupational & Environmental Health, Social & Behavioural Health Sciences)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4 years full-time (6 years flexible-time option); fall-only admission; identifies faculty supervisor prior to application",
        "ddl": "Fall 2027: late November 2026 (DLSPH PhD/DrPH deadline typically ~Nov 24; check SGS portal for exact date). Applications available mid-October.",
        "lang": "TOEFL/IELTS required for non-native English speakers; UofT SGS minimum scores.",
        "test": {"cls": "GRE NOT REQUIRED (DLSPH FAQ: 'The GRE is not required for admission to any degree program or field of study in the Graduate Department of Public Health Sciences. Do not upload GRE test scores; they will not be reviewed.'). No GRE scores considered. Note: DrPH is mid-career requiring 5+ years experience and is excluded; PhD is research doctorate."},
        "tui": "Full funding for admitted PhD students (tuition + stipend + benefits) through DLSPH and SGS. Contact DLSPH graduate coordinator for current package.",
        "url": "details/ut-phs-phd.html",
    },
    {
        "id": "ubc-spph-phd",
        "s": "ubc",
        "n": "人口与公共卫生博士",
        "en": "PhD in Population and Public Health (University of British Columbia School of Population and Public Health, SPPH)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "16.5 credits core courses (7.5 credits if entering with UBC MSc-equivalent); fall-only admission; 35-40 hours/week full-time; part-time option available with approval",
        "ddl": "September 2027 intake: January 7, 2027 (application opens November 15, 2026). Referee deadline January 14, 2027. One admission cycle per year.",
        "lang": "TOEFL iBT minimum 100 (higher component scores per UBC FGPS). IELTS/CAEL/CELPIP/PTE accepted. Test scores within 2 years.",
        "test": {"cls": "GRE NOT REQUIRED (UBC SPPH: 'GRE/GMAT or Other Test Scores (optional). Test scores, including GRE or GMAT, are not required. If you would like to submit test scores, you can, and they will be reviewed as part of your application.'). ETS UBC code 0965. Minimum B+ GPA on master's degree. 3 reference letters."},
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits) through UBC SPPH and FGPS. Contact SPPH graduate coordinator for current package.",
        "url": "details/ubc-spph-phd.html",
    },
    {
        "id": "mcg-epi-phd",
        "s": "mcg",
        "n": "流行病学博士",
        "en": "PhD in Epidemiology (McGill University, Department of Epidemiology, Biostatistics and Occupational Health; Epi-Biostat-Occh)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "Fall-only admission; requires prior master's in Epidemiology/Public Health/related; strong quantitative preparation (calculus, statistics, master's-level quantitative courses)",
        "ddl": "Fall 2027: December 1, 2026 (application opens September 15, 2026). Incomplete applications not considered. Winter/Summer admissions not offered.",
        "lang": "TOEFL/IELTS required per McGill SGS for non-native English speakers.",
        "test": {"cls": "GRE NOT REQUIRED (McGill Epi-Biostat-Occh: 'Although the GRE is not required, GRE results with a strong score (160+) in the Quantitative score may strengthen your application.'). ETS McGill code 0935. CGPA minimum 3.0/4.0 overall (or 3.2/4.0 last 2 years); most successful applicants exceed minimums."},
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits) through McGill GPS and Epi-Biostat-Occh. Contact department graduate coordinator for current package.",
        "url": "details/mcg-epi-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> This is a research-oriented PhD program in public health / health services research / epidemiology at a top-30 U.S. or top Canadian school of public health. Admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification. STEM designation status per department and CIP code.
</div>
</body>
</html>
"""

PAGES = {
    "jhu-hpm-phd": {
        "school": "Johns Hopkins Bloomberg School of Public Health",
        "en": "PhD in Health Policy and Management",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time residential; fall-only; SOPHAS; 4 concentrations",
        "ddl": "Fall 2027: December 1, 2026. Decisions early-mid February. Supporting docs due within 2 weeks.",
        "lang": "TOEFL/IELTS required for international; transcript evaluation as needed.",
        "test_cls": "GRE REQUIRED (HPM PhD FAQ: 'Yes, GRE scores are required. Department does not grant waivers or exceptions.'). ETS via SOPHAS. No minimum; holistic.",
        "tui": "Full funding for admitted PhD students (tuition + stipend + insurance). NIA T32 support for aging research.",
        "overview": "The Johns Hopkins Bloomberg School of Public Health PhD in Health Policy and Management is a full-time residential program based in Baltimore. Students complete a common core curriculum then choose one of four concentrations: Health Economics & Policy, Health Services Research & Policy, Health & Public Policy, or Bioethics & Health Policy. The program is one of the oldest and most respected of its type in the nation. For August 2027 entry, the department is particularly interested in applicants whose research aligns with aging-related health services, economic, ethical, systems, policy, and outcomes research supported by an NIA T32 training grant.",
        "requirements": "<ul><li>Bachelor's degree (prior graduate degree not required but highly recommended)</li><li>GRE REQUIRED (no waivers/exceptions; no minimum score; holistic review)</li><li>TOEFL/IELTS (international); transcript evaluation as needed</li><li>SOPHAS online application (select PhD in Health Policy and Management, JHU)</li><li>Statement of purpose and objectives</li><li>CV/resume</li><li>3 letters of recommendation</li><li>Official transcripts and/or credential evaluations</li><li>December 1, 2026 deadline (supporting docs within 2 weeks)</li><li>Fall entry only; full-time residential</li><li>Health Economics & Policy concentration: strong math prep (multivariable calculus, etc.)</li></ul>",
        "research": "<ul><li>Health economics and policy (Health Economics & Policy concentration)</li><li>Health services research and policy (HSR & Policy concentration)</li><li>Health and public policy (Health & Public Policy concentration)</li><li>Bioethics and health policy (Bioethics & Health Policy concentration)</li><li>Aging-related health services, economic, ethical, systems, policy, and outcomes research (NIA T32)</li><li>Cross-disciplinary work with JHU School of Medicine, Whiting Engineering, and SAIS</li></ul>",
        "source": '<a href="https://e-catalogue.jhu.edu/public-health/departments/health-policy-management/health-policy-management-phd/" target="_blank">JHU Catalogue: HPM PhD (4 concentrations, full-time residential)</a> | <a href="https://publichealth.jhu.edu/academics/programs/phd/health-policy-and-management" target="_blank">JHU Bloomberg HPM PhD FAQ (GRE required, no waivers, Dec 1)</a> | <a href="https://publichealth.jhu.edu/admissions/application-deadlines" target="_blank">JHU Bloomberg Deadlines (Dec 1, 2026 for all PhD)</a>',
    },
    "ucsd-hsris-phd": {
        "school": "UC San Diego Herbert Wertheim School of Public Health",
        "en": "PhD in Public Health, Health Services Research and Implementation Science (HSRIS)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "72 units (56 HSRIS content/methods + colloquium + grantwriting); fall-only; community-engaged, transdisciplinary",
        "ddl": "Fall 2027: December 16, 2026 (opens Sept 16). Interviews late Jan/early Feb; nominations mid-March.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (DET) for non-native English.",
        "test_cls": "GRE NOT REQUIRED (UCSD Herbert Wertheim SPH: 'GRE not required'). ETS 4836 if self-submitted. No minimum; holistic. Min GPA 3.0. Master's recommended but not required.",
        "tui": "Full funding for admitted PhD students (tuition + stipend + benefits).",
        "overview": "The UCSD PhD in Public Health with a concentration in Health Services Research and Implementation Science (HSRIS) addresses the social determinants of health through community-engaged research in both traditional and non-traditional health service settings. The program is transdisciplinary (faculty across disciplines), translational (linking evidence-based programs to real-world implementation), and team-based (collaborating with health care providers and communities). Degree requirements include 72 units: 56 units of required HSRIS content and methods, an HSRIS colloquium series, successful grantwriting, and dissertation research. The program prepares students for research careers in public health and health services, teaching, and public service in university, governmental, and public policy settings.",
        "requirements": "<ul><li>Bachelor's degree; minimum GPA 3.0</li><li>GRE NOT required (no scores considered; optional self-submission)</li><li>TOEFL iBT / IELTS Academic / Duolingo DET (non-native English)</li><li>UC San Diego Graduate Application</li><li>Writing sample (preferably a research paper)</li><li>Official transcripts</li><li>3 letters of recommendation (at least 2 addressing academic/professional qualifications for HSRIS)</li><li>Curriculum vitae</li><li>December 16, 2026 deadline</li><li>Fall entry only; full-time</li><li>Master's degree in public health or related field recommended but not required</li></ul>",
        "research": "<ul><li>Health services research and delivery science</li><li>Implementation science and community-engaged research</li><li>Social determinants of health and health equity</li><li>Health care quality, cost, and delivery</li><li>Translational research linking evidence to real-world practice</li><li>Cross-disciplinary work with UCSD School of Medicine, Salk Institute, and Rady School of Management</li></ul>",
        "source": '<a href="https://ph.ucsd.edu/phd/public-health/index.html" target="_blank">UCSD HSRIS PhD (72 units, transdisciplinary, community-engaged)</a> | <a href="https://ph.ucsd.edu/phd/public-health/admissions.html" target="_blank">UCSD PhD Admissions (Dec 16, 2026; GRE not required; writing sample; 3 recs)</a>',
    },
    "ut-phs-phd": {
        "school": "University of Toronto Dalla Lana School of Public Health",
        "en": "PhD in Public Health Sciences",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4 years full-time (6 years flexible-time); fall-only; identify faculty supervisor prior to application",
        "ddl": "Fall 2027: late November 2026 (DLSPH PhD/DrPH deadline typically ~Nov 24; verify on SGS portal). Applications available mid-October.",
        "lang": "TOEFL/IELTS required for non-native English speakers; UofT SGS minimum scores.",
        "test_cls": "GRE NOT REQUIRED (DLSPH FAQ: 'The GRE is not required for admission to any degree program or field of study in the Graduate Department of Public Health Sciences. Do not upload GRE test scores; they will not be reviewed.'). Note: DrPH is mid-career (5+ years experience) and excluded; PhD is research doctorate.",
        "tui": "Full funding for admitted PhD students (tuition + stipend + benefits) through DLSPH and SGS.",
        "overview": "The University of Toronto Dalla Lana School of Public Health (DLSPH) PhD in Public Health Sciences prepares students for research and academic careers in the public health science disciplines. Students choose one of four fields: Biostatistics, Epidemiology, Occupational and Environmental Health, or Social and Behavioural Health Sciences. The PhD may be completed on a full-time basis (4 years) or flexible-time (6 years). Students typically identify a faculty supervisor prior to application. The separate DrPH program is a practice-based mid-career doctorate requiring 5+ years of experience and is excluded from this research-focused listing.",
        "requirements": "<ul><li>Master's degree in public health or related discipline (strongly preferred)</li><li>GRE NOT required (do not upload; scores not reviewed)</li><li>TOEFL/IELTS (non-native English) per UofT SGS</li><li>UofT School of Graduate Studies (SGS) online application</li><li>Official transcripts from all post-secondary institutions</li><li>CV/résumé</li><li>Statement of purpose / letter of intent</li><li>3 letters of recommendation (submitted directly by referees)</li><li>Writing sample (e.g., master's thesis chapter, published paper, or major research essay)</li><li>Late November 2026 deadline (verify exact date on SGS portal)</li><li>Fall entry only; full-time or flexible-time</li><li>Identify and contact potential faculty supervisor prior to application</li></ul>",
        "research": "<ul><li>Biostatistics (advanced quantitative research and data science)</li><li>Epidemiology (disease, disability, death, prevention)</li><li>Occupational and environmental health</li><li>Social and behavioural health sciences (social determinants, health promotion, disease prevention)</li><li>Cross-disciplinary work with UofT Faculty of Medicine, Munk School, and Vector Institute</li></ul>",
        "source": '<a href="https://www.sgs.utoronto.ca/programs/public-health-sciences/" target="_blank">UofT SGS: Public Health Sciences (PhD fields; 4-yr FT / 6-yr flex)</a> | <a href="https://www.dlsph.utoronto.ca/students/future-students/application-process/application-frequently-asked-questions/" target="_blank">DLSPH FAQ (GRE not required; do not upload; late Nov deadline)</a>',
    },
    "ubc-spph-phd": {
        "school": "University of British Columbia School of Population and Public Health",
        "en": "PhD in Population and Public Health",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "16.5 credits core (7.5 if entering with UBC MSc-equivalent); fall-only; 35-40 hrs/week full-time; part-time option with approval",
        "ddl": "September 2027 intake: January 7, 2027 (opens November 15, 2026). Referee deadline January 14, 2027. One admission cycle per year.",
        "lang": "TOEFL iBT minimum 100 (higher component scores per UBC FGPS). IELTS/CAEL/CELPIP/PTE accepted. Test scores within 2 years.",
        "test_cls": "GRE NOT REQUIRED (UBC SPPH: 'GRE/GMAT optional; not required. If you submit scores, they will be reviewed as part of the application.'). ETS UBC code 0965. Min B+ GPA on master's. 3 reference letters.",
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits) through UBC SPPH and FGPS.",
        "overview": "The UBC PhD in Population and Public Health is offered through the School of Population and Public Health (SPPH). Applicants must hold a master's degree (or recognized equivalent) in the health or related sciences. The program requires 16.5 credits of core courses (reduced to 7.5 credits for students entering with a UBC MSc-equivalent), plus additional courses determined by the supervisory committee. Students are expected to devote 35-40 hours per week to full-time study; part-time classification is available with approval at admission. Transfer from the master's to the PhD program is permitted under FGPS regulations.",
        "requirements": "<ul><li>Master's degree in health or related sciences (recognized equivalent to UBC master's)</li><li>GPA B+ or higher on all master's-level coursework</li><li>GRE NOT required (optional submission; ETS 0965)</li><li>TOEFL iBT 100 minimum (or IELTS/CAEL/CELPIP/PTE equivalent); scores within 2 years</li><li>UBC Graduate School online application</li><li>3 reference letters (referee deadline January 14, 2027)</li><li>Transcripts</li><li>Statement of intent</li><li>CV/résumé</li><li>January 7, 2027 application deadline (September 2027 intake)</li><li>Fall entry only; full-time or approved part-time</li></ul>",
        "research": "<ul><li>Population and public health across SPPH faculty</li><li>Health services research and health systems</li><li>Social determinants of health and health equity</li><li>Environmental and occupational health</li><li>Biostatistics and epidemiology</li><li>Cross-disciplinary work with UBC Faculty of Medicine, Centre for Health Evaluation and Outcome Sciences (CHEOS), and PHSA</li></ul>",
        "source": '<a href="https://spph.ubc.ca/phd/admission-requirements/" target="_blank">UBC SPPH PhD Admission Requirements (master\'s in health; B+ GPA; TOEFL 100; 3 refs)</a> | <a href="https://spph.ubc.ca/phd/admission-requirements/how-to-apply/" target="_blank">UBC SPPH How to Apply (Jan 7, 2027 deadline; GRE optional; ETS 0965)</a> | <a href="https://vancouver.calendar.ubc.ca/faculties-colleges-and-schools/faculty-graduate-and-postdoctoral-studies/degree-programs/population-and-public-health" target="_blank">UBC Calendar: Population and Public Health (16.5 credits core)</a>',
    },
    "mcg-epi-phd": {
        "school": "McGill University Department of Epidemiology, Biostatistics and Occupational Health",
        "en": "PhD in Epidemiology",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "Fall-only admission; requires prior master's in Epidemiology/Public Health/related; strong quantitative preparation",
        "ddl": "Fall 2027: December 1, 2026 (application opens September 15, 2026). Incomplete applications not considered. Winter/Summer not offered.",
        "lang": "TOEFL/IELTS required per McGill SGS for non-native English speakers.",
        "test_cls": "GRE NOT REQUIRED (McGill Epi-Biostat-Occh: 'Although the GRE is not required, GRE results with a strong score (160+) in the Quantitative score may strengthen your application.'). ETS McGill code 0935. CGPA 3.0/4.0 min (or 3.2/4.0 last 2 years).",
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits) through McGill GPS and Epi-Biostat-Occh.",
        "overview": "The McGill PhD in Epidemiology is offered through the Department of Epidemiology, Biostatistics and Occupational Health (Epi-Biostat-Occh). The program requires substantial quantitative skills: the Admissions Committee looks for proof of quantitative proficiency including good grades in undergraduate differential/integral calculus and statistics, and strong results in master's-level quantitative courses. Applicants must hold a master's degree in Epidemiology, Public Health, or a related discipline; applicants from other disciplines may be considered on a case-by-case basis but are expected to have sufficient substantive preparation for PhD-level coursework. The program admits only in the Fall term.",
        "requirements": "<ul><li>Master's degree in Epidemiology, Public Health, or related discipline (other disciplines may be considered case-by-case)</li><li>Strong quantitative preparation: undergraduate calculus (differential/integral), statistics, master's-level quantitative courses</li><li>GRE NOT required (Q 160+ may strengthen application; ETS 0935)</li><li>TOEFL/IELTS (non-native English) per McGill SGS</li><li>McGill admissions online application</li><li>Official transcripts from all post-secondary institutions</li><li>CV/résumé</li><li>Statement of purpose / research interests</li><li>Letters of recommendation</li><li>CGPA minimum 3.0/4.0 overall (or 3.2/4.0 over last 2 years); most successful applicants exceed minimums</li><li>December 1, 2026 deadline (Fall 2027 only)</li><li>Fall entry only; Winter/Summer admissions not offered</li></ul>",
        "research": "<ul><li>Epidemiology of chronic diseases, infectious diseases, cancer</li><li>Biostatistics and quantitative methods</li><li>Occupational and environmental health</li><li>Social and behavioural epidemiology</li><li>Computational and data science in population health (e.g., child health AI/data science faculty)</li><li>Cross-disciplinary work with McGill Faculty of Medicine, School of Population and Global Health, and RI-MUHC</li></ul>",
        "source": '<a href="https://www.mcgill.ca/epi-biostat-occh/education/grad/epidemiology/phd-epidemiology-admission-information" target="_blank">McGill PhD Epidemiology Admissions (Dec 1, 2026; master\'s required; Fall only)</a> | <a href="https://coursecatalogue.mcgill.ca/en/graduate/medicine-health-sciences/population-global-health/" target="_blank">McGill Catalogue: Population and Global Health (GRE not required; Q 160+ may strengthen; CGPA 3.0/3.2)</a> | <a href="https://www.mcgill.ca/gradapplicants/how-apply/application-support" target="_blank">McGill FAQ (ETS 0935; submit scores only if required by program)</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)}")
