#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Round 275: add 5 independent Pharmacology / Human Genetics PhD pages."""
import os, re, json, ast

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

PAGES = [
    {
        "id": "duke-pharmacology-phd",
        "s": "duke",
        "n": "药理学博士",
        "en": "Pharmacology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5.5 years average",
        "ddl": "Dec 1, 2026 11:59pm EST",
        "lang": "TOEFL iBT / IELTS / Duolingo required for non-native speakers",
        "test": {"cls": "GRE General Optional (submitted scores reviewed; absence not penalized; self-reported scores require official scores upon admission)"},
        "tui": "Full tuition + fees + annual stipend guaranteed for first year; after Year 1 supported by thesis advisor; average time to completion 5.5 years",
        "url": "details/duke-pharmacology-phd.html",
        "school": "Duke University",
        "dept": "Department of Pharmacology and Cancer Biology",
        "website": "https://pcb.duke.edu/education-training/pharmacology-phd-program",
        "overview": "The Duke Pharmacology PhD is an independent doctoral program in the Department of Pharmacology and Cancer Biology. The program prepares students for independent research careers in academia, industry, and government. Pharmacology is the science of drug action on biological systems, encompassing targets of drug action, mechanisms of action, therapeutic and toxic effects, and development of new therapeutic agents. Duke is consistently ranked among the top pharmacology graduate programs in the nation.",
        "requirements": "Bachelor's degree in biology, chemistry, molecular biology, biochemistry, neuroscience, pharmacy, or related sciences. 3 letters of recommendation required. Statement of Purpose required. Resume/CV required. Unofficial transcripts at application; official transcripts upon admission. Undergraduate GPA on 4.0 scale required.",
        "research": "Particular strengths in receptor function and cellular signaling mechanisms as targets of drug action. Research areas include cancer biology, neuropharmacology, cardiovascular pharmacology, drug metabolism, toxicology, molecular pharmacology, immunopharmacology, receptors and signal transduction, RNA drug development, and drug design. 30 graded units minimum for the degree.",
    },
    {
        "id": "jhu-pharmacology-molecular-sciences-phd",
        "s": "jhu",
        "n": "药理学与分子科学博士",
        "en": "Pharmacology and Molecular Sciences PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (VTSI applicants also Dec 1)",
        "lang": "TOEFL / IELTS required for international applicants",
        "test": {"cls": "GRE NOT required and will not be considered in admissions; applicants should not submit GRE scores (policy per Department of Pharmacology and Molecular Sciences)"},
        "tui": "NIH-supported Pharmacology Graduate Program; full tuition + stipend + health insurance guaranteed for PhD students; 45+ PhD students currently enrolled",
        "url": "details/jhu-pharmacology-molecular-sciences-phd.html",
        "school": "Johns Hopkins University",
        "dept": "Department of Pharmacology and Molecular Sciences (formerly Physiology, Pharmacology & Therapeutics)",
        "website": "https://www.hopkinsmedicine.org/pharmacology-molecular-sciences/graduate-program/prospective-students",
        "overview": "The Johns Hopkins Pharmacology and Molecular Sciences PhD is an independent doctoral program in the Department of Pharmacology and Molecular Sciences at the School of Medicine. The program trains students in drug discovery, protein chemistry, glyco- and lipid-pharmacology, anti-infective agents, oncology therapeutics, neuropharmacology, and clinical pharmacology. Research training covers a broad spectrum of biomedical sciences including chemical biology, immunology, virology, cancer, and neuroscience.",
        "requirements": "B.A. or B.S. degree with a major in biological or physical sciences. Expected coursework: chemistry (inorganic, organic, physical), calculus, physics; strong background in biochemistry particularly desirable. 3 letters of recommendation (at least one from past or current academic/research advisor). CV including research experience, publications, posters, presentations. One-page personal statement. Unofficial transcripts at application; official upon matriculation.",
        "research": "Research areas: signal transduction, structural biology and drug design, NMR spectroscopy, molecular genetics, cancer chemoprevention, viral immunosuppression, cancer immunology, cell-mediated immunity, mechanisms of HIV infection, vaccine development, glycobiology, biomedical mass spectrometry, clinical pharmacology, drug delivery, anti-parasite drug development, histone acetylation and gene regulation. ETS institution code 5316 (JHU PhD Medicine).",
    },
    {
        "id": "ucla-mol-med-pharmacology-phd",
        "s": "ucla",
        "n": "分子与医学药理学博士",
        "en": "Molecular and Medical Pharmacology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL iBT minimum 87 / paper 560; IELTS accepted for international applicants",
        "test": {"cls": "GRE General and Subject optional per UCLA Graduate Division 2027-2028 catalog; department page states 'GRE scores are not required'; as of September 2020 all GPB Home Areas make GRE General optional"},
        "tui": "Full tuition + stipend + health insurance guaranteed; ETS institution code 4837; application fee $120 US / $140 International",
        "url": "details/ucla-mol-med-pharmacology-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Molecular and Medical Pharmacology (David Geffen School of Medicine)",
        "website": "https://pharmacology.ucla.edu/education/mmp-graduate-program/application-requirements",
        "overview": "The UCLA Molecular and Medical Pharmacology (MMP) PhD is an independent doctoral program offered through the Graduate Programs in Bioscience (GPB) as a Home Area. The department admits only applicants whose objective is the PhD; the MS degree is offered only under special circumstances (e.g., students already in the program who cannot continue to PhD, or doctoral-degree holders seeking additional training). The MMP department is one of several basic-science departments in the David Geffen School of Medicine.",
        "requirements": "B.A. or B.S. degree in engineering, physical sciences, or life sciences. Prerequisite courses: basic biology, basic chemistry, organic chemistry, biochemistry, and laboratory. Courses in computer science, engineering, genetics, molecular biology, physical chemistry, and physics encouraged. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Resume. Unofficial transcripts. Fellowship application optional for Graduate Division fellowships.",
        "research": "Research areas include molecular pharmacology, drug action mechanisms, cancer therapeutics, neuropharmacology, cardiovascular pharmacology, gene therapy, imaging, and translational pharmacology. Alternate PhD entry programs: MSTP (Medical Scientist Training Program) and UCLA STAR (Specialty Training and Advanced Research). The Division of Laboratory Animal Medicine jointly offers PhD or postdoctoral training with the MMP department.",
    },
    {
        "id": "weill-cornell-pharmacology-phd",
        "s": "cornell",
        "n": "药理学博士",
        "en": "Pharmacology PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026",
        "lang": "TOEFL required for applicants whose native language is not English",
        "test": {"cls": "GRE General and Subject optional for all Weill Cornell PhD programs; scores valid for 5 years; ETS institution code 2119 for Weill Cornell Graduate School of Medical Sciences"},
        "tui": "Full tuition + stipend + health insurance guaranteed; application fee $80 (waivable for US citizens/permanent residents/undocumented applicants with demonstrated financial hardship or pipeline program participation)",
        "url": "details/weill-cornell-pharmacology-phd.html",
        "school": "Weill Cornell Medicine (Cornell University, New York City campus)",
        "dept": "Graduate School of Medical Sciences, Pharmacology Doctoral Program",
        "website": "https://gradschool.weill.cornell.edu/programs/pharmacology",
        "overview": "The Weill Cornell Pharmacology PhD is an independent doctoral program at the Weill Cornell Graduate School of Medical Sciences in New York City. The program is distinct from the Ithaca campus Biomedical and Biological Sciences (BBS) PhD. A strength of the Weill Cornell Pharmacology Program is proximity to diverse patient populations at affiliated hospitals and the Memorial Sloan Kettering Cancer Institute, enabling translational research on diseases such as cancer, epilepsy, Alzheimer's disease, diabetes, mental illness, alcohol addiction, and heart disease.",
        "requirements": "Baccalaureate degree with strong background in natural sciences and/or health sciences. Research experience strongly encouraged. Application opens September 1. Virtual Open House and application workshops in October/November. Interview invitations sent December/January; interviews by invitation January/February. Admissions decisions sent mid/late-February. Acceptance reply deadline April 15 (CGS resolution).",
        "research": "Research areas: cancer pharmacology, neuropharmacology, cardiovascular pharmacology, drug metabolism, toxicology, proteomics, molecular pharmacology, immunopharmacology, receptors and signal transduction, RNA drug development, and drug design. Year 1 core curriculum includes Essential Principles of Pharmacology, Principles of Pharmacology I-IV (Chemical Biology / Molecular Pharmacology / Cancer), Critical Analysis of Scientific Literature, and electives. Students holding a Master's degree are exempt from one elective requirement.",
    },
    {
        "id": "jhu-human-genetics-genomics-phd",
        "s": "jhu",
        "n": "人类遗传学与基因组学博士",
        "en": "Human Genetics and Genomics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 15, 2026 (VTSI applicants Dec 1, 2026)",
        "lang": "TOEFL / IELTS required for international applicants",
        "test": {"cls": "GRE no longer required per JHU School of Medicine catalogue; applicants not required to submit GRE scores"},
        "tui": "Full tuition + minimum stipend USD 52,000 (2026-27) + health insurance guaranteed for at least 5 years; VTSI fellowship for eligible students from HBCU/community college/regional MD-VA-DC undergrad institutions",
        "url": "details/jhu-human-genetics-genomics-phd.html",
        "school": "Johns Hopkins University",
        "dept": "Department of Genetic Medicine, Human Genetics and Genomics Training Program",
        "website": "https://e-catalogue.jhu.edu/medicine/graduate-programs/human-genetics-genomics-phd/",
        "overview": "The Johns Hopkins Human Genetics and Genomics PhD is an independent doctoral training program in the Department of Genetic Medicine at the School of Medicine. The program provides training in all aspects of human genetics and genomics relevant to human biology, health, and disease. The program aims to educate students at the interface between genetics and medicine. It is also offered as training for medical students in the combined MD/PhD program. Fall matriculation only.",
        "requirements": "Strong academic foundation with coursework in biology, chemistry, and quantitative analysis. Encouraged: exposure to lab research or data science. Bachelor's degree from a qualified college or university required for matriculation. 3 letters of recommendation. One-page personal statement indicating basis of interest in graduate study and career objectives, including discussion of research experience. Up-to-date CV. Unofficial transcripts at application; official upon matriculation.",
        "research": "Curriculum provides strong foundation in basic science through rigorous graduate education in genetics, genomics, molecular biology, cell biology, biochemistry, and biostatistics, plus a core of medically-related courses selected to provide knowledge of human biology in health and disease. ETS institution code 5316 (JHU PhD Medicine). VTSI (Vivien Thomas Scholars Initiative) applicants must submit all application and supplementary materials by December 1.",
    },
]

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:
    """Append new program entries to PROGRAMS array and new URLs to VERIFIED_DETAILS set."""
    # Build new PROGRAMS block
    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)

    # Locate PROGRAMS array: find `const PROGRAMS=[` then depth-match to closing `]`
    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()  # position right after `[`
    depth = 1
    i = start
    while i < len(html) and depth > 0:
        ch = html[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
        i += 1
    # i is position after closing `]`
    close_pos = i - 1  # position of `]`
    # Insert new_block before `]`, with leading comma if previous content is non-empty and doesn't end with comma
    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

    # Now re-locate VERIFIED_DETAILS set on the NEW html (positions shifted!)
    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()  # position after `[`
    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  # position of `]`
    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():
    # Pre-inject fields used by template
    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"]

    # Write detail HTML files
    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']}")

    # Read index_main.html
    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()
