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-plantbio-phd": {
        "id": "berkeley-plantbio-phd",
        "s": "berkeley",
        "n": "植物生物学博士",
        "en": "PhD in Plant Biology (UC Berkeley Department of Plant and Microbial Biology)",
        "dept": "Department of Plant and Microbial Biology",
        "college": "UC Berkeley College of Natural Resources",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time",
        "ddl": "Nov 16, 2026 at 8:59pm PST (Fall admission only; applications open Sep 24, 2026).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833. Applicants with 1+ year full-time study at a U.S. institution with grades B or higher may be exempt.",
        "test": {
            "cls": "GRE NOT required and will not be reviewed or considered even if submitted (confirmed by PMB department). No Subject GRE required. Note: Berkeley Graduate Division lists Plant Biology PhD GRE=No."
        },
        "tui": "Fully funded for all PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. ~42 students enrolled in the program; ~10-20 admits per year; typically ~1 international student per program per year.",
        "url": "details/berkeley-plantbio-phd.html",
        "school": "UC Berkeley",
        "website": "https://plantandmicrobiology.berkeley.edu/graduate-programs/admissions",
        "overview": "The PhD in Plant Biology is offered by the Department of Plant and Microbial Biology (PMB) at UC Berkeley. Students are admitted to the program as a whole rather than to a specific faculty lab; during the first semester, students participate in lab rotations to identify the best research fit, with lab placement finalized by the start of the second semester. The department does not offer a master's degree. Applications are reviewed holistically by an admissions committee of faculty, graduate students, and staff, using rubrics designed to minimize implicit bias.",
        "requirements": "Required: bachelor's degree from an accredited institution. GPA minimum 3.0 (B). 3 letters of recommendation (additional letters will not be reviewed). Statement of Purpose. Personal History Statement. Official transcripts. Application fee (or approved fee waiver). GRE not required and not considered. International students: TOEFL/IELTS required unless exempt. Students may apply to only one UC Berkeley program per admission term.",
        "research": "Research areas: plant development, genomics, physiology, molecular biology, plant evolution, plant ecology, plant pathology, plant biotechnology, computational plant biology, microbiome interactions, abiotic stress responses, synthetic biology in plants, and plant-microbe symbiosis."
    },
    "berkeley-microbio-phd": {
        "id": "berkeley-microbio-phd",
        "s": "berkeley",
        "n": "微生物学博士",
        "en": "PhD in Microbiology (UC Berkeley Department of Plant and Microbial Biology)",
        "dept": "Department of Plant and Microbial Biology",
        "college": "UC Berkeley College of Natural Resources",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time",
        "ddl": "Nov 16, 2026 at 8:59pm PST (Fall admission only; shared deadline with Plant Biology PhD).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833.",
        "test": {
            "cls": "GRE NOT required and will not be reviewed or considered even if submitted (confirmed by PMB department). No Subject GRE required."
        },
        "tui": "Fully funded for all PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. ~40 students enrolled in the program; ~10-20 admits per year; typically ~1 international student per year.",
        "url": "details/berkeley-microbio-phd.html",
        "school": "UC Berkeley",
        "website": "https://plantandmicrobiology.berkeley.edu/graduate-programs/admissions",
        "overview": "The PhD in Microbiology is offered by the Department of Plant and Microbial Biology (PMB) at UC Berkeley. It is the sister program to Plant Biology, with the same admissions process, deadline, and funding model. Students whose research interests are in microbial ecology and evolution, fungal diversity, or mycology should apply to Microbiology rather than Plant Biology. Students are admitted to the program as a whole, with lab rotations during the first semester and lab placement finalized by the start of the second semester. The department does not offer a master's degree.",
        "requirements": "Required: bachelor's degree from an accredited institution. GPA minimum 3.0 (B). 3 letters of recommendation (additional letters will not be reviewed). Statement of Purpose. Personal History Statement. Official transcripts. Application fee (or approved fee waiver). GRE not required and not considered. International students: TOEFL/IELTS required unless exempt. Students may apply to only one UC Berkeley program per admission term.",
        "research": "Research areas: microbial ecology and evolution, fungal diversity, mycology, bacterial genomics, virology, microbiome studies, environmental microbiology, symbiotic interactions, microbial biotechnology, extremophiles, microbial pathogenesis, and computational microbiology."
    },
    "berkeley-compbiochem-phd": {
        "id": "berkeley-compbiochem-phd",
        "s": "berkeley",
        "n": "比较生物化学博士",
        "en": "PhD in Comparative Biochemistry (UC Berkeley Comparative Biochemistry Graduate Group)",
        "dept": "Comparative Biochemistry Graduate Group",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time",
        "ddl": "Jan 11, 2027 (Fall admission only; one of the latest PhD deadlines at UC Berkeley).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833.",
        "test": {
            "cls": "GRE NOT required (Graduate Division lists GRE=No). No Subject GRE required. Note: deadline is unusually late (Jan 11) compared with most Berkeley PhD programs (Nov-Dec)."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees) via graduate researcher appointments and fellowships across participating departments.",
        "url": "details/berkeley-compbiochem-phd.html",
        "school": "UC Berkeley",
        "website": "https://grad.berkeley.edu/program/comparative-biochemistry-phd/",
        "overview": "The PhD in Comparative Biochemistry is administered by an interdisciplinary Graduate Group rather than a single department. It is designed for students interested in a biochemical and molecular approach to problems in the biological sciences. Students work under the supervision of faculty from diverse disciplines including Molecular and Cell Biology, Nutritional Science and Toxicology, Plant and Microbial Biology, Chemistry, Chemical Engineering, Environmental Science, Policy, and Management, Public Health, and the Lawrence Berkeley National Laboratory (LBNL).",
        "requirements": "Required: bachelor's degree in biochemistry, molecular biology, chemistry, 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. Contact: compar.biochem@berkeley.edu, (510) 643-1711, 324 Barker Hall.",
        "research": "Research areas: comparative biochemistry, molecular biology, structural biology, enzymology, metabolic regulation, chemical biology, toxicology, nutrition, molecular endocrinology, developmental biology at the molecular level, and interdisciplinary approaches to biological problems spanning biology, chemistry, engineering, and public health."
    },
    "berkeley-are-phd": {
        "id": "berkeley-are-phd",
        "s": "berkeley",
        "n": "农业与资源经济学博士",
        "en": "PhD in Agricultural and Resource Economics (UC Berkeley Department of Agricultural and Resource Economics)",
        "dept": "Department of Agricultural and Resource Economics",
        "college": "UC Berkeley College of Natural Resources",
        "disc": "soc",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time",
        "ddl": "Dec 1, 2026 at 8:59pm PST (Fall admission only).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833; ARE department code 0101.",
        "test": {
            "cls": "GRE General Test REQUIRED (confirmed by ARE department FAQ and Berkeley Graduate Division listing). Quantitative score weighted more heavily, but Verbal and Analytical Writing are also considered. ETS dept code 0101. Scores valid for 5 years. Note: departmental website older page references COVID-era optional policy; current official policy is required."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees) via GSI/GSR appointments and fellowships. ~225 applications per cycle; ~20 admits; ~15 accept offers.",
        "url": "details/berkeley-are-phd.html",
        "school": "UC Berkeley",
        "website": "https://are.berkeley.edu/graduate-program/graduate-admissions",
        "overview": "The Department of Agricultural and Resource Economics (ARE) offers a PhD program stressing economic theory, quantitative methods, and two elective fields defined in consultation with the graduate adviser. The department does not admit students for a terminal master's degree; the MA may be awarded en route to the PhD. Common elective fields include development economics, natural resource and environmental economics, agricultural policy, and international markets and trade. The program is relatively flexible, allowing students to tailor coursework across the College of Natural Resources and the College of Letters and Science.",
        "requirements": "Required: bachelor's degree in economics, agricultural economics, or related quantitative field (strong preparation in microeconomics, macroeconomics, and calculus). GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE General required. International students: TOEFL/IELTS required. Contact: carmenk@berkeley.edu, (510) 642-3347, 207 Giannini Hall.",
        "research": "Research areas: environmental and natural resource economics, development economics, agricultural policy, international trade, energy economics, climate economics, behavioral economics, econometrics, applied microeconomics, industrial organization, political economy, and interdisciplinary work with ESPM, Goldman School of Public Policy, and the Energy and Resources Group."
    },
    "berkeley-deveng-ms": {
        "id": "berkeley-deveng-ms",
        "s": "berkeley",
        "n": "发展工程硕士",
        "en": "Master of Development Engineering (MDevEng, UC Berkeley Blum Center)",
        "dept": "Blum Center for Developing Economies / Graduate Group in Development Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MDevEng",
        "stem": 1,
        "dur": "3 semesters (15 months), including summer internship",
        "ddl": "Final: Feb 15, 2027 at 8:59pm PT (rolling review; fee-waiver deadline Nov 16, 2026 at 12:59pm PDT; priority/fellowship deadline earlier).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS institution code 4833.",
        "test": {
            "cls": "GRE NOT required (Graduate Division lists GRE=No). No minimum score. Note: professional master's program with rolling review after priority deadline."
        },
        "tui": "Tuition ~$30,000/year (professional program; partial fellowships available for applicants who meet priority deadline). Most admits complete a paid summer internship between year 1 and year 2.",
        "url": "details/berkeley-deveng-ms.html",
        "school": "UC Berkeley",
        "website": "https://developmentengineering.berkeley.edu/master-of-development-engineering/",
        "overview": "The Master of Development Engineering (MDevEng) is a 3-semester, 15-month professional degree program launched by the Blum Center for Developing Economies at UC Berkeley. It integrates engineering training with entrepreneurship, design, business, and policy to support students in creating technological interventions for people living in poverty. The program is cross-disciplinary, drawing on faculty from Berkeley Engineering, Social Sciences, and the Blum Center. Initial support came from USAID's Global Development Lab; the program also hosts an NSF Traineeship for Digital Transformation of Development (DToD). The DE in DevEng is also a separate interdisciplinary training program for UC Berkeley doctoral students.",
        "requirements": "Required: bachelor's degree in engineering, computer science, or a related STEM 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. Contact: devenginfo@berkeley.edu, 100 Blum Hall, MC 5570.",
        "research": "Curriculum: design and management of technology, application of emerging technologies (AI, remote sensing, data science), evidence-based assessment techniques, economic development, social problem solving, cross-cultural collaboration, community engagement. Includes a summer internship and a final capstone project. Career outcomes: Global Impact Program Manager, Technical Director of Sustainable Innovation, AI Ethics Strategist, roles at development NGOs, social enterprises, and impact-focused tech companies."
    }
}

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