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-me-ms": {
        "id": "berkeley-me-ms",
        "s": "berkeley",
        "n": "机械工程硕士",
        "en": "MS in Mechanical Engineering (UC Berkeley Department of Mechanical Engineering)",
        "dept": "Department of Mechanical Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (MS/PhD combined track; Fall admission only)",
        "ddl": "Dec 1, 2026 at 8:59pm PST (PhD/MS/CWO same deadline; no Spring admission; late applications not accepted).",
        "lang": "TOEFL iBT 90 (tests before Jan 21, 2026) / new TOEFL 5+ with 4.5 Speaking/Writing (tests on/after Jan 21, 2026). IELTS 7.0 (old) / 7.0 with 6.5 Speaking/Writing (new). ETS code 4833.",
        "test": {
            "cls": "GRE NOT required for Fall 2027 admission cycle (confirmed by ME department). No Subject GRE required. Note: MS is typically awarded along the PhD path; terminal MS admission is rare and highly competitive. The separate Professional MEng has a Jan 6, 2027 deadline and requires 2 letters."
        },
        "tui": "Tuition ~$26,000/year resident / ~42,000/non-resident + fees. Research assistantships (GSR) and teaching assistantships (GSI) available for PhD-track admits; MS-only admits typically self-fund.",
        "url": "details/berkeley-me-ms.html",
        "school": "UC Berkeley",
        "website": "https://me.berkeley.edu/graduate/admissions/",
        "overview": "The MS in Mechanical Engineering at UC Berkeley is a research-oriented degree offered through the Department of Mechanical Engineering. Most students pursue the MS/PhD combined track, with the MS awarded en route to the PhD. The program emphasizes application of natural sciences to engineering systems analysis and solution. Research areas include energy conversion, mechanical systems, controls, design, manufacturing, biomechanical engineering, heat transfer, and fluid mechanics. The separate 5th-year MS is restricted to current UC Berkeley undergraduates and is not open to external applicants.",
        "requirements": "Required: bachelor's degree in engineering, physics, or related quantitative field. GPA minimum 3.0 (Berkeley Graduate Division). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Prerequisites: undergraduate coursework in calculus, differential equations, physics, thermodynamics, mechanics, and basic programming. Contact: mech@me.berkeley.edu, (510) 642-5084.",
        "research": "Curriculum: advanced engineering mathematics, continuum mechanics, thermodynamics, fluid mechanics, heat transfer, controls, dynamics, design methodology, and electives across mechanical engineering. Research groups: Biomechanical Engineering, Design, Controls, and Manufacturing, Energy Science & Technology, Solid Mechanics, Fluid Mechanics, and Ocean Engineering. Facilities include the Berkeley Lab, Jacobs Institute, and Technology Entrepreneurship program."
    },
    "berkeley-mse-ms": {
        "id": "berkeley-mse-ms",
        "s": "berkeley",
        "n": "材料科学与工程硕士",
        "en": "MS in Materials Science and Engineering (UC Berkeley Department of Materials Science & Engineering)",
        "dept": "Department of Materials Science & Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (MS/PhD combined track; Fall admission only)",
        "ddl": "Dec 1, 2026 at 8:59pm PST (PhD/MS/5th Year same deadline; MEng has separate Jan 14, 2027 deadline).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "GRE Optional (MSE department states General GRE is optional; Berkeley Graduate Division lists GRE=Optional for MS/PhD). Historical guide PDF references 85th percentile as desirable but current department policy is optional. Note: MSE PhD deadline Dec 1, 2026; MEng professional deadline Jan 14, 2027."
        },
        "tui": "Tuition ~$26,000/year resident / ~42,000/non-resident + fees. GSR/GSI support available for PhD-track admits. MEng is a self-funded professional program.",
        "url": "details/berkeley-mse-ms.html",
        "school": "UC Berkeley",
        "website": "https://mse.berkeley.edu/graduate-admissions/",
        "overview": "The MS in Materials Science and Engineering at UC Berkeley is offered through the Department of Materials Science & Engineering. The department offers three graduate degree programs: Master of Engineering (MEng, professional), 5th-Year BS/MS (UC Berkeley undergraduates only), and Doctor of Philosophy (PhD, with MS awarded en route). The research-oriented MS/PhD program trains students in the relationship between structure and properties of materials, from nanoscale to bulk. Research areas include electronic materials, energy materials, biomaterials, structural materials, computational materials science, and synthesis/characterization.",
        "requirements": "Required: bachelor's degree in engineering, physics, or chemistry (MSE does not accept applicants without these degree backgrounds). GPA minimum 3.0 (international applicants should be in top 5% of class). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Prerequisites: undergraduate physics, chemistry, calculus, linear algebra, and basic materials science. Contact: mse_academic@berkeley.edu.",
        "research": "Curriculum: thermodynamics of materials, kinetics, crystallography, mechanical behavior, electronic materials, magnetic materials, optical materials, biomaterials, computational materials science, and characterization techniques (TEM, SEM, XRD, AFM). Research groups: Electronic and Photonic Materials, Energy Storage and Conversion, Structural Materials, Soft Materials and Biomaterials, and Materials Theory. Many students collaborate with Lawrence Berkeley National Laboratory."
    },
    "berkeley-nuclear-ms": {
        "id": "berkeley-nuclear-ms",
        "s": "berkeley",
        "n": "核工程硕士",
        "en": "MS in Nuclear Engineering (UC Berkeley Department of Nuclear Engineering)",
        "dept": "Department of Nuclear Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (Fall admission only; MS/MPP concurrent also available)",
        "ddl": "Dec 1, 2026 at 8:59pm PST (MS/MPP deadline; PhD deadline is Dec 8, 2026, one week later; MEng professional deadline Jan 6, 2027).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 Academic (Nuclear Engineering department confirms IELTS 7.0 overall). ETS code 4833 (no separate department code required).",
        "test": {
            "cls": "GRE General REQUIRED for all applicants (Nuclear Engineering department explicitly requires official General GRE scores sent through ETS; this is one of the few Berkeley engineering departments still mandating GRE). Scores valid for 5 years. Note: PhD deadline Dec 8 is one week later than MS Dec 1."
        },
        "tui": "Tuition ~$26,000/year resident / ~42,000/non-resident + fees. GSR/GSI support available for PhD-track admits. Application fee $135 (US) / $155 (international); fee waivers available for US citizens/permanent residents demonstrating financial need.",
        "url": "details/berkeley-nuclear-ms.html",
        "school": "UC Berkeley",
        "website": "https://nuc.berkeley.edu/graduate-admissions/",
        "overview": "The MS in Nuclear Engineering at UC Berkeley is offered through the Department of Nuclear Engineering, one of the top-ranked nuclear engineering programs in the world. The department offers three graduate degrees: Doctor of Philosophy (PhD), Master of Engineering (MEng, professional, one-year), and the Public Policy (MPP)/Nuclear Engineering (MS) concurrent degree with the Goldman School of Public Policy. Research areas include nuclear fission reactors, nuclear fusion, radiation transport, medical physics, nuclear materials, non-proliferation and policy, and nuclear energy systems analysis. The MS/MPP concurrent degree allows students to earn both degrees in two years including a summer internship.",
        "requirements": "Required: bachelor's degree in engineering, physics, or related quantitative field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE General REQUIRED. International students: TOEFL/IELTS required (IELTS 7.0 overall). Prerequisites: calculus, differential equations, linear algebra, physics (mechanics, electromagnetism, modern physics), and basic nuclear engineering recommended. Contact: admissions-nuc@berkeley.edu.",
        "research": "Curriculum: nuclear reactor physics, radiation detection and measurement, thermal hydraulics, reactor design, radiation transport, nuclear materials, plasma physics and fusion, medical physics, and nuclear energy policy. Research groups: Fusion Science, Fission and Reactor Physics, Radiation Science and Dosimetry, Nuclear Materials, and Energy and Nuclear Security. Facilities include the Berkeley Research Reactor (BCR) and collaboration with Lawrence Livermore National Laboratory."
    },
    "berkeley-mcp": {
        "id": "berkeley-mcp",
        "s": "berkeley",
        "n": "城市规划硕士",
        "en": "Master of City Planning (MCP, UC Berkeley Department of City & Regional Planning)",
        "dept": "Department of City and Regional Planning (DCRP)",
        "college": "UC Berkeley College of Environmental Design",
        "disc": "soc",
        "lvl": "m",
        "deg": "MCP",
        "stem": 1,
        "dur": "2 years full-time on-campus",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only; concurrent MCP/CEE, MArch/MCP, MLA/MCP also Dec 1).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "GRE Optional (Berkeley Graduate Division lists GRE=Optional for MCP). MCP is a STEM-designated degree (officially approved field of study within U.S. Homeland Security STEM list), qualifying graduates for 36-month OPT extension. PAB-accredited (Planning Accreditation Board)."
        },
        "tui": "Tuition ~$26,000/year resident / ~42,000/non-resident + fees. Departmental fellowships and GSI positions available. Concurrent degree programs with MArch, MLA, and CEE professional MS also available.",
        "url": "details/berkeley-mcp.html",
        "school": "UC Berkeley",
        "website": "https://ced.berkeley.edu/academics/city-regional-planning/graduate-programs",
        "overview": "The two-year Master of City Planning (MCP) at UC Berkeley is one of the oldest accredited planning programs in the United States. The program comprises a solid core of knowledge in city and regional planning, including history and theory, planning skills and methods, planning law, and urban economics. Students specialize in one or two of four concentration areas: Environmental Planning and Healthy Cities (EPHC); Housing, Community and Economic Development (HCED); Transportation Policy and Planning; and Urban Design. The MCP is STEM-designated, qualifying international graduates for the 36-month OPT extension. Concurrent dual degrees are available with Architecture (MArch/MCP), Landscape Architecture (MLA/MCP), and Civil and Environmental Engineering (MCP/CEE Prof MS).",
        "requirements": "Required: bachelor's degree from an accredited institution (any field). GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE optional. International students: TOEFL/IELTS required. No specific undergraduate prerequisites, but coursework in economics, statistics, GIS, or urban studies is recommended. Professional planning experience is favorably considered but not required. Contact: dcrpgrad@berkeley.edu, (510) 642-4929.",
        "research": "Curriculum: planning history and theory, urban economics, planning law, quantitative methods, GIS, land use planning, environmental planning, transportation planning, housing policy, community development, urban design studio, and a final thesis or professional project. Research centers: Institute of Urban and Regional Development (IURD), Center for Environmental Design Research, and Berkeley Food Institute. Graduates pursue careers in city planning, urban design, transportation agencies, housing authorities, environmental non-profits, real estate development, and public policy."
    },
    "berkeley-metabolic-ms": {
        "id": "berkeley-metabolic-ms",
        "s": "berkeley",
        "n": "代谢生物学硕士",
        "en": "MS in Metabolic Biology (UC Berkeley Graduate Group in Metabolic Biology & Nutrition, joint with UCSF)",
        "dept": "Graduate Group in Metabolic Biology & Nutrition",
        "college": "UC Berkeley College of Natural Resources",
        "disc": "sci",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (Fall admission only; UCB + UCSF inter-campus program)",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only; applications open Sep 24, 2026; no late applications).",
        "lang": "TOEFL iBT 90 (tests before Jan 21, 2026) / new TOEFL 5+ with 4.5 Speaking/Writing (tests on/after Jan 21, 2026). ETS code 4833.",
        "test": {
            "cls": "GRE NOT required and will NOT be considered (Metabolic Biology department explicitly states GRE scores are not required and will not be reviewed, even if submitted). This is consistent with the PhD track (berkeley-metabolic-phd). Note: applicants may only apply to ONE UC Berkeley graduate program per admission cycle."
        },
        "tui": "Tuition ~$26,000/year resident / ~42,000/non-resident + fees. PhD admits receive full support (stipend + tuition + fees); MS admits typically self-fund or seek external fellowships. Application fee $135 (US) / $155 (international); AB540 and fee-waiver eligible.",
        "url": "details/berkeley-metabolic-ms.html",
        "school": "UC Berkeley",
        "website": "https://mbn.berkeley.edu/graduate-programs/metabolic-biology/",
        "overview": "The MS in Metabolic Biology is offered through the Graduate Group in Metabolic Biology & Nutrition, an inter-campus program combining faculty from UC Berkeley and UCSF. The program provides comprehensive training in metabolic regulation, nutrient function, and metabolic disorders. Research focus includes nutritional and hormonal regulation of metabolic homeostasis, lipid droplet physiology, gastrointestinal physiology, neuronal control of feeding behaviors, cancer metabolism, and translational drug discovery. The MS track is ideal for students seeking deeper understanding through focused coursework and research projects; the PhD track (already in catalog) is for students aspiring to become independent researchers. The department also offers a separate Endocrinology PhD (currently paused for Fall 2026 admission).",
        "requirements": "Required: bachelor's degree in biology, biochemistry, nutrition, or related life science. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required and not reviewed. International students: TOEFL/IELTS required. Prerequisites: undergraduate biology, chemistry (organic, biochemistry), and physiology recommended. Applicants should indicate preferred faculty mentors on the application. Contact: mbn-grad@berkeley.edu.",
        "research": "Curriculum: mammalian metabolism, nutritional biochemistry, endocrine regulation, molecular genetics of metabolic disease, lipid biology, cancer metabolism, translational therapeutics, and a research thesis. Research areas: obesity and diabetes, metabolic syndrome, cardiovascular metabolism, mitochondrial biology, autophagy and lipid droplets, gut-brain axis, cancer metabolism, and drug development for metabolic diseases. Students rotate through UCB and UCSF laboratories and collaborate with Molecular Toxicology, Endocrinology, and Comparative Biochemistry graduate groups."
    },
}

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