# -*- coding: utf-8 -*-
# r267: Batch add 5 more Neuroscience PhD entries
# 1. Caltech Computation and Neural Systems (CNS) PhD
# 2. Princeton Neuroscience Institute (PNI) PhD
# 3. UChicago Neurobiology PhD
# 4. UCLA Neuroscience PhD (NSIDP)
# 5. Duke Neurobiology 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": "caltech-cns-phd",
        "s": "caltech",
        "n": "加州理工计算与神经系统博士",
        "en": "Computation and Neural Systems PhD (CNS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1 (Fall entry only; application opens October 15)",
        "lang": "TOEFL iBT / PTE Academic / IELTS / Cambridge / Duolingo accepted; self-reported scores accepted",
        "test": {"cls": "GRE not required. Per newer biology.caltech.edu page: absence of GRE scores will not be negatively considered; if submitted, scores will be considered. (Legacy bbe.caltech.edu page says 'strongly recommended' - newer page is authoritative.)"},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; 3 LOR + CV + SOP + transcripts; one academic option per cycle; existing PhD holders not considered",
        "url": "details/caltech-cns-phd.html",
        "title": "Caltech Computation and Neural Systems PhD",
        "school": "California Institute of Technology (Caltech)",
        "curriculum": ("Interdisciplinary PhD jointly organized by three divisions: Biology and Biological Engineering, "
                       "Engineering and Applied Science, and Humanities and Social Sciences. "
                       "Undergraduate majors welcome: electrical engineering, biology, physics, mathematics, or computer science. "
                       "Curriculum spans experimental and theoretical molecular/cellular/neural/systems biology, computational devices, "
                       "information theory, emergent/collective systems, modeling, and complex systems. "
                       "Timeline: interview invitations December 22; interviews early February (by invitation only); "
                       "admissions decisions mid-February. Note: Caltech also offers separate Neurobiology option; "
                       "CNS is the flagship interdisciplinary computational neuroscience track."),
        "src": "https://www.bbe.caltech.edu/academics/cns/graduate-admissions ; https://www.biology.caltech.edu/academics/cns/graduate-admissions ; https://www.bbe.caltech.edu/academics/applying-to-caltech-2026-2027"
    },
    {
        "id": "princeton-pni-phd",
        "s": "princeton",
        "n": "普林斯顿神经科学研究所博士",
        "en": "Neuroscience PhD (Princeton Neuroscience Institute, PNI)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "November 21, 11:59 PM ET (Fall entry only; historically earlier than typical Dec 1 cycle)",
        "lang": "TOEFL iBT required for non-native English applicants; ETS institution code 2672 (no department code)",
        "test": {"cls": "GRE General optional/not required. Submitted scores are accepted but not required; holistic review with greatest emphasis on SOP and research-mentor letters."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; $75 application fee; 3 LOR + SOP + CV + unofficial transcripts; optional diversity statement (max 500 words)",
        "url": "details/princeton-pni-phd.html",
        "title": "Princeton Neuroscience Institute PhD",
        "school": "Princeton University",
        "curriculum": ("5-year PhD. Year 1: 2-week Neuro Boot Camp in August; year-long Neuroscience Core Course; "
                       "up to 3 lab rotations; grant-writing workshops; attend Society for Neuroscience Annual Conference. "
                       "Year 2: half-time teaching; thesis advisor selection. Year 3: general exam (thesis proposal defense) "
                       "beginning of third year / fifth semester. "
                       "QCN (Quantitative and Computational Neuroscience) track available with NIMH T32 support. "
                       "Joint Graduate Degree Program in Neuroscience option: students earn PhD in 'X and neuroscience' "
                       "where X is home department (Psychology, Molecular Biology, Philosophy, etc.)."),
        "src": "https://pniweb.princeton.edu/graduate-program/how-to-apply ; https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/neuroscience ; http://pni.princeton.edu/graduate-program/course-study"
    },
    {
        "id": "uchicago-neurobiology-phd",
        "s": "uchicago",
        "n": "芝加哥大学神经生物学博士",
        "en": "Neurobiology PhD (Committee on Neurobiology, Neuroscience cluster)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 2026 (Autumn Quarter 2027 entry; application opens early September)",
        "lang": "TOEFL iBT minimum 100 (pre-Jan 21 2026: 26 R/W/L, 22 S); on/post-Jan 21 2026: 5 R/W, 4.5 S; IELTS Academic 7.0",
        "test": {"cls": "GRE optional for all BSD PhD programs. Per UChicago Biosciences How to Apply: majority of BSD programs do not use submitted GRE scores; Neurobiology is NOT in the list of programs that explicitly review GRE (Public Health Sciences, Medical Physics, Biochemistry and Molecular Biophysics are the BSD exceptions). ETS 1832, no department code."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; $90 application fee; 3 LOR; may apply to up to 4 BSD programs with one application (rank by preference)",
        "url": "details/uchicago-neurobiology-phd.html",
        "title": "UChicago Neurobiology PhD",
        "school": "University of Chicago (Biological Sciences Division)",
        "curriculum": ("Part of the Neuroscience cluster within BSD: Neurobiology + Computational Neuroscience + Integrative Neuroscience (Psychology). "
                       "Applicants from biology, neuroscience, cognitive science, psychology, and life sciences backgrounds. "
                       "Suggested undergraduate preparation: introductory neurobiology, introductory psychology, calculus/statistics. "
                       "Research experience is a key element. Interviews by invitation; formal recruitment weekends. "
                       "Response deadline April 15. Note: UChicago also offers separate Committee on Computational Neuroscience PhD "
                       "(9 formal courses, 9 quarters research, 2 lab rotations, written+oral qualifying exam end of Year 2)."),
        "src": "https://neurograd.uchicago.edu/page/admissions ; https://biosciences.uchicago.edu/admissions/how-to-apply ; https://apply-bsd.uchicago.edu/apply/ ; http://graduateannouncements.uchicago.edu/graduate/committeeoncomputationalneuroscience/"
    },
    {
        "id": "ucla-neuroscience-phd",
        "s": "ucla",
        "n": "UCLA神经科学博士",
        "en": "Neuroscience PhD (Neuroscience Interdepartmental Program, NSIDP)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years (18 quarters normative TTD)",
        "ddl": "December 1, 2026, 11:59 PM PST (2:59 AM EST; Fall entry only)",
        "lang": "TOEFL iBT per UCLA Graduate Division minimum; IELTS accepted; ETS institution code 4837, department/major code 99",
        "test": {"cls": "GRE General not required (effective Fall 2020); GRE Subject not required. Students may voluntarily submit scores; they will be reviewed holistically but applications with GRE scores are not given greater weight than those without."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; application fee $120 US/$140 international; major code 004F; 3 LOR; SOP + Personal Statement + CV; no writing sample required",
        "url": "details/ucla-neuroscience-phd.html",
        "title": "UCLA Neuroscience PhD (NSIDP)",
        "school": "University of California, Los Angeles (David Geffen School of Medicine)",
        "curriculum": ("Interdepartmental PhD in Graduate Programs in Bioscience (GPB). Year 1 core courses: "
                       "Neuroscience M201, M202, M203, 205, 210ABC, 211A (211A may be Year 2). "
                       "Scientific ethics course; annual program retreat; Joint Seminars in Neuroscience (JSN). "
                       "Written qualifying exam after core requirements (typically before end of Year 2); oral qualifying exam "
                       "by end of Spring Year 3. Normative time to degree 18 quarters (max 21). "
                       "Recommended prep: math through calculus; 1 year general chemistry, organic chemistry, biochemistry, physics, basic biology incl. molecular/cell biology. "
                       "Timeline: review Dec-early Jan; interview invites late Dec-early Jan; virtual interviews Jan-Feb; "
                       "offers late Feb; on-campus visit March; acceptance deadline April 15."),
        "src": "https://www.neuroscience.ucla.edu/admissions ; https://www.neuroscience.ucla.edu/admissions-faq-subject-revision ; https://grad.ucla.edu/requirements/?app=admission&major=004F"
    },
    {
        "id": "duke-neurobiology-phd",
        "s": "duke",
        "n": "杜克神经生物学博士",
        "en": "Neurobiology PhD (Department of Neurobiology, Duke University Medical Center)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 2026, 11:59:59 PM EST (Fall entry only)",
        "lang": "TOEFL iBT / IELTS / Duolingo English Test required for non-native English applicants; waiver may apply; ETS institution code 5156",
        "test": {"cls": "GRE General Optional for Fall 2027 cycle. No department-specific GRE requirement."},
        "tui": "100% of students receiving financial aid; 3 LOR; SOP (required) + CV (required); no writing sample; no video material considered; unofficial transcripts with application, official upon admission",
        "url": "details/duke-neurobiology-phd.html",
        "title": "Duke Neurobiology PhD",
        "school": "Duke University (Duke University Medical Center)",
        "curriculum": ("PhD in the Department of Neurobiology. 50 faculty, 63 students, 100% financial aid. "
                       "Research areas: learning, memory, movement, behavior, sensation, perception, and restoration of nervous system function after trauma/disease. "
                       "Interdisciplinary faculty with broad collaboration across Duke. "
                       "Fall-only admission. Note: Duke also offers Psychology & Neuroscience PhD in the Department of Psychology & Neuroscience "
                       "with 5 training areas (Clinical, Cognition & Brain, Developmental, Social, Systems and Integrative Neuroscience/SINS) - "
                       "separate from the Department of Neurobiology PhD entry here."),
        "src": "https://gradschool.duke.edu/academics/programs-degrees/neurobiology/ ; https://gradschool.duke.edu/admissions/application-deadlines/ ; https://psychandneuro.duke.edu/graduate/SINS"
    },
]

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