# -*- coding: utf-8 -*-
# r269: Batch add 5 more Neuroscience PhD entries (fourth wave)
# 1. Vanderbilt Neuroscience PhD (VBI)
# 2. Emory Neuroscience PhD (GDBBS)
# 3. Brown Neuroscience PhD (BioMed)
# 4. Cornell Neurobiology and Behavior PhD (NBB)
# 5. Georgetown Interdisciplinary Program in Neuroscience PhD (IPN)
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": "vanderbilt-neuroscience-phd",
        "s": "vanderbilt",
        "n": "范德堡大学神经科学博士",
        "en": "Neuroscience PhD (Vanderbilt Brain Institute)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1 (Fall entry; both IGP and NGP pathways share Dec 1 deadline)",
        "lang": "TOEFL iBT / IELTS / Duolingo English Test required for international applicants (unless English is first language or degree from US university). ETS institution 1871; department code 0213 for Educational Neuroscience track.",
        "test": {"cls": "GRE scores NOT required for applying to the Neuroscience PhD Program. Exception: GRE scores ARE required for applicants specifically interested in the Educational Neuroscience track. Per Vanderbilt Graduate School program table: Neuroscience PhD = GRE Exempt. Official scores to institution 1871. Note: separate from Psychological Sciences PhD where GRE is required for Clinical/Developmental/QMC divisions and optional for Neuroscience division."},
        "tui": "5-year funding package (full tuition waiver + health insurance + stipend); application fee $95; writing sample in the form of SOP required; two pathways: (1) Interdisciplinary Graduate Program (IGP) for Cellular & Molecular Neuroscience track, (2) direct NGP application for Cognitive & Systems Neuroscience track. Minimum 72 total hours graduate credit; PhD Qualifying Exam at end of Year 2. Note: separate from Psychological Sciences PhD (Arts & Science, different application).",
        "url": "details/vanderbilt-neuroscience-phd.html",
        "title": "Vanderbilt Neuroscience PhD",
        "school": "Vanderbilt University School of Medicine (Vanderbilt Brain Institute)",
        "curriculum": ("Two pathways into the Neuroscience PhD based on concentration: (1) Cellular & Molecular Neuroscience track - apply via Interdisciplinary Graduate Program (IGP) or directly to NGP; (2) Cognitive & Systems Neuroscience track - apply directly to NGP. "
                       "Students in both pathways perform laboratory rotations and select a thesis advisor. "
                       "Minimum 72 total hours of graduate credit; course work typically completed during first two years. "
                       "PhD Qualifying Examination must be passed at end of Year 2 to advance to doctoral candidacy. "
                       "Educational Neuroscience track is a separate specialization requiring GRE submission and additional coursework in education and methodology."),
        "src": "https://medschool.vanderbilt.edu/brain-institute/neuroscience-ph-d-program/application-procedure/ ; https://gradschool.vanderbilt.edu/admissions/apply/application-requirements-by-program/ ; https://medschool.vanderbilt.edu/brain-institute/new-vbi-homepage-inprogress/join-our-graduate-program/application-procedure/"
    },
    {
        "id": "emory-neuroscience-phd",
        "s": "emory",
        "n": "埃默里大学神经科学博士",
        "en": "Neuroscience PhD (Graduate Division of Biological and Biomedical Sciences, GDBBS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "~6 years (average time to degree)",
        "ddl": "December 1, 11:59pm (for Fall 2027; online application available early September)",
        "lang": "TOEFL iBT or IELTS required for non-native English applicants; scores must be no more than 2 years old from application date. ETS institution 5187; no department code needed. International transcript credential evaluation recommended but not required.",
        "test": {"cls": "GRE scores NOT required by ANY program in the Graduate Division of Biological and Biomedical Sciences (GDBBS), and there is no field in the application to enter GRE information. Per GDBBS Apply page: 'GRE scores are not required and there is no field to enter this information in the application.' Submitted scores will not be considered during admissions review."},
        "tui": "Tuition scholarship + health insurance + stipend guaranteed for duration as long as student makes satisfactory progress. ~15 new students admitted per year; ~80-100 total enrolled. 3 LOR; strong undergraduate background in physical, biological, or behavioral sciences; cumulative average B+ or better in major science courses; SOP detailing research interests and prior experience. Three laboratory rotations before affiliating with a thesis advisor. GDBBS umbrella: 8 interdisciplinary PhD programs (Immunology and Molecular Pathogenesis, Neuroscience, Population Biology/Ecology/Evolution, etc.).",
        "url": "details/emory-neuroscience-phd.html",
        "title": "Emory Neuroscience PhD",
        "school": "Emory University Laney Graduate School (GDBBS)",
        "curriculum": ("Nationally top-ranked multidisciplinary PhD program providing broad interdisciplinary doctoral training in the nervous system, "
                       "ranging from molecular and cellular level to systems neurobiology covering developmental, behavioral, and cognitive levels. "
                       "Over 120 neuroscientists drawn from more than 20 departments across Emory College of Arts and Sciences, Emory School of Medicine, "
                       "Rollins School of Public Health, plus collaborators at Georgia Institute of Technology and Atlanta VA Medical Center. "
                       "One third of Emory's American Academy (AAAS) Fellows are in the Neuroscience program. "
                       "Training includes significant component on understanding and treatment of neurological and psychiatric diseases. "
                       "Students typically perform three rotations before affiliating with a faculty member for dissertation research. "
                       "Alumni careers in industry, academia, law, and government."),
        "src": "https://biomed.emory.edu/ ; https://biomed.emory.edu/admissions/apply.html ; https://biomed.emory.edu/PROGRAM_SITES/NS/pages/neuroscience-research.html ; https://gs.emory.edu/admissions/faq"
    },
    {
        "id": "brown-neuroscience-phd",
        "s": "brown",
        "n": "布朗大学神经科学博士",
        "en": "Neuroscience PhD (BioMed: Neuroscience)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "~5 years (average time to completion slightly above 5 years)",
        "ddl": "December 1, 2026, 11:59pm ET",
        "lang": "TOEFL iBT required for international students (with exceptions); TOEFL reporting code Brown University 3094, Neuroscience department code 30. IELTS accepted per Brown Graduate School minimums.",
        "test": {"cls": "GRE scores NOT required as part of the application. Per Brown Graduate Programs page: 'GRE Subject: Not required; GRE General: Not required.' Per Neuroscience GP FAQ: 'GRE scores are not required as part the application.' No minimum GPA. Note: Brown-NIH GPP applicants also do not need to submit GRE scores."},
        "tui": "5-year funding package (tuition + stipend + health insurance); application fee $75 (US citizens/permanent residents demonstrating financial need may apply for waiver). ETS institution 3094; Neuroscience department code 0213. Brown-NIH Graduate Partnership Program (GPP): students complete Year 1 coursework at Brown then up to 4 years thesis research at NIH; PhD awarded by Brown. Decisions announced by early March. No specific course requirements but applicants typically have undergraduate degree in biology, psychology, neurobiology, chemistry, physics, applied math, engineering, or computer science.",
        "url": "details/brown-neuroscience-phd.html",
        "title": "Brown Neuroscience PhD",
        "school": "Brown University (Warren Alpert Medical School)",
        "curriculum": ("Founded in 1986. Intensive multidisciplinary PhD in neuroscience. Core curriculum covers molecular, cellular, systems, cognitive, "
                       "and translational neuroscience, plus diseases of the nervous system. Research spans genes, molecules, cells, networks, systems, "
                       "and behavior. Integrates skills essential for independent research careers: critical thinking, science writing, oral presentation, "
                       "knowledge of scientific review process, ethics training. "
                       "Brown-NIH Graduate Partnership Program (GPP): Year 1 at Brown for coursework and rotations, then up to 4 years thesis research "
                       "at NIH; PhD awarded by Brown. Applicants wishing to be considered for both Brown Neuroscience and Brown-NIH GPP must submit "
                       "applications to both Brown and NIH by the December 1 deadline. "
                       "Research themes include computational approaches to cognition, frontal lobe function, decision making and cognitive control."),
        "src": "https://neuroscience-gp.brown.edu/prospective-students/frequently-asked-questions ; https://graduateprograms.brown.edu/graduate-program/biomed-neuroscience-phd ; https://neuroscience-gp.brown.edu/prospective-students/how-apply ; https://neuroscience-nih.brown.edu/about-program/faqs"
    },
    {
        "id": "cornell-neurobiology-phd",
        "s": "cornell",
        "n": "康奈尔大学神经生物学与行为学博士",
        "en": "Neurobiology and Behavior PhD (NBB)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-7 years (A Exam Summer Year 3; B Exam before Year 7)",
        "ddl": "December 1 (Fall admission only; no spring admission; application available online early September)",
        "lang": "English language proficiency requirement per Cornell Graduate School minimums for all international applicants. Official TOEFL/IELTS scores to Cornell Graduate School.",
        "test": {"cls": "GRE scores NOT required or accepted. Per NBB department page: 'GRE Scores are not required or accepted.' Per Applying page: 'GRE exam scores are no longer required nor even permitted for an application to our program.' Per Cornell Courses catalog: 'GRE scores are no longer required or accepted.' No GRE Subject test requirement."},
        "tui": "Guaranteed 6 years of support via Cornell fellowships, graduate research assistantships, or teaching assistantships. Minimum one semester of teaching experience required. 3 LOR; clear statement of research purpose and career interests. Fee waiver available based on financial hardship. 6 minimum semesters for degree; 126 minimum credits. A Exam (candidacy) Summer of Year 3; B Exam (dissertation defense) before Year 7. Each student must give a publicly announced seminar as part of dissertation defense. No formal language requirement but special committee may impose one.",
        "url": "details/cornell-neurobiology-phd.html",
        "title": "Cornell Neurobiology and Behavior PhD",
        "school": "Cornell University College of Agriculture and Life Sciences",
        "curriculum": ("Unique PhD integrating neurobiology with behavior and interactions of organisms at all levels of analysis from mechanism to evolution. "
                       "Research approaches the field from ion channels through neural networks to behavioral ecology and the evolution of behavior. "
                       "Faculty drawn from a variety of departments. "
                       "Six concentrations: cellular and molecular neurobiology; neuroanatomy; neurochemistry; neuropharmacology; neurophysiology; sensory physiology; "
                       "plus Behavioral Biology (ethology, neuroethology). "
                       "Special committee structure: each student has a 3-member special committee that meets annually. "
                       "Survey course in neurobiology behavior required. Public seminar required as part of dissertation defense. "
                       "Ithaca campus. Note: Cornell also has separate Biomedical PhD programs (BMCB, GGD, etc.) through Weill Cornell/"
                       "Graduate School; NBB is the main campus field."),
        "src": "https://nbb.cornell.edu/graduate-nbb ; https://courses.cornell.edu/programs/neurobiology-phd/ ; https://catalog.cornell.edu/programs/neurobiology-phd/neurobiology-phd.pdf ; https://nbb.cornell.edu/applying-neurobiology-behavior-phd-program"
    },
    {
        "id": "georgetown-neuroscience-phd",
        "s": "geo",
        "n": "乔治城大学跨学科神经科学博士",
        "en": "Interdisciplinary Program in Neuroscience PhD (IPN)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years (candidacy by beginning of Year 3)",
        "ddl": "December 1 (final deadline for Summer admission; interviews January-March; final decision late March; April 15 enrollment deadline; program starts July 1). Note: IPN primarily admits Summer entry cohort; Fall admission availability should be confirmed with program.",
        "lang": "TOEFL iBT / IELTS required per Georgetown BGE minimums. ETS institution 5244 (Georgetown BGE); no department code needed. TOEFL minimum 80 (original iBT scale) or 4 (new scale beginning Jan 21, 2026); IELTS 7.0 minimum.",
        "test": {"cls": "SEMI-VERIFIED: IPN department page does not explicitly list GRE requirement. BGE How to Apply page states 'GRE/MCAT Score (if applicable)' - implying program-dependent. IPN FAQ page does not mention GRE. Based on broader BGS/BGE trend of GRE-free PhD programs, GRE is likely not required but should be verified on current IPN admissions page before applying. Note: Georgetown Psychology PhD (separate department) explicitly requires all official GRE scores."},
        "tui": "PhD-only program (no terminal master's); Master's in Passing (MIP) available after completing requirements. 34 credits total (23 required + 11 electives). Comprehensive exam: written exam Spring Year 1, oral exam by end Year 2. Candidacy must be completed by beginning of Year 3. 3 LOR; academic SOP; transcripts; $90 application fee; GPA 3.0 minimum. Students may apply simultaneously to Interdisciplinary PhD Concentration in Cognitive Science (cross-listed with Psychology, Linguistics, Philosophy, CS). Note: separate from Georgetown MS in Integrative Neuroscience (terminal master's).",
        "url": "details/georgetown-neuroscience-phd.html",
        "title": "Georgetown Interdisciplinary Program in Neuroscience PhD",
        "school": "Georgetown University School of Medicine (Biomedical Graduate Education)",
        "curriculum": ("Interdisciplinary PhD focusing on research training and completion of independent dissertation research. "
                       "Close-knit IPN community enabling multiple research approaches during training. "
                       "Program ensures comprehensive background in neurosciences covering cellular, molecular, systems, and cognitive approaches. "
                       "Required neuroscience courses plus advanced electives and laboratory rotations. "
                       "34 credits total (23 required + 11 electives). "
                       "Comprehensive exam: written exam in Spring of Year 1; oral exam by end of Year 2. "
                       "Both exams must be passed before advancing to doctoral candidacy and beginning full-time thesis research. "
                       "Ascension to candidacy by beginning of Year 3. "
                       "Cross-applicable with Interdisciplinary PhD Concentration in Cognitive Science (spanning Psychology, Linguistics, Philosophy, Neuroscience, CS)."),
        "src": "https://bulletin.georgetown.edu/programs/neuroscience-phd/ ; https://neuroscience.georgetown.edu/admissions/ ; https://biomedicalprograms.georgetown.edu/prospective/how-to-apply/ ; https://grad.georgetown.edu/admissions/application-deadlines/"
    },
]

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