# -*- coding: utf-8 -*-
# r268: Batch add 5 more Neuroscience PhD entries (third wave)
# 1. Yale Interdepartmental Neuroscience Program (INP) PhD
# 2. Johns Hopkins Neuroscience PhD (Solomon H Snyder Department)
# 3. UPenn Neuroscience Graduate Group (NGG) PhD
# 4. University of Michigan Neuroscience Graduate Program (NGP) PhD
# 5. Northwestern Interdepartmental Neuroscience (NUIN) PhD
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": "yale-neuroscience-phd",
        "s": "yale",
        "n": "耶鲁大学跨系神经科学博士",
        "en": "Interdepartmental Neuroscience Program PhD (INP)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 11:59pm ET (Fall entry)",
        "lang": "TOEFL iBT minimum 100 (paper 600 / computer 250); IELTS Academic; Speaking threshold for teaching: 26 (pre-Jan 21, 2026) / 5.5 (on/after Jan 21, 2026); IELTS Speaking 8.0 for teaching. ETS institution 3987.",
        "test": {"cls": "GRE General Test NOT ACCEPTED. Per GSAS Standardized Testing Requirements table last updated June 29, 2026: 'Do not submit GRE General Test scores. If you submit scores, they will not be reviewed.' No GRE Subject test requirement."},
        "tui": "Full 5-year funding package (tuition + stipend + health insurance); 3 LOR; Statement of Academic Purpose; no minimum GPA (holistic review); prerequisite coursework in biology, chemistry through organic chemistry, physics, calculus. Note: Yale also admits Neuroscience via BBS (Biological & Biomedical Sciences) Neuroscience Track as a separate admissions gateway; INP is the independent interdepartmental PhD track.",
        "url": "details/yale-neuroscience-phd.html",
        "title": "Yale Interdepartmental Neuroscience Program PhD",
        "school": "Yale University (GSAS)",
        "curriculum": ("Flexible but structured interdisciplinary PhD training for independent research and teaching in neuroscience. "
                       "Goal: solid understanding of cellular and molecular neurobiology, physiology and biophysics, neural development, "
                       "systems and behavior, and neural computation. Beyond coursework, students participate in student research talks and "
                       "mentoring. Students rotate through laboratories and declare a thesis advisor. "
                       "Note: Yale offers two pathways to a Neuroscience PhD - the standalone Interdepartmental Neuroscience Program (INP, "
                       "this entry) and the Neuroscience Track within the combined BBS admissions gateway. Both share the same Dec 1 deadline "
                       "and GRE-not-accepted policy."),
        "src": "https://gsas.yale.edu/programs-of-study/interdepartmental-neuroscience-program ; https://gsas.yale.edu/programs-of-study/biological-biomedical-sciences-bbs ; https://gsas.yale.edu/admissions/phdmasters-application-process/standardized-testing-requirements"
    },
    {
        "id": "jhu-neuroscience-phd",
        "s": "jhu",
        "n": "约翰霍普金斯大学神经科学博士",
        "en": "Neuroscience PhD (Solomon H. Snyder Department of Neuroscience)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 2026 (this is an earlier deadline than other graduate programs at Johns Hopkins School of Medicine; all materials including LOR must be in by this date)",
        "lang": "TOEFL iBT or IELTS required for non-native English applicants. Official score reports to ETS institution 5316 (JHU PhD Medicine). Department code not required.",
        "test": {"cls": "GRE scores NOT REQUIRED. Department page explicitly states: 'The Neuroscience Program DOES NOT require GRE scores.' Legacy 2019 application PDF listed GRE as optional for BCMB/CMM/Neuroscience/PMB/XDBio; current dept page is authoritative and says no GRE required. No GRE Subject test requirement."},
        "tui": "All admitted PhD students receive full tuition + stipend + health insurance (School of Medicine standard package); VTSI fellowship for STEM PhD (HBCU/community college/regional MD/VA/DC undergrad) with Dec 1 deadline; B.S./B.A. prior to enrollment; laboratory research experience strongly preferred; core preparation in biology, neuroscience, math through calculus, general physics, general/organic chemistry, statistics, engineering, or computer science. Class size 14-16 per year (catalog PDF notes ~18). University-mandated Doctor of Philosophy Board Oral (DBO) Examination by second year. Note: JHU also has a separate PhD in Psychological & Brain Sciences (PBS) - different department, different application.",
        "url": "details/jhu-neuroscience-phd.html",
        "title": "Johns Hopkins Neuroscience PhD",
        "school": "Johns Hopkins University School of Medicine",
        "curriculum": ("Interdisciplinary PhD designed to train doctoral students for independent research and teaching in neuroscience. "
                       "A series of core courses in neuroscience, advanced electives, seminar series, laboratory rotations, and original "
                       "independent dissertation research form the training program. Minimum residency of two consecutive semesters. "
                       "Holistic admissions review valuing applicants who have taken full advantage of undergraduate and postbac research opportunities. "
                       "Note: This is the Solomon H. Snyder Department of Neuroscience (medical campus) track; the Department of Psychological & "
                       "Brain Sciences (Homewood campus) PhD is a separate program with its own application and GRE-recommended-but-not-required policy."),
        "src": "https://neuroscience.jhu.edu/graduate/apply ; https://e-catalogue.jhu.edu/medicine/graduate-programs/neuroscience-phd/ ; https://e-catalogue.jhu.edu/medicine/graduate-programs/neuroscience-phd/neuroscience-phd.pdf"
    },
    {
        "id": "upenn-neuroscience-phd",
        "s": "up",
        "n": "宾夕法尼亚大学神经科学博士",
        "en": "Neuroscience Graduate Group PhD (NGG)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "October 1 - December 1, 2026, 11:59pm ET (BGS unified application; Fall entry only)",
        "lang": "TOEFL iBT / IELTS / Duolingo required for non-native English applicants. Official score reports to BGS application.",
        "test": {"cls": "BGS does NOT require or ACCEPT GRE scores (general or subject tests). Per BGS Admissions FAQ: 'You will see a mention of the GRE on the application, as we share it with other divisions within the Perelman School of Medicine. However, the application clearly states GRE scores should not be submitted by BGS applicants.'"},
        "tui": "All NGG students receive full fellowship covering tuition and fees plus stipend; one semester of teaching required; total 14.5-18.5 course units; average GPA of admitted applicants (last 3 years) = 3.71 (admitted distribution, not minimum threshold); CV + Personal Statement (~500 words) + Research Statement; applicants may apply to only one BGS group; first-year transfer between BGS groups permitted for students in good standing.",
        "url": "details/upenn-neuroscience-phd.html",
        "title": "UPenn Neuroscience Graduate Group PhD",
        "school": "University of Pennsylvania Perelman School of Medicine",
        "curriculum": ("Collaborative and interdisciplinary PhD program providing training for careers in neuroscience research and teaching. "
                       "186 faculty members across 30 academic departments (Arts and Sciences, Engineering and Applied Science, Wharton, "
                       "Veterinary Medicine, Dental Medicine, Nursing, and Perelman School of Medicine). Covers computational, systems, cellular "
                       "and molecular, developmental, behavioral, and cognitive neuroscience, plus neurobiology of disease. "
                       "Students rotate and declare thesis advisor within the BGS umbrella. BGS policy allows first-year transfer between groups "
                       "if research focus changes."),
        "src": "https://www.med.upenn.edu/ngg/admissions/ ; https://www.med.upenn.edu/bgs/phd-application-information.html ; https://www.cceb.upenn.edu/bgs/admissions-faqs.html ; https://catalog.upenn.edu/graduate/programs/neuroscience-phd/"
    },
    {
        "id": "umich-neuroscience-phd",
        "s": "umich",
        "n": "密歇根大学安娜堡神经科学博士",
        "en": "Neuroscience Graduate Program PhD (NGP)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1 (applications go live early September; final decisions by March 30)",
        "lang": "TOEFL iBT / IELTS required per Rackham Graduate School minimums for non-native English applicants. Official score reports to Rackham (ETS institution 1839).",
        "test": {"cls": "GRE is NOT required for either Direct or PIBS admissions. Per NGP Apply page: 'The GRE test is not required for either route of admission and any scores submitted will not be reviewed by the admissions committee.' No GRE Subject test requirement."},
        "tui": "All admitted students receive guaranteed stipend + health insurance for duration of graduate studies, regardless of route (DIRECT or PIBS). Two admissions routes: DIRECT (apply directly to NGP) and PIBS (Program in Biomedical Sciences - first-year umbrella rotation). Both paths complete same NGP neuroscience courses and receive identical funding packages. Cohort ~15-20 Neuroscience PhD students per year; >95 current Neuroscience PhD students; >150 affiliated faculty.",
        "url": "details/umich-neuroscience-phd.html",
        "title": "University of Michigan Neuroscience Graduate Program PhD",
        "school": "University of Michigan Medical School",
        "curriculum": ("Launched in 1971, the longest-standing Neuroscience PhD program in the country. "
                       "Interdisciplinary and interdepartmental approach with more than 150 affiliated faculty distributed throughout the institution. "
                       "Faculty includes members of the National Academy of Sciences, National Academy of Medicine, past presidents of the "
                       "Society for Neuroscience, AAAS fellows, and Highly Cited Researchers. "
                       "Two routes: DIRECT (enter NGP directly) and PIBS (enter via the broader Program in Biomedical Sciences first-year umbrella). "
                       "PIBS students additionally take the PIBS Seminar during Year 1. Both routes combine into a single NGP cohort after rotations. "
                       "Final admissions decisions communicated no later than March 30."),
        "src": "https://medschool.umich.edu/interdisciplinary-programs/neuroscience-graduate-program/education/apply ; https://medschool.umich.edu/interdisciplinary-programs/neuroscience-graduate-program"
    },
    {
        "id": "northwestern-neuroscience-phd",
        "s": "nu",
        "n": "西北大学跨系神经科学博士",
        "en": "Interdepartmental Neuroscience PhD (NUIN)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 2026, 11:59pm (Fall entry only; no winter or spring matriculation; late applications not accepted)",
        "lang": "TOEFL iBT / IELTS required per The Graduate School minimums for international applicants. Official score reports to ETS institution 1565 (Northwestern TGS).",
        "test": {"cls": "NUIN does NOT require GRE general or subject score submissions. Per NUIN How to Apply page: 'NUIN does not require GRE general or subject score submissions.' No minimum GPA; holistic review."},
        "tui": "Entering students fully supported (tuition + stipend + health insurance) for duration of graduate studies. 5-year average GPA of incoming students = 3.71, median 3.75 (admitted distribution, not minimum threshold). ~160 PhD students and 160 faculty representing 20 departments across Chicago campus (Feinberg School of Medicine, Shirley Ryan AbilityLab, Ann & Robert H. Lurie Children's Hospital) and Evanston campus (Weinberg College of Arts and Sciences, McCormick School of Engineering, School of Communication). Joint PhD programs (e.g. JD-PhD) must be declared at initial application. Note: Department of Neurobiology MS Program is a separate March 1 deadline master's track; this entry is the NUIN PhD.",
        "url": "details/northwestern-neuroscience-phd.html",
        "title": "Northwestern Interdepartmental Neuroscience PhD",
        "school": "Northwestern University Feinberg School of Medicine",
        "curriculum": ("Research-oriented PhD program anchored in the Feinberg School of Medicine on the Chicago campus and Weinberg/McCormick/"
                       "Communication on the Evanston campus. Highly interdisciplinary and collaborative with diverse research foci. "
                       "Laboratory rotation requirements provide students the opportunity to experience training cultures on both campuses "
                       "(bustling Chicago medical district vs. quieter Evanston undergraduate campus). "
                       "NUIN accepts applicants from diverse backgrounds and majors including psychology, engineering, physics, computer science, "
                       "chemistry, biology, and neuroscience. Students also receive training in teaching and other professional skills for "
                       "diverse career paths. NU PREP postbaccalaureate program feeds into the PhD pipeline."),
        "src": "https://www.nuin.northwestern.edu/prospective-students/how-to-apply.html ; https://www.nuin.northwestern.edu/about/ ; https://nuin.northwestern.edu/ ; https://www.tgs.northwestern.edu/admission/application-procedures/application-requirements/test-scores.html"
    },
]

