import re
from pathlib import Path

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

PAGES = {
    "ucsd-bmb-phd": {
        "id": "ucsd-bmb-phd",
        "s": "ucsd",
        "n": "生物化学与分子生物物理博士",
        "en": "PhD in Biochemistry and Molecular Biophysics (UC San Diego Department of Biochemistry and Molecular Biophysics; top-10 nationally)",
        "dept": "Department of Biochemistry and Molecular Biophysics (BMB)",
        "college": "UC San Diego School of Physical Sciences",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5.5 years full-time average (Fall admission only)",
        "ddl": "Dec 2, 2026 (PhD, Fall 2027). Fee waiver request deadline Nov 18, 2026; fee waiver decisions emailed by Nov 25, 2026. Application opens Sep 2, 2026.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (UCSD graduate minimum). ETS institution code 4836 (no department code needed).",
        "test": {
            "cls": "GRE General Test and GRE Subject Test are NOT required and will NOT be used in the evaluation of the application (department admissions page explicitly states 'The GRE General & GRE Subject are not required and will not be used in the evaluation of your application'). No minimum GRE score. Note: BMB program established as independent graduate program in 2022; department formally established in 2025."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments, fellowships, and NIH T32 training grants (Molecular Biophysics Training Grant). Application fee $135 (US) / $155 (international); fee waivers available. In-person interviews in February 2027; admission offers by April 15, 2027.",
        "url": "details/ucsd-bmb-phd.html",
        "school": "UC San Diego",
        "website": "https://bmb.ucsd.edu/graduates/admissions",
        "overview": "The PhD in Biochemistry and Molecular Biophysics at UC San Diego ranks in the top 10 nationally and represents a traditional strength at UCSD. The program was established as an independent graduate program in 2022, with a new Department of Biochemistry and Molecular Biophysics formally created in 2025 within the School of Physical Sciences. The program prepares students for careers in the biochemical sciences as researchers and educators, with an average graduation time of 5.5 years attributed to the quality of applicants admitted, flexible program of study, opportunity to begin research in the first year, and generous financial support policies. Students work with faculty across the UCSD campus with research programs focused on structural biology, protein, RNA, and lipid biochemistry, experimental and computational biophysics, and systems biology.",
        "requirements": "Required: bachelor's or master's degree in biochemistry, chemistry, molecular biology, biophysics, or a related quantitative life science field. Minimum GPA 3.0 (UCSD graduate minimum; competitive applicants typically 3.5+). 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required and not evaluated. International students: TOEFL/IELTS/DET required. Recommended coursework: calculus, biochemistry, organic and physical chemistry, biology, and preferably cell and molecular biology and mammalian physiology. Contact: bmb-grad@ucsd.edu.",
        "research": "Curriculum: graduate courses in biochemistry, molecular biology, biophysics, and electives; first-year research rotations; thesis proposal; candidacy exam; and dissertation defense. Research areas: Molecular Biophysics, Multiscale Structure and Imaging, RNA Biochemistry, Lipids, and Computation and Data-Driven Biochemistry. The department has 26 faculty (most from the former Biochemistry and Biophysics Section in the Department of Chemistry & Biochemistry), long-running NIH T32 training grant in Molecular Biophysics, and strong cross-campus connections to UCSD School of Medicine, Scripps Institution of Oceanography, and Sanford Burnham Prebys Medical Discovery Institute. In-person interviews in February 2027."
    },
    "ucla-aero-phd": {
        "id": "ucla-aero-phd",
        "s": "ucla",
        "n": "航空航天工程博士",
        "en": "PhD in Aerospace Engineering (UCLA Henry Samueli School of Engineering, Department of Mechanical and Aerospace Engineering)",
        "dept": "Department of Mechanical and Aerospace Engineering (MAE)",
        "college": "UCLA Henry Samueli School of Engineering and Applied Science",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only; MS holders expected to finish one year earlier)",
        "ddl": "Dec 1, 2026, 23:59 PST (PhD and MS, Fall 2027). Application submission period Sep 15 - Dec 1, 2026. Note: Slate servers are on Eastern Time, so applications submitted at 23:59 Pacific appear as 2:59 Eastern next day but are still on time.",
        "lang": "TOEFL iBT / IELTS Academic (UCLA graduate minimum: TOEFL 87, IELTS 7.0). ETS institution code 4837.",
        "test": {
            "cls": "GRE General Test is REQUIRED for the 2027-2028 admissions cycle (MAE graduate admissions page explicitly states 'Note that the GRE is required for the 2027-2028 admissions cycle.'; grad.ucla.edu 2027-2028 requirements page confirms 'GRE: General and Required'). No Subject GRE required. Note: this is one of the few remaining UCLA Samueli engineering departments that still requires GRE; other Samueli departments (CSE, ECE, Bioengineering, BME) have moved to GRE-optional or GRE-not-required."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments and fellowships. Application fee $135 (US) / $155 (international). Students normally admitted as MS students unless they already hold an MS degree; conversion to PhD requires passing the PhD preliminary exam and securing a faculty sponsor (PI). Students with an MS degree expected at enrollment are normally admitted directly as PhD students.",
        "url": "details/ucla-aero-phd.html",
        "school": "UCLA",
        "website": "https://www.mae.ucla.edu/graduate-admissions/",
        "overview": "The PhD in Aerospace Engineering at UCLA is offered through the Department of Mechanical and Aerospace Engineering (MAE), one of the top engineering departments in the country. The program prepares students for research and careers in aerospace engineering, including aerodynamics, propulsion, structural dynamics, flight mechanics, control systems, and space systems. UCLA MAE is particularly renowned for aerospace design, fluid dynamics, combustion, and controls research, with strong ties to the local Southern California aerospace industry (NASA JPL, SpaceX, Northrop Grumman, Boeing, Lockheed Martin). All graduate students (terminal MS or PhD-seeking) are normally admitted as masters students unless they already have an MS degree; conversion to the PhD program and candidacy requires passing the PhD preliminary exam and a faculty sponsor (PI).",
        "requirements": "Required: B.S. or M.S. degree in aerospace engineering, mechanical engineering, or a related engineering/science field. Minimum GPA 3.0 (UCLA graduate minimum; PhD competitive applicants typically 3.5+). 3 letters of recommendation. Statement of Purpose. Personal Statement. Resume/CV. Official transcripts. GRE General Test required. International students: TOEFL/IELTS required. Expected preparation: advanced calculus, differential equations, linear algebra, classical mechanics, thermodynamics, fluid mechanics, aerodynamics, propulsion, and control systems. Contact: maeapp@ucla.edu.",
        "research": "Curriculum: graduate courses in aerospace engineering core (aerodynamics, propulsion, structures, controls, flight mechanics), breadth requirements, PhD preliminary exam, faculty sponsor matching, and dissertation defense. Research areas: Aerodynamics & Fluid Dynamics, Propulsion & Combustion, Structural Dynamics & Materials, Flight Mechanics & Control Systems, Space Systems & Astrodynamics, Computational Fluid Dynamics, Aerospace Design. The department offers MS and PhD degrees in both Aerospace Engineering and Mechanical Engineering; students can cross-register between the two."
    },
    "ucla-cheme-phd": {
        "id": "ucla-cheme-phd",
        "s": "ucla",
        "n": "化学与生物分子工程博士",
        "en": "PhD in Chemical Engineering (UCLA Department of Chemical and Biomolecular Engineering; latest deadline in Samueli School)",
        "dept": "Department of Chemical and Biomolecular Engineering (CBE)",
        "college": "UCLA Henry Samueli School of Engineering and Applied Science",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only)",
        "ddl": "Dec 31, 2026 (PhD and MS, Fall 2027). Note: this is the latest deadline in the entire UCLA Samueli School - one month later than most other Samueli departments (Dec 1). No exceptions; all materials must be received by deadline.",
        "lang": "TOEFL iBT / IELTS Academic (UCLA graduate minimum). ETS institution code 4837.",
        "test": {
            "cls": "GRE is OPTIONAL for the 2027-2028 admissions cycle (CBE graduate admissions page states 'GRE is optional'; PhD degree requirements page confirms 'The Graduate Record Examination (GRE) is NOT required'). No Subject GRE required. Note: older program requirements page (2012-2013 archive) lists GRE as General; the current department admissions page is authoritative."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments and fellowships. Application fee $135 (US) / $155 (international). Minimum undergraduate GPA: PhD 3.5, MS 3.2 (cumulative GPA only; department does not calculate major GPA). No Department Supplement required.",
        "url": "details/ucla-cheme-phd.html",
        "school": "UCLA",
        "website": "https://www.chemeng.ucla.edu/graduate-admissions/",
        "overview": "The PhD in Chemical Engineering at UCLA (Department of Chemical and Biomolecular Engineering, CBE) is one of the top chemical engineering programs in the country. The program is unique in UCLA Samueli for having the latest application deadline (December 31, one month later than most other Samueli departments). The department offers MS and PhD degrees in Chemical Engineering, with research areas spanning bioengineering, energy, materials, semiconductor manufacturing, process systems, and molecular engineering. The PhD program requires a minimum undergraduate GPA of 3.5, higher than UCLA's general graduate minimum of 3.0. The department also offers a specialized track in semiconductor manufacturing for students holding a B.S. in engineering or physical science.",
        "requirements": "Required: B.S. degree in chemical engineering, chemistry, materials science, or a related engineering/physical science field. Minimum cumulative GPA: PhD 3.5, MS 3.2. 3 letters of recommendation. Statement of Purpose. Personal Statement. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Expected preparation: two years of mathematics, physics, chemistry, and engineering. Students specializing in semiconductor manufacturing must hold a B.S. in engineering or physical science. Contact: chemeng@ucla.edu.",
        "research": "Curriculum: graduate courses in chemical engineering core (thermodynamics, transport phenomena, reaction engineering, process control, mathematics), 200-level letter-graded courses (three required), PhD qualifying exam, and dissertation defense. Research areas: Bioengineering & Biomolecular Engineering, Energy & Sustainability, Materials Science & Nanotechnology, Semiconductor Manufacturing, Process Systems Engineering, Molecular Engineering, Computational Science. The department is located in 5531 Boelter Hall. PhD program timeline: Year 1 - coursework and advisor consultation; Year 2 - qualifying exam; Years 3-5 - dissertation research."
    },
    "uchicago-cns-phd": {
        "id": "uchicago-cns-phd",
        "s": "uchicago",
        "n": "计算神经科学博士",
        "en": "PhD in Computational Neuroscience (University of Chicago Committee on Computational Neuroscience; Neuroscience Cluster, Biological Sciences Division)",
        "dept": "Committee on Computational Neuroscience (CNS)",
        "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, Fall 2027). Application opens early September 2026.",
        "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.'). Subject tests are optional. No minimum GRE score. Note: scores older than 5 years (before Dec 1, 2021 for Fall 2027) are not valid."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants. Application fee $90 (US) / $90 (international); fee waivers available. Students may apply to up to four BSD programs with one application; list the program of most interest first as it will be given priority in review.",
        "url": "details/uchicago-cns-phd.html",
        "school": "UChicago",
        "website": "https://cns.uchicago.edu/page/admissions-1",
        "overview": "The PhD in Computational Neuroscience at the University of Chicago is offered through the Committee on Computational Neuroscience (CNS), an interdisciplinary committee comprising faculty from numerous departments in the Physical and Biological Sciences Divisions. Computational neuroscience is inherently interdisciplinary, and most students doing graduate work in this area will have strengths in one of the relevant areas and weaknesses in others. The program is designed to address background deficiencies, so students with uneven backgrounds should not hesitate to apply. Admission is coordinated through the Neuroscience Cluster within the Division of the Biological Sciences (BSD), alongside Neurobiology and Medical Physics. The program requires nine formal courses in the computational neuroscience curriculum and at least nine quarters of research.",
        "requirements": "Required: bachelor's degree (BA/BS) in a relevant field (neuroscience, computer science, mathematics, physics, engineering, psychology, or a related quantitative field). Minimum GPA 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Absolute prerequisite: one year of college-level calculus. Ideally: collegiate-level coursework in biology (optimally including an introductory neurobiology course), an introductory psychology course, and mathematics (linear algebra and elementary differential equations) beyond calculus. Students without prior linear algebra or differential equations may be asked to take remedial courses. Contact: neurograd@uchicago.edu.",
        "research": "Curriculum: nine formal courses in the computational neuroscience curriculum (including computational modeling, neural systems, statistics, and machine learning), at least nine quarters of research, thesis proposal, candidacy exam, and dissertation defense. Research areas: Theoretical Neuroscience, Computational Psychiatry, Machine Learning for Neuroscience, Neural Engineering, Cognitive Neuroscience, Systems Neuroscience. The Committee comprises faculty from Computer Science, Statistics, Psychology, Neurobiology, Physics, and Applied Mathematics. In-person interviews typically held in January/February; admission offers by April 15."
    },
    "stanford-bdsi-phd": {
        "id": "stanford-bdsi-phd",
        "s": "stanford",
        "n": "生物医学数据科学博士",
        "en": "PhD in Biomedical Data Science (Stanford University Department of Biomedical Data Science; Stanford Biosciences PhD program)",
        "dept": "Department of Biomedical Data Science (BDSI)",
        "college": "Stanford University School of Medicine",
        "disc": "cs",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; PhD and Academic MS share same deadline)",
        "ddl": "Dec 1, 2026, 11:59:59pm PST (PhD and Academic MS, Autumn 2027). Late applications will not be accepted. Application opens mid-September 2026.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford graduate minimum: TOEFL 100, IELTS 7.0). ETS institution code 4700.",
        "test": {
            "cls": "GRE General Test score is NOT required and WILL NOT be considered if submitted (department prospective students page explicitly states 'The GRE General Test score is not required and will not be considered if submitted. We do not require any GRE Subject Test scores.'). No minimum GRE score. Note: this is a strict no-GRE policy - submitted scores will not be reviewed, not merely optional."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments, fellowships, and training grants. Application fee $125 (US) / $125 (international). Interview invitations sent mid-January to early February; in-person interview session March 3-6, 2027; admission offers mid-March; final decisions due April 15, 2027. Note: HCP MS and Co-terminal MS programs have different quarterly deadlines.",
        "url": "details/stanford-bdsi-phd.html",
        "school": "Stanford",
        "website": "https://dbds.stanford.edu/for-prospective-students/",
        "overview": "The PhD in Biomedical Data Science at Stanford University is offered through the Department of Biomedical Data Science (BDSI), one of the 14 Stanford Biosciences PhD programs. The program is quantitatively and computationally rigorous, with students taking graduate-level coursework in statistics and computer science at Stanford. The department focuses on interdisciplinary research at the intersection of computer science, statistics, biomedicine, and health care, including biomedical informatics, clinical research, machine learning for healthcare, and data-driven biomedical discovery. The PhD program requires a total of 135 units, with 52 units of formal coursework. In the first year, at least two research rotations are required. Doctoral students are generally advanced to PhD candidacy after passing the qualifying exam by the end of the second year.",
        "requirements": "Required: bachelor's degree in a quantitative field (computer science, statistics, applied mathematics, engineering, bioinformatics, or a related quantitative life science). Minimum GPA 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required and not considered. International students: TOEFL/IELTS/DET required. Expected preparation: strong quantitative and computational background; graduate-level coursework in statistics and computer science is expected at Stanford. Note: applicants are only allowed to submit one application per cycle/academic year. Contact: dbds-phd@stanford.edu.",
        "research": "Curriculum: 135 total units (52 formal coursework units), at least two first-year research rotations, qualifying exam by end of year 2, application for candidacy by beginning of year 3, and dissertation defense. Research areas: Biomedical Informatics, Clinical Research, Machine Learning for Healthcare, Biostatistics, Computational Biology, Health Data Science, Foundation Models for Longitudinal Healthcare Data. The department is part of the Stanford Biosciences umbrella (14 PhD programs), with unified application and interview timeline. In-person interview session March 3-6, 2027."
    },
}

# 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!")
