# -*- coding: utf-8 -*-
# r271: Batch add 5 more basic-science PhD entries
# 1. UBC Neuroscience PhD (Vancouver)
# 2. McGill Integrated Program in Neuroscience (IPN) PhD
# 3. Stanford Immunology PhD (Biosciences family)
# 4. Harvard Immunology PhD (HILS)
# 5. Yale Immunobiology PhD (via BBS)
# Skipped UofT (only Collaborative Specialization, no independent Neuroscience PhD)
# Skipped Waterloo (no independent Neuroscience PhD; Cognitive Neuroscience is a Psychology PhD research field)
import os, re, json

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

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{font-size:24px;border-bottom:3px solid #1a4480;padding-bottom:8px}}
h2{{font-size:18px;color:#1a4480;margin-top:28px;border-left:4px solid #1a4480;padding-left:10px}}
.card{{background:#f7f9fc;border:1px solid #d8e1ee;border-radius:8px;padding:14px 18px;margin:10px 0}}
.label{{color:#666;font-size:13px}}
.val{{font-weight:600;color:#111}}
a{{color:#1a4480}}
.tag{{display:inline-block;background:#e8f0fb;color:#1a4480;border-radius:4px;padding:2px 8px;font-size:12px;margin-right:6px}}
</style>
</head>
<body>
<h1>{title}</h1>
<div class="card">
<div class="label">School</div><div class="val">{school}</div>
<div class="label">Program</div><div class="val">{en}</div>
<div class="label">Degree</div><div class="val">{deg}</div>
<div class="label">STEM</div><div class="val">{stem_label}</div>
</div>
<h2>1. Degree & Curriculum</h2>
<div class="card">{curriculum}</div>
<h2>2. Application Deadline</h2>
<div class="card">{ddl}</div>
<h2>3. Language Requirement</h2>
<div class="card">{lang}</div>
<h2>4. Standardized Tests</h2>
<div class="card">{test}</div>
<h2>5. Tuition & Funding</h2>
<div class="card">{tui}</div>
<h2>6. Source</h2>
<div class="card">{src}</div>
<p><a href="index_main.html">&larr; Back to Program Index</a></p>
</body>
</html>
"""

PAGES = [
    {
        "id": "ubc-neuroscience-phd",
        "s": "ubc",
        "n": "英属哥伦比亚大学神经科学博士",
        "en": "Neuroscience PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4 years typical (full-time research)",
        "ddl": "September 2027 Intake: Application opens 15 July 2026; Canadian and International applicants deadline 15 November 2026; Transcript and Referee deadline 1 December 2026.",
        "lang": "TOEFL iBT 100 overall (Reading 22 / Writing 21 / Speaking 21 / Listening 22); IELTS Academic 7.0 overall (minimum 6.5 each band). Tests must be taken within 24 months of application.",
        "test": {"cls": "GRE NOT REQUIRED per UBC Faculty of Graduate and Postdoctoral Studies program listing (grad.ubc.ca). No GRE field in application."},
        "tui": ("Acceptance is contingent on securing a faculty supervisor who agrees to mentor and financially support the student. "
                "Research supervisors must commit to minimum financial support of $22,000 CAD per year for 4 years (PhD students), which may be composed of external awards (CIHR, NSERC, MSFHR, etc.) combined with supervisor research funds. "
                "Program receives 100+ applications for approximately 25 spots per year (highly competitive). "
                "B+ (76% at UBC) minimum academic average required for Canadian/US credentials; higher for international credentials. "
                "Applications not supported by a faculty supervisor cannot be admitted even if academically strong. "
                "Encouraged to contact faculty whose research interests match the applicant before applying."),
        "url": "details/ubc-neuroscience-phd.html",
        "title": "University of British Columbia Neuroscience PhD",
        "school": "University of British Columbia (Vancouver) - Faculty of Graduate and Postdoctoral Studies, Neuroscience Graduate Program",
        "curriculum": ("Research-based PhD in Neuroscience at UBC Vancouver. "
                       "Students work with a faculty supervisor across multiple participating departments (including the Djavad Mowafaghian Centre for Brain Health). "
                       "Program covers cellular and molecular neuroscience, systems and behavioral neuroscience, cognitive neuroscience, computational neuroscience, and clinical/translational neuroscience. "
                       "No fixed course curriculum; program tailored to student's research project and supervisor's guidance. "
                       "Students normally begin at start of Winter Session (early September). "
                       "Note: UBC Neuroscience is a research degree; meeting the minimum academic requirement does not guarantee admission because positions depend on supervisor availability and funding."),
        "src": "https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-neuroscience ; https://med-neuroscience-2021.sites.olt.ubc.ca/files/2021/10/Neuroscience-Prospective-Students-Fact-Sheet-Sep-2022-entry.pdf"
    },
    {
        "id": "mcgill-ipn-phd",
        "s": "mcg",
        "n": "麦吉尔大学整合神经科学博士",
        "en": "Integrated Program in Neuroscience (IPN) PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years (full-time thesis-based)",
        "ddl": ("Fall 2027 (September) entry: International application deadline 15 January 2027; Deadline to Find a Supervisor 2 March 2027. "
                "Canadian application deadline 21 June 2027; Find a Supervisor 13 July 2027. "
                "PhD Rotation applicants: final application deadline 1 December 2026. "
                "Winter 2027 (January) entry: Canadian application 10 November 2026; Find a Supervisor 1 December 2026; International application 31 July 2026; Find a Supervisor 1 October 2026. "
                "Note: IPN does not accept Summer semester admissions (only Fall and Winter)."),
        "lang": "English proficiency test required for non-native English speakers (TOEFL iBT / IELTS Academic accepted per McGill Graduate and Postdoctoral Studies).",
        "test": {"cls": "GRE NOT REQUIRED per IPN FAQ (mcgill.ca/ipn). No GRE field in application. Per McGill policy, reference letters must be submitted from institutional email addresses (gmail/yahoo/hotmail addresses are not accepted)."},
        "tui": ("Two-step admissions process: (1) submit online application form and supporting documents by the first deadline; "
                "(2) notify admissions office of a prospective supervisor by the second 'Find a Supervisor' deadline. "
                "If no supervisor is identified by the second deadline, the application will be declined. "
                "Applications are reviewed on a rolling basis (no specific decision date). "
                "PhD Candidacy Examination may be taken in the 3rd or 4th semester (excluding summer); requires cGPA >= 3.5/4.0 at Master's level, completion of at least one core course (NEUR 630 or NEUR 631), and an approved thesis proposal. "
                "MSc-to-PhD fast-track available for exceptional students. "
                "IPN faculty span multiple McGill departments and research institutes (including the Montreal Neurological Institute - Neuro)."),
        "url": "details/mcgill-ipn-phd.html",
        "title": "McGill University Integrated Program in Neuroscience (IPN) PhD",
        "school": "McGill University - Integrated Program in Neuroscience (IPN), Graduate and Postdoctoral Studies",
        "curriculum": ("McGill IPN is an interdisciplinary PhD program integrating neuroscience research across multiple departments and McGill-affiliated research institutes. "
                       "Core courses include NEUR 630 and NEUR 631 (two foundational neuroscience courses). "
                       "Students also complete seminar series, journal clubs, and thesis research. "
                       "The program covers cellular/molecular neuroscience, systems neuroscience, cognitive neuroscience, computational neuroscience, and translational/clinical neuroscience. "
                       "Thesis defense and dissertation required. "
                       "Located on McGill's downtown Montreal campus, with close ties to the Montreal Neurological Institute (The Neuro), McGill University Health Centre (MUHC), and Douglas Mental Health University Institute."),
        "src": "https://www.mcgill.ca/ipn/prospective/application-deadlines ; https://www.mcgill.ca/ipn/prospective/admissions-faq ; https://www.mcgill.ca/ipn/prospective/admission-requirements"
    },
    {
        "id": "stanford-immunology-phd",
        "s": "stanford",
        "n": "斯坦福大学免疫学博士",
        "en": "Immunology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical (full-time)",
        "ddl": "Tuesday, December 1, 2026 at 11:59:59 PM PST (Autumn 2027-28 entry only). No late applications accepted. Knight-Hennessy Scholars deadline October 6, 2026 at 1:00 PM PST (separate application).",
        "lang": "TOEFL / IELTS / Duolingo accepted for international applicants. Stanford Biosciences standard English proficiency requirement applies. ETS institution 4704.",
        "test": {"cls": "GRE General and Subject Test score requirements vary across the 14 Home Programs per Stanford Biosciences policy. For Immunology, the legacy Bulletin page lists GRE Subject Test as OPTIONAL (not required); if submitted, scores are considered. Verify on current Immunology admissions page before applying (submitted scores may be considered but absence not penalized per Biosciences holistic review)."},
        "tui": ("All admitted PhD students are fully funded with tuition, stipend, and health insurance (no separate application needed for funding). "
                "Application fee waivable for eligible applicants. "
                "Highly qualified applicants may be nominated for Stanford Graduate Fellowship. "
                "External fellowship (NSF, HHMR, etc.) greatly improves admission chances. "
                "Two tracks available: Track 1 = Molecular, Cellular, and Translational Immunology (MCTI); Track 2 = Computational and Systems Immunology (CSI). "
                "Applicants should indicate preferred track in personal statement. "
                "Interviews held at the Biosciences interview session (March 3-6, 2027). "
                "14 Biosciences PhD programs share the unified application; students apply to one Home Program (Immunology) per application cycle."),
        "url": "details/stanford-immunology-phd.html",
        "title": "Stanford University Immunology PhD",
        "school": "Stanford University School of Medicine - Immunology Program (one of 14 Biosciences PhD Programs)",
        "curriculum": ("Interdepartmental PhD in Immunology at Stanford. "
                       "Two tracks: (1) Molecular, Cellular, and Translational Immunology (MCTI); (2) Computational and Systems Immunology (CSI). "
                       "Students perform laboratory rotations during the first year and declare a thesis advisor by the end of Year 1. "
                       "Required coursework includes foundational immunology, advanced topics in immunology, quantitative/computational biology (for CSI track), ethics, and journal club (IMMUNOL 305 required for years 1-3 for all students). "
                       "Annual Immunology Scientific Retreat held each autumn quarter. "
                       "Qualifying exam and thesis defense required for PhD. "
                       "Undergraduate majors in biological sciences are typical; majors from other areas (e.g., computer science, physics, engineering) are welcome with sufficient biology/chemistry coursework."),
        "src": "https://med.stanford.edu/immunol/phd-program/admissions.html ; https://biosciences.stanford.edu/how-to-apply/ ; https://22-23.bulletin.stanford.edu/programs/IMMUN-PHD/2064032"
    },
    {
        "id": "harvard-immunology-phd",
        "s": "harvard",
        "n": "哈佛大学免疫学博士",
        "en": "Immunology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "December 1, 2026 at 5:00 PM ET (for Autumn/Fall 2027 entry; per Harvard GSAS Immunology program page, the Fall 2026 cycle deadline was December 1, 2025 5pm ET and the cycle repeats annually).",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0. ETS institution 3451. Summer English Language program at Yale in August prior to matriculation required if Speaking score below teaching threshold (per GSAS).",
        "test": {"cls": "GRE General: NOT ACCEPTED per Harvard GSAS Immunology program page (gsas.harvard.edu/program/immunology). GRE Subject: NOT ACCEPTED. Submitted scores will not be reviewed."},
        "tui": ("All PhD students are fully funded: 12-month stipend + full tuition + health insurance coverage for the duration of the program (subject to satisfactory academic progress). "
                "Funding sources include graduate fellowship, research assistantship (RA) with faculty, and teaching assistantship (TA) opportunities. "
                "Personal Statement required; interviews conducted by invitation (interview invitations sent late December to early January). "
                "The program is part of Harvard Integrated Life Sciences (HILS), which facilitates cross-disciplinary research across 17 Harvard life-science PhD programs. "
                "Faculty are located at Harvard Medical School, Harvard T.H. Chan School of Public Health, Harvard teaching hospitals, and affiliated institutes (Broad Institute, Dana-Farber Cancer Institute, Ragon Institute)."),
        "url": "details/harvard-immunology-phd.html",
        "title": "Harvard University Immunology PhD",
        "school": "Harvard Kenneth C. Griffin Graduate School of Arts and Sciences - Immunology Program (HILS member)",
        "curriculum": ("Harvard Immunology PhD is a member of the Harvard Integrated Life Sciences (HILS) consortium. "
                       "Program offers in-depth training in immunology with faculty located across Harvard Medical School, Harvard T.H. Chan School of Public Health, Harvard teaching hospitals, Broad Institute, Dana-Farber Cancer Institute, and the Ragon Institute. "
                       "Students take foundational courses in immunology, molecular biology, cell biology, and biostatistics during Year 1, perform laboratory rotations (typically 3), and declare a thesis advisor by the end of Year 1. "
                       "Weekly seminar series brings together diverse faculty, students, postdocs, and alumni. "
                       "Qualifying examination and dissertation defense required. "
                       "Graduates have gone on to faculty positions at Harvard, Yale, Stanford, UPenn, Emory, UCSF, and to leadership roles in pharma, biotech, and venture capital (Pfizer, Janssen, Genentech, Flagship Pioneering)."),
        "src": "https://gsas.harvard.edu/program/immunology ; https://gsas.harvard.edu/programs?f%5B0%5D=areas_of_study%3A178"
    },
    {
        "id": "yale-immunobiology-phd",
        "s": "yale",
        "n": "耶鲁大学免疫生物学博士",
        "en": "Immunobiology PhD (via BBS Immunology Track)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "December 1, 2026 at 11:59 PM ET (via BBS application).",
        "lang": "TOEFL iBT minimum 100 (paper 600 / computer 250); IELTS Academic 7.0. ETS institution 3987. Speaking score of 26 (pre-Jan 21, 2026 TOEFL) or 5.5 (on/after Jan 21, 2026) or IELTS 8.0 required for teaching. Summer English Language program required if below threshold.",
        "test": {"cls": "GRE NOT ACCEPTED per Yale GSAS Standardized Testing Requirements table (last updated June 29, 2026): Immunology (BBS) = Not Accepted. If submitted, scores will not be reviewed."},
        "tui": ("All PhD students are fully funded: 12-month stipend + full tuition + student healthcare fellowship. "
                "Funding guaranteed for the duration of the program (typically 5 years) subject to satisfactory academic progress. "
                "Applicants apply through the Combined Program in the Biological and Biomedical Sciences (BBS) and select the Immunology Track. "
                "Preferred undergraduate preparation: biology, organic chemistry, biochemistry, genetics, cell biology, physics, and mathematics. "
                "Additional Immunology-specific application question: identify an important question in immunology, explain why it is important, and describe a testable hypothesis (250-word limit). "
                "No minimum GPA requirement, but strong performance in science and math courses is heavily considered. "
                "12 PhD programs share the BBS umbrella: Cell Biology; Cellular & Molecular Physiology; Computational Biology & Biomedical Informatics; Experimental Pathology; Genetics; Immunobiology; Interdepartmental Neuroscience Program; Microbiology; Molecular Biophysics & Biochemistry; Molecular, Cellular, and Developmental Biology; Pharmacology; and Program in Translational Biomedicine."),
        "url": "details/yale-immunobiology-phd.html",
        "title": "Yale University Immunobiology PhD",
        "school": "Yale Graduate School of Arts and Sciences - Department of Immunobiology (via BBS Immunology Track)",
        "curriculum": ("Yale Immunobiology PhD is part of the BBS umbrella application. "
                       "Department of Immunobiology is multidisciplinary and focuses on the cellular, genetic, and molecular basis of immune system function. "
                       "Research areas: molecular/cellular/genetic underpinnings of immune system, host-pathogen interactions, autoimmune disorders, allergy, graft rejection. "
                       "Human and Translational Immunology (HTI) section addresses human immunological disorders and translational research. "
                       "Year 1 includes coursework and laboratory rotations across BBS departments. "
                       "Qualifying exam and dissertation defense required. "
                       "The Immunology Track is one of 9 scientific Tracks within BBS; admitted students join the Track's scientific home for their first year."),
        "src": "https://gsas.yale.edu/programs-of-study/immunobiology ; https://gsas.yale.edu/programs-of-study/biological-biomedical-sciences-bbs ; https://gsas.yale.edu/admissions/phdmasters-application-process/standardized-testing-requirements"
    },
]


def build_detail_page(p):
    stem_label = "STEM-designated (research-based science PhD)" if p["stem"] == 1 else "Non-STEM"
    return DETAIL_TEMPLATE.format(
        title=p["title"],
        school=p["school"],
        en=p["en"],
        deg=p["deg"],
        stem_label=stem_label,
        curriculum=p["curriculum"],
        ddl=p["ddl"],
        lang=p["lang"],
        test=p["test"]["cls"],
        tui=p["tui"],
        src=p["src"],
    )


def main():
    # 1. Write detail pages
    for p in PAGES:
        out = os.path.join(ROOT, p["url"].replace("/", os.sep))
        os.makedirs(os.path.dirname(out), exist_ok=True)
        with open(out, "w", encoding="utf-8") as f:
            f.write(build_detail_page(p))
        print("Wrote:", p["url"])

    # 2. Read index_main.html
    with open(INDEX, "r", encoding="utf-8") as f:
        html = f.read()

    # 3. Build PROGRAMS block
    prog_lines = []
    for p in PAGES:
        prog_lines.append(
            '{{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"].replace('"', '\\"'),
                lang=p["lang"].replace('"', '\\"'),
                test_cls=p["test"]["cls"].replace('"', '\\"'),
                tui=p["tui"].replace('"', '\\"'),
                url=p["url"],
            )
        )
    new_prog_block = ",".join(prog_lines) + ","

    # Locate PROGRAMS array end: find "const PROGRAMS=[" then scan bracket depth
    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS array 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
    prog_end = i - 1  # position of closing "]"

    # Insert new block before closing "]"
    # Make sure previous entry ends with comma: check char before prog_end
    before = html[:prog_end].rstrip()
    if not before.endswith(","):
        before = before + ","
    new_html = before + "\n" + new_prog_block + "\n" + html[prog_end:]

    # 4. Build VD block: "details/xxx.html", ...
    vd_entries = ", ".join('"{}"'.format(p["url"]) for p in PAGES)
    new_vd_block = vd_entries + ", "

    # Now re-locate VERIFIED_DETAILS=new Set( on the NEW html (positions shifted)
    m2 = re.search(r"VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[", new_html)
    if not m2:
        raise RuntimeError("VERIFIED_DETAILS Set start not found")
    vd_start = m2.end()
    # Find matching closing "]" then ")"
    depth = 1
    j = vd_start
    while j < len(new_html) and depth > 0:
        c = new_html[j]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
        j += 1
    vd_end = j - 1  # position of closing "]"

    before_vd = new_html[:vd_end].rstrip()
    if not before_vd.endswith(","):
        before_vd = before_vd + ","
    new_html = before_vd + " " + new_vd_block + " " + new_html[vd_end:]

    # 5. Write back
    with open(INDEX, "w", encoding="utf-8") as f:
        f.write(new_html)
    print("Appended {} PROGRAMS entries and {} VD entries".format(len(PAGES), len(PAGES)))
    print("Done. File size:", os.path.getsize(INDEX))


if __name__ == "__main__":
    main()
