# -*- coding: utf-8 -*-
"""Round 272: Immunology PhD second wave - UCSD BMS, UPenn BGS Immunology, Columbia IP-CMBS Immunology, UMich PIBS Immunology, UChicago Immunology."""
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": "ucsd-bms-phd",
        "s": "ucsd",
        "n": "Biomedical Sciences PhD (Immunology track)",
        "en": "Biomedical Sciences Graduate Program PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "5-6 years",
        "ddl": "Dec 2, 2026 (11:59 PM PST)",
        "lang": "TOEFL iBT min 85 / IELTS 7.0 / Duolingo 120 (university-wide minimum)",
        "ets": "4836 (no department code)",
        "gre": "GRE General and Subject Tests: not required since 2018; optional self-reported scores considered",
        "tui": "Full tuition waiver + stipend + health insurance for all admitted PhD students (NIH T32 and training-grant support)",
        "url": "details/ucsd-bms-phd.html",
        "school": "UC San Diego",
        "title": "Biomedical Sciences PhD (Immunology track)",
        "overview": "The UCSD Biomedical Sciences (BMS) Graduate Program is an umbrella PhD program that trains students across biomedical disciplines including Immunology, Cancer Biology, Molecular Biology, and Genetics. Students complete first-year rotations and select a thesis lab from over 180 BMS-affiliated faculty. Immunology is one of several tracks within BMS.",
        "field": "Biomedical Sciences / Immunology",
        "reqs": "BMS unified application; 3 rotations in Year 1; thesis advisor declared by end of Year 1; qualifying exam by end of Year 2; dissertation defense. Minimum cumulative GPA 3.0. Recommended courses: calculus, biochemistry, organic and physical chemistry, biology, cell and molecular biology, mammalian physiology.",
        "opens": "September 2, 2026",
        "fee": "Waivable (BMS fee waiver for international students opened Sep 2, 2026; closes Nov 1)",
        "interviews": "Zoom interviews January 14, 15, 19-22 and 25, 2027; in-person recruitment weekend March 4, 2027",
        "funding": "All admitted PhD students receive a package including full tuition waiver, competitive stipend, and health insurance. Support is renewed annually contingent on satisfactory academic progress.",
        "note1": "BMS is the umbrella biomedical PhD at UCSD; Immunology is one of several tracks. UCSD Neurosciences PhD (NGP) is a separate program (code NE75) with an earlier Nov 19 deadline.",
        "note2": "GRE policy has been optional since 2018; applicants who choose to submit self-reported scores are not penalized for absence.",
        "note3": "No faculty contact required before applying; admissions is holistic based on academic record, research experience, letters, and statement.",
        "source_url": "https://biomedsci.ucsd.edu/how-to-apply/phd-program1.html",
    },
    {
        "id": "upenn-bgs-immunology-phd",
        "s": "upenn",
        "n": "Immunology PhD (BGS)",
        "en": "Immunology Graduate Group PhD, Biomedical Graduate Studies",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "~5.8 years average time to degree",
        "ddl": "Dec 1, 2026 (11:59 PM ET)",
        "lang": "TOEFL iBT / IELTS / Duolingo accepted; no minimum score required (English proficiency required for non-native speakers)",
        "ets": "Penn ETS code (use institutional code from application)",
        "gre": "BGS does not require or accept GRE scores (general or subject tests) since July 2018; application explicitly states GRE should not be submitted by BGS applicants",
        "tui": "Full fellowship: competitive stipend $49,000 effective Fall 2026 + tuition + fees + health insurance",
        "url": "details/upenn-bgs-immunology-phd.html",
        "school": "University of Pennsylvania",
        "title": "Immunology PhD (BGS)",
        "overview": "The Immunology Graduate Group is one of 15 graduate groups within Penn's Biomedical Graduate Studies (BGS) at Perelman School of Medicine. BGS is the unified umbrella PhD application for basic biomedical sciences at Penn. Immunology faculty span 35 academic departments across 7 schools including Perelman, Veterinary, Dental, Arts and Sciences, Engineering, Wharton, and Nursing. Students may also train at the Wistar Institute, Children's Hospital of Philadelphia Research Institute, and the NIH Graduate Partnership Program.",
        "field": "Immunology",
        "reqs": "Apply via BGS; personal statement on motivations for PhD in Immunology; 3 letters of recommendation; CV/r\u00e9sum\u00e9 (do not include GPA or GRE information on CV); transcripts; one BGS group only per application. Approximately 85% of enrolled students complete the degree.",
        "opens": "October 1, 2026",
        "fee": "Application fee (waivable via fee waiver request)",
        "interviews": "Recruitment weekend typically in late January/early February; offers released by early March; acceptances due April 15",
        "funding": "All BGS students receive a full fellowship package including competitive stipend, tuition, fees, and health insurance. Stipend is $49,000 effective Fall 2026.",
        "note1": "BGS allows application to only one graduate group per cycle; students in good academic standing may apply to transfer groups during Year 1.",
        "note2": "BGS explicitly does not accept GRE scores since July 2018; submitted scores will not be reviewed.",
        "note3": "Immunology group is one of 15 BGS groups including Biochemistry & Molecular Biophysics, Cell & Molecular Biology, Cancer Biology, Genetics and Epigenetics, Neuroscience, Pharmacology, and others.",
        "source_url": "https://www.cceb.upenn.edu/bgs/admissions-faqs.html",
    },
    {
        "id": "columbia-ipcmbs-immunology-phd",
        "s": "col",
        "n": "Microbiology & Immunology PhD (IP-CMBS)",
        "en": "Doctoral Program in Microbiology, Immunology and Infection, Integrated Program in Cellular, Molecular and Biomedical Studies",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "5-6 years",
        "ddl": "Dec 2, 2026 (11:59 PM ET)",
        "lang": "TOEFL iBT 100 / IELTS 7.5 / Duolingo accepted",
        "ets": "2162 (GSAS) or 2619 (Vagelos); no department code required",
        "gre": "GRE General: no longer required; submitted scores may be considered (Vagelos VIBRE FAQ: GREs are not required for all programs, though you may submit them)",
        "tui": "Full tuition waiver + 12-month stipend + health insurance (guaranteed 5 years)",
        "url": "details/columbia-ipcmbs-immunology-phd.html",
        "school": "Columbia University",
        "title": "Microbiology & Immunology PhD (IP-CMBS)",
        "overview": "The Doctoral Program in Microbiology, Immunology and Infection is based in the Department of Microbiology & Immunology at Columbia's Vagelos College of Physicians and Surgeons. It is one of the specialized research and training areas within the Integrated Program in Cellular, Molecular and Biomedical Studies (IP-CMBS), the Coordinated Doctoral Program in Biomedical Sciences at Columbia University Medical Center. The program bridges modern molecular biology with research on infectious disease and immunology.",
        "field": "Microbiology, Immunology, Infection",
        "reqs": "Apply via VIBRE PhD Pathway; personal statement; CV/r\u00e9sum\u00e9; 3-4 letters of recommendation; transcripts; must specify Microbiology & Immunology / Immunology as area of interest. Students who already hold a PhD (or equivalent M.Phil + 3 years doctoral coursework) are not eligible.",
        "opens": "September 2026",
        "fee": "Waivable",
        "interviews": "Open House typically early February and mid-February; applicants invited by email at least two weeks before each Open House",
        "funding": "Vagelos VIBRE PhD students receive a comprehensive package: full tuition waiver, competitive 12-month stipend, and health insurance for the duration of PhD training (typically 5 years).",
        "note1": "VIBRE (Vagelos Institutes of Biomedical Research Education) is the unified PhD application umbrella at Columbia's medical center; Immunology is one track within it.",
        "note2": "GRE is not required but may be submitted (no more than 5 years old). No minimum GRE score requirement.",
        "note3": "Columbia GSAS main campus Biological Sciences PhD (Morningside) is a separate application with a Dec 2 deadline and GRE not required.",
        "source_url": "https://microbiology.columbia.edu/home",
    },
    {
        "id": "umich-pibs-immunology-phd",
        "s": "umich",
        "n": "Immunology PhD (PIBS)",
        "en": "Immunology PhD Program, Program in Biomedical Sciences",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "~5.5 years average",
        "ddl": "Dec 1, 2026 (11:59 PM EST)",
        "lang": "TOEFL / IELTS accepted (Rackham Graduate School minimums)",
        "ets": "1839 (Rackham); program code 01416",
        "gre": "GRE scores are not required for either direct or PIBS admissions; submitted scores are not reviewed",
        "tui": "Full tuition waiver + competitive stipend + health insurance for all admitted PhD students",
        "url": "details/umich-pibs-immunology-phd.html",
        "school": "University of Michigan",
        "title": "Immunology PhD (PIBS)",
        "overview": "The University of Michigan Immunology Graduate Program is an interdisciplinary PhD program within the Program in Biomedical Sciences (PIBS). More than 54 faculty members from the Medical School, Pharmacy, Dentistry, and the College of Literature, Science and the Arts (LSA) provide graduate training in immunology. Over 50% of the Immunology faculty are in clinical departments, providing unprecedented opportunities for translational research.",
        "field": "Immunology",
        "reqs": "Apply via PIBS (one application covers 14 PhD programs); specify Immunology as first choice. Minimum 18 credit hours of didactic graduate-level coursework; maintain 3.0 cumulative GPA; complete lab rotations; pass preliminary exam (written + oral); conduct original research and defend dissertation; first-author primary research publication in press before defense (waivers considered under exceptional circumstances).",
        "opens": "Early September 2026",
        "fee": "Waivable",
        "interviews": "Interviews typically in January; offers released by March 30",
        "funding": "All PIBS PhD students receive a comprehensive package including full tuition waiver, competitive stipend, and health insurance. Support is renewed annually contingent on satisfactory academic progress.",
        "note1": "PIBS is the unified gateway for 14 PhD programs at U-M Medical School; one application is sufficient to be considered across all programs.",
        "note2": "GRE not required for either PIBS or direct admissions; submitted scores are not reviewed.",
        "note3": "U-M also has a separate Department of Microbiology & Immunology PhD (also via PIBS); the standalone Immunology Graduate Program is an interdisciplinary track drawing faculty across multiple schools.",
        "source_url": "https://medschool.umich.edu/interdisciplinary-programs/immunology-graduate-program/phd-program",
    },
    {
        "id": "uchicago-immunology-phd",
        "s": "uchicago",
        "n": "Immunology PhD (Biomedical Sciences cluster)",
        "en": "Immunology PhD Program, Biomedical Sciences Cluster",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "stem_label": "STEM-designated",
        "dur": "5-6 years",
        "ddl": "Dec 1, 2026 (11:59 PM CST)",
        "lang": "TOEFL iBT min 100 (pre-Jan 21, 2026) / 5/5.5/4.5 (post-Jan 21, 2026); IELTS 7.0 (7.0 each subscore)",
        "ets": "1832 (no department code)",
        "gre": "GRE test scores are optional for all PhD programs; submitted scores (within 5 years) considered; Subject tests also optional",
        "tui": "Full tuition waiver + competitive 12-month stipend + health insurance (guaranteed 5 years)",
        "url": "details/uchicago-immunology-phd.html",
        "school": "University of Chicago",
        "title": "Immunology PhD (Biomedical Sciences cluster)",
        "overview": "The Immunology PhD Program at the University of Chicago is part of the Biomedical Sciences Cluster within the Biological Sciences Division (BSD). The cluster also includes Cancer Biology, Microbiology, and Molecular Metabolism. UChicago Biosciences offers a unified application that allows students to apply to up to 4 PhD programs across BSD. The program emphasizes research experience, with 97 students per class and 365 training faculty.",
        "field": "Immunology",
        "reqs": "Apply via UChicago Biosciences unified application; personal statement; 3 letters of recommendation (at least one from a research mentor); CV/r\u00e9sum\u00e9; transcripts. Students may apply to up to 4 BSD programs in order of preference. Interviews are required; students invited to formal recruitment weekends.",
        "opens": "Early September 2026",
        "fee": "$90 (waivable)",
        "interviews": "Formal recruitment weekends typically in late January/early February; decisions by late February",
        "funding": "All admitted Biosciences PhD students receive full tuition waiver, competitive 12-month stipend, and health insurance for the duration of PhD training. Support is independent of domestic/international status.",
        "note1": "Immunology is in the Biomedical Sciences Cluster (alongside Cancer Biology, Microbiology, Molecular Metabolism), not the Molecular Biosciences Cluster.",
        "note2": "GRE is optional for all PhD programs; if submitted, must be taken within 5 years of Dec 1, 2026 deadline.",
        "note3": "BSD allows up to 4 program choices on a single application; units communicate directly with the student.",
        "source_url": "https://biosciences.uchicago.edu/admissions/how-to-apply",
    },
]

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):
    # Find PROGRAMS array end by bracket depth
    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
    # i now points just after the closing ]
    insert_pos = i - 1  # position of the closing ]
    # Ensure previous record ends with comma
    before = html[:insert_pos].rstrip()
    if before and not before.endswith(","):
        before = before + ","
    after = html[insert_pos:]
    html = before + "\n" + new_block + "\n" + after

    # Re-scan for VD Set( on the new html
    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
    # j points just after the closing ]; need to find the matching ) too
    # j is position after ]; skip whitespace and expect )
    vd_close = j  # position of ]
    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()
