#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Round 276: add 5 independent PhD pages (Weill Cornell NYC 4 + UCLA Human Genetics)."""
import os, re, json, ast

ROOT = os.path.dirname(os.path.abspath(__file__))
INDEX = os.path.join(ROOT, "index_main.html")

PAGES = [
    {
        "id": "weill-cornell-bcmb-allied-phd",
        "s": "cornell",
        "n": "生物化学与分子生物学联盟博士",
        "en": "BCMB Allied Program PhD (Biochemistry & Structural Biology / Cell & Developmental Biology / Molecular Biology)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL / IELTS / Duolingo accepted for non-native speakers; NACES member transcript evaluation required for post-secondary degrees outside the US",
        "test": {"cls": "GRE General optional for all Weill Cornell PhD programs; scores valid for 5 years; ETS institution code 2119; no minimum GPA or test score required"},
        "tui": "Full tuition + stipend + health benefits + subsidized NYC housing guaranteed; application fee $80 (waivable for US citizens/permanent residents/undocumented applicants with demonstrated financial hardship or pipeline program participation)",
        "url": "details/weill-cornell-bcmb-allied-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Graduate School of Medical Sciences, BCMB Allied Program",
        "website": "https://gradschool.weill.cornell.edu/programs/biochemistry-cell-biology-molecular-biology-bcmb",
        "overview": "The Weill Cornell BCMB Allied Program is an interdisciplinary doctoral program uniting three historically separate PhD programs - Biochemistry & Structural Biology, Cell & Developmental Biology, and Molecular Biology - under a single admissions umbrella since 1995. With over 150 member laboratories across Weill Cornell Medicine and the Sloan Kettering Institute, BCMB offers research training spanning structural biology, cell signaling, developmental biology, and molecular pathways controlling cell growth. The program is distinct from the Ithaca campus BBS PhD.",
        "requirements": "Baccalaureate degree with strong undergraduate coursework in natural sciences and at least one significant research experience. Application opens September 1. Three laboratory rotations in Year 1 help students select a thesis mentor by end of Year 1; the mentor's research area determines the program assignment (Biochemistry & Structural Biology, Cell & Developmental Biology, or Molecular Biology). Admissions decisions sent mid/late-February. Acceptance reply deadline April 15 (CGS resolution).",
        "research": "Year 1 core curriculum: Molecular Genetics, Biochemistry and Structural Biology, Cell Biology, Gene Structure/Function, and Logic and Critical Analysis. Spring of Year 2: Admission to Doctoral Candidacy Examination (ACE) - written NIH-style research proposal plus oral defense. Years 2-4: two elective courses; research in the chosen program area. Research areas: cryo-EM, single-molecule fluorescence, membrane biochemistry, chromatin structure, gene expression, cell signaling, cancer and neurodegenerative disease mechanisms, tissue development and stem cell biology.",
    },
    {
        "id": "weill-cornell-immunology-microbial-pathogenesis-phd",
        "s": "cornell",
        "n": "免疫学与微生物致病机理博士",
        "en": "Immunology & Microbial Pathogenesis PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL / IELTS / Duolingo required for non-native speakers",
        "test": {"cls": "Applicants are not required to take the General Graduate Record Examination (GRE); optional for all Weill Cornell PhD programs; ETS institution code 2119"},
        "tui": "Full tuition + stipend + health benefits + subsidized NYC housing guaranteed; application fee $80 (waivable)",
        "url": "details/weill-cornell-immunology-microbial-pathogenesis-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Graduate School of Medical Sciences, Immunology & Microbial Pathogenesis Doctoral Program",
        "website": "https://gradschool.weill.cornell.edu/programs/immunology-microbial-pathogenesis",
        "overview": "The Weill Cornell Immunology & Microbial Pathogenesis (IMP) PhD is an independent doctoral program at the Weill Cornell Graduate School of Medical Sciences in New York City. The program trains students in immunology, microbiology, and microbial pathogenesis, with research spanning host-pathogen interactions, immune regulation, vaccine development, and infectious disease mechanisms. It is distinct from the Ithaca campus Biomedical and Biological Sciences (BBS) PhD.",
        "requirements": "Strong undergraduate background and record of engagement in biological sciences, including immunology, biochemistry, molecular genetics, and microbiology. Expected undergraduate laboratory research experience. Official undergraduate transcript. Three letters of recommendation from faculty who can evaluate academic and research potential. Personal statement describing background and specific interest in the IMP program. TOEFL required for non-native English speakers.",
        "research": "Research areas: innate and adaptive immunity, immune cell development and differentiation, autoimmunity, cancer immunology, host-pathogen interactions, viral and bacterial pathogenesis, vaccine development, mucosal immunology, and immunotherapy. Program Coordinator: Thelma Lopez. Year 1 includes core coursework and laboratory rotations before selecting a thesis advisor.",
    },
    {
        "id": "weill-cornell-neuroscience-phd",
        "s": "cornell",
        "n": "神经科学博士",
        "en": "Neuroscience PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL / IELTS / Duolingo accepted for non-native speakers",
        "test": {"cls": "Applicants are not required to take the Graduate Record Examination (GRE); optional for all Weill Cornell PhD programs; ETS institution code 2119"},
        "tui": "Full tuition + stipend + health benefits + subsidized NYC housing guaranteed; application fee $80 (waivable)",
        "url": "details/weill-cornell-neuroscience-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Graduate School of Medical Sciences, Neuroscience Doctoral Program",
        "website": "https://gradschool.weill.cornell.edu/programs/neuroscience",
        "overview": "The Weill Cornell Neuroscience PhD is an independent doctoral program at the Weill Cornell Graduate School of Medical Sciences in New York City. The program trains students in neuroscience at the molecular, cellular, systems, and behavioral levels, with research spanning neural development, synaptic function, neurodegenerative disease, neurobiology of disease, and computational neuroscience. It is distinct from the Ithaca campus Neurobiology and Behavior graduate field.",
        "requirements": "Thorough undergraduate training in neuroscience, psychology, biology, immunology, organic chemistry, physics, and/or mathematics. Online application required. International applicants must provide proof of English language proficiency (TOEFL, IELTS, or Duolingo). Application opens September 1; interviews by invitation January/February; admissions decisions mid/late-February; acceptance reply deadline April 15.",
        "research": "Research areas: molecular and cellular neuroscience, developmental neuroscience, synaptic transmission and plasticity, systems and computational neuroscience, neurodegenerative disease (Alzheimer's, Parkinson's), neuro-oncology, neuro-immunology, and sensory neuroscience. Proximity to NewYork-Presbyterian Hospital and Rockefeller University enables cross-institutional research collaborations. Program contact: Maullika Dua.",
    },
    {
        "id": "weill-cornell-pbsb-phd",
        "s": "cornell",
        "n": "生理学生物物理与系统生物学博士",
        "en": "Physiology, Biophysics & Systems Biology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL / IELTS / Duolingo accepted for non-native speakers",
        "test": {"cls": "GRE optional for all Weill Cornell PhD programs; ETS institution code 2119; no minimum GPA or test score required; holistic review"},
        "tui": "Full tuition + stipend + health benefits + subsidized NYC housing guaranteed; application fee $80 (waivable)",
        "url": "details/weill-cornell-pbsb-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Graduate School of Medical Sciences, Physiology, Biophysics & Systems Biology Doctoral Program",
        "website": "https://gradschool.weill.cornell.edu/programs/physiology-biophysics-systems-biology",
        "overview": "The Weill Cornell Physiology, Biophysics & Systems Biology (PBSB) PhD is an independent doctoral program that brings together quantitative approaches - physics, chemistry, computer science, statistics, and mathematics - to address fundamental questions in biological systems relevant to human health. The program emphasizes spatial transcriptomics, metabolomics, cryo-electron microscopy, single-molecule imaging, and machine learning as tools to understand chromatin architecture, transmembrane signaling, and tumor-immune microenvironment interactions.",
        "requirements": "Baccalaureate degree with demonstrated excellence and intellectual ambition in prior coursework and at least one significant research experience. Successful applicants typically have meaningful exposure to biochemistry, molecular biology, chemistry, physics, statistics, calculus, linear algebra, and coding (Python, C, Matlab, R, or similar). Bioinformatics-track applicants benefit from machine learning exposure; Biophysics-track applicants benefit from differential equations. First-year advisors help design an individualized program of study.",
        "research": "Research areas: 3D chromatin architecture and gene regulation, macromolecular assembly dynamics and transmembrane signaling, tumor-immune stromal interactions, spatial transcriptomics, single-molecule biophysics, cryo-EM, computational biology, and systems physiology. Candidacy exam expected by July of Year 2. Special Committee consists of thesis advisor plus two additional Graduate School faculty advisors.",
    },
    {
        "id": "ucla-human-genetics-phd",
        "s": "ucla",
        "n": "人类遗传学博士",
        "en": "Human Genetics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical (normative TTD 16 quarters; max 24)",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL / IELTS required for international applicants",
        "test": {"cls": "GRE General and Subject optional per UCLA Graduate Division 2027-2028 catalog (major 0994); as of September 2020 all GPB Home Areas make GRE General optional; no minimum GRE score requirement"},
        "tui": "Full tuition + stipend + health insurance guaranteed; ETS institution code 4837; application fee $120 US / $140 International; major code 0994",
        "url": "details/ucla-human-genetics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Human Genetics, David Geffen School of Medicine (GPB Genetics and Genomics Home Area)",
        "website": "https://grad.ucla.edu/requirements/?app=admission&major=0994",
        "overview": "The UCLA Human Genetics PhD is an independent doctoral program in the Department of Human Genetics at the David Geffen School of Medicine, offered through the Graduate Programs in Bioscience (GPB) as the Genetics and Genomics Home Area. The program admits only PhD applicants; the MS degree is offered only under exceptional circumstances after consultation with and approval by the Department of Human Genetics. The program trains the next generation of leaders in human genetics, with research spanning statistical genetics, genomic technologies, gene regulation, and disease genetics.",
        "requirements": "Bachelor's degree with preparation through upper-division courses in genetics, biology, molecular biology, cell biology, or other life sciences. Advanced courses in statistics or computer science may be substituted for advanced biologically-oriented courses given the data analysis expertise required in some areas of human genetics. More advanced degrees (M.S., M.D. or equivalent) are also acceptable. Three letters of recommendation. Statement of Purpose required. Unofficial transcripts at application.",
        "research": "Research areas: statistical genetics and genomics, genomic technologies, gene regulation and epigenomics, population genetics, evolutionary genetics, complex disease genetics, neurogenetics, cancer genetics, and ethical, legal, and social implications (ELSI) of human genetics. Written Qualifying Examination (First Exam) and University Oral Qualifying Examination (Second Exam) required before advancement to candidacy. Normative time to ATC: 10 quarters; normative TTD: 16 quarters; maximum TTD: 24 quarters. Articulated MD/PhD program available.",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} - {en} | {school}</title>
<style>
body{{font-family:-apple-system,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;max-width:960px;margin:0 auto;padding:24px;color:#222;line-height:1.6}}
h1{{font-size:24px;border-bottom:3px solid #1a5fb4;padding-bottom:10px}}
h2{{font-size:18px;color:#1a5fb4;margin-top:28px;border-left:4px solid #1a5fb4;padding-left:10px}}
.meta{{background:#f5f7fa;padding:14px;border-radius:6px;margin:16px 0;display:grid;grid-template-columns:repeat(2,1fr);gap:8px 20px}}
.meta b{{color:#555}}
.card{{background:#fff;border:1px solid #e0e4ea;border-radius:8px;padding:16px;margin:12px 0;box-shadow:0 1px 3px rgba(0,0,0,.04)}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a5fb4;padding:2px 10px;border-radius:12px;font-size:12px;margin-right:6px}}
a{{color:#1a5fb4}}
</style>
</head>
<body>
<h1>{n} <small style="font-size:14px;color:#888">({en})</small></h1>
<p><span class="tag">{school}</span><span class="tag">{dept}</span><span class="tag">{lvl_label}</span></p>

<div class="meta">
<div><b>学位：</b>{deg}</div>
<div><b>学制：</b>{duration}</div>
<div><b>申请截止：</b>{ddl}</div>
<div><b>语言要求：</b>{lang}</div>
<div><b>标化：</b>{test_cls}</div>
<div><b>学费/资助：</b>{tui}</div>
</div>

<h2>项目概览</h2>
<div class="card"><p>{overview}</p></div>

<h2>申请要求</h2>
<div class="card"><p>{requirements}</p></div>

<h2>研究方向</h2>
<div class="card"><p>{research}</p></div>

<h2>官方链接</h2>
<div class="card"><p><a href="{website}" target="_blank">{website}</a></p></div>

<p style="color:#888;font-size:12px;margin-top:30px">本页面为项目库核验页，信息以学校官网最新公布为准。录取分布数据非最低门槛。</p>
</body>
</html>
"""


def append_programs_and_vd(html: str, new_entries: list) -> str:
    new_lines = []
    for p in new_entries:
        line = (
            f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",deg:"{p["deg"]}",'
            f'lvl:"{p["lvl"]}",stem:{p["stem"]},dur:"{p["dur"]}",ddl:"{p["ddl"]}",'
            f'lang:"{p["lang"]}",test:{{cls:"{p["test"]["cls"]}"}},tui:"{p["tui"]}",url:"{p["url"]}"}}'
        )
        new_lines.append(line)
    new_block = ",\n".join(new_lines)

    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html) and depth > 0:
        ch = html[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
        i += 1
    close_pos = i - 1
    before = html[:close_pos].rstrip()
    after = html[close_pos:]
    if before.endswith(","):
        html = before + "\n" + new_block + "\n" + after
    else:
        html = before + ",\n" + new_block + "\n" + after

    m2 = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[", html)
    if not m2:
        raise RuntimeError("VERIFIED_DETAILS set not found")
    vstart = m2.end()
    depth = 1
    j = vstart
    while j < len(html) and depth > 0:
        ch = html[j]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
        j += 1
    vclose = j - 1
    vd_urls = ",\n".join(f'"{p["url"]}"' for p in new_entries)
    vbefore = html[:vclose].rstrip()
    vafter = html[vclose:]
    if vbefore.endswith(","):
        html = vbefore + "\n" + vd_urls + "\n" + vafter
    else:
        html = vbefore + ",\n" + vd_urls + "\n" + vafter
    return html


def main():
    for p in PAGES:
        p["lvl_label"] = "Doctoral" if p["lvl"] == "d" else "Master's"
        p["duration"] = p["dur"]
        p["test_cls"] = p["test"]["cls"]

    for p in PAGES:
        out = DETAIL_TEMPLATE.format(**p)
        path = os.path.join(ROOT, p["url"].replace("/", os.sep))
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write(out)
        print(f"wrote {p['url']}")

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

    orig_size = len(html.encode("utf-8"))
    new_html = append_programs_and_vd(html, PAGES)
    new_size = len(new_html.encode("utf-8"))
    print(f"index_main.html: {orig_size} -> {new_size} bytes (delta +{new_size-orig_size})")

    with open(INDEX, "w", encoding="utf-8") as f:
        f.write(new_html)
    print("done.")


if __name__ == "__main__":
    main()