# Render detail pages
for p in PAGES:
    p["stem_label"] = "STEM-designated" if p["stem"] == 1 else "Non-STEM"
    html = DETAIL_TEMPLATE.format(**p)
    out = os.path.join(ROOT, p["url"])
    with open(out, "w", encoding="utf-8") as f:
        f.write(html)
    print("Wrote:", os.path.basename(out))

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

# Locate PROGRAMS array end via bracket-depth matching
def find_array_end(text, start_token):
    i = text.find(start_token)
    if i < 0:
        raise RuntimeError("token not found: " + start_token)
    j = text.find("[", i)
    depth = 1
    k = j + 1
    while k < len(text) and depth > 0:
        c = text[k]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
        k += 1
    return k - 1

# Build new program block
new_programs = []
for p in PAGES:
    test_cls = p["test"]["cls"].replace('"', '\\"')
    block = (
        '{{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(**p, test_cls=test_cls)
    new_programs.append(block)

prog_start = "const PROGRAMS="
prog_end_pos = find_array_end(html, prog_start)
before = html[:prog_end_pos].rstrip()
if before.endswith("["):
    insert_block = ",".join(new_programs)
else:
    if not before.endswith(","):
        insert_block = "," + ",".join(new_programs)
    else:
        insert_block = ",".join(new_programs)

new_html = html[:prog_end_pos] + insert_block + html[prog_end_pos:]

# VD Set end via paren-depth matching on new_html
def find_set_end(text, start_token):
    i = text.find(start_token)
    if i < 0:
        raise RuntimeError("VD token not found")
    j = text.find("(", i)
    depth = 1
    k = j + 1
    while k < len(text) and depth > 0:
        c = text[k]
        if c == "(":
            depth += 1
        elif c == ")":
            depth -= 1
        k += 1
    return k - 1

vd_start = "const VERIFIED_DETAILS=new Set("
vd_end_pos = find_set_end(new_html, vd_start)
bracket_pos = new_html.rfind("]", 0, vd_end_pos)
if bracket_pos < 0:
    raise RuntimeError("VD closing bracket not found")

new_vd_entries = ",".join('"' + p["url"] + '"' for p in PAGES)
before_bracket = new_html[:bracket_pos].rstrip()
if before_bracket.endswith("["):
    vd_block = new_vd_entries
else:
    if not before_bracket.endswith(","):
        vd_block = "," + new_vd_entries
    else:
        vd_block = new_vd_entries

new_html = new_html[:bracket_pos] + vd_block + new_html[bracket_pos:]

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))
