# -*- coding: utf-8 -*-
"""Round 273: Immunology PhD third wave - Duke, JHU, Emory IMP, UBC MicroImm, McGill MicroImm."""
import os, re, json

ROOT = r"D:\work buddy\2026-11-05-14-15-52"
INDEX = os.path.join(ROOT, "index_main.html")
DETAILS = os.path.join(ROOT, "details")

DETAIL_TEMPLATE = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>{title} | {school}</title>
<link rel="stylesheet" href="../style.css">
</head><body class="det">
<header class="det-hdr"><a class="back" href="../index_main.html">← Back to Program Database</a></header>
<main>
<h1>{title}</h1>
<p class="meta">{school} · {deg} · {lvl_label} · {stem_label}</p>

<section class="card"><h2>Overview</h2><p>{overview}</p></section>

<section class="card"><h2>Degree &amp; Requirements</h2><ul>
<li><strong>Degree:</strong> {deg}</li>
<li><strong>Field:</strong> {field}</li>
<li><strong>Typical duration:</strong> {duration}</li>
<li><strong>STEM-designated:</strong> {stem_label}</li>
<li><strong>Degree requirements:</strong> {reqs}</li>
</ul></section>

<section class="card"><h2>Application Deadline</h2><ul>
<li><strong>Deadline:</strong> {ddl}</li>
<li><strong>Application opens:</strong> {opens}</li>
<li><strong>Fee:</strong> {fee}</li>
<li><strong>Interviews:</strong> {interviews}</li>
</ul></section>

<section class="card"><h2>Language &amp; Standardized Tests</h2><ul>
<li><strong>English proficiency:</strong> {lang}</li>
<li><strong>TOEFL institution code:</strong> {ets}</li>
<li><strong>GRE policy:</strong> {gre}</li>
</ul></section>

<section class="card"><h2>Funding &amp; Stipend</h2><p>{funding}</p></section>

<section class="card"><h2>Notes</h2><ul>
<li>{note1}</li>
<li>{note2}</li>
<li>{note3}</li>
</ul></section>

