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-mph-epibiostat": {
        "id": "berkeley-mph-epibiostat",
        "s": "berkeley",
        "n": "公共卫生硕士（流行病学/生物统计）",
        "en": "MPH in Epidemiology/Biostatistics (2-year, UC Berkeley School of Public Health)",
        "dept": "Division of Epidemiology & Biostatistics",
        "college": "UC Berkeley School of Public Health",
        "disc": "sci",
        "lvl": "m",
        "deg": "MPH",
        "stem": 1,
        "dur": "2 years full-time on-campus",
        "ddl": "Priority: Dec 1, 2026 at 8:59pm PST (Fall admission only; SOPHAS application; no secondary deadline for this concentration).",
        "lang": "TOEFL iBT 90 / IELTS 7.0. ETS institution code 4833. GRE score report to SOPHAS code 4227.",
        "test": {
            "cls": "GRE Optional (Graduate Division lists GRE=Optional). Scores valid for 5 years. If submitted, sent to SOPHAS code 4227, not Berkeley directly. Note: this is the 2-year on-campus residential MPH; the 11-month Epidemiology MPH has a separate track."
        },
        "tui": "Tuition ~$25,000/year resident / ~40,000/non-resident + fees. Partial scholarships/assistantships available for priority deadline applicants.",
        "url": "details/berkeley-mph-epibiostat.html",
        "school": "UC Berkeley",
        "website": "https://publichealth.berkeley.edu/admissions/on-campus",
        "overview": "The 2-year MPH in Epidemiology/Biostatistics is a professional degree offered by the UC Berkeley School of Public Health. It combines rigorous training in epidemiologic methods and biostatistical theory with applied practice in population health research. The program is designed for students pursuing careers in public health practice, research, health policy, or doctoral study. Applications are submitted through SOPHAS (not the Berkeley Graduate Application directly), with a separate Berkeley supplemental application.",
        "requirements": "Required: bachelor's degree from an accredited institution. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose (1,000 words). Personal History Statement (500-1,000 words). Official transcripts. SOPHAS application + Berkeley supplemental application. GRE optional. International students: TOEFL/IELTS required. Prerequisites: college-level mathematics, biology, and statistics recommended.",
        "research": "Curriculum: epidemiologic methods, biostatistics, probability theory, regression analysis, categorical data analysis, infectious disease epidemiology, chronic disease epidemiology, environmental epidemiology, clinical trials, causal inference, survey design, and a practicum/internship. Research areas: cancer epidemiology, cardiovascular disease, infectious diseases, maternal and child health, global health, social epidemiology, health disparities, and data science in public health."
    },
    "berkeley-mph-hpm": {
        "id": "berkeley-mph-hpm",
        "s": "berkeley",
        "n": "公共卫生硕士（健康政策与管理）",
        "en": "MPH in Health Policy and Management (2-year, UC Berkeley School of Public Health)",
        "dept": "Division of Health Policy & Management",
        "college": "UC Berkeley School of Public Health",
        "disc": "soc",
        "lvl": "m",
        "deg": "MPH",
        "stem": 0,
        "dur": "2 years full-time on-campus",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only; SOPHAS application).",
        "lang": "TOEFL iBT 90 / IELTS 7.0. ETS institution code 4833. GRE score report to SOPHAS code 4227.",
        "test": {
            "cls": "GRE Optional (Graduate Division lists GRE=Optional). Concurrent MPP/MPH with Goldman School of Public Policy also available (~3 years, GRE may be required for MPP side). Note: 2-year on-campus residential MPH."
        },
        "tui": "Tuition ~$25,000/year resident / ~40,000/non-resident + fees. Partial scholarships/assistantships available.",
        "url": "details/berkeley-mph-hpm.html",
        "school": "UC Berkeley",
        "website": "https://publichealth.berkeley.edu/admissions/on-campus",
        "overview": "The 2-year MPH in Health Policy and Management is a professional degree offered by the UC Berkeley School of Public Health. It trains students in health policy analysis, health economics, health care management, and organizational leadership. The program prepares graduates for careers in government health agencies, hospital systems, consulting firms, insurance companies, non-profit organizations, and global health institutions. A concurrent MPP/MPH dual degree with the Goldman School of Public Policy is also available (~3 years total).",
        "requirements": "Required: bachelor's degree from an accredited institution. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose (1,000 words). Personal History Statement (500-1,000 words). Official transcripts. SOPHAS application + Berkeley supplemental application. GRE optional. International students: TOEFL/IELTS required. Quantitative coursework (microeconomics, statistics) recommended.",
        "research": "Curriculum: health policy analysis, health economics, health care management, organizational behavior, health law, health financing, global health policy, health systems, data analysis for health policy, and a practicum. Research areas: health reform, insurance markets, Medicare/Medicaid, public health policy, pharmaceutical policy, mental health policy, global health systems, and health disparities."
    },
    "berkeley-sesame-phd": {
        "id": "berkeley-sesame-phd",
        "s": "berkeley",
        "n": "科学与数学教育博士（SESAME）",
        "en": "PhD in Science and Mathematics Education (SESAME Graduate Group, UC Berkeley)",
        "dept": "Graduate Group in Science and Mathematics Education (SESAME)",
        "college": "UC Berkeley School of Education",
        "disc": "edu",
        "lvl": "d",
        "deg": "PhD",
        "stem": 0,
        "dur": "5-6 years full-time",
        "ddl": "Dec 1, 2026 at 8:59pm Pacific (Fall admission only; application opens Sep 24, 2026).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833.",
        "test": {
            "cls": "GRE NOT required for current application cycle (confirmed by SESAME department and Berkeley Graduate Division). No Subject GRE required."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSI/GSR appointments and fellowships. Students expected to attain master's-level competency in their chosen STEM discipline.",
        "url": "details/berkeley-sesame-phd.html",
        "school": "UC Berkeley",
        "website": "https://bse.berkeley.edu/admissions/sesame",
        "overview": "The Graduate Group in Science and Mathematics Education (SESAME) offers an interdisciplinary PhD in science, mathematics, technology, and engineering education. The program is designed to give graduates advanced expertise in a STEM discipline as well as in educational theory and research methodologies. SESAME produces scholars who can communicate effectively with scientists, mathematicians, and engineers as well as with educational researchers and practitioners. Students are expected to attain a level of expertise equivalent to a master's student in their chosen STEM discipline. Thesis work typically consists of basic research on learning or cognition in a STEM field, or development of improved pedagogical approaches. SESAME also offers a Learning Sciences Certificate in Instructional Design, Learning Technologies, and Education Research.",
        "requirements": "Required: bachelor's degree (preferably master's) in natural science, mathematics, engineering, or computer science. Excellent academic record. Experience teaching, developing instructional materials, or conducting educational/psychological research is favorably considered. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Contact: sesame@berkeley.edu.",
        "research": "Research areas: STEM learning and cognition, physics education, mathematics education, computer science education, engineering education, teacher professional development, educational technology, instructional design, informal science education, equity and diversity in STEM, and assessment. Faculty are drawn from the School of Education, as well as STEM departments across Berkeley."
    },
    "berkeley-mbe": {
        "id": "berkeley-mbe",
        "s": "berkeley",
        "n": "生物过程工程硕士",
        "en": "Master of Bioprocess Engineering (MBE/MBPE, UC Berkeley College of Chemistry)",
        "dept": "Department of Chemical and Biomolecular Engineering",
        "college": "UC Berkeley College of Chemistry",
        "disc": "eng",
        "lvl": "m",
        "deg": "MBE",
        "stem": 1,
        "dur": "9 months intensive (2 semesters + pilot lab)",
        "ddl": "Priority: Dec 14, 2026; Final: Jan 19, 2027 (Fall admission only; rolling review after priority deadline).",
        "lang": "TOEFL iBT 90 minimum (tests taken on/after Jan 21, 2026 follow Berkeley's new TOEFL policy). ETS institution code 4833.",
        "test": {
            "cls": "GRE NOT required (Graduate Division lists GRE=No). No minimum score. Note: this is a professional 9-month master's, not research thesis; capstone/pilot project replaces thesis."
        },
        "tui": "Tuition ~$30,000 total for 9-month program. 90%+ graduates secure biotech roles within 6 months. Alumni at AbbVie, Amgen, Amyris, Genentech, Gilead, Merck, Pfizer, Novonesis, UPSIDE Foods, Vaxcyte.",
        "url": "details/berkeley-mbe.html",
        "school": "UC Berkeley",
        "website": "https://chemistry.berkeley.edu/grad/cbe/bioprocess-engineering",
        "overview": "The Master of Bioprocess Engineering (MBPE) is an intensive 9-month professional degree hosted in Gilman Hall by the College of Chemistry. It combines Berkeley's world-class faculty with industry leaders from the Bay Area biotech industry. Students are trained in the classroom, laboratory, and pilot plant with a comprehensive curriculum in the analysis, design, development, scale-up, and commercialization of bio-based processes and products. Hands-on pilot-scale training at the ABPDU (Advanced Biofuels Process Demonstration Unit) in Emeryville uses industry-standard equipment including the Sartorius Ambr250, ABEC 300L bioreactor, Alfa Laval disc stack centrifuge, Alfa Laval M20 filtration skid, and Cytiva ÄKTA Avant chromatography unit.",
        "requirements": "Required: BS in chemical engineering, biochemistry, bioengineering, molecular & cell biology, or related field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Address: 301 Gilman Hall, Berkeley, CA 94720. Email: mbpe@berkeley.edu.",
        "research": "Core curriculum: bioprocess fundamentals, biochemical engineering, bioreactor design, downstream processing, quality by design (QbD), statistical experimental design, scale-up. Electives span Bioengineering, Chemistry, Chemical Engineering, MCB, and Public Health. Careers: Bioprocess Scientist/Engineer at biopharma, industrial biotech, and food tech companies."
    },
    "berkeley-rangeland-ms": {
        "id": "berkeley-rangeland-ms",
        "s": "berkeley",
        "n": "牧场与野生动物管理硕士",
        "en": "MS in Rangeland and Wildlife Management (UC Berkeley ESPM)",
        "dept": "Rangeland & Wildlife Management Graduate Group",
        "college": "UC Berkeley College of Natural Resources",
        "disc": "sci",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (research thesis)",
        "ddl": "Dec 1, 2026 (Fall admission only; TOEFL score deadline Dec 20).",
        "lang": "TOEFL iBT 90 / IELTS 7.0. ETS institution code 4833. TOEFL scores due Dec 20 (later than application deadline).",
        "test": {
            "cls": "GRE NOT required (Graduate Division lists GRE=No). No Subject GRE required. Note: this is a research-thesis MS, not professional; students work with ESPM faculty on range management research."
        },
        "tui": "MS students typically receive GSR/GSI support or external fellowships. ESPM admits 35-40 offers across PhD/MF/MS combined from 300-400 applications; enrolls 25-30 new students/year.",
        "url": "details/berkeley-rangeland-ms.html",
        "school": "UC Berkeley",
        "website": "https://grad.berkeley.edu/program/rangeland-and-wildlife-management-ms/",
        "overview": "The MS in Rangeland and Wildlife Management prepares students with a bachelor's degree in resource management or related disciplines for advanced study of rangelands and range management. The program is administered by an interdepartmental group of faculty from the Department of Environmental Science, Policy, and Management (ESPM) and related departments. It serves as the basis for a professional career in rangeland livestock production systems; grassland, savanna, wetland, and shrubland ecology and management; native plants; rangeland rehabilitation; conservation easements; wildlife habitat; water quality; working landscapes; and rangeland economics and policy. Excellent laboratory and field facilities include several experimental range properties.",
        "requirements": "Required: bachelor's degree in resource management, range science, ecology, wildlife biology, or related field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required (TOEFL scores due Dec 20). Address: 130 Mulford Hall, Berkeley, CA 94720-3114. Email: espm_gradsupport@berkeley.edu.",
        "research": "Research areas: rangeland ecology and management, livestock production systems, grassland/savanna/wetland/shrubland ecology, native plant restoration, rangeland rehabilitation, conservation easements, wildlife habitat management, water quality on working landscapes, rangeland economics and policy, fire ecology, climate change adaptation on rangelands, and invasive species management."
    }
}

TEMPLATE = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} {n} - {en}</title>
<style>
body {{ font-family: -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; max-width: 900px; margin: 30px auto; padding: 0 20px; line-height: 1.7; color: #222; }}
h1 {{ color: #003366; border-bottom: 2px solid #003366; padding-bottom: 10px; }}
h2 {{ color: #0055a5; margin-top: 30px; }}
.meta {{ background: #f4f7fb; padding: 15px 20px; border-radius: 6px; margin: 20px 0; }}
.meta div {{ margin: 6px 0; }}
.label {{ font-weight: 600; color: #003366; display: inline-block; min-width: 90px; }}
a.url {{ color: #0055a5; word-break: break-all; }}
</style>
</head>
<body>
<h1>{school} {n} <small style="font-size:0.6em;color:#666">({lvl_label})</small></h1>
<p><strong>{en}</strong></p>
<div class="meta">
<div><span class="label">院系：</span>{dept} / {college}</div>
<div><span class="label">学位：</span>{deg}</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"],
        college=p["college"],
        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!")
