import re
from pathlib import Path

ROOT = Path(r"D:\work buddy\2026-11-05-14-15-52")
INDEX = ROOT / "index_main.html"

PAGES = {
    "stanford-biophysics-phd": {
        "id": "stanford-biophysics-phd",
        "s": "stanford",
        "n": "生物物理博士",
        "en": "PhD in Biophysics (Stanford University; one of 14 Stanford Biosciences PhD programs)",
        "dept": "Biophysics Graduate Program",
        "college": "Stanford University School of Medicine",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; one application cycle per year)",
        "ddl": "Dec 1, 2026, 11:59:59pm PST (Autumn 2027). Late applications will not be accepted. Application opens mid-September 2026. Interview session March 3-6, 2027; admission offers mid-March; acceptances due April 15, 2027.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford graduate minimum: TOEFL 100, IELTS 7.0). ETS institution code 4704 (no department code needed).",
        "test": {
            "cls": "GRE General Test and GRE Subject Test scores are NOT considered for admission to Stanford Biosciences PhD programs (Stanford Graduate Admissions: 'If your graduate program does not consider GRE scores, any GRE scores we receive will not be displayed to the admission committee'). No minimum GRE score. Strict no-GRE policy across all 14 Biosciences PhD programs."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants. Application fee $125 (US) / $125 (international); fee waivers available. Knight-Hennessy Scholars deadline: Oct 6, 2026, 1:00pm PT (separate application required). Note: applicants may only submit one application per cycle; all 14 Stanford Biosciences PhD programs share a unified application and timeline.",
        "url": "details/stanford-biophysics-phd.html",
        "school": "Stanford",
        "website": "https://biosciences.stanford.edu/program/biophysics/",
        "overview": "The PhD in Biophysics at Stanford University is offered through the Biophysics Graduate Program, one of the 14 Stanford Biosciences PhD programs administered through the Stanford Biosciences umbrella. The program trains students at the interface of physics, chemistry, biology, and computation, with research spanning structural biology, single-molecule biophysics, membrane biophysics, computational biophysics, biophotonics, and quantitative biology. Applications are processed through the Stanford Biosciences Admissions Office (not the department directly), and all 14 programs share a unified application, deadline, and interview timeline.",
        "requirements": "Required: bachelor's degree in a relevant field (physics, chemistry, biophysics, biology, engineering, or related quantitative field). Minimum GPA per Stanford graduate minimum. 3 letters of recommendation (maximum 4 accepted). Statement of Purpose (1-3 pages). Official transcripts (unofficial uploaded; official required upon acceptance). GRE not considered. International students: TOEFL/IELTS/DET required (TOEFL 100 minimum). Note: applicants are only allowed to submit one application per cycle/academic year. Contact: biosciences@stanford.edu.",
        "research": "Curriculum: graduate-level courses in biophysics, structural biology, physical chemistry, and quantitative biology; first-year research rotations (at least 2); qualifying exam; candidacy; and dissertation defense. Research areas: Structural Biology (X-ray crystallography, Cryo-EM, NMR), Single-Molecule Biophysics, Membrane Biophysics, Computational Biophysics, Biophotonics and Imaging, Quantitative Systems Biology, and Biophysics of Disease. Faculty have appointments in Structural Biology, Radiation Oncology, Applied Physics, and SLAC National Accelerator Laboratory."
    },
    "stanford-cancer-phd": {
        "id": "stanford-cancer-phd",
        "s": "stanford",
        "n": "癌症生物学博士",
        "en": "PhD in Cancer Biology (Stanford University School of Medicine; one of 14 Stanford Biosciences PhD programs)",
        "dept": "Cancer Biology Graduate Program",
        "college": "Stanford University School of Medicine",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; one application cycle per year)",
        "ddl": "Dec 1, 2026, 11:59:59pm PST (Autumn 2027). Late applications will not be accepted. Application opens mid-September 2026. Interview session March 3-6, 2027; admission offers mid-March; acceptances due April 15, 2027. Note: the Oct 16, 2026 date on the program page refers to a separate workshop/early event, not the PhD application deadline.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford graduate minimum: TOEFL 100, IELTS 7.0). ETS institution code 4704 (no department code needed).",
        "test": {
            "cls": "GRE General Test and GRE Subject Test scores are NOT considered for admission to Stanford Biosciences PhD programs. No minimum GRE score. Strict no-GRE policy across all 14 Biosciences PhD programs; submitted scores will not be displayed to the admissions committee."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants (including NCI T32 Cancer Biology Training Grant). Application fee $125 (US) / $125 (international); fee waivers available. Knight-Hennessy Scholars deadline: Oct 6, 2026, 1:00pm PT (separate application required). The program directors are Erinn Rankin (Radiation Oncology / Obstetrics and Gynecology) and Aaron Newman (Biomedical Data Science).",
        "url": "details/stanford-cancer-phd.html",
        "school": "Stanford",
        "website": "https://med.stanford.edu/cancerbiology.html",
        "overview": "The PhD in Cancer Biology at Stanford University is offered through the Cancer Biology Graduate Program, one of the 14 Stanford Biosciences PhD programs. The program trains students at the interface of basic cancer biology, translational oncology, cancer immunology, cancer genomics, and cancer data science. The program welcomes students from diverse scientific backgrounds (molecular biology, genetics, immunology, biomedical engineering, computational biology, and related fields). The 2026 entering class included 8 students from Northwestern, Simmons, Harvard/Stanford MD, Stanford MSTP, Northeastern, Claremont McKenna, MD Anderson/Washington State, and UCLA.",
        "requirements": "Required: bachelor's degree in a relevant field (biology, biochemistry, biomedical engineering, immunology, genetics, computational biology, or related). Minimum GPA per Stanford graduate minimum. 3 letters of recommendation (maximum 4 accepted). Statement of Purpose (1-3 pages). Official transcripts. GRE not considered. International students: TOEFL/IELTS/DET required (TOEFL 100 minimum). Note: applicants may only submit one application per cycle/academic year. Contact: biosciences@stanford.edu.",
        "research": "Curriculum: graduate-level courses in cancer biology, molecular biology, genetics, immunology, and cancer data science; first-year research rotations (at least 2); qualifying exam; candidacy; and dissertation defense. Research areas: Tumor Microenvironment and Immunology, Cancer Genetics and Genomics, Cancer Cell Biology, Cancer Therapeutics and Drug Resistance, Cancer Bioinformatics and Data Science, Radiation Biology, and Translational Cancer Research. Faculty have appointments in the Departments of Radiation Oncology, Obstetrics and Gynecology (Oncology), Biomedical Data Science, Genetics, Microbiology & Immunology, and Stem Cell Biology & Regenerative Medicine."
    },
    "stanford-csb-phd": {
        "id": "stanford-csb-phd",
        "s": "stanford",
        "n": "化学生物与系统生物学博士",
        "en": "PhD in Chemical and Systems Biology (Stanford University; NRC top-ranked pharmacology-related training program; one of 14 Stanford Biosciences PhD programs)",
        "dept": "Department of Chemical and Systems Biology",
        "college": "Stanford University School of Medicine",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; one application cycle per year)",
        "ddl": "Dec 1, 2026, 11:59:59pm PST (Autumn 2027). Late applications will not be accepted. Application opens mid-September 2026. Knight-Hennessy Scholars deadline: Oct 6, 2026, 1:00pm PT (separate application).",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford minimum per program page: TOEFL 90 pre-1/21/26; TOEFL 100 post-1/21/26 per graduate minimum; IELTS 7.0). ETS institution code 4704.",
        "test": {
            "cls": "GRE General Test and GRE Subject Test scores are NOT considered for admission to Stanford Biosciences PhD programs. No minimum GRE score. Strict no-GRE policy across all 14 Biosciences PhD programs; submitted scores will not be displayed to the admissions committee."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants. Application fee $125 (US) / $125 (international); fee waivers available. Note: NRC ranked the program top among pharmacology-related training programs in the United States based on student GRE scores, faculty publications, median time to degree, program requirements, and training resources.",
        "url": "details/stanford-csb-phd.html",
        "school": "Stanford",
        "website": "https://chemsysbio.stanford.edu/",
        "overview": "The PhD in Chemical and Systems Biology at Stanford University is offered through the Department of Chemical and Systems Biology, one of the 14 Stanford Biosciences PhD programs. The program is uniquely focused on understanding cell biology at the molecular and systems levels, with faculty expertise in biochemistry, chemistry, physics, and engineering. The research community includes scientists trained in molecular biology, cell biology, chemistry, physics, and engineering. The National Research Council named the program the top pharmacology-related training program in the United States. The department emphasizes collaborative learning, developing novel technologies for basic research, and translating discoveries into therapeutic strategies.",
        "requirements": "Required: bachelor's degree in a relevant field (chemistry, biochemistry, biology, physics, engineering, or related quantitative field). Minimum GPA per Stanford graduate minimum. 3 letters of recommendation (maximum 4 accepted). Statement of Purpose (1-3 pages). Official transcripts. GRE not considered. International students: TOEFL/IELTS/DET required. Note: applicants may only submit one application per cycle/academic year. Contact: csb-phd@stanford.edu.",
        "research": "Curriculum: graduate-level courses in chemical biology, systems biology, molecular biology, biochemistry, and quantitative biology; first-year research rotations (at least 2); qualifying exam; candidacy; and dissertation defense. Research areas: Chemical Biology and Probe Development, Systems Biology and Cell Signaling, Single-Cell Analysis, Genomics and Functional Genomics, Drug Discovery and Therapeutics, Synthetic Biology, and Quantitative Cell Biology. The department is interdisciplinary, spanning molecular biology, cell biology, chemistry, physics, and engineering."
    },
    "uchicago-cancer-phd": {
        "id": "uchicago-cancer-phd",
        "s": "uchicago",
        "n": "癌症生物学博士",
        "en": "PhD in Cancer Biology (University of Chicago Committee on Cancer Biology; Biomedical Sciences Cluster, BSD)",
        "dept": "Committee on Cancer Biology (CCB)",
        "college": "University of Chicago Division of the Biological Sciences",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only)",
        "ddl": "Dec 1, 2026, 11:59pm CT (all BSD PhD programs unified deadline, Autumn 2027). Application opens early September 2026. Late applications reviewed only at Dean's discretion; incomplete applications evaluated on materials received at regular review.",
        "lang": "TOEFL iBT / IELTS Academic (UChicago graduate minimum). ETS institution code 1832 (no department code needed).",
        "test": {
            "cls": "GRE is OPTIONAL for all PhD programs in the Biological Sciences Division (BSD Admissions FAQ explicitly states 'The GRE test is optional for all PhD programs. However, if you have taken the GRE test within the last 5 years and wish to submit your scores, you may do so by sending the results to institution code 1832.'). No department code needed. Subject tests are optional. Scores older than 5 years (before Dec 1, 2021 for Autumn 2027) are not valid."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants (including NCI T32 Cancer Biology Training Grant). Application fee $90 (US) / $90 (international); fee waivers available. Students may apply to one BSD cluster (Biomedical Sciences) and up to four individual units (e.g., Cancer Biology, Immunology, Microbiology, Molecular Metabolism) with one application. Interviews held in January/February recruitment weekends; admission offers by April 15.",
        "url": "details/uchicago-cancer-phd.html",
        "school": "UChicago",
        "website": "http://graduateannouncements.uchicago.edu/graduate/committeeoncancerbiology/",
        "overview": "The PhD in Cancer Biology at the University of Chicago is offered through the Committee on Cancer Biology (CCB), part of the Biomedical Sciences Cluster within the Division of the Biological Sciences (BSD). The program provides multidisciplinary and integrated training in cancer biology with an emphasis on innovation and critical thinking in cancer research. With 60 faculty members from across the University of Chicago, students have a broad choice of research concentrations for their thesis project. The program prepares students for leadership and research careers in academia, industry, clinical research, science journalism, advocacy and policy, and other areas of the biomedical workforce.",
        "requirements": "Required: bachelor's degree in a relevant field (biology, biochemistry, biomedical engineering, genetics, immunology, or related). Minimum GPA 3.0. 3 letters of recommendation addressing scientific abilities and potential. Statement of Purpose. Official transcripts. GRE optional (scores must be within 5 years). International students: TOEFL/IELTS required. Previous research experience is considered a strong asset. Note: apply to Biomedical Sciences cluster and select Cancer Biology as degree program. Contact: ccb-admissions@uchicago.edu.",
        "research": "Curriculum: 7 course credits consisting of basic science, cancer biology, and elective courses; first-year research rotations; qualifying examination; thesis proposal; and dissertation defense. Research areas: Molecular Mechanisms of Cancer, Tumor Progression and Metastasis, Autophagy and Tumor Metabolism, Cancer Genomics, Computational Approaches and Big Data Analysis, Mechanisms of Drug Resistance and Tumor Heterogeneity, and Translational Research Approaches. The committee comprises 60 faculty across the University of Chicago, including Pritzker School of Medicine, Department of Human Genetics, Department of Medicine, and Department of Radiation and Cellular Oncology."
    },
    "ucla-bio-phd": {
        "id": "ucla-bio-phd",
        "s": "ucla",
        "n": "生物学博士（生态与进化方向）",
        "en": "PhD in Biology (Ecology and Evolutionary Biology) - UCLA Department of Ecology and Evolutionary Biology; one of 18 Graduate Programs in Biosciences",
        "dept": "Department of Ecology and Evolutionary Biology (EEB)",
        "college": "UCLA College of Letters and Science (Division of Life Sciences)",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only; MS specialization in Ecology and Evolution of Medicine also admits Spring)",
        "ddl": "Dec 1, 2026 (PhD, Fall 2027). MS specializing in Ecology and Evolution of Medicine: May 1, 2027 (Fall and Spring admission). Note: PhD admission is limited to Fall only.",
        "lang": "TOEFL iBT / IELTS Academic (UCLA graduate minimum). ETS institution code 4837.",
        "test": {
            "cls": "GRE scores are NO LONGER CONSIDERED during the application review process (department Requirements page explicitly states 'Please note GRE scores are no longer considered during the application review process. You may see a place for them on the general application, but you do not need to send us an official score report.'). No minimum GRE score. Subject tests not required."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments and fellowships. Application fee $135 (US) / $155 (international); fee waivers available. Recent entering PhD cohorts: 10-15 PhD students and 4-7 MS students per year. Students enter with a provisional faculty advisor; final advisor chosen after first-year coursework and rotations.",
        "url": "details/ucla-bio-phd.html",
        "school": "UCLA",
        "website": "https://www.eeb.ucla.edu/graduate",
        "overview": "The PhD in Biology (Ecology and Evolutionary Biology) at UCLA is offered through the Department of Ecology and Evolutionary Biology (EEB), one of 18 Graduate Programs in Biosciences at UCLA. The doctoral program prepares students to excel in research, academia, industry, and governmental/non-governmental organizations. Students have access to seminars and courses on a wide range of topics in evolutionary biology, ecology, and animal behavior, as well as biomathematics, theoretical modeling, and statistics. The department does not require specific coursework for admission, but applicants should demonstrate sufficient preparation for advanced scholarship in ecology, evolution, and/or behavior. Admission is highly competitive, with recently admitted cohorts ranging from 10-15 PhD and 4-7 MS students.",
        "requirements": "Required: bachelor's degree in biology or related field. Minimum undergraduate cumulative GPA 3.0. 3 letters of recommendation (preferably from professors familiar with research ability). Statement of Purpose. CV. Diversity statement. Official transcripts. GRE not required and not considered. International students: TOEFL/IELTS required. Desirable background: chemistry, physics, and mathematics. Note: the department encourages applications from students in all areas of science, but expects successful applicants to have or acquire a background comparable to the UCLA bachelor's in biology. Contact: eebgrad@ucla.edu.",
        "research": "Curriculum: minimum 20 units of graduate-level (200-series) courses; first-year required courses EEB M200A, 200B, and 250; one advanced course (100 or 200 series) in statistics, biomathematics, or bioinformatics; Departmental Written Qualifying Examination in first year (8-10 page research proposal); oral qualifying exam; and dissertation defense. Research areas: Evolutionary Biology, Ecology (terrestrial, marine, freshwater), Animal Behavior, Computational Biology and Bioinformatics, Biomathematics and Theoretical Modeling, Conservation Biology, and Marine Biology. The department is located in the Life Sciences Building and shares facilities with the UCLA Institute of the Environment and Sustainability."
    },
}