<section class="card"><h2>Official Source</h2><p><a href="{source_url}" target="_blank" rel="noopener">{source_url}</a></p></section>
</main></body></html>
"""

PAGES = [
    {
        "id": "duke-immunology-phd",
        "s": "duke",
        "n": "Immunology PhD",
        "en": "PhD in Immunology, Department of Integrative Immunobiology",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "5-6 years",
        "ddl": "Dec 1, 2026 (11:59 PM EST)",
        "lang": "TOEFL iBT min 90 / IELTS 7.0 / Duolingo 125 (Graduate School minimums; admitted average above)",
        "ets": "5156 (Duke Graduate School; no department code needed)",
        "gre": "GRE General: Optional per Duke Graduate School (submitted scores reviewed; absence not penalized). GRE Subject: not required.",
        "tui": "100% of students receive financial aid; full tuition waiver + stipend + health insurance",
        "url": "details/duke-immunology-phd.html",
        "school": "Duke University",
        "title": "Immunology PhD",
        "overview": "The Department of Integrative Immunobiology offers graduate training in molecular and cellular immunology at Duke University. The department hosts 35 graduate faculty and 37 graduate students, with research topics spanning adaptive immunity, innate immunity, antigen receptor gene recombination and hypermutation, immune signaling pathways, and lymphocyte development. The program integrates seminars, journal clubs, group meetings, and student teaching.",
        "field": "Immunology / Integrative Immunobiology",
        "reqs": "Apply via Duke Graduate School; 3 letters of recommendation; Statement of Purpose (required); Resume/CV (required); unofficial transcripts (official upon admission). Undergraduate GPA calculated on 4.0 scale. Holistic review of academic performance, research experience, letters of reference, evidence of resilience, and commitment to science service.",
        "opens": "Early September 2026",
        "fee": "Application fee (waiver available case-by-case; built into application system for eligible applicants)",
        "interviews": "Virtual interviews late December; on-campus recruitment visit February; decisions shortly thereafter",
        "funding": "100% of PhD students receive financial aid including full tuition waiver, competitive stipend, and health insurance. Average class size is 6 students; ~180 applications received per year, 25-30 invited for interviews.",
        "note1": "Duke MSTP (MD-PhD) students may apply to the Immunology Graduate Training Program during their second year of medical school.",
        "note2": "GRE General is optional; if self-reported scores are entered, official scores become a required component.",
        "note3": "Fall admission only; no spring admission.",
        "source_url": "https://gradschool.duke.edu/academics/programs-degrees/immunology/",
    },
    {
        "id": "jhu-immunology-phd",
        "s": "jhu",
        "n": "Immunology PhD (School of Medicine)",
        "en": "Graduate Program in Immunology, Johns Hopkins School of Medicine",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "~5.4-5.7 years average time to degree",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL iBT recommended; admitted international students typically score above 550 paper-based equivalent. TOEFL/IELTS valid 2 years from expected entrance.",
        "ets": "5316 (Johns Hopkins School of Medicine)",
        "gre": "GRE scores are not required and will not be considered in the admissions process. Applicants should not submit GRE scores (policy since October 2019).",
        "tui": "Guaranteed financial support per JHU PhD Union Collective Bargaining Agreement (CBA); minimum rate of pay $52,000 for 2026-27; tuition covered; student health benefits included.",
        "url": "details/jhu-immunology-phd.html",
        "school": "Johns Hopkins University",
        "title": "Immunology PhD (School of Medicine)",
        "overview": "The Graduate Program in Immunology at Johns Hopkins School of Medicine is a PhD training program based on the East Baltimore and Bayview campuses. As of August 2026, the program enrolls 28 students. In 2026, the program admitted 3 students from a pool of 282 applicants. The program offers interdisciplinary training across immunology faculty at the school of medicine.",
        "field": "Immunology",
        "reqs": "Apply via the School of Medicine graduate application; 3 letters of recommendation; CV/r\u00e9sum\u00e9; one-page personal statement describing motivation for science career and research experience, concluding with a concise explanation of why Johns Hopkins Immunology; transcripts from all colleges/universities attended. Acceptance is dependent on an invited personal interview for international applicants.",
        "opens": "September 8, 2026",
        "fee": "$125 (current Apply Now page; older catalog PDF lists $115)",
        "interviews": "In-person interviews expected; invitations extended mid-December; on-campus recruitment typically in February",
        "funding": "All PhD students receive guaranteed financial support per the JHU PhD Union CBA. For 2026-27, the minimum rate of pay is $52,000. Tuition is covered and eligible PhD students receive student health benefits. Support is contingent on the terms of the CBA.",
        "note1": "JHU has TWO separate Immunology PhD programs: (1) School of Medicine Graduate Program in Immunology (this entry), and (2) Bloomberg School of Public Health PhD in Molecular Microbiology and Immunology (MMI, GRE optional).",
        "note2": "GRE is not required and will not be considered; applicants should not submit GRE scores.",
        "note3": "VTSI (Vivian Thomas Scholars Initiative) eligible students may apply for additional funding; VTSI application and SOPHAS materials due Dec 1, 2026; fee waiver request by Nov 15, 2026.",
        "source_url": "https://gradimmunology.med.som.jhmi.edu/apply-now/",
    },
    {
        "id": "emory-immunology-imp-phd",
        "s": "emory",
        "n": "Immunology and Molecular Pathogenesis PhD (IMP)",
        "en": "Immunology and Molecular Pathogenesis (IMP) PhD, Graduate Division of Biological and Biomedical Sciences",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "~5.5-6 years",
        "ddl": "Dec 1, 2026 (11:59 PM PST)",
        "lang": "TOEFL / IELTS required for non-native English speakers; scores must be no more than 2 years old from date of application",
        "ets": "Emory ETS code (use institutional code from application)",
        "gre": "GRE scores are not required by any GDBBS program; there is no field to enter GRE information in the application. Submitted scores will not be considered.",
        "tui": "Tuition scholarship + health insurance + stipend guaranteed for all GDBBS PhD students",
        "url": "details/emory-immunology-imp-phd.html",
        "school": "Emory University",
        "title": "Immunology and Molecular Pathogenesis PhD (IMP)",
        "overview": "The Immunology and Molecular Pathogenesis (IMP) program is one of eight interdisciplinary PhD programs within Emory's Graduate Division of Biological and Biomedical Sciences (GDBBS). The IMP program offers interdisciplinary training in molecular and cellular immunology and the role of the immune system in the pathogenesis of infectious disease. Faculty are affiliated with basic science and clinical departments in the School of Medicine, the Emory Vaccine Center, the Emory National Biomedical Research Center, and the adjacent U.S. Centers for Disease Control and Prevention (CDC).",
        "field": "Immunology / Molecular Pathogenesis",
        "reqs": "Apply via GDBBS unified application; 3 letters of recommendation; Statement of Purpose (recommended no longer than two pages double-spaced); Resume/CV; transcripts (official upon admission). Strong undergraduate background in physical, biological, or behavioral sciences; cumulative average of B+ or better in major science courses; high motivation for biomedical research; strong letters of recommendation (research mentor letters weighted most heavily).",
        "opens": "Early September 2026",
        "fee": "$75 (waivable for certain prep-program participants or financial hardship)",
        "interviews": "Invited interviews typically in January; recruitment visit weekend February; decisions by early March",
        "funding": "All GDBBS PhD students receive a guaranteed package including tuition scholarship, health insurance, and competitive stipend. Support is renewed annually contingent on satisfactory academic progress.",
        "note1": "GDBBS is the umbrella for 8 interdisciplinary PhD programs at Emory; ~400 total graduate students; ~330 faculty across basic science and clinical departments.",
        "note2": "GRE scores are not required by any GDBBS program; there is no field to enter GRE information in the application.",
        "note3": "Emory IMP has unique access to the CDC and Emory Vaccine Center for infectious disease and translational immunology research.",
        "source_url": "https://biomed.emory.edu/#top",
    },
    {
        "id": "ubc-microbiology-immunology-phd",
        "s": "ubc",
        "n": "Microbiology and Immunology PhD",
        "en": "Doctor of Philosophy in Microbiology and Immunology, Faculty of Science / Faculty of Medicine",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "4-5 years",
        "ddl": "Sept 2027 intake: Feb 15, 2027 (Canadian and International); transcript/referee deadline Mar 15, 2027. May 2027 intake: Nov 30, 2026.",
        "lang": "TOEFL iBT / IELTS required for non-native English speakers (UBC graduate minimums)",
        "ets": "UBC ETS code (use institutional code from application)",
        "gre": "GRE is not required per UBC Graduate and Postdoctoral Studies program listing.",
        "tui": "Minimum support $22,000/year for 4 years (PhD); TA/GRA opportunities",
        "url": "details/ubc-microbiology-immunology-phd.html",
        "school": "University of British Columbia",
        "title": "Microbiology and Immunology PhD",
        "overview": "The PhD in Microbiology and Immunology at UBC is a research-intensive graduate program based in the Department of Microbiology and Immunology. Faculty research spans geobiology, biogeochemistry, microbial evolution, host-microbe interactions, and molecular immunology. The program is part of UBC's Faculty of Science and Faculty of Medicine collaborative graduate training.",
        "field": "Microbiology, Immunology",
        "reqs": "Apply via UBC Graduate and Postdoctoral Studies; 3 letters of reference; Statement of Interest; transcripts from all past post-secondary study. All applicants need firm commitment from a supervisor prior to applying. Browse faculty directory and contact potential thesis supervisors before submitting application.",
        "opens": "Sept 30, 2026 (Sept 2027 intake)",
        "fee": "UBC application fee (CAD)",
        "interviews": "Supervisor interview prior to application; admissions decisions follow faculty review",
        "funding": "PhD students receive minimum support of $22,000/year for 4 years, supplemented by TA/GRA appointments and research grants. UBC Fellowship and Tri-Council awards available on a competitive basis.",
        "note1": "UBC M&I is a supervisor-before-offer program: applicants must secure a commitment from a faculty supervisor before the application is reviewed.",
        "note2": "Two intakes per year: May (deadline Nov 30) and September (deadline Feb 15).",
        "note3": "3 references required; transcript and referee deadlines are 2 weeks after the application deadline.",
        "source_url": "https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-microbiology-immunology",
    },
    {
        "id": "mcgill-microbiology-immunology-phd",
        "s": "mcg",
        "n": "Microbiology and Immunology PhD",
        "en": "Doctor of Philosophy in Microbiology and Immunology, Department of Microbiology & Immunology, Faculty of Medicine & Health Sciences",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "4-5 years",
        "ddl": "Fall 2027: International Jan 15, 2027; Canadian/Permanent Resident Jun 21, 2027. Winter: International Aug 1; Domestic Nov 10. Summer: International Oct 1; Domestic Apr 1.",
        "lang": "Proof of English proficiency required for non-native speakers; official test results sent directly to McGill",
        "ets": "0935 (McGill University)",
        "gre": "GRE not required per McGill Department of Microbiology & Immunology (no GRE field in Slate application).",
        "tui": "Research stipend + tuition support via supervisor grants and fellowships; NSERC and Quebec FRQNT awards available",
        "url": "details/mcgill-microbiology-immunology-phd.html",
        "school": "McGill University",
        "title": "Microbiology and Immunology PhD",
        "overview": "The Doctor of Philosophy in Microbiology and Immunology at McGill University is a research-intensive program offered by the Department of Microbiology & Immunology in the Faculty of Medicine & Health Sciences. The program emphasizes cutting-edge and experiential learning opportunities, original thinking, knowledge synthesis, and academic writing. The department fosters close ties with hospitals and research centres across Montreal to promote multidisciplinary research.",
        "field": "Microbiology, Immunology",
        "reqs": "Eligible Bachelor's degree with minimum 3.0/4.0 GPA; apply via Slate (McGill online application); CV; one-page Personal Statement indicating interest in the program; transcripts; Supervisor Confirmation Form (signed by both supervisor and applicant, uploaded to supporting documentation). All applicants must approach academic staff directly during or before the application process; no applicants are accepted without a supervisor.",
        "opens": "Sept 15, 2026 (Fall term)",
        "fee": "McGill application fee (CAD)",
        "interviews": "Supervisor interview prior to application; admissions committee review after Slate submission",
        "funding": "PhD students are supported through supervisor research grants, teaching assistantships, and external fellowships (NSERC, FRQNT). Stipend levels vary by supervisor and award.",
        "note1": "Supervisor Confirmation Form is mandatory: an application will not be considered unless the form is fully completed, signed by both the supervisor and the applicant, and uploaded to Slate.",
        "note2": "Fall admission is the primary intake; Winter and Summer intakes available but international deadlines differ.",
        "note3": "3 LOR with institutional email required; gmail/yahoo/hotmail not accepted.",
        "source_url": "https://www.mcgill.ca/gradapplicants/program/microbiology-and-immunology-phd",
    },
]

def write_detail(page):
    html = DETAIL_TEMPLATE.format(**page)
    out = os.path.join(DETAILS, page["id"] + ".html")
    with open(out, "w", encoding="utf-8") as f:
        f.write(html)
    print("Wrote:", os.path.relpath(out, ROOT))
    return out

def build_programs_block(pages):
    lines = []
    for p in pages:
        lines.append(
            '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{gre}"}},tui:"{tui}",url:"{url}"}}'.format(**p)
        )
    return ",\n".join(lines)

def append_programs_and_vd(html, new_block):
    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS start not found")
    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
    before = html[:insert_pos].rstrip()
    if before and not before.endswith(","):
        before = before + ","
    after = html[insert_pos:]
    html = before + "\n" + new_block + "\n" + after

    m2 = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[", html)
    if not m2:
        raise RuntimeError("VD Set start not found")
    vstart = m2.end()
    depth = 1
    j = vstart
    while j < len(html) and depth > 0:
        c = html[j]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
        j += 1
    vd_close = j
    before_vd = html[:vd_close].rstrip()
    if before_vd and not before_vd.endswith(","):
        before_vd = before_vd + ","
    new_vd_items = ",".join('"{}"'.format(p["url"]) for p in PAGES)
    after_vd = html[vd_close:]
    html = before_vd + "\n" + new_vd_items + "\n" + after_vd
    return html

def main():
    for p in PAGES:
        p["lvl_label"] = "Doctoral" if p["lvl"] == "d" else "Master's"
        p["duration"] = p["dur"]
        write_detail(p)
    with open(INDEX, "r", encoding="utf-8") as f:
        html = f.read()
    block = build_programs_block(PAGES)
    html = append_programs_and_vd(html, block)
    with open(INDEX, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Appended {len(PAGES)} PROGRAMS entries and {len(PAGES)} VD entries")
    print("Done. File size:", os.path.getsize(INDEX))

if __name__ == "__main__":
    main()
