#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Round 277: add 5 independent PhD pages (Weill Cornell PHS + UCLA GPB 4 Home Areas)."""
import os, re, ast

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

PAGES = [
    {
        "id": "weill-cornell-population-health-sciences-phd",
        "s": "cornell",
        "n": "人群健康科学博士",
        "en": "Population Health Sciences PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years typical",
        "ddl": "Dec 1, 2026 (Early Consideration); Scholarship Feb 1, 2027; Final extension Apr 1, 2027",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test accepted; competitive TOEFL iBT 100+ (pre-Jan 21, 2026) or 5+ new scale; DET 130+",
        "test": {"cls": "GRE not required per program page; GRE/GMAT/LSAT/MCAT optional and recommended to strengthen application; scores valid 5 years; ETS institution code 2119"},
        "tui": "Full tuition + stipend + health benefits guaranteed for all admitted PhD students; application fee $80 (waivable for US citizens/permanent residents/undocumented applicants with demonstrated financial hardship or pipeline program participation)",
        "url": "details/weill-cornell-population-health-sciences-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Department of Population Health Sciences, Graduate School of Medical Sciences",
        "website": "https://phs.weill.cornell.edu/education/phd-program",
        "overview": "The Weill Cornell Population Health Sciences (PHS) PhD is an independent doctoral program at the Weill Cornell Graduate School of Medical Sciences in New York City. The program trains students in quantitative population health research - biostatistics, epidemiology, health policy, health economics, and biomedical informatics - with a strong computational and data science orientation. It is distinct from the Ithaca campus Applied Economics and Management / Policy Analysis PhD programs.",
        "requirements": "Baccalaureate degree from an accredited college or university with strong academic record and demonstrated research interest aligned with faculty. Prerequisite coursework in statistics, calculus, and at least one computer programming or statistical programming language (R, Python, or SAS). Successful applicants typically have a background in public health, statistics/biostatistics, epidemiology, health/biomedical informatics, economics, health policy, computer science, industrial engineering/operations research, quantitative social sciences, mathematics, or medical/genetics/natural sciences. Three letters of recommendation, CV/résumé, and statement of purpose. Application opens September 1; interviews by invitation January/February; decisions mid/late-February; acceptance reply deadline April 15.",
        "research": "Research areas: biostatistics and statistical genetics, causal inference and epidemiology, health economics and policy, health services and outcomes research, biomedical and health informatics, machine learning in medicine, population genetics, and quantitative social science. Students complete at least one 3-credit-hour research rotation before selecting a thesis advisor. Typical time to degree within 5 years. The department also offers MS in Biostatistics & Data Science and MS in Health Policy and Economics (professional master's degrees, separate application).",
    },
    {
        "id": "ucla-bioinformatics-phd",
        "s": "ucla",
        "n": "生物信息学博士",
        "en": "Bioinformatics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only; MS deadline Apr 16, 2027)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General optional, not a requirement, and not recommended for submission per current bioinformatics.ucla.edu admissions page; grad.ucla.edu 2027-2028 catalog (major 025F) lists GRE Not required; no Subject Test required; ETS institution code 4837, dept 0224 (Biological Sciences - Other)"},
        "tui": "Full tuition + stipend + health insurance guaranteed; application fee $120 US / $140 International; major code 025F; official transcripts required before admission (unlike most other GPB Home Areas which require transcripts after admission)",
        "url": "details/ucla-bioinformatics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "UCLA Bioinformatics Interdepartmental PhD Program (GPB Bioinformatics Home Area)",
        "website": "https://bioinformatics.ucla.edu/admissions/",
        "overview": "The UCLA Bioinformatics PhD is an independent interdepartmental doctoral program at UCLA, offered as the Bioinformatics Home Area within the Graduate Programs in Bioscience (GPB). The program admits PhD students only; MS admission is separate (April 16 deadline). Successful applicants are expected to have or acquire a background comparable to the requirements for UCLA's bachelor's degree in Computational and Systems Biology, with a strong background in computer science and mathematics. The program is closely aligned with the Medical Informatics Home Area.",
        "requirements": "Bachelor's degree with strong preparation in computer science, mathematics, statistics, and the biological sciences. Statement of Purpose (no more than 2 pages) addressing: (1) what question in bioinformatics interests you most; (2) describe research experience(s) including publications. Three letters of recommendation from professors, supervisors, or others who can evaluate research accomplishments and potential. CV/résumé and transcripts. Unofficial transcripts at application; official transcripts required before admission for interviewed applicants (one of the few GPB Home Areas requiring transcripts before admission).",
        "research": "Research areas: computational biology and genomics, machine learning in biology, single-cell and spatial transcriptomics, structural bioinformatics, comparative genomics, proteomics, biomedical informatics, clinical data science, and AI-driven drug discovery. Application reviews begin in December; selected applicants invited to UCLA for personal interview in early February; admission offers follow the interview. PhD only - no terminal MS through this Home Area (MS in Bioinformatics is a separate program with April 16 deadline).",
    },
    {
        "id": "ucla-mbidp-bbs-phd",
        "s": "ucla",
        "n": "生物化学生物物理与结构生物学博士",
        "en": "Biochemistry, Biophysics & Structural Biology PhD (MBIDP BBS Home Area)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General optional per UCLA GPB policy since September 2020; no minimum GRE score requirement; GRE Subject Test not required; ETS institution code 4837, dept 74; PhD only (no terminal MS)"},
        "tui": "Full tuition + stipend + health insurance guaranteed; application fee $120 US / $140 International; major code 0573 (Molecular Biology); official transcripts required after admission (unlike Bioinformatics/MMP/Neurosciences/Physics & Biology in Medicine which require before admission)",
        "url": "details/ucla-mbidp-bbs-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Molecular Biology Institute, MBIDP - Biochemistry, Biophysics & Structural Biology (BBS) Home Area",
        "website": "https://www.mbi.ucla.edu/bbs/",
        "overview": "The UCLA Biochemistry, Biophysics & Structural Biology (BBS) PhD is one of four Home Areas within the Molecular Biology Institute Doctoral Program (MBIDP) at UCLA, alongside Cell & Developmental Biology (CDB), Gene Regulation, Epigenomics & Transcriptomics (GREAT), and Immunity, Microbes & Molecular Pathogenesis (IMMP). All four Home Areas share major code 0573 (Molecular Biology) and award the same PhD degree, but each is independently reviewed by its own faculty and director. The BBS Home Area trains students in the molecular and structural basis of biological function.",
        "requirements": "Bachelor's degree from an accredited institution with minimum GPA 3.0 overall (exception request required for GPA below 3.0). Strong preparation in chemistry, biochemistry, physics, mathematics, and biology. Three letters of recommendation. Statement of Purpose required. Unofficial transcripts at application; official transcripts required after admission. International applicants should take TOEFL no later than November to ensure official scores arrive by December 1. PhD only - MBIDP does not accept MS applications.",
        "research": "Research areas: protein structure and folding, cryo-electron microscopy, X-ray crystallography, NMR spectroscopy, enzyme mechanisms, membrane biochemistry, molecular biophysics, single-molecule biophysics, nucleic acid structure, and biophysical chemistry. Students complete at least three laboratory rotations in Year 1 before selecting a thesis advisor. The Eli and Edythe Broad Center for Regenerative Medicine and Stem Cell Research and the California Nanosystems Institute provide core research resources. MBIDP Home Area Director contact: hcoller@ucla.edu.",
    },
    {
        "id": "ucla-mbidp-cdb-phd",
        "s": "ucla",
        "n": "细胞与发育生物学博士",
        "en": "Cell & Developmental Biology PhD (MBIDP CDB Home Area)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General optional per UCLA GPB policy since September 2020; no minimum GRE score requirement; GRE Subject Test not required; ETS institution code 4837, dept 74; PhD only (no terminal MS)"},
        "tui": "Full tuition + stipend + health insurance guaranteed; application fee $120 US / $140 International; major code 0573 (Molecular Biology); official transcripts required after admission",
        "url": "details/ucla-mbidp-cdb-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Molecular Biology Institute, MBIDP - Cell & Developmental Biology (CDB) Home Area",
        "website": "https://www.mbi.ucla.edu/cdb/",
        "overview": "The UCLA Cell & Developmental Biology (CDB) PhD is one of four Home Areas within the Molecular Biology Institute Doctoral Program (MBIDP) at UCLA. CDB trains students in the fundamental processes of single cells and how these processes contribute to the development of entire organisms. The Home Area's strengths span stem cells and regeneration, morphogenesis, metabolism, cell structure and signaling, chromatin biology, and cancer. Students rotate in at least three laboratories during Year 1 before choosing a thesis lab.",
        "requirements": "Bachelor's degree from an accredited institution with minimum GPA 3.0 overall (exception request required for GPA below 3.0). Strong preparation in biology, biochemistry, cell biology, and genetics. Three letters of recommendation. Statement of Purpose required. Unofficial transcripts at application; official transcripts required after admission. International applicants should take TOEFL no later than November. PhD only - MBIDP does not accept MS applications.",
        "research": "Research areas: stem cell biology and regeneration, developmental biology and morphogenesis, cell cycle and division, cell signaling and membrane trafficking, chromatin biology and epigenetics, cancer cell biology, cellular metabolism, and model organism development (C. elegans, Drosophila, zebrafish, mouse). Students work with a mentor who guides training until conferral of the PhD. The Eli and Edythe Broad Center for Regenerative Medicine and the UCLA Center for Cell and Developmental Biology provide core resources.",
    },
    {
        "id": "ucla-mbidp-great-phd",
        "s": "ucla",
        "n": "基因调控表观遗传与转录组学博士",
        "en": "Gene Regulation, Epigenomics & Transcriptomics PhD (MBIDP GREAT Home Area)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General optional per UCLA GPB policy since September 2020; no minimum GRE score requirement; GRE Subject Test not required; ETS institution code 4837, dept 74; PhD only (no terminal MS)"},
        "tui": "Full tuition + stipend + health insurance guaranteed; application fee $120 US / $140 International; major code 0573 (Molecular Biology); official transcripts required after admission",
        "url": "details/ucla-mbidp-great-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Molecular Biology Institute, MBIDP - Gene Regulation, Epigenomics & Transcriptomics (GREAT) Home Area",
        "website": "https://www.mbi.ucla.edu/genereg/",
        "overview": "The UCLA Gene Regulation, Epigenomics & Transcriptomics (GREAT) PhD is one of four Home Areas within the Molecular Biology Institute Doctoral Program (MBIDP) at UCLA. The program trains students in the principles and concepts of contemporary gene regulation research, with an emphasis on developing skills in cellular, proteomic, and genome-wide analyses to study mechanisms of differential gene expression during cell signaling, differentiation, development, and disease. Studies range from basic biochemical analysis of chromatin transcription to detailed analysis of RNA-based pathways in cancer.",
        "requirements": "Bachelor's degree from an accredited institution with minimum GPA 3.0 overall (exception request required for GPA below 3.0). Strong preparation in molecular biology, biochemistry, genetics, and bioinformatics. Three letters of recommendation. Statement of Purpose required. Unofficial transcripts at application; official transcripts required after admission. International applicants should take TOEFL no later than November. PhD only - MBIDP does not accept MS applications.",
        "research": "Research areas: chromatin structure and remodeling, transcription and RNA processing, epigenetics (DNA and histone modifications), deep sequencing and transcriptomics, mass spectrometry and proteomics, genome-wide analysis, gene regulatory networks, RNA-based pathways, cancer biology, and developmental gene regulation. Students are trained to use state-of-the-art technologies including deep sequencing, informatics, and mass spectrometry to study gene regulation across organisms ranging from plants to humans. GREAT Home Area Director: guillom@g.ucla.edu.",
    },
]

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