# -*- coding: utf-8 -*-
"""Round 263: batch add 5 - Canadian Chemistry PhD (UofT/UBC/McGill/Waterloo) + JHU Astronomy & Astrophysics PhD
- UofT Chemistry PhD (international Dec 5; domestic Early Feb 1 / Final Apr 30; GRE NOT required; min GPA China 87% / US A-; TOEFL iBT 93 overall 22 writing/speaking; direct BSc to PhD; supervisor assigned by graduate unit AFTER admission; 4 years with MSc / 5 years direct BSc; 7 sub-disciplines)
- UBC Chemistry PhD (Sept 2027: app open Oct 1, 2026; scholarship priority Dec 1, 2026 11:59pm PST; final Feb 15, 2027; docs Mar 15, 2027; GRE not mandatory for non-North American applicants; TOEFL 90 / IELTS 6.5; direct BSc B+; 3 LOR; no supervisor commitment required prior to applying)
- McGill Chemistry PhD (Fall: app opens Sep 15; international Jan 15; domestic Jun 15; Winter: app opens Feb 15; international May 31; domestic Sep 30; direct BSc cGPA 3.7/4.0; MSc cGPA 3.0/4.0; 2 LOR; supervisor chosen after arrival; 4-5 years; rolling admissions)
- Waterloo Chemistry PhD (Fall: Feb 1; Winter: Jun 1; Spring: Oct 1; GRE and GRE subject NOT required; TOEFL 90 W25/S25; IELTS 7.0 W6.5/S6.5; direct BSc 89% standing; MSc 75%; 3 academic references; 48 months full-time; GWC collaborative with Guelph)
- JHU Astronomy & Astrophysics PhD (Dec 15 for September; GRE General and Physics GRE optional; TOEFL 100 iBT preferred; 3 LOR; $75 fee waivable; PhD only; no separate MS; thesis advisor by Year 3; 5-6 years; collaboration with APL/STScI/Goddard; ETS 5332)
Key finding: Canadian Chemistry PhD supervisor policy is more flexible than expected - UofT assigns supervisor after admission, UBC requires no prior commitment, McGill students choose after arrival. Only Waterloo expects students to find supervisor. This differs from earlier observation that all Canadian PhD programs require supervisor agreement before offer.
"""
import os, re

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

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} - {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{color:#1a3a6c;border-bottom:2px solid #1a3a6c;padding-bottom:8px;font-size:22px}}
h2{{color:#1a3a6c;margin-top:28px;font-size:17px}}
.card{{background:#f7f9fc;border-left:4px solid #1a3a6c;padding:14px 18px;margin:12px 0;border-radius:4px}}
.meta{{display:inline-block;background:#e8eef7;color:#1a3a6c;padding:2px 10px;border-radius:12px;font-size:13px;margin-right:6px}}
a{{color:#1a6cc8}}
</style>
</head>
<body>
<h1>{school} - {en}</h1>
<div>
<span class="meta">学位：{deg}</span>
<span class="meta">{stem_label}</span>
</div>
<h2>项目概览</h2>
<div class="card">{overview}</div>
<h2>学制与课程</h2>
<div class="card">{dur}</div>
<h2>申请截止</h2>
<div class="card">{ddl}</div>
<h2>语言要求</h2>
<div class="card">{lang}</div>
<h2>标化与录取要求</h2>
<div class="card">{test_cls}</div>
<h2>学费与资助</h2>
<div class="card">{tui}</div>
<h2>申请材料与研究方向</h2>
<div class="card">{requirements}</div>
<h2>研究领域</h2>
<div class="card">{research}</div>
<h2>来源</h2>
<div class="card">{source}</div>
</body>
</html>"""

PROGRAMS = [
    {
        "id": "ut-chem-phd",
        "s": "ut",
        "n": "化学博士",
        "en": "PhD in Chemistry (University of Toronto, Department of Chemistry; located in Toronto, ON; international Dec 5; domestic Early Feb 1 / Final Apr 30; GRE NOT required; min GPA China 87% / US A-; TOEFL iBT 93 overall 22 writing/speaking; direct BSc to PhD; supervisor assigned after admission; 4 years with MSc / 5 years direct BSc)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4 years for students with completed MSc degree; 5 years for direct-entry PhD from BSc (or including first year in MSc program for PhD transfers). On-campus residential (Toronto, Ontario). PhD students select one of seven sub-disciplines: Analytical Chemistry, Environmental Chemistry, Inorganic Chemistry, Organic and Biological Chemistry, Physical Chemistry and Chemical Physics, Polymers and Materials Chemistry, or Interdisciplinary. Each field requires minimum 2.0 to 3.0 full-course equivalents (FCEs) from approved graduate courses. Students with MSc from another department or university may request course reduction of up to two half-courses. Seminar program required: at least 2-3 presentations per field. Departmental comprehensive oral examination required. Doctoral thesis is original investigation.",
        "ddl": "Fall 2027 (September) / Winter 2028 (January) entry. **International applicants: deadline December 5, 2026** (School of Graduate Studies application system opens mid-September 2026). **Domestic applicants: early deadline February 1, 2027; final deadline April 30, 2027.** Applications reviewed on rolling basis. Strongly recommend applying well before deadline due to limited space for international students. NSERC Canada Graduate Scholarship Master's applicants encouraged to submit by January 2. Application considered complete only when all components (including letters of reference) received before deadline. Contact: chem.gradcoord@utoronto.ca.",
        "lang": "TOEFL iBT minimum: 93 overall with 22 in both writing and speaking. TOEFL paper-based: 580 and TWE 4.0. IELTS minimum per SGS policy. Applicants from outside North America required to submit English language scores. Note: Entry to the Master's program is considered for applicants who completed their undergraduate degree in Canada. Otherwise, study permit holders with a BSc are normally admitted directly into the PhD Direct-Entry program.",
        "test": {"cls": "GRE NOT REQUIRED (Department of Chemistry International Applicants page: 'GRE scores are not required for admission to the MSc or PhD programs.' Domestic Applicants page confirms same policy. Minimum GPA requirements by country for PhD admission: China 87%; Bangladesh First Class (A-) or 70-75% or 3.50 GPA; Iran 17/20; Sri Lanka 85%; Korea 93/100; 4.0/4.5; 3.7/4.3; Mexico 9/10; Pakistan First Class; Turkey 3.74/4 (3.44/4 for METU), 8.5/10; United States A-. Direct-entry PhD from BSc requires A- or better average in relevant discipline. Master's degree minimum B+ average."},
        "tui": "UofT Chemistry PhD students receive multi-year funding support. Department established in 1859, one of leading chemistry institutions globally. Three entry routes: (1) following completion of appropriate master's degree; (2) transfer from UofT master's program; (3) direct entry following completion of appropriate BSc degree. Note: Unlike many other Canadian PhD programs, UofT Chemistry assigns supervisor by graduate unit AFTER admission (not before). Students strongly encouraged to reach out to research faculty to discuss proposed research prior to applying, but admission is not conditional on securing supervisor. Collaborative program available: Environmental Studies. Department located at 80 St. George Street, Toronto, Ontario.",
        "url": "details/ut-chem-phd.html",
    },
    {
        "id": "ubc-chem-phd",
        "s": "ubc",
        "n": "化学博士",
        "en": "PhD in Chemistry (University of British Columbia, Department of Chemistry; located in Vancouver, BC; Sept 2027: app open Oct 1, 2026; scholarship priority Dec 1, 2026 11:59pm PST; final Feb 15, 2027; docs Mar 15, 2027; GRE not mandatory for non-North American applicants; TOEFL 90 / IELTS 6.5; direct BSc B+; 3 LOR; no supervisor commitment required prior to applying)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 4-5 years; on-campus residential (Vancouver, British Columbia). For direct entry to PhD from bachelor's degree: students must within first 24 months complete 12 credits with first class average, of which at least 9 credits must be at 500 level or above and at least 9 credits must be of first class standing, to maintain registration as doctoral student. For entry to PhD by students with MSc: successfully defended master's thesis required. Research areas span analytical, biological, inorganic, organic, materials, physical, polymer, nanoscience, theoretical chemistry and interdisciplinary.",
        "ddl": "September 2027 intake. **Application opens October 1, 2026.** **Top scholarship priority deadline: December 1, 2026 11:59 pm Vancouver time (Pacific Time, UTC-7).** Applications must be submitted by February 15, 2027; all supporting documentation (including official English language test results sent directly from testing center) must be received by March 15, 2027. International students strongly encouraged to apply as early as possible to allow sufficient time for study permit application process. Top applicants based in Canada or U.S. may be eligible for in-person visit of department if application completed by December 1. Contact: admissions@chem.ubc.ca.",
        "lang": "TOEFL iBT minimum: 90 overall (R22/L22/S22/W21). IELTS minimum: overall 6.5 with no subscore below 6.0. Duolingo accepted per UBC Graduate School policy. Scores sent directly from testing center required. No commitment from supervisor prior to applying is necessary, but contacting faculty members is encouraged.",
        "test": {"cls": "GRE NOT MANDATORY (UBC Chemistry Graduate Admissions page: 'Graduate Record Examination (GRE) General and Subject (Chemistry or another applicable subject) test scores are not mandatory. While it is advantageous to submit GRE test scores, it is not a requirement.' This applies specifically to applicants from universities outside Canada, United States and United Kingdom. UBC Graduate School page lists 'GRE is required by some applicants. Please check the program website.' which is superseded by department page. Direct entry to PhD requires B+ overall average from all courses taken in bachelor's degree. For applicants with Canadian/US post-secondary credential: B+ average in senior undergraduate level courses plus successfully defended master thesis. 3 letters of reference required. Statement of interest required."},
        "tui": "UBC Chemistry strongly encourages all international applicants to apply for direct entry into PhD program, as number of admissions offered to international MSc applicants is very limited. Students meeting academic requirements and demonstrating advanced research ability may apply for direct admission to PhD. UBC Graduate School page for Sept 2027 intake confirms: Canadian applicant deadline February 15, 2027; international applicant deadline February 15, 2027; transcript deadline March 15, 2027. 3 references required. Statement of interest required. Supervisor: browse faculty profiles and indicate in application who you are interested in working with; no commitment from supervisor prior to applying is necessary, but contacting faculty members is encouraged. Faculty research areas include luminescent materials, bio/chemical sensing, CO2 conversion, clean energy, atmospheric chemistry, bioanalytical, nanoscience. Department located in Vancouver, British Columbia.",
        "url": "details/ubc-chem-phd.html",
    },
    {
        "id": "mcg-chem-phd",
        "s": "mcg",
        "n": "化学博士",
        "en": "PhD in Chemistry (McGill University, Department of Chemistry; located in Montreal, QC; Fall: app opens Sep 15, international Jan 15, domestic Jun 15; Winter: app opens Feb 15, international May 31, domestic Sep 30; direct BSc cGPA 3.7/4.0; MSc cGPA 3.0/4.0; 2 LOR; supervisor chosen after arrival; 4-5 years; rolling admissions)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Most students require four to five years study to complete PhD. On-campus residential (Montreal, Quebec). Students admitted to PhD1 (direct from BSc) required to register in two PhD1 research courses consecutively during first Fall and Winter terms: CHEM 716 in first term, followed by CHEM 717 in second term. Students entering with MSc degree normally take three graduate-level courses. Students entering without MSc degree normally take five graduate-level courses. Complementary courses: 9-16 credits of CHEM (or approved) courses at 500 or 600 level. Thesis must constitute original scholarship and distinct contribution to knowledge. Seminars in Chemistry required.",
        "ddl": "Fall (September) entry: applications open September 15; **international deadline January 15, 2027**; domestic deadline June 15, 2027. Winter (January) entry: applications open February 15; international deadline May 31; domestic deadline September 30. Summer term admission NOT considered. Department follows rolling admissions process; applications reviewed by Admissions Committee that meets regularly. Applicants encouraged to contact Department for pre-evaluation before submitting application. Note: institutional email required for letters of reference (Gmail/Yahoo/Hotmail not accepted).",
        "lang": "McGill English language proficiency requirements apply. TOEFL/IELTS/Duolingo accepted per GPS policy. After test scores sent by testing centre, allow 15 business days for results to be matched to application. Applicants must meet McGill's English proficiency requirements. Note: McGill is located in Montreal, Quebec; while department is English-language, familiarity with French may be advantageous for daily life in Montreal.",
        "test": {"cls": "GRE NOT EXPLICITLY REQUIRED (McGill Department of Chemistry Graduate Admission page: minimum academic requirement for MSc and PhD is high second-class standing (cGPA above 3.00). Applicants applying directly from BSc to PhD without completing MSc must have minimum cGPA of 3.7/4.0. Course catalogue page lists cGPA 3.5 for direct BSc to PhD (slightly different from dept page 3.7). Applicants from other institutions must have academic background equivalent to McGill graduate with Honours or Major degree in Chemistry or related field (Physics or Biochemistry). Admission is competitive. 2 letters of reference required (with institutional or organizational email addresses). Note: McGill Course Catalogue legacy page mentions GRE as part of general graduate requirements, but current department page does not list GRE as required. Students should verify with graduate program administrator. Contact: Director of Graduate Studies, Department of Chemistry.)"},
        "tui": "McGill Chemistry PhD is research-intensive program emphasizing analytical and rigorous learning opportunities. Keywords: analytical/environmental, chemical biology, chemical physics, green/sustainable, materials, synthesis/catalysis. Faculty conduct research in Materials, Chemical Synthesis, Bio-organic Chemistry, Biophysical Chemistry, Nanochemistry plus disciplinary areas of Analytical, Physical, Inorganic and Organic Chemistry. Unique feature: Incoming students are NOT committed to a supervisor before arriving at the Department. In early August, incoming students receive list of professors and are responsible for arranging meetings to explore research options, co-supervision arrangements, and meet current graduate students. This is different from Canadian programs that require supervisor agreement before offer. Research history: Soddy's research on transmutation of elements, Belleau's discovery of antiviral 3TC, Ogilvie's co-development of first 'gene machine'. Department located in Montreal, Quebec.",
        "url": "details/mcg-chem-phd.html",
    },
    {
        "id": "uw-chem-phd",
        "s": "uw",
        "n": "化学博士",
        "en": "PhD in Chemistry (University of Waterloo, Department of Chemistry; located in Waterloo, ON; Fall Feb 1, Winter Jun 1, Spring Oct 1; GRE and GRE subject NOT required; TOEFL 90 W25/S25; IELTS 7.0 W6.5/S6.5; direct BSc 89% standing; MSc 75%; 3 academic references; 48 months full-time; GWC collaborative with Guelph)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "48 months full-time; on-campus residential (Waterloo, Ontario). Also part-time registration option. Thesis-based study option. Students in PhD program must successfully complete two additional one-term courses (0.5 unit weights) beyond those required for MSc; pass PhD Comprehensive Examination; present 30-minute seminar (PhD Seminar); submit and defend acceptable PhD Thesis. For direct admission from BSc: four regular graduate courses, MSc Seminar and research proposal (second term), PhD Oral Comprehensive Examination (fifth term), PhD Research Seminar (seventh term), and PhD thesis. Co-operative option also available: after two terms of coursework, candidate spends one year (three terms) working in industrial or governmental laboratory. GWC (Guelph-Waterloo Centre for Graduate Work in Chemistry and Biochemistry) collaborative program.",
        "ddl": "**Fall (September-December) entry: February 1, 2027.** **Winter (January-April) entry: June 1, 2026 (previous year).** **Spring (May-August) entry: October 1, 2026 (previous year).** Domestic students (Canadians and PR) applications considered after these deadlines, though this may impact eligibility for major awards and scholarships in first year. Application must be complete and all supporting documentation uploaded by deadline. Department strongly recommends international students apply at least nine months prior to start of term to allow sufficient time to arrange study permit. Major awards: OGS, Tri-Agency Scholarships, internal UW awards.",
        "lang": "TOEFL iBT minimum: 90 (writing 25, speaking 25). IELTS minimum: 7.0 overall (writing 6.5, speaking 6.5). Proof of English language proficiency required if applicable. Note: Future Graduate Students page lists TOEFL 4.5 (writing 5, speaking 5) which appears to be legacy scoring scale; current graduate page confirms TOEFL 90 with W25/S25.",
        "test": {"cls": "GRE AND GRE SUBJECT NOT REQUIRED (University of Waterloo Chemistry How to Apply page: 'The GRE and the GRE subject area test in chemistry and/or biochemistry are not required.' Admission requirements: MSc degree (or equivalent) in Science with minimum overall standing of 75% in last 2 years (domestic). Direct admission to PhD from BSc possible for outstanding students with overall 89% standing at undergraduate level. Course requirements reduced by one course for students admitted directly from BSc. If Bachelor's 4-year honours degree is not in Chemistry, sufficient upper-level Chemistry course content required. In some cases, department may recommend completion of preliminary courses. 3 academic references required. Program-specific questions (PSQ) required. Transcripts required.)"},
        "tui": "Waterloo Chemistry PhD program ranks among top of its kind in Canada. Research fields: analytical, biochemistry, inorganic, material, nanotechnology, organic, physical, polymer, quantum, and theoretical chemistry. Also collaborative program: Chemistry (Quantum Information) PhD in collaboration with Institute for Quantum Computing (IQC), located in Mike and Ophelia Lazaridis Quantum-Nano Centre (QNC). GWC (Guelph-Waterloo Centre for Graduate Work in Chemistry and Biochemistry) joint program with University of Guelph. PhD Comprehensive Examination committee consists of two Chemistry graduate faculty members and one member from opposite campus (where applicable, from Guelph or Waterloo), chaired by GWC Director or designate. If first attempt unsuccessful, second attempt allowed not less than 2 and not more than 4 months from first attempt. Contact: gwc@uoguelph.ca. Department located in Waterloo, Ontario.",
        "url": "details/uw-chem-phd.html",
    },
    {
        "id": "jhu-astro-phd",
        "s": "jhu",
        "n": "天文与天体物理博士",
        "en": "PhD in Astronomy and Astrophysics (Johns Hopkins University, Zanvyl Krieger School of Arts and Sciences, William H. Miller III Department of Physics and Astronomy; located in Baltimore, MD; Dec 15 for September; GRE General and Physics GRE optional; TOEFL 100 iBT preferred; 3 LOR; $75 fee waivable; PhD only; no separate MS; thesis advisor by Year 3; 5-6 years; collaboration with APL/STScI/Goddard; ETS 5332)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "Typically 5-6 years; on-campus residential (Baltimore, Maryland). Students engage in original research starting in first semester. By end of second year, students typically complete required graduate classes and have explored several research directions. Students start thesis research no later than fall of third year. Students must find thesis advisor and submit thesis advisor form before first day of third year. Thesis research and defense required. Note: Applicants admitted only as full-time candidates for PhD. There is no separate Master's degree program and no provision for part-time students. However, a Master's degree is awarded as a stage of the PhD program. For MA in Astronomy: eight one-semester 3-credit graduate-level courses in Department of Physics and Astronomy, plus seminar 'Language of Astrophysics', and pass departmental research exam.",
        "ddl": "Fall 2027 (September) matriculation: **application deadline December 15, 2026.** All applications submitted online through Graduate Admissions portal. Offers of admission made by early February with decision deadline April 15, 2027. Vivien Thomas Scholars Initiative applicants must submit by December 1 for consideration. Students accepted to PhD programs at JHU can apply to receive $1500 need-based grant to offset costs of relocating to JHU. Application fee $75 non-refundable; may be waived per Krieger School policy.",
        "lang": "TOEFL preferred minimum: 600 paper-based or 250 computer-based or 100 internet-based. IELTS also accepted. International applicants must submit TOEFL or IELTS scores less than two years old. TOEFL institution code: 5332. IELTS institute code: 4610. International applicants with post-secondary degrees from United States and/or select countries may be exempt (must have completed at least two years of full-time study at such institutions). A reproduction of score is acceptable at application stage.",
        "test": {"cls": "GRE GENERAL AND PHYSICS GRE OPTIONAL (JHU e-catalogue Astronomy and Astrophysics PhD page: 'Note: submission of General GRE and Physics GRE scores is optional.' Krieger School Graduate Admissions Exams page lists 'Physics and Astronomy' under 'GRE is optional for'. GRE Subject exams also optional for Physics and Astronomy. Required materials: Statement of purpose (well-written, demonstrates ability to overcome challenges, dedication to goals, creativity, understanding of physics and/or astronomy, potential for research); Three letters of recommendation (evaluates capacity for research - most important criterion for admission); Transcripts of all previous work (unofficial acceptable with application; official required upon admission); TOEFL/IELTS for international students. $75 application fee, may be waived.)"},
        "tui": "JHU Physics and Astronomy PhD is fully-funded. Students study in close collaboration with world-renowned, award-winning faculty. Research leading to dissertation can be carried out not only within Department of Physics and Astronomy, but also in collaboration with other research centers: Johns Hopkins Applied Physics Laboratory (APL), Space Telescope Science Institute (STScI), and NASA Goddard Space Flight Center. Research areas: astrophysics, atomic/molecular/optical physics, biological physics, condensed matter physics, particle physics. Recent dissertation research includes work with APL, STScI, and Goddard. Graduate students can work toward PhD in either physics or astronomy and astrophysics. Faculty and staff nominate students for departmental and university fellowships; advisors support applications for NSF fellowships, NASA fellowships. Department located at 3400 North Charles Street, Baltimore, Maryland. ETS institution code 5332.",
        "url": "details/jhu-astro-phd.html",
    },
]

PAGES = {
    "ut-chem-phd": {
        "school": "多伦多大学",
        "en": "PhD in Chemistry (University of Toronto)",
        "deg": "PhD",
        "stem_label": "STEM-designated (Chemistry / CIP 40.0501)",
        "dur": "4 years with MSc / 5 years direct BSc. Seven sub-disciplines: Analytical, Environmental, Inorganic, Organic and Biological, Physical Chemistry and Chemical Physics, Polymers and Materials, Interdisciplinary. 2.0-3.0 FCEs required. Comprehensive oral exam required. Seminar program (2-3 presentations). Thesis = original investigation.",
        "ddl": "International Dec 5, 2026; domestic Early Feb 1 / Final Apr 30, 2027. SGS system opens mid-September 2026. Rolling review. Strongly recommend applying well before deadline. Contact: chem.gradcoord@utoronto.ca.",
        "lang": "TOEFL iBT 93 overall (22 writing/speaking). TOEFL paper 580/TWE 4.0. IELTS per SGS. Note: Study permit holders with BSc normally admitted directly to PhD Direct-Entry (not MSc).",
        "test_cls": "GRE NOT REQUIRED. Min GPA: China 87%, US A-. Direct-entry PhD from BSc requires A- or better. MSc minimum B+ average. 2 LOR. Statement of intent. CV. Transcripts.",
        "tui": "Multi-year funding. Three entry routes: after MSc, transfer from UofT MSc, or direct BSc. **Supervisor assigned by graduate unit AFTER admission** (not before) - differs from typical Canadian PhD model. Faculty outreach encouraged before applying but not required for admission. Collaborative program: Environmental Studies. Department established 1859.",
        "overview": "University of Toronto Department of Chemistry PhD program. Research in modern facilities leading to Doctor of Philosophy. Areas cover analytical, biological, environmental, inorganic, organic, materials, physical, polymers, theoretical chemistry and interdisciplinary areas. Established 1859.",
        "requirements": "SGS online application. 2 letters of reference. Transcripts from all post-secondary institutions. Statement of intent. CV. English language scores directly to SGS (if applicable). Note: Entry to MSc is considered for applicants who completed undergraduate degree in Canada; otherwise study permit holders with BSc normally admitted into PhD Direct-Entry.",
        "research": "Analytical Chemistry, Environmental Chemistry, Inorganic Chemistry, Organic and Biological Chemistry, Physical Chemistry and Chemical Physics, Polymers and Materials Chemistry, Interdisciplinary (bioanalytical, biophysics, bioinorganic, nanoscience, nanotechnology). Collaborative program: Environmental Studies.",
        "source": "https://www.chemistry.utoronto.ca/graduate/prospective-students/international-applicants ; https://www.chemistry.utoronto.ca/graduate/prospective-students/domestic-applicants ; https://www.sgs.utoronto.ca/programs/chemistry/ ; https://www.chemistry.utoronto.ca/graduate/current-students/phd-program-requirements",
    },
    "ubc-chem-phd": {
        "school": "英属哥伦比亚大学",
        "en": "PhD in Chemistry (University of British Columbia)",
        "deg": "PhD",
        "stem_label": "STEM-designated (Chemistry / CIP 40.0501)",
        "dur": "Typically 4-5 years. Direct BSc to PhD: within first 24 months must complete 12 credits with first class average (9 credits at 500+ level, 9 first class standing) to maintain doctoral registration. Research areas span analytical, biological, inorganic, organic, materials, physical, polymer, nanoscience, theoretical.",
        "ddl": "Sept 2027 intake: opens Oct 1, 2026. Scholarship priority Dec 1, 2026 11:59pm PST. Final Feb 15, 2027. Documents Mar 15, 2027. International students apply early for study permit. Top applicants in Canada/US may be eligible for in-person department visit if applied by Dec 1.",
        "lang": "TOEFL iBT 90 (R22/L22/S22/W21). IELTS 6.5 overall (no subscore below 6.0). Scores sent directly from testing center required.",
        "test_cls": "GRE NOT MANDATORY (for applicants from outside Canada/US/UK). Direct BSc to PhD requires B+ overall. With MSc: B+ in senior undergrad courses + successfully defended master thesis. 3 LOR. Statement of interest required.",
        "tui": "UBC strongly encourages international applicants to apply for direct entry to PhD (limited international MSc seats). Supervisor: browse faculty profiles and indicate in application; no commitment required before applying, but contacting faculty encouraged. Faculty research: luminescent materials, bio/chemical sensing, CO2 conversion, clean energy, atmospheric chemistry, bioanalytical, nanoscience.",
        "overview": "UBC Department of Chemistry PhD program. Research-intensive, on-campus residential in Vancouver, BC. September 2027 intake. Application opens October 1, 2026.",
        "requirements": "Online application via UBC Graduate School. 3 letters of reference. Statement of interest. Transcripts from all past post-secondary study. Official English test results sent directly from testing center by March 15, 2027. No supervisor commitment required prior to applying.",
        "research": "Analytical, Biological, Inorganic, Organic, Materials, Physical, Polymer, Nanoscience, Theoretical chemistry. Faculty include Gregory Dake (organic, bioactive, metal as catalyst), Derek Gates (inorganic, materials, polymer, catalysis), Edward Grant (spectroscopy, molecular electronic structure), Amani Hariri (biological chemistry, integrated biosensors), Jason Hein (organometallic, organocatalytic reactions), Tao Huan (bioinformatics, analytical spectrometry).",
        "source": "https://www.chem.ubc.ca/graduate-admissions ; https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-chemistry",
    },
    "mcg-chem-phd": {
        "school": "麦吉尔大学",
        "en": "PhD in Chemistry (McGill University)",
        "deg": "PhD",
        "stem_label": "STEM-designated (Chemistry / CIP 40.0501)",
        "dur": "4-5 years. PhD1 (direct from BSc): CHEM 716 first term + CHEM 717 second term. With MSc: 3 graduate courses; without MSc: 5 graduate courses. Complementary courses 9-16 credits at 500/600 level. Thesis = original scholarship. Seminars required.",
        "ddl": "Fall: opens Sep 15, international Jan 15, domestic Jun 15. Winter: opens Feb 15, international May 31, domestic Sep 30. Summer NOT considered. Rolling admissions. Institutional email required for LOR (Gmail/Yahoo/Hotmail not accepted).",
        "lang": "McGill English proficiency requirements. TOEFL/IELTS/Duolingo accepted. Allow 15 business days for score matching after testing centre sends. Note: Montreal is bilingual (French-speaking city), department is English-language.",
        "test_cls": "GRE not explicitly required on current dept page. Min cGPA: high second-class standing (above 3.00) for MSc/PhD. Direct BSc to PhD: minimum cGPA 3.7/4.0 (dept page) or 3.5 (course catalogue). 2 LOR with institutional email. Chemistry Honours/Major or related (Physics, Biochemistry) background required. Admission is competitive.",
        "tui": "Research-intensive PhD. **Supervisor chosen after arrival**: incoming students are not committed to supervisor before arriving. In early August, students receive list of professors and arrange meetings to explore research options. Research themes: Chemical Biology, Materials Chemistry (MIAM, Nanotools Facility), Synthesis/Catalysis. Historical: Soddy's transmutation, Belleau's 3TC antiviral, Ogilvie's 'gene machine'.",
        "overview": "McGill University Department of Chemistry PhD. Research-intensive program emphasizing analytical and rigorous learning. Keywords: analytical/environmental, chemical biology, chemical physics, green/sustainable, materials, synthesis/catalysis.",
        "requirements": "Online application via McGill Future Graduate Students. 2 letters of reference (referees receive automated email to upload letter and complete standardized questions). Transcripts. English proficiency scores. No summer admission. Director of Graduate Studies handles inquiries.",
        "research": "Analytical/Environmental, Chemical Biology (structural biology, enzymology, nucleic acids, signaling, single-molecule biophysics), Chemical Physics, Green/Sustainable, Materials Chemistry (MIAM, Nanotools Facility, Quebec Centre for Advanced Materials, Centre for Biorecognition and Biosensors), Synthesis/Catalysis (catalysts, synthetic methodologies, reaction mechanisms, synthetic routes to organic chemicals, natural products, materials).",
        "source": "https://www.mcgill.ca/gradapplicants/program/chemistry-phd ; https://www.mcgill.ca/chemistry/prospectivegraduate/gradadmission ; https://coursecatalogue.mcgill.ca/en/graduate/science/chemistry/",
    },
    "uw-chem-phd": {
        "school": "滑铁卢大学",
        "en": "PhD in Chemistry (University of Waterloo)",
        "deg": "PhD",
        "stem_label": "STEM-designated (Chemistry / CIP 40.0501)",
        "dur": "48 months full-time. Thesis-based. Regular option: 2 additional one-term courses beyond MSc, PhD Comprehensive Exam, 30-minute seminar, defend thesis. Direct BSc: 4 grad courses + MSc Seminar + research proposal (Y2) + Oral Comprehensive (Y5) + Research Seminar (Y7) + thesis. Co-op option available: 1 year (3 terms) industrial/government lab.",
        "ddl": "Fall (Sept): Feb 1. Winter (Jan): Jun 1 (previous year). Spring (May): Oct 1 (previous year). Domestic applications considered after deadlines (may impact awards). International students apply at least 9 months before term for study permit. Major awards: OGS, Tri-Agency, internal UW awards.",
        "lang": "TOEFL iBT 90 (writing 25, speaking 25). IELTS 7.0 (writing 6.5, speaking 6.5). Proof of English proficiency required if applicable.",
        "test_cls": "GRE AND GRE SUBJECT NOT REQUIRED (dept How to Apply page). MSc degree with minimum 75% in last 2 years (domestic). Direct BSc: outstanding students with 89% overall undergraduate standing. If BSc not in Chemistry, sufficient upper-level Chemistry content required. 3 academic references. Program-specific questions (PSQ). Transcripts.",
        "tui": "GWC (Guelph-Waterloo Centre) collaborative program. Comprehensive Exam committee: 2 Chemistry faculty + 1 from opposite campus (Guelph or Waterloo), chaired by GWC Director. Second attempt allowed 2-4 months after first. Also collaborative: Chemistry (Quantum Information) PhD with Institute for Quantum Computing (IQC), QNC building. Contact: gwc@uoguelph.ca.",
        "overview": "University of Waterloo Department of Chemistry PhD. Ranks among top of its kind in Canada. Research in analytical, biochemistry, inorganic, material, nanotechnology, organic, physical, polymer, quantum, theoretical chemistry.",
        "requirements": "Online application. Program-specific questions (PSQ). Transcripts. 3 academic references. Proof of English language proficiency. Find a research supervisor: browse faculty profiles. GWC joint program with University of Guelph.",
        "research": "Analytical Chemistry, Biological Chemistry/Biochemistry, Inorganic Chemistry, Nanoscience, Organic Chemistry, Physical Chemistry, Polymer Chemistry, Theoretical Chemistry. Collaborative: Chemistry (Quantum Information) with Institute for Quantum Computing (IQC).",
        "source": "https://uwaterloo.ca/future-graduate-students/programs/by-faculty/science/chemistry-doctor-philosophy-phd ; https://uwaterloo.ca/chemistry/graduate-students/how-apply",
    },
    "jhu-astro-phd": {
        "school": "约翰霍普金斯大学",
        "en": "PhD in Astronomy and Astrophysics (Johns Hopkins University)",
        "deg": "PhD",
        "stem_label": "STEM-designated (Astronomy / Astrophysics / CIP 40.0201)",
        "dur": "5-6 years. Research starts first semester. By end Y2: complete required graduate classes, explore research directions. Thesis research by fall of Y3. Thesis advisor form submitted before first day of Y3. MA in Astronomy (en route): 8 one-semester 3-credit grad courses + 'Language of Astrophysics' seminar + research exam. No separate terminal MS.",
        "ddl": "Fall 2027 (September): **December 15, 2026**. Applications online via Krieger Graduate Admissions. Offers by early February. Decision deadline April 15, 2027. Vivien Thomas Scholars Initiative applicants: apply by Dec 1. $75 fee (waivable). $1500 need-based relocation grant available for accepted students.",
        "lang": "TOEFL preferred: 600 paper / 250 computer / 100 iBT. IELTS accepted. Scores must be <2 years old. TOEFL ETS code 5332; IELTS institute code 4610. Exemption possible for 2+ years full-time study in US/select countries.",
        "test_cls": "GRE GENERAL AND PHYSICS GRE OPTIONAL (e-catalogue: 'Note: submission of General GRE and Physics GRE scores is optional.' Krieger School lists Physics and Astronomy under 'GRE is optional for'. Subject exams also optional. Required: SOP (research potential, creativity), 3 LOR (research capacity = most important criterion), transcripts (unofficial OK), TOEFL/IELTS. $75 fee waivable.",
        "tui": "Fully-funded PhD. Research collaboration with Johns Hopkins Applied Physics Laboratory (APL), Space Telescope Science Institute (STScI), NASA Goddard Space Flight Center. Research areas: astrophysics, AMO physics, biological physics, condensed matter, particle physics. Students nominated for department/university fellowships; advisors support NSF/NASA fellowship applications. ETS code 5332.",
        "overview": "Johns Hopkins University Zanvyl Krieger School of Arts and Sciences, William H. Miller III Department of Physics and Astronomy. PhD in Astronomy and Astrophysics. Full-time only, no part-time. No separate MS program.",
        "requirements": "Online application via Krieger Graduate Admissions. Statement of purpose. 3 letters of recommendation. Transcripts (unofficial with application; official upon admission). TOEFL/IELTS for international. $75 fee (waivable). Select 'School of Arts & Sciences - Natural Sciences' then Physics and Astronomy.",
        "research": "Astrophysics, Atomic/Molecular/Optical (AMO) physics, Biological physics, Condensed matter physics, Particle physics. Collaboration with APL, STScI, Goddard Space Flight Center. Recent research: little red dots / primordial black holes, QSO1.",
        "source": "https://e-catalogue.jhu.edu/arts-sciences/full-time-residential-programs/degree-programs/physics-astronomy/astronomy-astrophysics-phd/ ; https://physics-astronomy.jhu.edu/graduate/admissions/ ; https://krieger.jhu.edu/graduate-admissions/apply/exams/",
    },
}

# 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)}")
