# -*- coding: utf-8 -*-
"""Round 214: batch add 5 BME/BMI PhDs
- stanford-biom-phd (Biomedical Informatics)
- ucsd-bioe-phd
- cornell-bme-phd
- umich-bme-phd
- nu-bme-phd
Reuses r212 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": "stanford-biom-phd",
        "s": "stanford",
        "n": "生物医学信息学博士",
        "en": "PhD in Biomedical Informatics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years (135 units; 52 formal coursework units)",
        "ddl": "Fall only: December 1 (early December). Interviews early Jan; offers mid-March; reply by April 15.",
        "lang": "TOEFL/IELTS required for non-native English speakers.",
        "test": {"cls": "GRE not required; not considered if submitted."},
        "tui": "Fully funded via fellowship/RA/TA combination. NLM training grant available to US citizens/permanent residents (tuition+stipend+health insurance). International PhD students eligible for Stanford fellowship/RA support.",
        "url": "details/stanford-biom-phd.html",
    },
    {
        "id": "ucsd-bioe-phd",
        "s": "ucsd",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: December 2, 2026, 11:59:59 PST. No Winter/Spring admission.",
        "lang": "TOEFL/IELTS required; minimum speaking score per Graduate Division.",
        "test": {"cls": "GRE no longer required since Fall 2022; not recommended to submit."},
        "tui": "Fully funded: fellowship/traineeship/TA/GSR combination; stipend per UCOP-UAW Collective Bargaining Agreement; covers tuition, fees, and health insurance. GPA 3.4+ in technical courses expected (distribution, not minimum threshold).",
        "url": "details/ucsd-bioe-phd.html",
    },
    {
        "id": "cornell-bme-phd",
        "s": "cornell",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (Meinig School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "Fall only: December 1. No spring admission.",
        "lang": "TOEFL/IELTS required per Cornell Graduate School.",
        "test": {"cls": "GRE not required or accepted; applications reviewed blinded for GRE."},
        "tui": "Fully funded: fellowship/RA/TA combination. NYC Linkage Program: increased stipend + subsidized housing for thesis work in NYC labs (Weill Cornell / Cornell Tech).",
        "url": "details/cornell-bme-phd.html",
    },
    {
        "id": "umich-bme-phd",
        "s": "umich",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "Fall only: December 1, 2026 (PhD). MS deadline January 15, 2027.",
        "lang": "TOEFL/IELTS required per Rackham Graduate School.",
        "test": {"cls": "GRE neither required nor accepted."},
        "tui": "Fully funded: fellowship/RA/TA combination. Joint department of Michigan Engineering and U-M Medical School. Coulter Translational Research Partnership supports clinical translation.",
        "url": "details/umich-bme-phd.html",
    },
    {
        "id": "nu-bme-phd",
        "s": "nu",
        "n": "生物医学工程博士",
        "en": "PhD in Biomedical Engineering (McCormick)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "Fall only: December 1, 2026, 11:59 PM Central Time.",
        "lang": "TOEFL/IELTS required.",
        "test": {"cls": "GRE not required and not accepted."},
        "tui": "All admitted PhD students fully funded: University/school fellowship, external fellowship, RA, or TA. Minimum stipend $46,356/year (2025/26) for 5 years, paid year-round. Very few new PhD students enter with a master's degree.",
        "url": "details/nu-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 = {
    "stanford-biom-phd": {
        "school": "Stanford University",
        "en": "PhD in Biomedical Informatics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; 135 units total, of which 52 are formal coursework units",
        "ddl": "Fall only: December 1 (early December). Interview invitations early January; interviews late February/early March; offers rolling from mid-March; reply by April 15.",
        "lang": "TOEFL/IELTS required for non-native English speakers.",
        "test_cls": "GRE not required; not considered if submitted.",
        "tui": "Fully funded via fellowship/RA/TA combination. NLM training grant (US citizens/permanent residents) covers tuition+stipend+health insurance. International PhD students supported through Stanford fellowship/RA appointments.",
        "overview": "Stanford Biomedical Informatics PhD is an interdisciplinary program housed in the Department of Biomedical Data Science (DBDS), jointly between the School of Medicine and School of Engineering. It trains researchers to develop computational methods for biomedicine, spanning bioinformatics, clinical informatics, and imaging informatics.",
        "requirements": "<ul><li>BS in a quantitative field (CS, stats, engineering, biology, or related)</li><li>CV, Statement of Purpose, transcripts</li><li>3 letters of recommendation (no Interfolio/mail/fax)</li><li>TOEFL/IELTS (international applicants)</li><li>Do not upload papers/theses/writing samples</li></ul>",
        "research": "<ul><li>Bioinformatics and computational biology</li><li>Clinical informatics and electronic health records</li><li>Imaging informatics and medical image analysis</li><li>Machine learning for healthcare</li><li>Genomics and precision medicine</li><li>Health data science and AI</li></ul>",
        "source": '<a href="https://dbds.stanford.edu/for-prospective-students/" target="_blank">DBDS Prospective Students</a> | <a href="https://med.stanford.edu/bmi/prospective-students/PhD-degree-biomedical-informatics.html" target="_blank">BMI PhD at Stanford Medicine</a>',
    },
    "ucsd-bioe-phd": {
        "school": "UC San Diego",
        "en": "PhD in Bioengineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 2, 2026, 11:59:59 PST. No Winter/Spring admission. JDP (Joint Doctoral Program with San Diego State) deadline December 1.",
        "lang": "TOEFL/IELTS required; minimum speaking score per UCSD Graduate Division.",
        "test_cls": "GRE no longer required since Fall 2022; not recommended to submit.",
        "tui": "Fully funded: fellowship/traineeship/TA/GSR combination; stipend per UCOP-UAW Collective Bargaining Agreement; covers tuition, fees, and health insurance for academic year (Fall/Winter/Spring). Good academic standing (GPA 3.4+) required for continued support.",
        "overview": "The Shu Chien - Gene Lay Department of Bioengineering at UC San Diego offers a research PhD with specializations in bioinformatics, computational neuroscience, multiscale biology, and quantitative biology. The department only offers financial support to PhD students (MS students are self-funded).",
        "requirements": "<ul><li>BS and/or MS in engineering, natural sciences, mathematics, or quantitative life sciences</li><li>GPA 3.4+ in technical courses (distribution, not minimum threshold)</li><li>Statement of Purpose, CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical imaging and imaging devices</li><li>Bioinformatics and systems biology</li><li>Biomechanics and mechanobiology</li><li>Computational neuroscience</li><li>Tissue engineering and regenerative medicine</li><li>Biomedical devices and sensors</li></ul>",
        "source": '<a href="https://be.ucsd.edu/grad/prospective-students" target="_blank">UCSD BioE Prospective Students</a> | <a href="https://be.ucsd.edu/grad/prospective-students/admissions/faq" target="_blank">Graduate FAQ</a>',
    },
    "cornell-bme-phd": {
        "school": "Cornell University",
        "en": "PhD in Biomedical Engineering (Meinig School)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years",
        "ddl": "Fall only: December 1. No spring admission.",
        "lang": "TOEFL/IELTS required per Cornell Graduate School.",
        "test_cls": "GRE not required or accepted; applications reviewed blinded for GRE scores.",
        "tui": "Fully funded: fellowship/RA/TA combination. NYC Linkage Program: increased stipend + subsidized housing for students whose thesis is based in NYC labs (Weill Cornell Medicine / Cornell Tech).",
        "overview": "The Meinig School of Biomedical Engineering at Cornell offers a research PhD organized within the Cornell Graduate Field of Biomedical Engineering, with faculty from Ithaca, Weill Cornell Medicine, and Cornell Tech. The field focuses on quantitative understanding of human biology from molecules to organs.",
        "requirements": "<ul><li>BS in a recognized engineering subdiscipline; exceptional BS in sciences with advanced math/calculus physics/intro CS also considered</li><li>Statement of Purpose, CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Biomedical instrumentation and devices</li><li>Drug delivery, design, and metabolism</li><li>Biomaterials and tissue engineering</li><li>Computational and systems biology</li><li>Medical biomechanics</li><li>Neuroengineering</li></ul>",
        "source": '<a href="https://www.bme.cornell.edu/bme/programs/graduate-programs/phd-program" target="_blank">Meinig School BME PhD</a> | <a href="https://gradschool.cornell.edu/academics/fields-of-study/subject/biomedical-engineering/biomedical-engineering-phd-ithaca/" target="_blank">Graduate Field BME</a>',
    },
    "umich-bme-phd": {
        "school": "University of Michigan, Ann Arbor",
        "en": "PhD in Biomedical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years",
        "ddl": "Fall only: December 1, 2026 (PhD). MS deadline January 15, 2027.",
        "lang": "TOEFL/IELTS required per Rackham Graduate School.",
        "test_cls": "GRE neither required nor accepted.",
        "tui": "Fully funded: fellowship/RA/TA combination. Joint department of Michigan Engineering and U-M Medical School. Coulter Translational Research Partnership supports clinical translation of student research.",
        "overview": "U-M Biomedical Engineering is a joint department of the top-ranked Michigan Engineering and U-M Medical School. The program has 56 core faculty, 152 PhD students, and annual research expenditures of $32M. It welcomes applicants from engineering, math, physics, chemistry, and biology backgrounds.",
        "requirements": "<ul><li>BS in engineering, math, physics, chemistry, or biology</li><li>Statement of Purpose, CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li><li>PhD application workshop recorded annually in October</li></ul>",
        "research": "<ul><li>Biomaterials and regenerative medicine</li><li>Biomedical imaging and MRI</li><li>Biomechanics and rehabilitation</li><li>Computational biology and bioinformatics</li><li>Neuroengineering and neural interfaces</li><li>Medical devices and translational research</li></ul>",
        "source": '<a href="https://bme.umich.edu/academics/graduate/graduate-admissions/" target="_blank">UMich BME Graduate Admissions</a>',
    },
    "nu-bme-phd": {
        "school": "Northwestern University",
        "en": "PhD in Biomedical Engineering (McCormick)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years",
        "ddl": "Fall only: December 1, 2026, 11:59 PM Central Time.",
        "lang": "TOEFL/IELTS required.",
        "test_cls": "GRE not required and not accepted.",
        "tui": "All admitted PhD students fully funded: University/school fellowship, external fellowship, RA, or TA. Minimum stipend $46,356/year (2025/26) for 5 years, paid year-round across 4 quarters. Very few new PhD students enter with a master's degree.",
        "overview": "Northwestern BME PhD is offered through the Robert R. McCormick School of Engineering and Applied Science. Applications due by December 1 are automatically considered for school and university fellowships. Exceptional students are encouraged to apply for external fellowships (NSF, NIH, DoD, nonprofit organizations).",
        "requirements": "<ul><li>BS in engineering, physics, math, or related quantitative field</li><li>Statement of Purpose, CV, transcripts</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 intervention</li><li>Biomechanics and mechanobiology</li><li>Bioinformatics and computational biology</li><li>Neuroengineering and neural engineering</li><li>Biomaterials and drug delivery</li><li>Healthcare systems and medical devices</li></ul>",
        "source": '<a href="https://www.mccormick.northwestern.edu/biomedical/academics/graduate/phd/admissions.html" target="_blank">Northwestern BME PhD Admissions</a> | <a href="https://www.tgs.northwestern.edu/success/funding-resources/" target="_blank">TGS Funding Resources</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
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)}")