# Render detail pages
TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} {deg} {n} - 项目详情</title>
<style>
body{{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7;background:#fafafa}}
h1{{color:#1a3a6c;border-bottom:3px solid #c8102e;padding-bottom:10px;font-size:1.6em}}
h2{{color:#1a3a6c;margin-top:28px;font-size:1.2em;border-left:4px solid #c8102e;padding-left:10px}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin:18px 0}}
.card{{background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:14px;box-shadow:0 1px 3px rgba(0,0,0,0.06)}}
.card b{{color:#c8102e;display:block;margin-bottom:4px;font-size:0.9em}}
.card span{{font-size:0.95em}}
a{{color:#1a5fb4;word-break:break-all}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a3a6c;padding:2px 8px;border-radius:4px;font-size:0.85em;margin-right:6px}}
</style>
</head>
<body>
<h1>{school} {deg} · {n}</h1>
<p><span class="tag">{en}</span><span class="tag">{college}</span><span class="tag">{dept}</span></p>
<div class="grid">
<div class="card"><b>学位</b><span>{deg}（{lvl_label}）</span></div>
<div class="card"><b>时长</b><span>{dur}</span></div>
<div class="card"><b>截止日期</b><span>{ddl}</span></div>
<div class="card"><b>语言要求</b><span>{lang}</span></div>
<div class="card"><b>标化考试</b><span>{test_cls}</span></div>
<div class="card"><b>学费/资助</b><span>{tui}</span></div>
</div>
<h2>项目概览</h2>
<p>{overview}</p>
<h2>申请要求</h2>
<p>{requirements}</p>
<h2>课程与研究方向</h2>
<p>{research}</p>
<h2>官方链接</h2>
<p>官网项目页：<a href="{website}" target="_blank">{website}</a></p>
</body>
</html>"""

def render_page(p):
    lvl_label = "博士项目" if p["lvl"] == "d" else "硕士项目"
    test_cls = p["test"]["cls"]
    return TEMPLATE.format(
        school=p["school"], deg=p["deg"], n=p["n"], en=p["en"],
        college=p["college"], dept=p["dept"], lvl_label=lvl_label,
        dur=p["dur"], ddl=p["ddl"], lang=p["lang"], test_cls=test_cls,
        tui=p["tui"], overview=p["overview"], requirements=p["requirements"],
        research=p["research"], website=p["website"],
    )

for key, p in PAGES.items():
    out = ROOT / "details" / f"{key}.html"
    out.write_text(render_page(p), encoding="utf-8")
    print(f"Written: details/{key}.html")

html = INDEX.read_text(encoding="utf-8")
before_size = len(html.encode("utf-8"))
print(f"\nBefore size: {before_size} bytes")

def build_program_record(p):
    stem_val = 1 if p["stem"] else 0
    return (
        f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",'
        f'deg:"{p["deg"]}",lvl:"{p["lvl"]}",stem:{stem_val},dur:"{p["dur"]}",'
        f'ddl:"{p["ddl"]}",lang:"{p["lang"]}",test:{{cls:"{p["test"]["cls"]}"}},'
        f'tui:"{p["tui"]}",url:"{p["url"]}"}}'
    )

new_records = ",".join(build_program_record(p) for p in PAGES.values())

prog_match = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
if not prog_match:
    raise Exception("PROGRAMS array not found")

start = prog_match.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
    i += 1

insert_pos = i - 1
j = insert_pos - 1
while j >= 0 and html[j] in ' \t\n\r':
    j -= 1
if html[j] != ',':
    new_block = "," + new_records
else:
    new_block = new_records

html = html[:insert_pos] + new_block + html[insert_pos:]

vd_match = re.search(r'const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', html)
if not vd_match:
    raise Exception("VD Set not found")

vd_start = vd_match.end()
depth = 1
i = vd_start
while i < len(html) and depth > 0:
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
    i += 1

vd_insert_pos = i - 1
vd_new_items = ",".join(f'"{p["url"]}"' for p in PAGES.values())

j = vd_insert_pos - 1
while j >= 0 and html[j] in ' \t\n\r':
    j -= 1
if html[j] != ',':
    vd_new_block = "," + vd_new_items
else:
    vd_new_block = vd_new_items

html = html[:vd_insert_pos] + vd_new_block + html[vd_insert_pos:]

after_size = len(html.encode("utf-8"))
print(f"After size: {after_size} bytes")
print(f"Delta: +{after_size - before_size} bytes")

INDEX.write_text(html, encoding="utf-8")
print(f"\nPROGRAMS appended: {len(PAGES)} entries")
print(f"VD appended: {len(PAGES)} urls")
print("Done!")
