# -*- coding: utf-8 -*-
"""Round 216: batch add 5 more BME PhDs
- rice-bioe-phd
- vanderbilt-bme-phd
- uva-bme-phd
- unc-bme-phd (Lampe Joint with NC State)
- ubc-bme-phd
Note: GaTech BME PhD skipped because it is the same Coulter Department joint degree
already recorded as emory-bme-phd in round 213.
Reuses r214 VD fix pattern.
"""
import os, re

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

PROGRAMS = [
    {
        "id": "rice-bioe-phd",
        "s": "rice",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-6 years; 30 semester hours graduate-level 500+ (15 hours must be BIOE)",
        "ddl": "Fall only: December 1. Application fee waived for PhD applicants.",
        "lang": "TOEFL/IELTS required for international applicants.",
        "test": {"cls": "GRE no longer required for doctoral or masters admission, effective immediately. Holistic review. GPA 3.2+ average required for continuation."},
        "tui": "Fully funded. Located in the BioScience Research Collaborative (BRC) adjacent to the Texas Medical Center (TMC), with cross-institution partnerships with Baylor College of Medicine, Texas Children's Hospital, and MD Anderson Cancer Center. Joint MD/PhD MSTP with Baylor College of Medicine (30-year history). Cohort limited to ~20-25 entering PhD students per year.",
        "url": "details/rice-bioe-phd.html",
    },
    {
        "id": "vanderbilt-bme-phd",
        "s": "vanderbilt",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (School of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; minimum 27 semester hours didactic graduate courses (BME 15+ hours incl. BME 6110, life science 3+ hours at 6000-level)",
        "ddl": "Fall only: January 1, 2027 (final deadline January 8, 2027). December 1, 2026 is fee-waiver/priority review deadline. Offers early March; accept by April 15.",
        "lang": "TOEFL/IELTS required for international applicants.",
        "test": {"cls": "GRE Exempt - not required and not used to evaluate BME applications. No strict minimum GPA, but the department does not expect to admit students below a B average (3.0)."},
        "tui": "Fully funded via fellowship/RA/TA. Identify faculty of interest in the Personal Statement. Vanderbilt holds the highest Carnegie research university classification.",
        "url": "details/vanderbilt-bme-phd.html",
    },
    {
        "id": "uva-bme-phd",
        "s": "uva",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (SEAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; 24 graded credits of coursework past the bachelor's, plus two Elective Educational Experiences; annual Individual Development Plan (IDP)",
        "ddl": "Fall only: December 15, 2025 for Fall 2026 entry (expect Dec 15, 2026 for Fall 2027). Dec 15 deadline also required for assistantship/fellowship consideration.",
        "lang": "TOEFL iBT 90-100 recommended; IELTS 7.0+; institution code 5820 for GRE.",
        "test": {"cls": "GRE optional (waived for 2026 admission). Typical entering class average UGPA above 3.5 on a 4.0 scale (distribution, not minimum threshold). Holistic review - no negative view if scores not submitted."},
        "tui": "Fully funded via RA/TA/fellowship. Dissertation committee formed within first year; finalized by July 1 after second semester. Plan of Study due end of summer after second semester. Dissertation proposal defense required before candidacy.",
        "url": "details/uva-bme-phd.html",
    },
    {
        "id": "unc-bme-phd",
        "s": "unc",
        "n": "生物医学工程博士（Lampe联合）",
        "en": "PhD in Biomedical Engineering (Lampe Joint Department, UNC Chapel Hill × NC State)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: December 1, 2026 for Fall 2027 entry. December 19 for departmental financial support consideration. Apply through either UNC (#5816) or NC State (#5496) - both campuses evaluated identically by the joint committee.",
        "lang": "TOEFL iBT minimum 80 (Listening 18, Reading 18, Writing 18, Speaking 20). Scores no older than 24 months. IELTS or Duolingo also accepted.",
        "test": {"cls": "GRE no longer required. May be submitted if taken within 5 years. Admitted students expected average B (cumulative GPA 3.30). One-to-three page personal statement required; generic BME statements discouraged."},
        "tui": "Fully funded via NIH training grants, RA/TA. The Lampe Joint Department is administered by combined graduate faculty from UNC Chapel Hill and NC State, with close working relations with Research Triangle Institute and Research Triangle industry. Life-science degree holders without engineering background expected to make up deficiencies in first year.",
        "url": "details/unc-bme-phd.html",
    },
    {
        "id": "ubc-bme-phd",
        "s": "ubc",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (School of Biomedical Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years post-master's; students with research master's admitted directly",
        "ddl": "September 2027 intake: applications open October 15, 2026; deadline January 15, 2027 (Canadian and international same). Transcript and referee deadline January 31, 2027. Early Admission Review: December 20, 2026 (PhD Rotation-Track only).",
        "lang": "TOEFL required; institution code 0965. English proficiency self-reported during application.",
        "test": {"cls": "GRE not required. Normally requires a research master's degree in engineering or closely-related technical field (physics, biophysics, chemistry, CS). Exceptional Canadian/US bachelor's applicants with A-grade average and advanced research ability may be admitted directly to PhD."},
        "tui": "Funding via fellowship/RA/TA. Students hold a research master's as the normal point of entry; the School of Biomedical Engineering (SBME) is a pan-university school spanning engineering, medicine, and science.",
        "url": "details/ubc-bme-phd.html",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{school} - {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{font-size:24px;border-bottom:2px solid #1a73e8;padding-bottom:8px}}
h2{{font-size:18px;color:#1a73e8;margin-top:24px}}
.card{{background:#f8f9fa;border-left:4px solid #1a73e8;padding:12px 16px;margin:12px 0;border-radius:4px}}
.meta{{display:grid;grid-template-columns:120px 1fr;gap:6px 12px;font-size:14px}}
.meta b{{color:#555}}
ul{{margin:6px 0;padding-left:20px}}
.note{{background:#fff3cd;border-left-color:#ffc107;padding:10px 14px;margin-top:16px;font-size:13px}}
a{{color:#1a73e8}}
</style>
</head>
<body>
<h1>{school} - {en}</h1>
<div class="card">
<div class="meta">
<b>Degree</b><span>{deg}</span>
<b>Level</b><span>Research Doctorate (PhD)</span>
<b>STEM</b><span>Yes</span>
<b>Duration</b><span>{dur}</span>
<b>Deadline</b><span>{ddl}</span>
<b>Language</b><span>{lang}</span>
<b>Standardized</b><span>{test_cls}</span>
<b>Funding</b><span>{tui}</span>
</div>
</div>

<h2>Program Overview</h2>
<div class="card">
{overview}
</div>

<h2>Admissions Requirements</h2>
<div class="card">
{requirements}
</div>

<h2>Research Areas</h2>
<div class="card">
{research}
</div>

<h2>Official Source</h2>
<div class="card">
{source}
</div>

<div class="note">
<strong>Note:</strong> This is a research-oriented PhD program. Admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification.
</div>
</body>
</html>
"""

PAGES = {
    "rice-bioe-phd": {
        "school": "Rice University",
        "en": "PhD in Bioengineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-6 years; 30 semester hours graduate-level 500+ (15 hours must be BIOE); 3 semesters as TA; thesis proposal and public oral defense",
        "ddl": "Fall only: December 1. Application fee waived for PhD applicants. Best to start the application process before September.",
        "lang": "TOEFL/IELTS required for international applicants.",
        "test_cls": "GRE no longer required for doctoral or masters admission, effective immediately. Holistic review. GPA 3.2+ average required for continuation.",
        "tui": "Fully funded. Located in the BioScience Research Collaborative (BRC) adjacent to the Texas Medical Center (TMC), with cross-institution partnerships with Baylor College of Medicine, Texas Children's Hospital, and MD Anderson Cancer Center. Joint MD/PhD MSTP with Baylor College of Medicine (30-year history). Cohort limited to ~20-25 entering PhD students per year.",
        "overview": "Rice Bioengineering PhD is a top-ranked program located in the world's largest medical center. The department is housed in the Rice University BioScience Research Collaborative (BRC) and leverages close proximity to TMC institutions for interdisciplinary research. Prerequisites include System Physiology (BIOE 322 or equivalent), Cell Biology (BIOC 341 or equivalent), and Statistics.",
        "requirements": "<ul><li>BS in engineering, physics, math, biology, or related quantitative field</li><li>Prerequisites: System Physiology, Cell Biology, Statistics</li><li>Statement of Purpose, CV, transcripts</li><li>3 letters of recommendation (submitted via SLATE, not before September 1)</li><li>TOEFL/IELTS (international applicants)</li><li>Application fee waived</li></ul>",
        "research": "<ul><li>Biomedical imaging and sensors</li><li>Biomechanics and mechanobiology</li><li>Biomaterials and drug delivery</li><li>Neuroengineering and neural interfaces</li><li>Systems and synthetic biology</li><li>Regenerative medicine and tissue engineering</li></ul>",
        "source": '<a href="https://bioengineering.rice.edu/academics/phd-program" target="_blank">Rice BioE PhD</a> | <a href="https://bioengineering.rice.edu/academics/frequently-asked-questions" target="_blank">Graduate FAQ</a>',
    },
    "vanderbilt-bme-phd": {
        "school": "Vanderbilt University",
        "en": "PhD in Biomedical Engineering (School of Engineering)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; minimum 27 semester hours didactic graduate courses (BME 15+ hours incl. BME 6110, life science 3+ hours at 6000-level)",
        "ddl": "Fall only: January 1, 2027 (final deadline January 8, 2027). December 1, 2026 is fee-waiver/priority review deadline. Offers early March; accept by April 15.",
        "lang": "TOEFL/IELTS required for international applicants.",
        "test_cls": "GRE Exempt - not required and not used to evaluate BME applications. No strict minimum GPA, but the department does not expect to admit students below a B average (3.0).",
        "tui": "Fully funded via fellowship/RA/TA. Identify faculty of interest in the Personal Statement. Vanderbilt holds the highest Carnegie research university classification.",
        "overview": "Vanderbilt BME PhD admits only for Fall semester. Didactic credits cannot be taken on a Pass/Fail basis. The program requires students to identify faculty of interest and list them in the Personal Statement for matching.",
        "requirements": "<ul><li>BS in engineering, physics, math, biology, or related quantitative field</li><li>Statement of Purpose (identify faculty of interest)</li><li>CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li><li>Course deficiencies should be made up at an accredited institution before enrollment</li></ul>",
        "research": "<ul><li>Biomedical imaging and image-guided intervention</li><li>Neuroengineering and neurotechnology</li><li>Biomaterials and tissue engineering</li><li>Biomechanics and rehabilitation</li><li>Health data science and AI in medicine</li><li>Molecular and cellular bioengineering</li></ul>",
        "source": '<a href="https://engineering.vanderbilt.edu/departments/biomedical-engineering/graduate-programs/" target="_blank">Vanderbilt BME Graduate Programs</a> | <a href="https://engineering.vanderbilt.edu/academics/graduate/?program=1128" target="_blank">Engineering Graduate Deadlines</a>',
    },
    "uva-bme-phd": {
        "school": "University of Virginia",
        "en": "PhD in Biomedical Engineering (SEAS)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; 24 graded credits of coursework past the bachelor's, plus two Elective Educational Experiences; annual Individual Development Plan (IDP)",
        "ddl": "Fall only: December 15 for Fall entry. Dec 15 deadline also required for assistantship/fellowship consideration. M.E. rolling review December-July.",
        "lang": "TOEFL iBT 90-100 recommended; IELTS 7.0+; institution code 5820 for GRE.",
        "test_cls": "GRE optional (waived for 2026 admission). Typical entering class average UGPA above 3.5 on a 4.0 scale (distribution, not minimum threshold). Holistic review - no negative view if scores not submitted.",
        "tui": "Fully funded via RA/TA/fellowship. Dissertation committee formed within first year; finalized by July 1 after second semester. Plan of Study due end of summer after second semester. Dissertation proposal defense required before candidacy.",
        "overview": "UVA BME PhD is a research doctoral degree for students pursuing research careers in academia, government, or industry. Students entering with a prior MS in engineering from outside UVA must still take core BME courses, completing at least 12 credit hours of graduate-level coursework.",
        "requirements": "<ul><li>Bachelor's degree from an accredited college or university</li><li>Completed application packet with short essay and letters of recommendation</li><li>Statement of Purpose, CV, transcripts</li><li>TOEFL/IELTS (international applicants)</li><li>Deficiencies in prerequisites may be admitted with expectation of remediation during master's-level study</li></ul>",
        "research": "<ul><li>Biomedical imaging and medical image analysis</li><li>Biomechanics and rehabilitation engineering</li><li>Biomaterials and tissue engineering</li><li>Computational bioengineering and systems biology</li><li>Neuroengineering</li><li>Medical devices and translational research</li></ul>",
        "source": '<a href="https://engineering.virginia.edu/department/biomedical-engineering/apply-bme" target="_blank">UVA BME Apply</a> | <a href="https://records.ureg.virginia.edu/preview_program.php?catoid=57&poid=8684" target="_blank">UVA BME PhD Program</a>',
    },
    "unc-bme-phd": {
        "school": "UNC Chapel Hill × NC State",
        "en": "PhD in Biomedical Engineering (Lampe Joint Department)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 1, 2026 for Fall 2027 entry. December 19 for departmental financial support consideration. Apply through either UNC (#5816) or NC State (#5496) - both campuses evaluated identically by the joint committee.",
        "lang": "TOEFL iBT minimum 80 (Listening 18, Reading 18, Writing 18, Speaking 20). Scores no older than 24 months. IELTS or Duolingo also accepted.",
        "test_cls": "GRE no longer required. May be submitted if taken within 5 years. Admitted students expected average B (cumulative GPA 3.30). One-to-three page personal statement required; generic BME statements discouraged.",
        "tui": "Fully funded via NIH training grants, RA/TA. The Lampe Joint Department is administered by combined graduate faculty from UNC Chapel Hill and NC State, with close working relations with Research Triangle Institute and Research Triangle industry. Life-science degree holders without engineering background expected to make up deficiencies in first year.",
        "overview": "The Lampe Joint Department of Biomedical Engineering Graduate Program is administered by combined biomedical engineering graduate faculty from both NC State University and UNC Chapel Hill. The joint program has close working relations with Research Triangle Institute and industry within the Research Triangle area. Students may apply through either campus and are evaluated as a single cohort.",
        "requirements": "<ul><li>BS in engineering or a quantitative science</li><li>Good working knowledge of math through differential equations, plus two years physical/engineering science and basic biological science</li><li>3 letters of recommendation (from research advisors/faculty)</li><li>1-3 page personal statement identifying research interests and specific faculty</li><li>TOEFL/IELTS/Duolingo (international applicants)</li><li>Life/physical science degree holders expected to make up engineering/advanced math/physics deficiencies</li></ul>",
        "research": "<ul><li>Biomedical imaging and optical imaging</li><li>Biomechanics and mechanobiology</li><li>Biomaterials and tissue engineering</li><li>Neuroengineering and neural interfaces</li><li>Biomedical data science and AI</li><li>Regenerative medicine and drug delivery</li></ul>",
        "source": '<a href="https://catalog.unc.edu/graduate/schools-departments/biomedical-engineering/biomedical-engineering.pdf" target="_blank">UNC Lampe BME Catalogue</a> | <a href="https://bme.unc.edu/" target="_blank">Lampe BME Department</a>',
    },
    "ubc-bme-phd": {
        "school": "University of British Columbia",
        "en": "PhD in Biomedical Engineering (School of Biomedical Engineering)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years post-master's; students with research master's admitted directly",
        "ddl": "September 2027 intake: applications open October 15, 2026; deadline January 15, 2027 (Canadian and international same). Transcript and referee deadline January 31, 2027. Early Admission Review: December 20, 2026 (PhD Rotation-Track only).",
        "lang": "TOEFL required; institution code 0965. English proficiency self-reported during application.",
        "test_cls": "GRE not required. Normally requires a research master's degree in engineering or closely-related technical field (physics, biophysics, chemistry, CS). Exceptional Canadian/US bachelor's applicants with A-grade average and advanced research ability may be admitted directly to PhD.",
        "tui": "Funding via fellowship/RA/TA. Students hold a research master's as the normal point of entry; the School of Biomedical Engineering (SBME) is a pan-university school spanning engineering, medicine, and science.",
        "overview": "UBC School of Biomedical Engineering (SBME) is a pan-university school that spans engineering, medicine, and science. The PhD normally requires a research master's degree as the entry point, though exceptional bachelor's applicants from Canadian/US institutions with A-grade averages and advanced research ability may be admitted directly.",
        "requirements": "<ul><li>Research master's in engineering or closely-related technical field (physics, biophysics, chemistry, CS)</li><li>Life sciences/kinesiology/physical therapy degrees considered only with adequate technical preparation</li><li>Exceptional bachelor's applicants (A-grade average + advanced research) may be admitted directly</li><li>Statement of Purpose, CV, transcripts</li><li>3 references (referee deadline January 31, 2027)</li><li>TOEFL (institution code 0965)</li></ul>",
        "research": "<ul><li>Biomedical imaging and medical imaging</li><li>Biomechanics and rehabilitation engineering</li><li>Biomaterials and regenerative medicine</li><li>Neuroengineering and neural interfaces</li><li>Biomedical data science and AI</li><li>Systems biology and molecular bioengineering</li></ul>",
        "source": '<a href="https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-biomedical-engineering" target="_blank">UBC Grad School BME PhD</a> | <a href="https://bme.ubc.ca/education/prospective-graduate-students/applications-admissions/application-instructions-2/" target="_blank">UBC SBME Application Instructions</a>',
    },
}

# Write detail pages
for p in PROGRAMS:
    key = p["id"]
    d = PAGES[key]
    html = DETAIL_TEMPLATE.format(
        school=d["school"], en=d["en"], deg=d["deg"], dur=d["dur"],
        ddl=d["ddl"], lang=d["lang"], test_cls=d["test_cls"], tui=d["tui"],
        overview=d["overview"], requirements=d["requirements"],
        research=d["research"], source=d["source"],
    )
    path = os.path.join(DET, key + ".html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Wrote: {key}.html")

# Append PROGRAMS
idx_path = os.path.join(BASE, "index_main.html")
with open(idx_path, "r", encoding="utf-8") as f:
    html = f.read()

def build_entry(p):
    return ('{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
            'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},'
            'tui:"{tui}",url:"{url}"}}').format(
        id=p["id"], s=p["s"], n=p["n"], en=p["en"], deg=p["deg"], lvl=p["lvl"],
        stem=p["stem"], dur=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"].replace('"', "'"),
        tui=p["tui"].replace('"', "'"), url=p["url"],
    )

new_entries = ",\n".join(build_entry(p) for p in PROGRAMS)

m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[': depth += 1
    elif c == ']': depth -= 1
    i += 1
insert_pos = i - 1
prefix = html[:insert_pos].rstrip()
suffix = html[insert_pos:]
if prefix.endswith('{'):
    new_block = prefix + "\n" + new_entries + "\n" + suffix
else:
    new_block = prefix + ",\n" + new_entries + "\n" + suffix

# Append VD on new_block (re-locate to avoid offset)
vd_entries = ",\n".join(f'"{p["url"]}"' for p in PROGRAMS)
m2 = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', new_block)
vstart = m2.end()
vdepth = 1
j = vstart
while j < len(new_block) and vdepth > 0:
    c = new_block[j]
    if c == '[': vdepth += 1
    elif c == ']': vdepth -= 1
    j += 1
vinsert_pos = j - 1
vprefix = new_block[:vinsert_pos].rstrip()
vsuffix = new_block[vinsert_pos:]
if vprefix.endswith(','):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
elif vprefix.endswith('['):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
else:
    new_block = vprefix + ",\n" + vd_entries + "\n" + vsuffix

with open(idx_path, "w", encoding="utf-8") as f:
    f.write(new_block)

print(f"Appended {len(PROGRAMS)} PROGRAMS entries and {len(PROGRAMS)} VD entries")
print(f"Done. File size: {os.path.getsize(idx_path)}")
