# -*- coding: utf-8 -*-
"""Round 213: batch add 5 BME PhDs
- uw-bme-phd (Waterloo)
- yale-bme-phd
- brown-bme-phd
- wustl-bme-phd
- emory-bme-phd (Emory x Georgia Tech joint)
Reuses r212 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": "uw-bme-phd",
        "s": "uw",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years (research thesis-based)",
        "ddl": "3 intakes: Sep (Feb 1), Jan (Jun 1), May (Oct 1). Supervisor required before admission.",
        "lang": "TOEFL/IELTS required (English proficiency per Waterloo ECE graduate minimums)",
        "test": {"cls": "GRE not listed as required"},
        "tui": "Competitive Engineering graduate funding (GRS/RA/TA). Tuition per term; PhD housing guarantee available.",
        "url": "details/uw-bme-phd.html",
    },
    {
        "id": "yale-bme-phd",
        "s": "yale",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: December 15, 11:59 PM ET. No spring admission.",
        "lang": "TOEFL iBT or IELTS Academic required of non-native English speakers (exempt if 3+ years at English-medium undergrad).",
        "test": {"cls": "GRE optional for PhD; MS track requires GRE."},
        "tui": "12-month stipend (BBS/Physical Sciences floor $52,046 for 2026-27) + full fellowship covering tuition + student healthcare. One-time $1,500 relocation award in year 1.",
        "url": "details/yale-bme-phd.html",
    },
    {
        "id": "brown-bme-phd",
        "s": "brown",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years (guaranteed support)",
        "ddl": "Fall only: December 1, 2026 (11:59 PM ET). Interviews Feb-Mar.",
        "lang": "English proficiency required for international applicants.",
        "test": {"cls": "GRE General and Subject not required / optional."},
        "tui": "Guaranteed 5-year support: stipend + tuition remission + health-services fee + health-insurance subsidy. Mostly RA at 20 hrs/week; some fellowships (Graduate School / School of Engineering).",
        "url": "details/brown-bme-phd.html",
    },
    {
        "id": "wustl-bme-phd",
        "s": "wustl",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: December 15 (11:59 PM ET). Decisions by March 15; reply by April 15.",
        "lang": "TOEFL 100+ (no subscore below 20) for international applicants; scores within 2 years.",
        "test": {"cls": "GRE optional for 2026-27 (neither helps nor hurts)."},
        "tui": "Fully funded: full tuition + health and dental insurance + living stipend. About 1/3 of BME PhD students hold external fellowships. Named awards: Olin-Chancellor's Fellowship, McDonnell International Scholars Academy.",
        "url": "details/wustl-bme-phd.html",
    },
    {
        "id": "emory-bme-phd",
        "s": "emory",
        "n": "生物医学工程博士（Emory×Georgia Tech 联合）",
        "en": "PhD in Biomedical Engineering (Emory-Georgia Tech Joint BME)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: December 1, 2026 (11:59 PM ET). Decisions by April 15.",
        "lang": "TOEFL/IELTS required (scores within 2 years); credential evaluation recommended for international transcripts.",
        "test": {"cls": "GRE not required; not considered in review."},
        "tui": "Stipend $43,260/year (PhD union CBA) + full tuition scholarship + 100% health-insurance subsidy. 5-year guaranteed; tuition scholarship up to 7 years. Woodruff Fellowship: +$5,000/year stipend + fees covered 5 years.",
        "url": "details/emory-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 = {
    "uw-bme-phd": {
        "school": "University of Waterloo",
        "en": "PhD in Biomedical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years, research thesis-based",
        "ddl": "3 intakes per year: September (apply by February 1), January (apply by June 1), May (apply by October 1). A supervisor must be secured before an offer is extended.",
        "lang": "TOEFL/IELTS required; English proficiency per Waterloo School of Engineering graduate minimums.",
        "test_cls": "GRE not listed as required.",
        "tui": "Competitive Engineering graduate funding package (GRS/RA/TA combination). Tuition per term; PhD housing guarantee available for eligible students.",
        "overview": "Waterloo's BME PhD is a thesis-based research degree housed in the Faculty of Engineering. Students may enter with a relevant MASc (80%+ average) or via direct entry from an Honours BME undergraduate degree (80%+ average). A confirmed faculty supervisor is required before admission. Substantial research experience is expected.",
        "requirements": "<ul><li>Research thesis-based master's in engineering/applied science/science with at least 80% overall average; OR direct-entry from Honours BME undergraduate with 80% average</li><li>Confirmed faculty supervisor before application/offer</li><li>3 letters of reference (at least 2 academic)</li><li>Curriculum vitae, transcripts</li><li>Plan of Research / Statement of research interests</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Biomaterials and biomechanics</li><li>Medical imaging and biosensors</li><li>Biomedical devices and instrumentation</li><li>Neuroengineering and neural interfaces</li><li>Regenerative medicine and tissue engineering</li><li>Health technology and data analytics</li></ul>",
        "source": '<a href="https://uwaterloo.ca/future-graduate-students/programs/by-faculty/engineering/biomedical-engineering-doctor-philosophy-phd" target="_blank">Waterloo BME PhD Program Page</a>',
    },
    "yale-bme-phd": {
        "school": "Yale University",
        "en": "PhD in Biomedical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 15, 11:59 PM ET. No spring admission.",
        "lang": "TOEFL iBT or IELTS Academic required of applicants whose native language is not English; exempt if undergraduate degree at an English-medium institution for 3+ years.",
        "test_cls": "GRE optional for PhD; MS track requires GRE.",
        "tui": "12-month stipend (BBS/Physical Sciences floor $52,046 for 2026-27; Biological & Biomedical Sciences $53,629) + full fellowship covering tuition + student healthcare. One-time $1,500 relocation award in year 1.",
        "overview": "Yale BME PhD is offered through the Graduate School of Arts and Sciences (GSAS) and Yale School of Engineering and Applied Science (SEAS). Applicants may apply with a BS in engineering, physics, chemistry, computer science, or mathematics. The program admits only students who will be fully funded.",
        "requirements": "<ul><li>BS in engineering or related field (physics/chemistry/CS/math/materials)</li><li>Statement of Purpose, transcripts, CV</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li><li>Application fee (waiver available)</li></ul>",
        "research": "<ul><li>Biomedical imaging and image-guided therapy</li><li>Bioinformatics and computational biology</li><li>Biomechanics and mechanobiology</li><li>Neural engineering</li><li>Tissue engineering and regenerative medicine</li><li>Biomedical devices and biosensors</li></ul>",
        "source": '<a href="https://gsas.yale.edu/programs-of-study/biomedical-engineering" target="_blank">Yale GSAS BME</a> | <a href="https://seas.yale.edu/graduate-study/admissions" target="_blank">Yale SEAS Graduate Admissions</a> | <a href="https://gsas.yale.edu/resources/graduate-financial-aid/phd-stipends" target="_blank">PhD Stipends 2026-27</a>',
    },
    "brown-bme-phd": {
        "school": "Brown University",
        "en": "PhD in Biomedical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years (guaranteed support)",
        "ddl": "Fall only: December 1, 2026 (11:59 PM ET). Selected applicants interviewed February-March.",
        "lang": "English proficiency required for international applicants.",
        "test_cls": "GRE General and Subject not required / optional.",
        "tui": "Guaranteed 5-year support: stipend + tuition remission + health-services fee + health-insurance subsidy. Most PhD students supported by RA at 20 hrs/week; some named Graduate School / School of Engineering fellowships.",
        "overview": "Brown BME PhD is run through the Institute for Biology, Engineering and Medicine (I-BEAM). It sits at the interface of engineering, biology and medicine, with four complementary research areas. Students take engineering, biology and medical school courses and gain clinical experience at nearby Warren Alpert Medical School teaching hospitals.",
        "requirements": "<ul><li>BS in engineering, physics, applied math, or computer science; life-science BS accepted with documented quantitative coursework</li><li>3 letters of recommendation</li><li>Personal statement</li><li>CV/Resume</li><li>Indicate BME PhD Program on application</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Neuroengineering</li><li>Biosensors and bioplatforms</li><li>Mechanobiology</li><li>Tissue engineering and regenerative medicine</li><li>Medical imaging and data science</li><li>Biomedical devices and translational medicine</li></ul>",
        "source": '<a href="https://ibeam.brown.edu/education-and-training/bme-graduate-program/doctoral-program/phd-admissions-requirements" target="_blank">I-BEAM BME PhD Admissions</a> | <a href="https://graduateprograms.brown.edu/graduate-program/biomedical-engineering-phd" target="_blank">Brown Graduate Programs BME PhD</a>',
    },
    "wustl-bme-phd": {
        "school": "Washington University in St. Louis",
        "en": "PhD in Biomedical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 15 (11:59 PM ET). Decision by March 15; reply by April 15.",
        "lang": "TOEFL 100+ (no subscore below 20) for international applicants; scores within 2 years.",
        "test_cls": "GRE optional for 2026-27; neither helps nor hurts admission.",
        "tui": "Fully funded: full tuition + health and dental insurance + living stipend. About 1/3 of BME PhD students hold external fellowships. Named awards: Ann W. & Spencer T. Olin-Chancellor's Fellowship; McDonnell International Scholars Academy.",
        "overview": "WashU BME PhD is offered through the McKelvey School of Engineering. The department also offers combined MD/PhD degrees with the School of Medicine. Typical admitted PhD students have GPA around 3.7/4.0 (historical distribution, not minimum threshold).",
        "requirements": "<ul><li>BS in engineering, physical sciences, or mathematics; life-science BS accepted with quantitative coursework evidence</li><li>3 letters of recommendation</li><li>Statement of Purpose</li><li>CV/Resume</li><li>Transcripts</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical imaging and imaging sciences</li><li>Biomechanics and mechanobiology</li><li>Bioinformatics and computational biology</li><li>Biomedical devices and sensors</li><li>Neuroengineering and neural interfaces</li><li>Therapeutic engineering and drug delivery</li></ul>",
        "source": '<a href="https://bme.wustl.edu/academics/graduate-programs/" target="_blank">WashU BME Graduate Programs</a> | <a href="https://engineering.wustl.edu/academics/graduate-admissions/deadlines.html" target="_blank">McKelvey Engineering Deadlines</a>',
    },
    "emory-bme-phd": {
        "school": "Emory University (joint with Georgia Tech)",
        "en": "PhD in Biomedical Engineering (Emory-Georgia Tech Joint)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 1, 2026 (11:59 PM ET). Decisions by April 15.",
        "lang": "TOEFL/IELTS required (scores within 2 years); course-by-course credential evaluation recommended for international transcripts.",
        "test_cls": "GRE not required; not considered in review (no field in application).",
        "tui": "Stipend $43,260/year (PhD union CBA) + full tuition scholarship + 100% health-insurance subsidy. 5-year guaranteed; tuition scholarship up to 7 years. George W. Woodruff Fellowship: +$5,000/year stipend + all student fees covered for 5 years.",
        "overview": "Emory BME PhD is a joint program between Emory University Laney Graduate School and the Georgia Institute of Technology (Woodruff School of Mechanical Engineering). Applicants apply through Georgia Tech BME admissions. The program emphasizes interdisciplinary biomedical research in Atlanta's clinical and biotech ecosystem (Emory Healthcare, CDC, Georgia Tech).",
        "requirements": "<ul><li>Strong BS background in physical, biological, or behavioral sciences</li><li>Cumulative B+ or better in major science courses</li><li>3 letters of recommendation (research mentors prioritized)</li><li>Statement of Purpose (recommended <=2 pages double-spaced)</li><li>CV/Resume, transcripts</li><li>TOEFL/IELTS (international applicants)</li><li>Application fee $75 (waiver available)</li></ul>",
        "research": "<ul><li>Biomedical imaging and image analysis</li><li>Bioinformatics and computational biology</li><li>Biomechanics and rehabilitation engineering</li><li>Neuroengineering and neural interfaces</li><li>Cancer bioengineering and therapeutics</li><li>Health informatics and clinical data science</li></ul>",
        "source": '<a href="https://biomed.emory.edu/admissions/apply.html" target="_blank">Emory GDBBS Apply</a> | <a href="https://gs.emory.edu/admissions/finance_overview.html" target="_blank">Laney Graduate School Financial Support</a> | <a href="https://www.gradschool.emory.edu/admissions/program-admissions-requirements.html" target="_blank">Program Deadlines</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 to index_main.html
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)

# Step 1: append 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

# Step 2: append VD on new_block
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)}")
