# -*- coding: utf-8 -*-
"""Round 215: batch add 5 more BME PhDs
- duke-bme-phd
- col-bme-phd
- jhu-bme-phd
- upenn-bioe-phd
- ucla-bioe-phd
Reuses r214 VD fix pattern (re-locate VD Set on new_block).
"""
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": "duke-bme-phd",
        "s": "duke",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (Pratt)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years; 30 credits coursework + 2 seminars + 2 semesters TA",
        "ddl": "Fall: December 3, 2026 (guaranteed review); rolling until March 4, 2027. Spring: October 1.",
        "lang": "TOEFL iBT minimum 90 required for non-native English speakers; IELTS/Duolingo also accepted.",
        "test": {"cls": "GRE General optional; not required. Holistic review. Recent admitted UGPA ~3.7 (distribution, not minimum threshold); minimum undergraduate GPA 3.2."},
        "tui": "Fully funded: 5 years guaranteed stipend paid 12 months/year, plus paid tuition, plus 6 years health and dental coverage. More than half of BME faculty hold secondary appointments at Duke University School of Medicine.",
        "url": "details/duke-bme-phd.html",
    },
    {
        "id": "col-bme-phd",
        "s": "col",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (Fu Foundation)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; 30 points of credit beyond the MS",
        "ddl": "Fall: December 15, 2026 (PhD/MS-leading-PhD/EngScD). Spring: early October. Final fall decisions sent week of April 15.",
        "lang": "TOEFL/IELTS required for applicants whose bachelor's degree country is not English-dominant.",
        "test": {"cls": "GRE not required as of July 2026; optional. Submission not penalized. Minimum cumulative GPA 3.2 (without research credit) to register for doctoral qualifying exam."},
        "tui": "Fully funded via fellowship/RA/TA. The department is the only engineering department at Columbia that offers PhD training to MD/PhD students in partnership with Columbia University Irving Medical Center (CUIMC). MS-leading-to-PhD track available for students without a prior master's.",
        "url": "details/col-bme-phd.html",
    },
    {
        "id": "jhu-bme-phd",
        "s": "jhu",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (Whiting School of Medicine)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall: December 3, 2026, 11:59:59 pm ET (Vivien Thomas Scholars Initiative / VTSI: December 1, 2026). Offers by March; reply by April 15.",
        "lang": "TOEFL/IELTS/Cambridge English required for non-native speakers.",
        "test": {"cls": "GRE recommended but not required. Submission encouraged; no penalty for not submitting. Two offer types: rotation offer (choose lab after first-year rotations) and direct-match offer (join a specific lab from day one)."},
        "tui": "Full offer includes yearly stipend, full tuition, matriculation fee, medical and dental insurance, and paid health benefits for eligible dependent children and spouses - regardless of citizenship. Department is uniquely positioned jointly between Johns Hopkins School of Medicine and Whiting School of Engineering.",
        "url": "details/jhu-bme-phd.html",
    },
    {
        "id": "upenn-bioe-phd",
        "s": "upenn",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering (SEAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall: December 15, 2026 (application opens September 15, 2026).",
        "lang": "TOEFL iBT minimum 100 recommended; IELTS minimum 7.0; Duolingo English Test minimum 130.",
        "test": {"cls": "GRE scores no longer evaluated as part of admissions; not required. Institution code 2888 if submitted. Applicants from broad STEM backgrounds: engineering, biophysics, physics, chemistry, biology, computer science."},
        "tui": "Fully funded via fellowship/RA/TA. Combined PhD programs available: MD/PhD with Perelman School of Medicine and VMD/PhD with School of Veterinary Medicine. Medical Physics Concentration available (limited funding for radiation oncology projects).",
        "url": "details/upenn-bioe-phd.html",
    },
    {
        "id": "ucla-bioe-phd",
        "s": "ucla",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering (Samueli)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "6 years (18 quarters)",
        "ddl": "Fall only: December 1, 2026 (application opens September 1, 2026). No Winter/Spring admission.",
        "lang": "TOEFL iBT minimum 100 or IELTS overall band 8.0 for non-native English speakers.",
        "test": {"cls": "GRE optional; MCAT accepted in lieu of GRE. Final-two-years GPA minimum 3.00. Admission granted to a small cohort each year based on research capacity, recommendation letters, and written communication skills."},
        "tui": "Fully funded via fellowship/RA/TA. Requirements: pass Ph.D. Preliminary Examination, University Oral Qualifying Examination, and Final Oral Examination; complete Group I/II/III coursework. Time-to-degree within 6 years (18 quarters) with continuous registration or approved leave.",
        "url": "details/ucla-bioe-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 = {
    "duke-bme-phd": {
        "school": "Duke University",
        "en": "PhD in Biomedical Engineering (Pratt School of Engineering)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years; 30 credits coursework (life science 3cr + advanced math 3cr + additional 24cr), 2 seminars, 2 semesters TA, Responsible Conduct of Research (RCR) training, thesis and defense",
        "ddl": "Fall: December 3, 2026 (guaranteed review); rolling review until March 4, 2027 based on space/funding. Spring: October 1. All deadlines 11:59:59 pm Eastern.",
        "lang": "TOEFL iBT minimum 90 required; IELTS or Duolingo English Test accepted. Waiver may apply for some applicants.",
        "test_cls": "GRE General optional; not required. Holistic review. Recent admitted UGPA ~3.7 (distribution, not minimum threshold); minimum undergraduate GPA 3.2.",
        "tui": "Fully funded: 5 years guaranteed stipend paid 12 months/year, plus paid tuition, plus 6 years health and dental coverage. More than half of BME faculty hold secondary appointments at Duke University School of Medicine.",
        "overview": "Duke BME PhD is housed in the Pratt School of Engineering and consistently ranks among the top BME programs in the US. It emphasizes translational research with clinical partners at Duke Health. Nearly 20% of recent graduates launch into academic careers; more than 60% join leading health-technology organizations.",
        "requirements": "<ul><li>BS in engineering, physics, math, biology, or related quantitative field</li><li>Unofficial transcripts with application; official upon admission</li><li>3 letters of recommendation</li><li>Statement of Purpose and Resume/CV</li><li>TOEFL/IELTS/Duolingo (international applicants)</li><li>Writing sample (not typically required for BME)</li></ul>",
        "research": "<ul><li>Translational and preclinical imaging</li><li>Biomedical dynamics and systems biology</li><li>Biomechanics and rehabilitation engineering</li><li>Neuroengineering and neural interfaces</li><li>Biomaterials and tissue engineering</li><li>Health data science and AI in medicine</li></ul>",
        "source": '<a href="https://bme.duke.edu/phd" target="_blank">Duke BME PhD</a> | <a href="https://gradschool.duke.edu/academics/programs-degrees/biomedical-engineering/" target="_blank">Duke Graduate School BME</a>',
    },
    "col-bme-phd": {
        "school": "Columbia University",
        "en": "PhD in Biomedical Engineering (Fu Foundation School)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; 30 points of credit beyond the MS; qualifying exam after 30 points; research proposal by end of year 4",
        "ddl": "Fall: December 15, 2026 (PhD/MS-leading-PhD/EngScD). Spring: early October. Final fall decisions sent week of April 15.",
        "lang": "TOEFL/IELTS required for applicants whose bachelor's degree country is not English-dominant.",
        "test_cls": "GRE not required as of July 2026; optional. Submission not penalized. Minimum cumulative GPA 3.2 (without research credit) to register for doctoral qualifying exam.",
        "tui": "Fully funded via fellowship/RA/TA. The department is the only engineering department at Columbia that offers PhD training to MD/PhD students in partnership with Columbia University Irving Medical Center (CUIMC). MS-leading-to-PhD track available for students without a prior master's.",
        "overview": "Columbia BME PhD offers exceptional access to premier research hospitals and clinical collaborators through Columbia University Irving Medical Center (CUIMC), combined with the resources of New York City. It offers three tracks: direct PhD (for applicants with an MS), MS-leading-to-PhD (for incoming students without a master's), and MD/PhD (with Columbia Vagelos College of Physicians and Surgeons).",
        "requirements": "<ul><li>BS in engineering or a cognate scientific program</li><li>MS holders may apply directly to doctoral program</li><li>3 letters of recommendation</li><li>Personal statement, resume/CV</li><li>Publications optional</li><li>TOEFL (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical imaging and image processing</li><li>Biomechanics and mechanobiology</li><li>Neuroengineering and rehabilitation</li><li>Biomaterials and drug delivery</li><li>Medical physics and radiation oncology</li><li>Systems biology and genomics</li></ul>",
        "source": '<a href="https://www.bme.columbia.edu/biomedical-engineering/academics/graduate/phd" target="_blank">Columbia BME PhD</a> | <a href="https://bulletin.columbia.edu/columbia-engineering/academic-departments-programs/biomedical-engineering/graduate-programs/biomedical-engineering-phd/" target="_blank">Columbia Bulletin BME PhD</a>',
    },
    "jhu-bme-phd": {
        "school": "Johns Hopkins University",
        "en": "PhD in Biomedical Engineering (Whiting School of Medicine)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall: December 3, 2026, 11:59:59 pm ET (Vivien Thomas Scholars Initiative / VTSI: December 1, 2026). Offers by March; reply by April 15.",
        "lang": "TOEFL/IELTS/Cambridge English required for non-native speakers.",
        "test_cls": "GRE recommended but not required. Submission encouraged; no penalty for not submitting. Two offer types: rotation offer (choose lab after first-year rotations) and direct-match offer (join a specific lab from day one).",
        "tui": "Full offer includes yearly stipend, full tuition, matriculation fee, medical and dental insurance, and paid health benefits for eligible dependent children and spouses - regardless of citizenship. Department is uniquely positioned jointly between Johns Hopkins School of Medicine and Whiting School of Engineering.",
        "overview": "Johns Hopkins BME is widely regarded as the top-ranked biomedical engineering department in the US. It is uniquely positioned between the School of Medicine and Whiting School of Engineering, giving all students access to top clinicians, researchers, and engineers. Applications are submitted through the School of Medicine application system.",
        "requirements": "<ul><li>BS in engineering, physics, math, biology, CS, or related quantitative field</li><li>CV (may be updated before deadline)</li><li>Statement of interest and motivation</li><li>Transcripts, letters of recommendation</li><li>TOEFL/IELTS/Cambridge (international applicants)</li><li>Application fee (waived for Fall 2027)</li></ul>",
        "research": "<ul><li>Biomedical Data Science</li><li>Computational Medicine</li><li>Genomics and Systems Biology</li><li>Imaging and Medical Devices</li><li>Immunoengineering</li><li>Neuroengineering</li><li>Translational Cell and Tissue Engineering</li></ul>",
        "source": '<a href="https://www.bme.jhu.edu/academics/graduate/phd-program/apply-to-the-phd-program/" target="_blank">JHU BME PhD Apply</a> | <a href="https://e-catalogue.jhu.edu/engineering/full-time-residential-programs/degree-programs/biomedical-engineering/biomedical-engineering-phd/" target="_blank">JHU Catalogue BME PhD</a>',
    },
    "upenn-bioe-phd": {
        "school": "University of Pennsylvania",
        "en": "PhD in Bioengineering (School of Engineering and Applied Science)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall: December 15, 2026 (application opens September 15, 2026). No spring admission.",
        "lang": "TOEFL iBT minimum 100 recommended; IELTS minimum 7.0; Duolingo English Test minimum 130.",
        "test_cls": "GRE scores no longer evaluated as part of admissions; not required. Institution code 2888 if submitted. Applicants from broad STEM backgrounds: engineering, biophysics, physics, chemistry, biology, computer science.",
        "tui": "Fully funded via fellowship/RA/TA. Combined PhD programs available: MD/PhD with Perelman School of Medicine and VMD/PhD with School of Veterinary Medicine. Medical Physics Concentration available (limited funding for radiation oncology projects).",
        "overview": "Penn Bioengineering PhD trains students for research careers in academia, government, or industry. It sits at the intersection of biology, medicine, and engineering, with access to Perelman School of Medicine and Penn's clinical enterprise. No specific course requirements, but competitive applicants show strong quantitative preparation and biology foundation.",
        "requirements": "<ul><li>BS in engineering, biophysics, physics, chemistry, biology, or CS</li><li>Strong quantitative preparation (math and/or physical sciences)</li><li>Biology foundation via coursework or research experience</li><li>Statement of purpose, CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS/Duolingo (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical imaging and imaging science</li><li>Biomechanics and mechanobiology</li><li>Biomaterials and tissue engineering</li><li>Neuroengineering and neural interfaces</li><li>Medical physics and radiation oncology</li><li>Computational biology and health data science</li></ul>",
        "source": '<a href="https://be.engineering.upenn.edu/academics/doctoral/doctoral-program-admissions/" target="_blank">Penn BioE Doctoral Admissions</a> | <a href="https://gradadm.seas.upenn.edu/doctoral/" target="_blank">Penn Engineering Doctoral Programs</a>',
    },
    "ucla-bioe-phd": {
        "school": "University of California, Los Angeles",
        "en": "PhD in Bioengineering (Samueli School of Engineering)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "6 years (18 quarters)",
        "ddl": "Fall only: December 1, 2026 (application opens September 1, 2026). No Winter/Spring admission.",
        "lang": "TOEFL iBT minimum 100 or IELTS overall band 8.0 for non-native English speakers.",
        "test_cls": "GRE optional; MCAT accepted in lieu of GRE. Final-two-years GPA minimum 3.00. Admission granted to a small cohort each year based on research capacity, recommendation letters, and written communication skills.",
        "tui": "Fully funded via fellowship/RA/TA. Requirements: pass Ph.D. Preliminary Examination, University Oral Qualifying Examination, and Final Oral Examination; complete Group I/II/III coursework. Time-to-degree within 6 years (18 quarters) with continuous registration or approved leave.",
        "overview": "UCLA Bioengineering PhD is offered through the Henry Samueli School of Engineering and Applied Science. The department only admits a small cohort each year based on demonstrated capacity for original research, outstanding letters of recommendation, and communication skills. Students must pass a written preliminary exam and oral qualifying exams before advancement to candidacy.",
        "requirements": "<ul><li>BS degree or equivalent in engineering, life science, or physical science</li><li>Final-two-years GPA 3.00 minimum</li><li>3 letters of recommendation (research accomplishments, academic preparation, communication skills)</li><li>Statement of purpose and resume</li><li>Departmental application plus UCLA Graduate application</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical imaging and medical imaging devices</li><li>Biomechanics and rehabilitation engineering</li><li>Bioinformatics and computational biology</li><li>Neuroengineering and neural engineering</li><li>Biomaterials and tissue engineering</li><li>Healthcare systems and medical devices</li></ul>",
        "source": '<a href="https://grad.ucla.edu/requirements/?app=admission&major=0288" target="_blank">UCLA Graduate Admissions Bioengineering</a> | <a href="https://www.bioeng.ucla.edu/graduate-admissions/" target="_blank">UCLA BE Graduate Admissions</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)}")
