import re
from pathlib import Path

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

PAGES = {
    "berkeley-mfe": {
        "id": "berkeley-mfe",
        "s": "berkeley",
        "n": "金融工程硕士",
        "en": "Master of Financial Engineering (MFE, UC Berkeley Haas School of Business)",
        "dept": "Haas School of Business",
        "college": "UC Berkeley",
        "disc": "bus",
        "lvl": "m",
        "deg": "MFE",
        "stem": 1,
        "dur": "1 year full-time (also 2-year Flex part-time option, no F-1 for part-time)",
        "ddl": "Spring 2028 entry only (no Fall admission). R1: Dec 1, 2026 9am ET; R2: Jan 27, 2027; R3: Apr 1, 2027; R4: Jul 1, 2027. Late applications accepted to Jul 15, 2027 space-available.",
        "lang": "TOEFL iBT 90 (Home Edition accepted; MyBest / ITP / Duolingo NOT accepted) / IELTS Academic 7.0. ETS code 4833, dept 82.",
        "test": {
            "cls": "GRE General or GMAT / GMAT Focus REQUIRED for all applicants. Test scores must be no older than Jan 1, 2023. ETS code 4833, dept 4399. Waiver available only for: (a) PhD degree holder before starting MFE; or (b) 4-year US bachelor's with final cumulative GPA 3.70+ on 4.0 scale (GPA cannot be rounded; non-US degrees not eligible). Admitted class profile: ~91st percentile average Quant (reference distribution, not minimum threshold)."
        },
        "tui": "Tuition ~$80,000 total for 1-year program (2025 cohort); living expenses ~$25,000. Career services and internship support included. No formal funding package for MFE.",
        "url": "details/berkeley-mfe.html",
        "school": "UC Berkeley",
        "website": "https://mfe.haas.berkeley.edu/admissions",
        "overview": "The Berkeley MFE is a one-year, full-time STEM-designated professional graduate degree offered by the Haas School of Business. It integrates finance, mathematics, data science, machine learning, and computer programming. Students specialize in areas such as portfolio management, trading, data science, quantitative research, strats and modeling, derivative valuation, risk management, and asset management. A two-year Flex option exists for working professionals, but F-1 visas are not issued for part-time enrollment. The program starts in March (Spring) only; there is no Fall admission.",
        "requirements": "Required: bachelor's degree in finance, economics, statistics, mathematics, engineering, CS, or related quantitative field. GPA 3.0+ upper-division minimum (competitive applicants higher). Strong quantitative prerequisites: calculus, multivariable calculus, linear algebra, differential equations, numerical analysis, advanced probability/statistics or econometrics; programming in C++ and Python; at least 2 finance/economics courses. 2 letters of recommendation (from people who know quantitative work). Resume. Essays. 2-minute video essay. Interview by invitation. Professional experience preferred but not required. Application fee $275.",
        "research": "Curriculum: asset/liability modeling, derivative valuation, securities structuring, sales and trading, investment banking, risk management, financial data science, machine learning in finance, algorithmic trading, fintech, private equity, asset management, quantitative research. Careers at hedge funds, investment banks, commercial banks, insurance, fintech, asset management, corporate treasuries."
    },
    "berkeley-cph-phd": {
        "id": "berkeley-cph-phd",
        "s": "berkeley",
        "n": "计算精准健康博士（UCSF 联合）",
        "en": "PhD in Computational Precision Health (UC Berkeley × UCSF Joint Program)",
        "dept": "Joint Computational Precision Health Graduate Group",
        "college": "UC Berkeley / UCSF",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only; application opens Sep 24, 2026).",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "GRE NOT required for admission; GRE scores will not be evaluated or considered even if submitted. No minimum GPA but 4.0-scale GPA calculation required on application."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees) through the joint Berkeley/UCSF graduate group.",
        "url": "details/berkeley-cph-phd.html",
        "school": "UC Berkeley",
        "website": "https://computationalhealth.berkeley.edu/admissions/",
        "overview": "The PhD in Computational Precision Health (CPH) is a joint program between UC Berkeley and UCSF, admitting its inaugural cohort in Fall 2023. The program bridges computational sciences (machine learning and AI, NLP, statistical inference, data standards, parallel computing, data at scale) and health sciences (clinical decision sciences, cognitive informatics, clinical delivery, implementation science, health information policy). Students develop interdisciplinary research skills from ideation to real-world validation. The application is submitted through UC Berkeley; students may also apply to a separate UCSF program in the same cycle.",
        "requirements": "Required: bachelor's degree with demonstrated excellence in at least two of three core areas: (1) mathematics, statistics, probability fundamentals; (2) programming in procedural language (Python, Java, C++, R); (3) biological or health sciences. Students weak in one area may compensate with core coursework at matriculation. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required.",
        "research": "Research areas: machine learning for healthcare, clinical NLP, medical imaging, predictive health models, biomedical informatics, implementation science, health policy, data standards, clinical decision support, population health, AI ethics in medicine, human-centered design, interdisciplinary research across Berkeley and UCSF campuses."
    },
    "berkeley-ib-phd": {
        "id": "berkeley-ib-phd",
        "s": "berkeley",
        "n": "综合生物学博士",
        "en": "PhD in Integrative Biology (UC Berkeley Department of Integrative Biology)",
        "dept": "Department of Integrative Biology",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Nov 19, 2026 (Fall admission only; no Spring admission).",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833, dept 0203.",
        "test": {
            "cls": "GRE General NOT required. GRE Subject (Biology or other relevant) NOT required. No minimum score if submitted. GRE Institution code 4833; Department code 0203."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Direct-admit program - no lab rotation; students enter directly into a specific faculty member's lab.",
        "url": "details/berkeley-ib-phd.html",
        "school": "UC Berkeley",
        "website": "https://ib.berkeley.edu/graduate-program/admissions/",
        "overview": "The Department of Integrative Biology admits students to the PhD program only (no terminal MS). The department takes a whole-organism approach, spanning genome, proteome, organismal traits, populations, communities, and ecosystems. Three main research areas: Tree of Life (Biodiversity and Global Change), Tangled Bank (Species Interactions and Biological Communities), and Human Connections (Origins, Health and Quality of Life). IB is a direct-admit program - there are no lab rotations; students enter directly into a particular faculty member's lab. Applicants are strongly advised to contact potential faculty mentors before applying.",
        "requirements": "Required: bachelor's degree in biological sciences or related field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. Must list at least one potential IB faculty member on application. GRE not required. International students: TOEFL/IELTS required. Prior research experience expected.",
        "research": "Research areas: evolutionary biology, ecology, organismal biology, biodiversity, global change biology, species interactions, community ecology, comparative physiology, biomechanics, developmental biology, population biology, conservation biology, origins of human diversity, ecological and ecosystem processes."
    },
    "berkeley-espm-phd": {
        "id": "berkeley-espm-phd",
        "s": "berkeley",
        "n": "环境科学政策与管理博士",
        "en": "PhD in Environmental Science, Policy, and Management (UC Berkeley)",
        "dept": "Department of Environmental Science, Policy, and Management",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only; TOEFL scores deadline Dec 20, 2026).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833, dept 40.",
        "test": {
            "cls": "GRE NOT required. As of Fall 2019, ESPM no longer requires or evaluates GRE scores. No GRE Subject Test required. Admissions is holistic: grades, research experience, letters of recommendation, personal statements. Admitted GPA range typically 3.5-3.7 (reference distribution, not minimum threshold)."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). ~35-40 offers made per year from 300-400 applicants; 25-30 new students enroll annually (acceptance rate ~10%).",
        "url": "details/berkeley-espm-phd.html",
        "school": "UC Berkeley",
        "website": "https://ourenvironment.berkeley.edu/graduate-programs/admissions",
        "overview": "The ESPM PhD is the main graduate program in Environmental Science, Policy, and Management at UC Berkeley. Students choose one of three disciplinary emphases: Ecosystem Sciences, Organisms and Environment, or Society and Environment. The program requires three core courses plus coursework in specialization, research skills, and experiential breadth. Graduates pursue careers in academia, government, and non-governmental agencies worldwide. The department also offers limited MS degrees in specialized areas: Master of Range Management and Master of Forestry.",
        "requirements": "Required: bachelor's degree in environmental science, ecology, biology, policy, or related field. GPA minimum 3.0 (competitive applicants 3.5-3.7). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Prospective students encouraged to contact potential PhD mentor before applying.",
        "research": "Research areas: ecosystem science, forestry, wildlife ecology, environmental policy, environmental management, insect biology, microbial ecology, environmental science, climate adaptation, conservation, sustainable development, urban ecology, energy and society, planetary health. Interdisciplinary across natural sciences, social sciences, and policy."
    },
    "berkeley-neuro-phd": {
        "id": "berkeley-neuro-phd",
        "s": "berkeley",
        "n": "神经科学博士",
        "en": "PhD in Neuroscience (UC Berkeley Neuroscience Graduate Program)",
        "dept": "Neuroscience Graduate Program",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Nov 19, 2026 at 8:59pm PST (Fall admission only; application opens Sep 24, 2026; no Spring admission; no late applications accepted).",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "GRE Optional for Fall 2027. Submitting GRE scores is not required and not submitting will not count against applicants. No minimum score. Application fee: $135 US citizens / permanent residents; $155 international."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). ~10 entering students per year. ~65 training faculty across Neuroscience Department and HWNI affiliates.",
        "url": "details/berkeley-neuro-phd.html",
        "school": "UC Berkeley",
        "website": "https://neuroscience.berkeley.edu/grad/admissions",
        "overview": "The Berkeley Neuroscience PhD program is an interdisciplinary, selective program that grants PhDs only (no master's degree offered). The program trains approximately 10 entering students per year across four broad research areas: Cellular and Molecular Neuroscience; Circuit, Systems and Behavioral Neuroscience; Human Cognition; and Computational Neuroscience. Approximately 65 training faculty are affiliated from the Neuroscience Department and the Helen Wills Neuroscience Institute (HWNI) faculty in other allied departments. Admissions are holistic, considering academic preparation, research experience, personal attributes, and program synergy.",
        "requirements": "Required: bachelor's degree in biology, chemistry, psychology, physics, engineering, CS, or related field. GPA minimum 3.0. 3 letters of recommendation. Resume/CV. Statement of Purpose. Personal History Statement. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Prior research experience expected.",
        "research": "Research areas: cellular and molecular neuroscience, systems and circuits, behavioral neuroscience, cognitive neuroscience, computational neuroscience, neural engineering, neuroimaging, developmental neuroscience, disease mechanisms, synaptic plasticity, neural computation. First two years require coursework in three broad areas: Cellular/Molecular/Developmental; Systems and Computational; Cognitive and Behavioral."
    }
}

