import re
from pathlib import Path

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

PAGES = {
    "ucla-bmsb-phd": {
        "id": "ucla-bmsb-phd",
        "s": "ucla",
        "n": "生物化学分子与结构生物学博士",
        "en": "PhD in Biochemistry, Molecular and Structural Biology (BMSB) - UCLA Department of Chemistry and Biochemistry",
        "dept": "Department of Chemistry and Biochemistry",
        "college": "UCLA College of Letters and Science (Division of Physical Sciences)",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only; MS only under exceptional circumstances)",
        "ddl": "Dec 5, 2026, 23:59 PST (BMSB PhD, Fall 2027). Note: Chemistry PhD track in same department has Dec 1 deadline; BMSB has Dec 5 deadline - 4 days later. MS only admitted under exceptional circumstances.",
        "lang": "TOEFL iBT / IELTS Academic (UCLA graduate minimum). ETS institution code 4837; BMSB department code 0202.",
        "test": {
            "cls": "GRE General Test is OPTIONAL for all applicants (General and Subject) for Fall 2027 cycle, though department says scores are 'encouraged' for those who have taken them. No Subject GRE required for domestic applicants; international applicants may self-report Subject scores if taken. ETS codes: UCLA R4837, BMSB 0202. Self-reported scores accepted; official scores may be sent after deadline."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/TA appointments and fellowships. Application fee $135 (US) / $155 (international). Note: BMSB (major 009O, housed in Chemistry & Biochemistry) is distinct from the GPB Home Area 'Biochemistry, Biophysics and Structural Biology' (major 0573, housed in the Graduate Programs in Bioscience) - students may apply to either but not both simultaneously.",
        "url": "details/ucla-bmsb-phd.html",
        "school": "UCLA",
        "website": "https://www.chemistry.ucla.edu/graduate/",
        "overview": "The PhD in Biochemistry, Molecular and Structural Biology (BMSB) at UCLA is offered through the Department of Chemistry and Biochemistry, one of the top chemistry and biochemistry departments in the country. The program covers both traditional and modern disciplines in biological chemistry and molecular biology, with faculty research spanning biochemistry, molecular biology, structural biology, biophysics, chemical biology, and mechanistic studies of biological systems. The department offers two PhD tracks - Chemistry (Dec 1) and BMSB (Dec 5) - and students may apply to either but not both at the same time. The MS degree is only offered under exceptional circumstances; the program is primarily PhD-oriented.",
        "requirements": "Required: bachelor's degree in biochemistry, chemistry, molecular biology, or a related quantitative life science field. Minimum GPA 3.0 (UCLA graduate minimum; competitive applicants typically 3.5+). 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE optional (encouraged). International students: TOEFL/IELTS required. Note: this is the Chemistry & Biochemistry department BMSB track (major 009O), not the separate GPB Home Area in the medical school. Contact: cbgrad@ucla.edu; address 4009 Young Hall, Box 951569, Los Angeles, CA 90095-1569.",
        "research": "Curriculum: graduate courses in biochemistry, molecular biology, structural biology, biophysics, and chemical biology; first-year research rotations; candidacy exam; and dissertation defense. Research areas: Protein Structure and Function, Nucleic Acids and RNA Biology, Chemical Biology, Structural Biology (X-ray crystallography, Cryo-EM, NMR), Biophysics, Enzymology, Metabolism, and Computational Biology. The department shares faculty and research infrastructure with UCLA Molecular Biology Institute and the Howard Hughes Medical Institute investigators on campus."
    },
    "uchicago-bmb-phd": {
        "id": "uchicago-bmb-phd",
        "s": "uchicago",
        "n": "生物化学与分子生物物理博士",
        "en": "PhD in Biochemistry and Molecular Biophysics (University of Chicago Graduate Program in Biochemistry and Molecular Biophysics; Molecular Biosciences Cluster, BSD)",
        "dept": "Graduate Program in Biochemistry and Molecular Biophysics (BCMB)",
        "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. Note: older BCMB department page lists Nov 30; BSD unified deadline of Dec 1 is authoritative.",
        "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. Application fee $90 (US) / $90 (international); fee waivers available. Students may apply to one BSD cluster (Molecular Biosciences) and up to four individual units (e.g., BMB, CMB, DRSB, GGSB, Human Genetics) with one application; list the program of most interest first. Interviews held in January/February; admission offers by April 15.",
        "url": "details/uchicago-bmb-phd.html",
        "school": "UChicago",
        "website": "https://bcmb.uchicago.edu/",
        "overview": "The PhD in Biochemistry and Molecular Biophysics at the University of Chicago is offered through the Graduate Program in Biochemistry and Molecular Biophysics (BCMB), part of the Molecular Biosciences Cluster within the Division of the Biological Sciences (BSD). The program trains students at the interface of biochemistry, molecular biology, structural biology, and biophysics, with faculty research spanning structural biology, mechanistic enzymology, gene regulation, membrane biophysics, single-molecule biophysics, chemical biology, and computational biophysics. The BSD uses a unified application: students apply to one cluster (Molecular Biosciences) and may select up to four individual programs of interest, with BMB as one of the options.",
        "requirements": "Required: bachelor's degree in biochemistry, chemistry, biology, biophysics, or a related quantitative field. Minimum GPA 3.0. 3 letters of recommendation. 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: UChicago BSD offers 97 students per class across 365 training faculty at 240 undergraduate degree institutions. Contact: bcmb-admissions@uchicago.edu.",
        "research": "Curriculum: graduate courses in biochemistry, molecular biology, biophysics, and structural biology; first-year research rotations (typically 3 rotations); candidacy exam; thesis proposal; and dissertation defense. Research areas: Structural Biology (X-ray crystallography, Cryo-EM, NMR), Mechanistic Enzymology, Gene Regulation and Chromatin Biology, Membrane Biophysics, Single-Molecule Biophysics, Chemical Biology, RNA Biology, and Computational Biophysics. Faculty have appointments in the Department of Biochemistry and Molecular Biology, Department of Chemistry, James Franck Institute, and Institute for Genomics and Systems Biology."
    },
    "stanford-biochem-phd": {
        "id": "stanford-biochem-phd",
        "s": "stanford",
        "n": "生物化学博士",
        "en": "PhD in Biochemistry (Stanford University Department of Biochemistry; one of 14 Stanford Biosciences PhD programs)",
        "dept": "Department of Biochemistry",
        "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 score is NOT required and WILL NOT be considered if submitted (Stanford Biosciences policy: programs that do not consider GRE will not display submitted scores to admissions committee). No GRE Subject Test required. Note: this is a strict no-GRE policy across all 14 Stanford Biosciences PhD programs - submitted scores are not merely optional, they will not be shown to the review 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. 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-biochem-phd.html",
        "school": "Stanford",
        "website": "https://biochemistry.stanford.edu/resources/phd-graduate-program",
        "overview": "The PhD in Biochemistry at Stanford University is offered through the Department of Biochemistry, one of the 14 Stanford Biosciences PhD programs administered through the Stanford Biosciences umbrella. The program trains students at the interface of biochemistry, molecular biology, structural biology, chemical biology, and quantitative biology, with faculty research spanning protein structure and function, nucleic acid biology, gene regulation, membrane biology, metabolic regulation, and systems biology. Applications are processed through the Stanford Biosciences Admissions Office (not the Department of Biochemistry directly), and all 14 programs share a unified application, deadline, and interview timeline.",
        "requirements": "Required: bachelor's degree in a relevant field (biochemistry, chemistry, biology, or related quantitative life science). 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 required and 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: Jazmyn Lamas, Student & Postdoctoral Affairs Manager, jlamas@stanford.edu.",
        "research": "Curriculum: graduate-level courses in biochemistry, molecular biology, structural biology, and chemical biology; first-year research rotations (at least 2); qualifying exam; candidacy; and dissertation defense. Research areas: Protein Structure and Function, Nucleic Acids (RNA/DNA) Biology, Gene Regulation and Epigenetics, Membrane Biology and Ion Channels, Metabolic Regulation and Signaling, Chemical Biology, Structural Biology (Cryo-EM, X-ray, NMR), and Quantitative/Systems Biology. The department is part of the Stanford Biosciences community (14 PhD programs), with shared first-year curriculum and cross-departmental research opportunities."
    },
    "stanford-bioe-phd": {
        "id": "stanford-bioe-phd",
        "s": "stanford",
        "n": "生物工程博士",
        "en": "PhD in Bioengineering (Stanford University Department of Bioengineering; jointly administered by School of Engineering and School of Medicine)",
        "dept": "Department of Bioengineering",
        "college": "Stanford University School of Engineering & School of Medicine (joint)",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; one application cycle per year)",
        "ddl": "Dec 1, 2026 (PhD and MS, Autumn 2027). Late applications will not be accepted. Knight-Hennessy Scholars deadline: Oct 6, 2026, 1:00pm PT (separate application). Note: Coterminal MS (Stanford current students) has Spring quarter entry with same Dec 1 deadline.",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford graduate minimum: TOEFL 100, IELTS 7.0). ETS institution code 4704.",
        "test": {
            "cls": "Scores from the general or subject GRE are NOT required for admission to the Bioengineering PhD or MS Program for Fall 2027 entry (department How-to-Apply page explicitly states 'Scores from the general or subject Graduate Record Examination (GRE) are not required for admission to the Bioengineering PhD or MS Program for Fall 2027 entry.'). No minimum GPA required. No particular undergraduate major required."
        },
        "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. PhD admission decisions typically by early March; MS decisions by early April. Virtual interviews and visit days by invitation only in March. Note: Bioengineering is jointly administered by School of Engineering and School of Medicine; it is NOT part of the 14 Stanford Biosciences umbrella (separate application).",
        "url": "details/stanford-bioe-phd.html",
        "school": "Stanford",
        "website": "https://bioengineering.stanford.edu/academics-admission/graduate-admission/how-apply",
        "overview": "The PhD in Bioengineering at Stanford University is offered through the Department of Bioengineering, jointly administered by the School of Engineering and the School of Medicine. The program trains students at the intersection of engineering, medicine, and the life sciences, with research spanning bioinformatics, biomechanics, biomaterials, biomedical imaging, cancer systems biology, molecular and cellular bioengineering, neuroengineering, and synthetic biology. Unlike the 14 Stanford Biosciences PhD programs (which share a unified medical school application), Bioengineering is an independent department in the School of Engineering and has its own application review. The department explicitly states it does not require a minimum GPA, GRE scores, particular undergraduate major, or other graduate degrees.",
        "requirements": "Required: bachelor's degree from an accredited institution (US regionally accredited or international equivalent). No minimum GPA required. 3 letters of recommendation. Statement of Purpose (1-3 pages). Transcripts/Education History uploaded directly. GRE not required for Fall 2027. International students: TOEFL/IELTS/DET required (TOEFL 100 minimum). No particular undergraduate major or prior graduate degree required. Note: coterminal MS (Stanford current students only) has separate Spring entry application with same Dec 1 deadline. Contact: bioe-grad@stanford.edu.",
        "research": "Curriculum: graduate-level courses in bioengineering core (quantitative biology, biomechanics, biomaterials, bioimaging, signals and systems); first-year research rotations; qualifying exam; candidacy; and dissertation defense. Research areas: Bioinformatics & Computational Biology, Biomechanics & Mechanobiology, Biomaterials & Drug Delivery, Biomedical Imaging (MRI, optical, ultrasound), Cancer Systems Biology, Molecular & Cellular Bioengineering, Neuroengineering, Synthetic Biology, and Tissue Engineering. The department is jointly based in the School of Engineering and School of Medicine, with strong cross-appointments to Radiology, Genetics, and Chemical Engineering."
    },
    "stanford-apl-phd": {
        "id": "stanford-apl-phd",
        "s": "stanford",
        "n": "应用物理博士",
        "en": "PhD in Applied Physics (Stanford University Department of Applied Physics; one of few Stanford programs still requiring both GRE General and Physics Subject for 2027-28)",
        "dept": "Department of Applied Physics",
        "college": "Stanford University School of Humanities and Sciences",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Autumn admission only; one application cycle per year)",
        "ddl": "Dec 14, 2026, 23:59 PST (PhD and MS, Autumn 2027). Hard deadline, no late applications accepted. Note: this is roughly two weeks later than most other Stanford PhD programs (Dec 1). Knight-Hennessy Scholars applicants must submit KHS application by Oct 6, 2026 and Stanford application by Dec 1, 2026 (one week earlier than regular deadline).",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (Stanford graduate minimum: TOEFL 100, IELTS 7.0). ETS institution code 4704.",
        "test": {
            "cls": "GRE General Test AND Physics GRE Subject Test are BOTH REQUIRED for all applicants for the 2027-2028 admissions cycle (department Admissions Overview and FAQ explicitly state 'The GRE General test and the Physics GRE Subject test are both required for all applicants, as it helps us fairly assess problem-solving skills.'). Note: this is a policy reversal from the 2023-24 bulletin (which listed subject GRE recommended and general GRE optional). Financial hardship waivers possible via Additional Information section with supporting documents. No minimum GPA or score cutoff."
        },
        "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 for financial hardship. Applicants notified of status by mid-February 2027; admitted applicants invited to a two-day Open House. Note: Applied Physics and Physics PhD share the same Dec 14 deadline and same dual-GRE requirement for 2027-28.",
        "url": "details/stanford-apl-phd.html",
        "school": "Stanford",
        "website": "https://ap.columbia.edu/",
        "overview": "The PhD in Applied Physics at Stanford University is offered through the Department of Applied Physics, part of the School of Humanities and Sciences. The program trains students at the intersection of physics and engineering, with research spanning condensed matter physics, photonics, quantum electronics, biophysics, applied math, materials science, plasma physics, and nanoscience. For the 2027-2028 admissions cycle, Applied Physics is one of the few Stanford programs that still requires both the GRE General Test and the Physics GRE Subject Test - a policy reversal from prior cycles where Subject GRE was recommended and General GRE optional. The department explicitly states that no minimum GPA or test score cutoff exists, and all aspects of the application are considered holistically.",
        "requirements": "Required: bachelor's degree in Physics or an equivalent engineering degree (per Stanford Bulletin). No minimum GPA or test score cutoff. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE General Test required. Physics GRE Subject Test required. International students: TOEFL/IELTS/DET required (TOEFL 100 minimum). Note: students unable to take the GRE due to financial hardship may explain in the Additional Information section with supporting documents; exceptions are reviewed case-by-case. Contact: apl-phd@stanford.edu.",
        "research": "Curriculum: graduate-level courses in advanced classical mechanics, quantum mechanics, electromagnetism, statistical mechanics, and specialized applied physics electives; first-year research rotations; qualifying exam; candidacy; and dissertation defense. Research areas: Condensed Matter Physics, Photonics and Quantum Electronics, Quantum Information Science, Biophysics, Applied Mathematics and Scientific Computing, Materials Science and Nanoscale Physics, Plasma Physics, Atomic Physics, and Soft Matter Physics. The department has strong ties to SLAC National Accelerator Laboratory, Geballe Laboratory for Advanced Materials, and Stanford Nano Shared Facilities."
    },
}

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