# -*- coding: utf-8 -*-
# r266: Batch add 5 Neuroscience PhD entries
# 1. MIT Brain and Cognitive Sciences (BCS) PhD
# 2. Harvard Neuroscience PhD (PiN, HILS)
# 3. Stanford Neurosciences PhD (Biosciences family)
# 4. UCSD Neurosciences PhD (NGP)
# 5. Columbia Neurobiology and Behavior PhD (NBB)
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": "mit-bcs-phd",
        "s": "mit",
        "n": "MIT 脑与认知科学博士",
        "en": "Brain and Cognitive Sciences PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 11:59 PM ET (Fall entry only)",
        "lang": "TOEFL iBT 100 / IELTS Academic 7.0 / Duolingo DET 135; Cambridge C1 Advanced or C2 Proficiency accepted",
        "test": {"cls": "GRE NOT accepted. BCS does not accept or consider GRE scores in evaluation; scores sent to MIT will not be reviewed."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; fee $90; ETS institution code 3514",
        "url": "details/mit-bcs-phd.html",
        "title": "MIT Brain and Cognitive Sciences PhD",
        "school": "Massachusetts Institute of Technology (MIT)",
        "curriculum": ("5-6 year PhD. Four research areas: Cellular and Molecular Neuroscience, Cognitive Science, Computation, "
                       "Systems Neuroscience. Students complete minimum 3 lab rotations by March 31, select thesis advisor by April 30. "
                       "Year 1-2 coursework + TA training; written and oral qualifying exam in October/November of second year; "
                       "thesis proposal by end of Spring Year 3; annual thesis committee meetings; final oral defense. "
                       "900+ applications per year, 15-18 enrolled; acceptance rate below 5%. "
                       "Interdisciplinary affiliation with IDPS (Interdisciplinary Doctoral Program in Statistics)."),
        "src": "https://bcs.mit.edu/academic-program/brain-and-cognitive-sciences-phd-program/how-apply ; https://oge.mit.edu/programs/brain-and-cognitive-sciences/"
    },
    {
        "id": "harvard-neuroscience-phd",
        "s": "harvard",
        "n": "哈佛神经科学博士",
        "en": "Neuroscience PhD (Program in Neuroscience, PiN)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 5:00 PM ET (Fall entry only)",
        "lang": "TOEFL iBT minimum 100 / IELTS minimum 7.0",
        "test": {"cls": "GRE General and GRE Subject NOT accepted (since 2019). Submitted scores will not be seen by admissions committee."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; part of Harvard Integrated Life Sciences (HILS); ETS codes per GSAS",
        "url": "details/harvard-neuroscience-phd.html",
        "title": "Harvard Neuroscience PhD (PiN)",
        "school": "Harvard University (Harvard Griffin GSAS / Harvard Medical School)",
        "curriculum": ("Full-time lab-based PhD in the Division of Medical Sciences. Core curriculum spans neuroscience with electives in "
                       "computational neuroscience and neuroanatomy. First-year lab rotations and dissertation research. "
                       "Statement of Purpose max 1000 words; required Personal Statement; 3 LOR (up to 4 accepted); "
                       "unofficial transcripts upload; fall-term grades may be added after Dec 1 deadline. "
                       "Timeline: portal opens mid-September; virtual open houses Oct-Nov; interview invites late Dec; "
                       "interview weekend in Boston Jan 16-19 (2026 cycle; 2027 date TBD); offers mid-Feb; waitlist March-April. "
                       "Prerequisites: rigorous undergrad coursework in biology, chemistry, physics; prior lab research experience."),
        "src": "https://pinphd.hms.harvard.edu/apply ; https://gsas.harvard.edu/program/neuroscience"
    },
    {
        "id": "stanford-neurosciences-phd",
        "s": "stanford",
        "n": "斯坦福神经科学博士",
        "en": "Neurosciences PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1, 2026, 11:59:59 PM PST (Autumn entry only)",
        "lang": "TOEFL / IELTS per Stanford Graduate Admissions minimum requirements",
        "test": {"cls": "GRE scores are NOT considered in the Neurosciences program admissions process."},
        "tui": "Full tuition + living stipend + basic health plan; 3 LOR (up to 4); ETS institution code 4704 (no department code); Knight-Hennessy Scholars deadline October 6, 2026",
        "url": "details/stanford-neurosciences-phd.html",
        "title": "Stanford Neurosciences PhD",
        "school": "Stanford University (School of Medicine / Biosciences family)",
        "curriculum": ("One of 14 Stanford Biosciences PhD programs, single annual autumn entry. "
                       "Students complete Stanford Intensive Neurosciences (SIN) Boot Camp; BIOS 217 Foundations of Statistics and "
                       "Reproducible Research; one graduate statistics course (e.g., STATS 216); nine quarters of Neuroscience Journal Club. "
                       "Five advanced topic courses distributed across three areas: (1) Systems, Computational, Cognitive and Behavioral "
                       "Neuroscience; (2) Cellular, Molecular and Developmental Neuroscience; (3) Translational Neuroscience. "
                       "Comprehensive qualifying exam for PhD candidacy; final dissertation defense with public seminar. "
                       "Timeline: interviews March 3-6, 2027 (in-person); offers mid-March; acceptance deadline April 15, 2027."),
        "src": "https://www.med.stanford.edu/neurogradprogram/prospective_students.html ; https://biosciences.stanford.edu/how-to-apply/"
    },
    {
        "id": "ucsd-neurosciences-phd",
        "s": "ucsd",
        "n": "UC圣地亚哥神经科学博士",
        "en": "Neurosciences PhD (Neurosciences Graduate Program, NGP)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "November 19, 2026, 11:59 PM PST (Fall entry only; application opens September 2, 2026)",
        "lang": "TOEFL iBT minimum 85 (previous scale) / 4.5 (new scale); IELTS per UCSD Graduate Division; exemption if 3.0+ GPA from regionally accredited US or English-only institution",
        "test": {"cls": "GRE is not required. Submission not an application requirement."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; application fee $135 US/PR, $155 international; program code NE75; ETS institution code 4836",
        "url": "details/ucsd-neurosciences-phd.html",
        "title": "UC San Diego Neurosciences PhD",
        "school": "University of California, San Diego (School of Medicine)",
        "curriculum": ("PhD-only program; no terminal Master's. Established 1969; NRC top-ranked neuroscience graduate program. "
                       "Suggested undergraduate preparation: 1 year general biology, calculus, physics; 2 years chemistry; advanced "
                       "coursework in biophysics, biochemistry, cell biology, genetics, molecular biology, neurobiology, microbiology, immunology. "
                       "3 LOR; CV/resume required; minimum GPA 3.0 on 4.0 scale. "
                       "Specialization track in Computational Neuroscience for students with data science background. "
                       "Timeline: decisions January; interview week late Feb-early March; offers by April. "
                       "Note: deadline Nov 19 is earlier than typical Dec 1 cycle."),
        "src": "https://neurograd.ucsd.edu/ ; https://neurograd.ucsd.edu/apply/application-info.html ; https://neurograd.ucsd.edu/apply/faqs-v2.html"
    },
    {
        "id": "columbia-nbb-phd",
        "s": "col",
        "n": "哥伦比亚神经生物学与行为博士",
        "en": "Neurobiology and Behavior PhD (NBB)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "December 1 (Fall entry only; portal opens mid-September)",
        "lang": "TOEFL iBT / IELTS / Duolingo English Test per GSAS policy for non-native English applicants",
        "test": {"cls": "GRE scores are not required."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; ETS institution code 2162 (Columbia GSAS); no US citizenship or permanent residency requirement",
        "url": "details/columbia-nbb-phd.html",
        "title": "Columbia Neurobiology and Behavior PhD",
        "school": "Columbia University (Graduate School of Arts and Sciences)",
        "curriculum": ("Interdisciplinary PhD in Neurobiology and Behavior (NBB), distinct from Morningside Biological Sciences PhD "
                       "(which lists Neuroscience as a subfield). Students enter from diverse backgrounds: computation, engineering, "
                       "psychology, biology. No minimum GPA or specific course requirements; excellence in undergraduate major expected. "
                       "Prior research experience strongly considered; reference letters from research advisors especially helpful. "
                       "Timeline: Open House for selected applicants late Jan/early Feb; acceptance decisions March; student decision deadline "
                       "April 15; incoming student bootcamp in August. "
                       "Note: NBB is a separate doctoral program from the Biological Sciences PhD already in the index; applications to both "
                       "Biological Sciences and CUIMC biomedical programs are permitted but submitted separately."),
        "src": "https://www.neurosciencephd.columbia.edu/content/application-process"
    },
]

# 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)
    # find first [ after 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  # position of closing ]

# 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)
# Insert before closing ]
insert_block = "," + ",".join(new_programs)
# Check preceding char: if last non-ws is [ then no leading comma needed
before = html[:prog_end_pos].rstrip()
if before.endswith("["):
    insert_block = ",".join(new_programs)
else:
    # ensure comma before
    if not before.endswith(","):
        insert_block = "," + ",".join(new_programs)

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

# Now on new_html, locate VERIFIED_DETAILS Set end via paren-depth matching
def find_set_end(text, start_token):
    i = text.find(start_token)
    if i < 0:
        raise RuntimeError("VD token not found")
    # find first ( after 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  # position of closing )

vd_start = "const VERIFIED_DETAILS=new Set("
vd_end_pos = find_set_end(new_html, vd_start)
# Inside Set, find closing ] before )
# Walk backwards from vd_end_pos to find ]
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)
# Insert before closing ]
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))
