# -*- coding: utf-8 -*-
"""Round 242: batch add 5 Chemical Engineering PhD (Canadian 4 + Columbia)
- UofT ChemE PhD (Feb 1, supervisor must be confirmed; $125 CAD fee; B+ research master's)
- UBC CHBE PhD (Dec 1 May 2027 / Feb 1 Sep 2027; GRE not required; min $25,000/yr + TA)
- McGill ChBE PhD (Jan 15 international / June 21 domestic; supervisor secured; 3.0 GPA)
- Waterloo ChemE PhD (Mar 1 Fall; supervisor approved in writing; TOEFL 80 / IELTS 6.5)
- Columbia ChemE PhD (Dec 15; GRE optional for 2027 cycle; $85 fee; Fu Foundation)
"""
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": "ut-chemeng-phd",
        "s": "ut",
        "n": "化学工程与应用化学博士",
        "en": "PhD in Chemical Engineering and Applied Chemistry (University of Toronto, Faculty of Applied Science and Engineering, Department of Chemical Engineering and Applied Chemistry, ChemE; research thesis; MASc-to-PhD transfer possible; collaborative specialization in Biomedical Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time residential; flexible-time option available; thesis under faculty supervision; coursework; Qualifying Examination; Reading Committee; PhD Thesis; Departmental Oral Examination; Final Oral Examination; Individual Development Plan required",
        "ddl": "Fall (September) 2027: application opens October 15, 2026. **MASc/PhD recommended deadline February 1, 2027** (per Faculty of Engineering); departmental page lists March 15, 2027 as final deadline. Winter (January) 2028 intake: application deadline October 15, 2027. Application fee $125 CAD. **Contact potential supervisors before applying; offer requires faculty agreement to provide research supervision and financial support.**",
        "lang": "TOEFL iBT / IELTS Academic required for international students whose native language is not English; ETS UofT code 0982; per School of Graduate Studies English proficiency standards; scores valid 2 years.",
        "test": {"cls": "GRE NOT REQUIRED (UofT ChemE department does not list GRE as required for PhD admission. Per School of Graduate Studies, meeting minimum requirements does not guarantee admission. 3 LOR; research proposal; CV; transcripts; minimum B+ in last two years of full-time undergraduate study AND successful completion of a research master's degree with overall B+; direct entry from MASc with B+ and exceptional ability)."},
        "tui": "UofT ChemE PhD students typically funded through faculty research assistantships and departmental teaching assistantships (tuition + stipend). Offer contingent on faculty supervisor agreeing to provide research supervision and financial support. Application fee $125 CAD.",
        "url": "details/ut-chemeng-phd.html",
    },
    {
        "id": "ubc-chbe-phd",
        "s": "ubc",
        "n": "化学与生物工程博士",
        "en": "PhD in Chemical and Biological Engineering (University of British Columbia, Faculty of Applied Science, Department of Chemical and Biological Engineering, CHBE; MEng/MSc/MASc are separate master's tracks; PhD focuses on independent research)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "48 months (4 years) full-time; up to 6 years maximum; thesis-based; comprehensive research proposal oral examination within 12 months of admission (if <=6 credits) or 15 months (if >6 credits); transfer from MASc possible after 1 year with 9 credits at 500-level or above and first-class standing",
        "ddl": "May 2027 intake: application opens September 1, 2026. **Canadian and International deadline December 1, 2026**. Transcript deadline January 1, 2027; Referee deadline January 1, 2027. September 2027 intake: application opens October 1, 2026. **Canadian and International deadline February 1, 2027**. Transcript deadline April 1, 2027; Referee deadline April 1, 2027.",
        "lang": "TOEFL iBT 90 overall (sectional R22/L22/W21/S21) / IELTS Academic 6.5 (sectional 6.0) / Duolingo DET 125; ETS UBC 0965; English-medium undergraduate may be exempted; scores within 2 years.",
        "test": {"cls": "GRE NOT REQUIRED (UBC Grad School: 'The GRE is not required.' No subject test required. 3 LOR; CV; research proposal; transcripts; recognized course and thesis-based master's degree required; high scholastic standing and demonstrated aptitude for research)."},
        "tui": "UBC CHBE PhD minimum funding package $25,000/year plus teaching assistantships; students accepted per year 15-25; full funding through RA/TA and faculty grants. Application fee ~$150 CAD.",
        "url": "details/ubc-chbe-phd.html",
    },
    {
        "id": "mcgill-chbe-phd",
        "s": "mcg",
        "n": "化学工程博士",
        "en": "PhD in Chemical Engineering (McGill University, Faculty of Engineering, Department of Chemical Engineering; research-intensive; MEng is non-thesis master's track; PhD emphasizes literature review, research methods, and laboratory safety)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "3-4 years full-time residential; 6-year maximum; Research Proposal; Research Seminar; Doctoral Thesis and Defense; governed by GPSO Red Book regulations; applicants must secure research supervisor before admission",
        "ddl": "Fall (September) 2027: application opens September 15, 2026. **International deadline January 15, 2027**; Domestic (Canadian/PR) deadline June 21, 2027. Winter (January) 2028: application opens February 15, 2027; International August 1, 2027; Domestic November 10, 2027. Summer (May) 2028: application opens May 15, 2027; International October 1, 2027; Domestic April 1, 2028. Decisions 2-3 weeks after deadline.",
        "lang": "TOEFL iBT / IELTS Academic required for international students whose native language is not English; ETS McGill 0935; English proficiency per McGill Graduate and Postdoctoral Studies Office; scores within 2 years.",
        "test": {"cls": "GRE NOT REQUIRED (McGill ChemE department does not list GRE as required for PhD admission. Recognized master's in related discipline with 3.0/4.0 cumulative GPA or 3.2/4.0 in last two years; direct entry from bachelor's possible for exceptional candidates. 3 LOR (institutional email required; gmail/yahoo/hotmail not accepted); research proposal; CV; transcripts)."},
        "tui": "McGill ChemE PhD admission contingent on qualified applicant being matched with supervisor and financial support; McGill Department of Chemical Engineering cannot issue application fee waivers. Full funding through faculty RA and TA appointments.",
        "url": "details/mcgill-chbe-phd.html",
    },
    {
        "id": "uw-chemeng-phd",
        "s": "uw",
        "n": "化学工程博士",
        "en": "PhD in Chemical Engineering (University of Waterloo, Faculty of Engineering, Department of Chemical Engineering; thesis-based; on-campus; full-time or part-time; named 'Chemical Engineering (Water)' reflecting Waterloo Engineering focus)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "48 months (4 years) full-time; full-time or part-time registration; thesis-based; at time of admission, each student must have an approved PhD supervisor who has agreed in writing to supervise (or co-supervise, with at least one approved PhD supervisor)",
        "ddl": "Fall (September) 2027: **March 1, 2027** (extended from February 1, 2026). Winter (January) 2028: June 1, 2027. Spring (May) 2028: October 1, 2027. All supporting documents must be uploaded within 10 business days of submission and before the deadline.",
        "lang": "TOEFL iBT 80 minimum (sectional W22/S20/R20/L18) / IELTS Academic 6.5 (sectional W6.0/S6.0); ETS Waterloo 0996; objective evidence of English language skills required per Engineering Graduate Studies; scores valid 2 years.",
        "test": {"cls": "GRE NOT REQUIRED (Waterloo ChemE department does not list GRE as required for PhD admission. Minimum 80% standing in relevant thesis-based master's program; excellence of background preparation and academic achievement. 3 academic references; research proposal; CV; transcripts; approved PhD supervisor must agree in writing before admission)."},
        "tui": "Waterloo ChemE PhD students typically funded through supervisor research grants and departmental TA appointments; tuition charged per term (three terms per year). Application requires written supervisor agreement before admission.",
        "url": "details/uw-chemeng-phd.html",
    },
    {
        "id": "col-chemeng-phd",
        "s": "col",
        "n": "化学工程博士",
        "en": "PhD / Doctor of Engineering Science in Chemical Engineering (Columbia University, Fu Foundation School of Engineering and Applied Science, Department of Chemical Engineering; MS/PhD track and EngScD; doctoral programs admit Fall and Spring)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time residential; thesis-based; doctoral candidacy examination; dissertation research and defense; MS may be earned en route; direct BS-to-PhD entry allowed; research assistantship and teaching assistantship appointments",
        "ddl": "Fall 2027 (September): **Doctoral deadline December 15, 2026**. Spring 2027 admission: October 15, 2026. All application materials should be submitted and received within 2-4 weeks after the posted deadline. Decisions released in months following deadline. Application fee $85.",
        "lang": "TOEFL iBT / IELTS Academic required for international students whose native language is not English; ETS Columbia Engineering 2111; English proficiency per Graduate School of Arts and Sciences / Fu Foundation; scores valid 2 years.",
        "test": {"cls": "GRE OPTIONAL FOR 2027 CYCLE (Columbia Engineering: 'The GRE is not required for the 2027 admission cycle. This includes Spring 2027 and Fall 2027. If you have taken the GRE and would like to provide your scores, you may, but it is not required as of July 2026. Students who do not submit scores will not be penalized. Applied Physics PhD may supply GRE Physics subject test, also not required as of July 2026. 3 LOR; CV/resume; personal statement; video interview (may be required for doctoral programs); transcripts)."},
        "tui": "Columbia Engineering PhD students typically receive full funding through departmental research/teaching assistantships and fellowships (tuition + stipend + health insurance). Application fee $85. Fall and Spring admission. Deferrals not offered.",
        "url": "details/col-chemeng-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> Research-oriented PhD in Chemical / Chemical and Biological / Chemical Engineering and Applied Chemistry at four Canadian universities (UofT, UBC, McGill, Waterloo) plus Columbia Engineering. Canadian model: supervisor must be contacted and agree to provide research supervision and financial support before an offer is considered. UBC CHBE minimum funding package $25,000/year plus TA. All five programs are STEM-designated per CIP code 14.0701. Key trend: UBC CHBE explicitly does not require GRE; McGill ChemE and Waterloo ChemE do not list GRE as required; Columbia Engineering makes GRE optional for the 2027 admission cycle (not required, absence not penalized). Combined with rounds 240-241 (9 U.S. ChBE PhDs), this round completes the top-tier Chemical Engineering PhD sweep across U.S. Top-10 and Canadian G4 universities.
</div>
</body>
</html>
"""

PAGES = {
    "ut-chemeng-phd": {
        "school": "University of Toronto, Department of Chemical Engineering and Applied Chemistry",
        "en": "PhD in Chemical Engineering and Applied Chemistry",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.0701)",
        "dur": "4-5 years full-time residential; flexible-time option available; thesis under faculty supervision; coursework; Qualifying Examination; Reading Committee; PhD Thesis; Departmental Oral Examination; Final Oral Examination; Individual Development Plan required",
        "ddl": "Fall (September) 2027: opens October 15, 2026. **MASc/PhD recommended deadline February 1, 2027** (Faculty of Engineering); departmental page lists March 15, 2027 as final. Winter (January) 2028: deadline October 15, 2027. Fee $125 CAD. **Contact supervisors before applying; offer requires faculty agreement to provide supervision and funding.**",
        "lang": "TOEFL iBT / IELTS Academic for international students whose native language is not English; ETS UofT 0982; per SGS English proficiency; scores valid 2 years.",
        "test_cls": "GRE NOT REQUIRED (UofT ChemE does not list GRE as required for PhD. 3 LOR; research proposal; CV; transcripts; minimum B+ in last two years undergrad AND research master's with overall B+; direct entry from MASc with B+ and exceptional ability).",
        "tui": "UofT ChemE PhD typically funded through faculty RA and departmental TA (tuition + stipend). Offer contingent on faculty supervisor agreeing to provide supervision and funding. Fee $125 CAD.",
        "overview": "The University of Toronto Department of Chemical Engineering and Applied Chemistry (ChemE) offers MEng, MASc, and PhD degrees. The PhD is designed for students who want to become experts in a specific research area and is a stepping stone to an academic career. Students complete a thesis under the supervision of a faculty member and take a number of courses. The program can be completed on a full-time or flexible-time basis. Required milestones include Qualifying Examination, Reading Committee, PhD Thesis, Departmental Oral Examination, and Final Oral Examination. The PhD also requires an Individual Development Plan. A Collaborative Specialization in Biomedical Engineering is available. For MASc and PhD applicants, an offer of admission may only be considered when the applicant both meets admission requirements and has a faculty member that agrees to provide research supervision and financial support.",
        "requirements": "<ul><li>Recognized research master's degree in engineering or physical/chemical/biological sciences with overall B+ (or equivalent)</li><li>B+ (or equivalent) in each of the last two years of full-time undergraduate study</li><li>GRE NOT required (UofT ChemE does not list GRE as required)</li><li>TOEFL iBT / IELTS Academic for international students whose native language is not English; ETS 0982</li><li>UofT School of Graduate Studies online application</li><li>3 letters of recommendation</li><li>Research proposal / statement of research interests</li><li>CV</li><li>Transcripts</li><li>**Recommended PhD deadline February 1, 2027** (Fall entry); departmental final March 15, 2027</li><li>Winter (January) 2028 intake: deadline October 15, 2027</li><li>**Supervisor must be contacted and agree to provide research supervision and financial support before offer is considered**</li><li>Application fee $125 CAD</li><li>Direct entry from MASc with B+ and exceptional ability possible</li></ul>",
        "research": "<ul><li>Chemical and materials process engineering</li><li>Biomolecular engineering and biotechnology</li><li>Energy and sustainability (batteries, fuel cells, carbon capture)</li><li>Environmental engineering and water treatment</li><li>Reaction engineering and catalysis</li><li>Transport phenomena and fluid mechanics</li><li>Process systems engineering and control</li><li>Nanomaterials and nanotechnology</li><li>Computational molecular science and simulation</li><li>Collaborative Specialization in Biomedical Engineering</li><li>Entrepreneurship training and commercialization support (54+ invention disclosures since 2008)</li></ul>",
        "source": '<a href="https://chem-eng.utoronto.ca/graduate-studies/applications-and-admissions/masc-and-phd-applications/" target="_blank">UofT ChemE MASc and PhD Admissions (Fall 2024 reference: opens Oct 15, closes Mar 15; minimum B+ research master\'s; offer requires faculty agreement to provide supervision and funding; flexible-time PhD available)</a> | <a href="https://gradstudies.engineering.utoronto.ca/admissions/how-to-apply/" target="_blank">UofT Engineering Graduate Studies How to Apply (SGS application fee $125 CAD; MASc/PhD recommended deadline Feb 1 for September start; contact supervisors before applying)</a> | <a href="https://chem-eng.utoronto.ca/graduate-studies/programs-degrees/research-degrees-masc-and-phd/" target="_blank">UofT ChemE Doctor of Philosophy (thesis under faculty supervision; Qualifying Examination; Reading Committee; PhD Thesis; Departmental Oral; Final Oral; Individual Development Plan; Collaborative Specialization in Biomedical Engineering)</a>',
    },
    "ubc-chbe-phd": {
        "school": "University of British Columbia, Department of Chemical and Biological Engineering",
        "en": "PhD in Chemical and Biological Engineering (CHBE)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.0701)",
        "dur": "48 months (4 years) full-time; up to 6 years maximum; thesis-based; comprehensive research proposal oral examination within 12 months of admission (if <=6 credits) or 15 months (if >6 credits); transfer from MASc possible after 1 year with 9 credits at 500-level or above and first-class standing",
        "ddl": "May 2027 intake: opens Sep 1, 2026. **Canadian and International deadline December 1, 2026**. Transcript and Referee deadline January 1, 2027. September 2027 intake: opens Oct 1, 2026. **Canadian and International deadline February 1, 2027**. Transcript and Referee deadline April 1, 2027.",
        "lang": "TOEFL iBT 90 overall (sectional R22/L22/W21/S21) / IELTS Academic 6.5 (sectional 6.0) / Duolingo DET 125; ETS UBC 0965; English-medium undergraduate may be exempted; scores within 2 years.",
        "test_cls": "GRE NOT REQUIRED (UBC Grad School: 'The GRE is not required.' No subject test required. 3 LOR; CV; research proposal; transcripts; recognized course and thesis-based master's degree; high scholastic standing and demonstrated aptitude for research).",
        "tui": "UBC CHBE minimum funding package $25,000/year plus teaching assistantships; 15-25 students accepted per year; full funding through RA/TA and faculty grants. Application fee ~$150 CAD.",
        "overview": "The UBC Department of Chemical and Biological Engineering (CHBE) in the Faculty of Applied Science offers MEng, MSc, MASc, and PhD degrees. The PhD program is designed to develop the candidate's ability for independent research. Applicants must have a high scholastic standing and demonstrate an aptitude for research. Substantial completion of PhD requirements is expected within three years for students with a master's degree, and within four years for students transferring from the MASc program. The University requires that the PhD program be completed within six years of initial registration. A comprehensive research proposal oral examination must be scheduled within 12 months of admission (if 6 credits or less of courses are taken) or within 15 months (if more than 6 credits are taken). Students may transfer from a master's program to the doctoral program after completing one year of studies with 9 credits at the 500-level or above and first-class standing.",
        "requirements": "<ul><li>Recognized course and thesis-based master's degree in chemical engineering or related field</li><li>High scholastic standing and demonstrated aptitude for research</li><li>GRE NOT required (UBC Grad School explicitly states 'The GRE is not required')</li><li>TOEFL iBT 90 (R22/L22/W21/S21) / IELTS 6.5 (6.0 each band) / Duolingo DET 125; ETS 0965; English-medium may be exempted</li><li>UBC Faculty of Graduate + Postdoctoral Studies online application</li><li>3 letters of recommendation</li><li>CV</li><li>Research proposal</li><li>Transcripts</li><li>**May 2027 intake: deadline December 1, 2026**; transcript and referee deadline January 1, 2027</li><li>**September 2027 intake: deadline February 1, 2027**; transcript and referee deadline April 1, 2027</li><li>Thesis-based; on-campus residential</li><li>Transfer from MASc possible after 1 year + 9 credits at 500-level or above + first-class standing</li><li>Comprehensive research proposal oral exam within 12-15 months of admission</li></ul>",
        "research": "<ul><li>Bioproducts and bioprocess engineering</li><li>Biomedical engineering and biomaterials</li><li>Energy and sustainability (biofuels, hydrogen, carbon capture)</li><li>Environmental engineering and water treatment</li><li>Reaction engineering and catalysis</li><li>Transport phenomena and fluid mechanics</li><li>Process systems engineering and control</li><li>Nanomaterials and nanotechnology</li><li>Process, environmental, and biological engineering options</li><li>Interdisciplinary with UBC Forestry, Medicine, and Biotechnology programs</li></ul>",
        "source": '<a href="https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-chemical-biological-engineering" target="_blank">UBC Grad School: PhD in Chemical and Biological Engineering (May 2027 deadline Dec 1, 2026; Sep 2027 deadline Feb 1, 2027; GRE not required; TOEFL 90 / IELTS 6.5 / DET 125)</a> | <a href="https://engineering.ubc.ca/sites/default/files/cgec/CHBE_Graduate_Programs_Brochure_2020-21.pdf" target="_blank">UBC CHBE Graduate Programs Brochure (PhD duration 48 months; 15-25 students accepted per year; minimum funding $25,000/year + TA; master\'s completion in 3 years, MASc-transfer in 4 years, max 6 years; transfer after 1 year + 9 credits 500-level + first-class)</a> | <a href="https://www.chbe.ubc.ca/files/2014/11/graduate_student_handbook.pdf" target="_blank">UBC CHBE Graduate Student Handbook (comprehensive research proposal oral exam within 12 months if <=6 credits or 15 months if >6 credits; ~175 graduate students; MEng/MSc/MASc/PhD degrees)</a>',
    },
    "mcgill-chbe-phd": {
        "school": "McGill University, Department of Chemical Engineering",
        "en": "PhD in Chemical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.0701)",
        "dur": "3-4 years full-time residential; 6-year maximum; Research Proposal; Research Seminar; Doctoral Thesis and Defense; governed by GPSO Red Book regulations; applicants must secure research supervisor before admission",
        "ddl": "Fall (September) 2027: opens Sep 15, 2026. **International deadline January 15, 2027**; Domestic (Canadian/PR) deadline June 21, 2027. Winter (January) 2028: opens Feb 15, 2027; International Aug 1, 2027; Domestic Nov 10, 2027. Summer (May) 2028: opens May 15, 2027; International Oct 1, 2027; Domestic Apr 1, 2028. Decisions 2-3 weeks after deadline.",
        "lang": "TOEFL iBT / IELTS Academic required for international students whose native language is not English; ETS McGill 0935; per GPSO English proficiency; scores within 2 years.",
        "test_cls": "GRE NOT REQUIRED (McGill ChemE does not list GRE as required. Recognized master's in related discipline with 3.0/4.0 cumulative GPA or 3.2/4.0 in last two years; direct BS entry possible for exceptional candidates. 3 LOR (institutional email required; gmail/yahoo/hotmail not accepted); research proposal; CV; transcripts).",
        "tui": "McGill ChemE PhD admission contingent on qualified applicant being matched with supervisor and financial support; McGill Department of Chemical Engineering cannot issue application fee waivers. Full funding through faculty RA and TA appointments.",
        "overview": "The McGill University Department of Chemical Engineering offers a Doctor of Philosophy (PhD) and a Master of Engineering (MEng, non-thesis). The PhD is a research-intensive program that emphasizes specialized and engaging learning opportunities. The program's objective is to equip students with skills in literature review, research methods, and laboratory safety to pursue professional opportunities in academia or industry. The PhD requires a Research Proposal, Research Seminar, and Doctoral Thesis and Defense. The program length is approximately 3-4 years full-time, with a 6-year maximum. Applications are reviewed by the Graduate Admissions Committee of the Department of Chemical Engineering; the committee makes recommendations of admission to the Graduate and Postdoctoral Studies Office (GPSO) when a qualified applicant is matched with a supervisor and financial support. Students should receive an acceptance or rejection letter 2-3 weeks after the applicable application closing date.",
        "requirements": "<ul><li>Recognized master's degree in related discipline with 3.0/4.0 cumulative GPA or 3.2/4.0 in last two years</li><li>Direct entry from bachelor's degree possible for exceptional candidates</li><li>GRE NOT required (McGill ChemE does not list GRE as required)</li><li>TOEFL iBT / IELTS Academic for international students whose native language is not English; ETS 0935</li><li>McGill online application via GPSO</li><li>3 letters of recommendation (institutional email required; gmail/yahoo/hotmail not accepted)</li><li>Research proposal</li><li>CV</li><li>Transcripts</li><li>**Fall 2027 international deadline January 15, 2027**; domestic deadline June 21, 2027</li><li>Winter 2028: international Aug 1, 2027; domestic Nov 10, 2027</li><li>Summer 2028: international Oct 1, 2027; domestic Apr 1, 2028</li><li>**Research supervisor must be secured before admission**</li><li>Department cannot issue application fee waivers</li><li>Thesis-based; on-campus residential (Montreal, QC)</li></ul>",
        "research": "<ul><li>Advanced materials and polymers</li><li>Biomedical engineering and biomaterials</li><li>Biotechnology and bioengineering</li><li>Energy and sustainability (batteries, fuel cells, biofuels)</li><li>Environmental engineering and water treatment</li><li>Plasma engineering and plasma medicine</li><li>Reaction engineering and catalysis</li><li>Transport phenomena and fluid mechanics</li><li>Process systems engineering and control</li><li>Nanomaterials and nanotechnology</li><li>Interdisciplinary with McGill BME, Physics, and Chemistry</li></ul>",
        "source": '<a href="https://www.mcgill.ca/gradapplicants/program/chemical-engineering-phd" target="_blank">McGill Future Graduate Students: Chemical Engineering PhD (Fall opens Sep 15, international Jan 15, domestic Jun 21; Winter opens Feb 15, international Aug 1, domestic Nov 10; Summer opens May 15, international Oct 1, domestic Apr 1; minimum 3.0 GPA; English proficiency)</a> | <a href="https://www.mcgill.ca/chemeng/grad/applicationprocess" target="_blank">McGill ChemE Application Process (applications reviewed by Graduate Admissions Committee; admission recommended when qualified applicant is matched with supervisor and financial support; decisions 2-3 weeks after deadline; department cannot issue fee waivers)</a> | <a href="https://www.mcgill.ca/engineering/files/engineering/chemical_graduate_flyer_-_fall_2015.pdf" target="_blank">McGill ChemE Program Flyer (PhD length 3-4 years full-time; master\'s with 3.0/4.0 cumulative or 3.2/4.0 last two years; direct BS entry for exceptional candidates; Research Proposal, Research Seminar, Thesis and Defense; research areas: advanced materials, biomedical, biotechnology, energy, environmental, plasma, polymers)</a>',
    },
    "uw-chemeng-phd": {
        "school": "University of Waterloo, Department of Chemical Engineering",
        "en": "PhD in Chemical Engineering (Water)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.0701)",
        "dur": "48 months (4 years) full-time; full-time or part-time registration; thesis-based; at time of admission, each student must have an approved PhD supervisor who has agreed in writing to supervise (or co-supervise, with at least one approved PhD supervisor)",
        "ddl": "Fall (September) 2027: **March 1, 2027** (extended from February 1, 2026). Winter (January) 2028: June 1, 2027. Spring (May) 2028: October 1, 2027. All supporting documents must be uploaded within 10 business days of submission and before the deadline.",
        "lang": "TOEFL iBT 80 minimum (sectional W22/S20/R20/L18) / IELTS Academic 6.5 (sectional W6.0/S6.0); ETS Waterloo 0996; objective evidence of English language skills required per Engineering Graduate Studies; scores valid 2 years.",
        "test_cls": "GRE NOT REQUIRED (Waterloo ChemE does not list GRE as required for PhD. Minimum 80% standing in relevant thesis-based master's program; excellence of background preparation and academic achievement. 3 academic references; research proposal; CV; transcripts; approved PhD supervisor must agree in writing before admission).",
        "tui": "Waterloo ChemE PhD students typically funded through supervisor research grants and departmental TA appointments; tuition charged per term (three terms per year). Application requires written supervisor agreement before admission.",
        "overview": "The University of Waterloo Department of Chemical Engineering (within the Faculty of Engineering) offers a thesis-based Doctor of Philosophy (PhD) in Chemical Engineering. The program is 48 months (4 years) full-time, with part-time registration also available. The program admits for Fall (September), Winter (January), and Spring (May) terms. At the time of admission, each student must have an approved PhD supervisor who has agreed in writing to supervise their academic program or co-supervisors (at least one of whom is an approved PhD supervisor). The Engineering Graduate Studies Sub-Committee requires objective evidence of English language skills. Applicants must demonstrate excellence of background preparation and academic achievement in prior degrees and, usually, possess a relevant thesis-based master's degree with a minimum 80% standing in the master's program. Three academic references are required.",
        "requirements": "<ul><li>Relevant thesis-based master's degree with minimum 80% standing</li><li>Excellence of background preparation and academic achievement in prior degrees</li><li>GRE NOT required (Waterloo ChemE does not list GRE as required)</li><li>TOEFL iBT 80 (W22/S20/R20/L18) / IELTS Academic 6.5 (W6.0/S6.0); ETS 0996; objective English language evidence required</li><li>Waterloo online application</li><li>3 academic references</li><li>Research proposal</li><li>CV</li><li>Transcripts</li><li>**Fall 2027 deadline March 1, 2027** (extended from February 1, 2026)</li><li>Winter 2028: June 1, 2027; Spring 2028: October 1, 2027</li><li>All supporting documents uploaded within 10 business days of submission and before deadline</li><li>**Approved PhD supervisor must agree in writing before admission**</li><li>Thesis-based; on-campus residential (Waterloo, ON)</li><li>Full-time or part-time registration</li></ul>",
        "research": "<ul><li>Biotechnology and bioengineering</li><li>Energy and sustainability (batteries, fuel cells, carbon capture)</li><li>Environmental engineering and water treatment</li><li>Reaction engineering and catalysis</li><li>Transport phenomena and fluid mechanics</li><li>Process systems engineering and control</li><li>Nanomaterials and nanotechnology</li><li>Polymers and soft matter</li><li>Biomedical engineering and biomaterials</li><li>Interdisciplinary with Waterloo AI, Cybersecurity, and Health programs</li></ul>",
        "source": '<a href="https://uwaterloo.ca/future-graduate-students/programs/by-faculty/engineering/chemical-engineering-water-doctor-philosophy-phd" target="_blank">Waterloo Future Graduate Students: Chemical Engineering PhD (Fall 2027 deadline March 1, 2027 extended; Winter June 1; Spring Oct 1; 48 months full-time; thesis-based; minimum 80% in relevant thesis-based master\'s; approved supervisor must agree in writing)</a> | <a href="https://uwaterloo.ca/graduate-studies-postdoctoral-affairs/future-students/programs/chemical-engineering-phd-waterloo" target="_blank">Waterloo GSPA: Chemical Engineering PhD at Waterloo (48 months; full-time/part-time; on-campus; TOEFL 80 (W22/S20/R20/L18); IELTS 6.5 (W6.0/S6.0); approved PhD supervisor must agree in writing)</a> | <a href="https://uwaterloo.ca/engineering/graduate-students/request-more-information" target="_blank">Waterloo Engineering Graduate Studies FAQ (research-based/PhD programs require a supervisor; tuition charged per term, three terms per year; Fall/Sept apply by Feb 1, Winter/Jan by June 1, Spring/May by Oct 1)</a>',
    },
    "col-chemeng-phd": {
        "school": "Columbia University, Fu Foundation School of Engineering, Department of Chemical Engineering",
        "en": "PhD / Doctor of Engineering Science in Chemical Engineering",
        "deg": "Doctor of Philosophy (PhD) / Doctor of Engineering Science (EngScD)",
        "stem_label": "STEM-designated (Engineering / CIP 14.0701)",
        "dur": "4-5 years full-time residential; thesis-based; doctoral candidacy examination; dissertation research and defense; MS may be earned en route; direct BS-to-PhD entry allowed; research assistantship and teaching assistantship appointments",
        "ddl": "Fall 2027 (September): **Doctoral deadline December 15, 2026**. Spring 2027 admission: October 15, 2026. All application materials should be submitted and received within 2-4 weeks after the posted deadline. Decisions released in months following deadline. Application fee $85. Deferrals not offered.",
        "lang": "TOEFL iBT / IELTS Academic required for international students whose native language is not English; ETS Columbia Engineering 2111; English proficiency per Graduate School / Fu Foundation; scores valid 2 years.",
        "test_cls": "GRE OPTIONAL FOR 2027 CYCLE (Columbia Engineering: 'The GRE is not required for the 2027 admission cycle. This includes Spring 2027 and Fall 2027. If you have taken the GRE and would like to provide your scores, you may, but it is not required as of July 2026. Students who do not submit scores will not be penalized. Applied Physics PhD may supply GRE Physics subject test, also not required. 3 LOR; CV/resume; personal statement; video interview (may be required for doctoral programs); transcripts).",
        "tui": "Columbia Engineering PhD students typically receive full funding through departmental research/teaching assistantships and fellowships (tuition + stipend + health insurance). Application fee $85. Fall and Spring admission. Deferrals not offered.",
        "overview": "The Columbia University Fu Foundation School of Engineering and Applied Science offers doctoral degrees in Chemical Engineering, including the Doctor of Philosophy (PhD) and the Doctor of Engineering Science (EngScD). The department admits doctoral students twice a year for Fall and Spring semesters. The PhD deadline is December 15 for Fall entry and October 15 for Spring entry. The MS/PhD track allows students to earn an MS en route to the doctorate. Columbia Engineering has made the GRE optional for the 2027 admission cycle (including Spring 2027 and Fall 2027): students who do not submit scores will not be penalized; those who do submit scores will have them reviewed. Applied Physics PhD applicants may supply GRE Physics subject test scores, also not required as of July 2026. A complete application includes the online form, $85 fee, transcripts, 3 letters of recommendation, resume/CV, test scores, personal statement, and a video interview (may be required for doctoral programs).",
        "requirements": "<ul><li>Bachelor's degree in engineering, chemistry, or related field</li><li>Direct BS-to-PhD entry allowed; MS may be earned en route</li><li>**GRE OPTIONAL for 2027 admission cycle** (not required; absence not penalized; submitted scores considered)</li><li>Applied Physics PhD may supply GRE Physics subject test, also not required</li><li>TOEFL iBT / IELTS Academic for international students whose native language is not English; ETS 2111</li><li>Columbia Engineering online application</li><li>$85 application fee</li><li>3 letters of recommendation</li><li>Resume / CV</li><li>Personal statement</li><li>Video interview (may be required for doctoral programs)</li><li>Transcripts</li><li>**Fall 2027 doctoral deadline December 15, 2026**</li><li>Spring 2027 admission: October 15, 2026</li><li>All materials received within 2-4 weeks after deadline</li><li>On-campus residential (Morningside Heights, New York)</li><li>Deferrals not offered</li></ul>",
        "research": "<ul><li>Biochemical engineering and biotechnology</li><li>Energy and sustainability (batteries, fuel cells, carbon capture)</li><li>Materials science and engineering (polymers, nanostructures, soft matter)</li><li>Thermodynamics and statistical mechanics</li><li>Reaction engineering and catalysis</li><li>Transport phenomena and fluid mechanics</li><li>Process systems engineering, control, and AI</li><li>Environmental engineering and climate science</li><li>Computational molecular science and simulation</li><li>Quantitative and systems biology</li><li>Columbia Electrochemical Energy Center (CEEC)</li><li>Data-driven engineering and machine learning</li></ul>",
        "source": '<a href="https://www.engineering.columbia.edu/admissions-aid/graduate-admissions/how-apply/application-requirements" target="_blank">Columbia Engineering Application Requirements (Doctoral deadline December 15; GRE optional for 2027 cycle including Spring/Fall 2027; school code 2111; $85 fee; 3 LOR; CV; personal statement; video interview may be required for doctoral programs)</a> | <a href="https://bulletin.columbia.edu/columbia-engineering/graduate-studies/graduate-admissions/" target="_blank">Columbia Engineering Bulletin: Graduate Admissions (Fall admission Dec 15 for PhD/EngScD/MS-to-PhD; Spring admission Oct 15; GRE not required as of July 2026; no penalty for not submitting; Applied Physics GRE subject test also not required; GRE scores valid 5 years)</a> | <a href="https://gradengineering.columbia.edu/admissions-aid/graduate-admissions/how-apply" target="_blank">Columbia Engineering How to Apply (online form; $85 fee; transcripts; 3 LOR; CV; test scores; personal statement; video interview for MS and possibly doctoral; Dec 15 doctoral; Jan 15 priority / Feb 15 regular for MS; Oct 15 for Spring)</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)}")