TEMPLATE = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} - {n}</title>
<style>
body {{ font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; max-width: 900px; margin: 0 auto; padding: 24px; line-height: 1.7; color: #222; }}
h1 {{ color: #1a3a6b; border-bottom: 2px solid #1a3a6b; padding-bottom: 8px; }}
h2 {{ color: #2a5a9b; margin-top: 28px; }}
.meta {{ background: #f5f7fa; padding: 16px; border-radius: 8px; margin: 16px 0; }}
.meta div {{ margin: 4px 0; }}
.label {{ font-weight: 600; color: #555; }}
.url {{ word-break: break-all; }}
</style>
</head>
<body>
<h1>{school}</h1>
<h2>{n}</h2>
<p><em>{en}</em></p>
<div class="meta">
<div><span class="label">学院/系：</span>{dept}</div>
<div><span class="label">学位：</span>{deg}（{lvl_label}）</div>
<div><span class="label">学制：</span>{duration}</div>
<div><span class="label">截止：</span>{ddl}</div>
<div><span class="label">语言：</span>{lang}</div>
<div><span class="label">标化：</span>{test_cls}</div>
<div><span class="label">学费/资助：</span>{tui}</div>
<div><span class="label">官网：</span><a href="{website}" target="_blank" class="url">{website}</a></div>
</div>
<h2>项目概述</h2>
<p>{overview}</p>
<h2>申请要求</h2>
<p>{requirements}</p>
<h2>研究方向</h2>
<p>{research}</p>
</body>
</html>'''

def render_page(p):
    lvl_label = "博士" if p["lvl"] == "d" else "硕士"
    stem_label = "（STEM）" if p["stem"] else ""
    return TEMPLATE.format(
        school=p["school"],
        n=p["n"],
        en=p["en"],
        dept=p["dept"],
        deg=p["deg"],
        lvl_label=lvl_label + stem_label,
        duration=p["dur"],
        ddl=p["ddl"],
        lang=p["lang"],
        test_cls=p["test"]["cls"],
        tui=p["tui"],
        website=p["website"],
        overview=p["overview"],
        requirements=p["requirements"],
        research=p["research"],
    )

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

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