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-appmath-phd": {
        "id": "berkeley-appmath-phd",
        "s": "berkeley",
        "n": "应用数学博士",
        "en": "PhD in Applied Mathematics (UC Berkeley Department of Mathematics)",
        "dept": "Department of Mathematics",
        "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).",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "Mathematics Subject GRE REQUIRED for Fall 2027. General GRE optional (may be submitted but not required). Math Subject score below 50th percentile considered low (reference distribution, not minimum threshold). ETS code 4833. Tests recommended to be taken by October for timely score reporting."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Department of Mathematics funding package.",
        "url": "details/berkeley-appmath-phd.html",
        "school": "UC Berkeley",
        "website": "https://math.berkeley.edu/graduate/admissions",
        "overview": "The Department of Mathematics offers both a PhD in Mathematics and a PhD in Applied Mathematics. Students are admitted to specific degree programs; requirements differ only in minor respects and no distinction is made in day-to-day matters. Graduate students typically take 5-6 years to complete the doctorate. Transfers between the two PhD programs are fairly routine but must be done prior to taking the qualifying examination.",
        "requirements": "Required: bachelor's degree in mathematics or related quantitative field. GPA minimum 3.0. 3 letters of recommendation (online only; no mailed letters). Statement of Purpose. Personal History Statement. Official transcripts. Math Subject GRE required; General GRE optional. International students: TOEFL/IELTS required.",
        "research": "Research areas: applied mathematics, mathematical modeling, numerical analysis, scientific computing, probability, statistics, differential equations, dynamical systems, mathematical physics, mathematical biology, financial mathematics, computational mathematics, interdisciplinary applications."
    },
    "berkeley-cbe-pdp-ms": {
        "id": "berkeley-cbe-pdp-ms",
        "s": "berkeley",
        "n": "化学与生物分子工程产品开发硕士",
        "en": "MS in Chemical and Biomolecular Engineering - Product Development Program (PDP, UC Berkeley College of Chemistry)",
        "dept": "Department of Chemical and Biomolecular Engineering",
        "college": "UC Berkeley College of Chemistry",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "9 months (with optional extension)",
        "ddl": "Priority: Dec 14, 2026; Final: Jan 11, 2027 (Fall admission only).",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum).",
        "test": {
            "cls": "GRE NOT required. No minimum score. Note: CBE research MS is paused for admissions; only PDP professional MS is open.",
        },
        "tui": "Tuition ~$30,000 total for 9-month program. 400+ alumni network. 80% graduates secure roles within 6 months.",
        "url": "details/berkeley-cbe-pdp-ms.html",
        "school": "UC Berkeley",
        "website": "https://chemistry.berkeley.edu/grad/cbe/pdp",
        "overview": "The Product Development Program (PDP) is a 9-month professional master's degree in Chemical Engineering launched in 2006. It is designed for STEM graduates ready to step into high-impact industry roles. The program combines advanced technical expertise with business strategy, including optional courses at the Haas School of Business in product management, finance, and marketing. Real-world capstone projects solve product development challenges for corporate clients. No research thesis required. Industry specializations: biotechnology, microelectronics, nanoscience, consumer products, alternative energy, new ventures.",
        "requirements": "Required: bachelor's degree in chemical engineering or related STEM field. GPA minimum 3.0 (competitive applicants higher). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Minimum 28 units with at least 18 letter-graded and 12 graduate-level (200 series) units.",
        "research": "Curriculum: advanced chemical engineering, product development, business strategy, marketing, finance, project management, biotechnology, microelectronics, nanoscience, consumer products, alternative energy. Careers: product manager, R&D director, founder, roles at Abbott, Amazon, Apple, Applied Materials, Baxter, Bloomberg, Dow, Gilead, Illumina, Intel, Schlumberger."
    },
    "berkeley-cee-ms": {
        "id": "berkeley-cee-ms",
        "s": "berkeley",
        "n": "土木与环境工程硕士",
        "en": "MS in Civil and Environmental Engineering (UC Berkeley)",
        "dept": "Department of Civil and Environmental Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "1.5-2 years full-time (research-oriented)",
        "ddl": "Dec 15, 2026 at 20:59 PST (Fall admission only; no Spring admission).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (Graduate Division minimum). ETS code 4833.",
        "test": {
            "cls": "GRE NOT required and NOT accepted by CEE department. No minimum score. Note: CEE no longer requires nor accepts the GRE."
        },
        "tui": "MS students typically self-funded or receive partial assistantships. Tuition ~$20,000/year resident / ~$35,000/non-resident + fees.",
        "url": "details/berkeley-cee-ms.html",
        "school": "UC Berkeley",
        "website": "https://ce.berkeley.edu/grad/admissions",
        "overview": "The CEE MS is a research-oriented master's degree offered by the Department of Civil and Environmental Engineering. The department supports seven programs of study for the MS and PhD: Structural Engineering, Geological Engineering, Transportation Engineering, Environmental Engineering, Energy Civil Infrastructure, Hydrology and Water Resources, and Systems Engineering. The MS is typically a stepping stone to the PhD, but may also be terminal. CEE also offers a separate MEng (professional, Jan 6 deadline) and three concurrent degree programs.",
        "requirements": "Required: bachelor's degree in civil engineering, environmental engineering, or related engineering field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. Advanced GPA worksheet. GRE not required and not accepted. International students: TOEFL/IELTS required. Environmental Engineering and Transportation Engineering have additional prerequisite courses.",
        "research": "Research areas: structural engineering, earthquake engineering, geological engineering, transportation engineering, environmental engineering, water resources, hydrology, energy infrastructure, sustainable engineering, climate resilience, geotechnical engineering, construction materials, computational mechanics."
    },
    "berkeley-mcb-phd": {
        "id": "berkeley-mcb-phd",
        "s": "berkeley",
        "n": "分子与细胞生物学博士",
        "en": "PhD in Molecular and Cell Biology (UC Berkeley Department of Molecular and Cell Biology)",
        "dept": "Department of Molecular and Cell 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; no late applications accepted).",
        "lang": "TOEFL iBT 90 / IELTS 7.0. ETS code 4833, dept 0206 (GRE cell biology), dept 74 (TOEFL).",
        "test": {
            "cls": "GRE General and Subject OPTIONAL. Submitting GRE is not required and omitting scores will have no negative impact. Department rationale: GRE may disadvantage certain populations due to cost and bias. A strong GRE may strengthen an otherwise weak application."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). MCB department funding package.",
        "url": "details/berkeley-mcb-phd.html",
        "school": "UC Berkeley",
        "website": "https://mcb.berkeley.edu/grad/application-requirements",
        "overview": "The MCB PhD program provides advanced training in research methods and concepts of the molecular structures and processes of cellular life. The faculty is organized into five divisions: Biochemistry, Biophysics, and Structural Biology; Cell Biology, Development, and Physiology; Genetics, Genomics, Evolution, and Development; Immunology and Molecular Medicine; and Molecular Therapeutics. Selected applicants are invited to in-person recruitment interviews. Offers made late February through mid-March.",
        "requirements": "Required: bachelor's degree in biology, biochemistry, chemistry, or related field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Prior research experience strongly expected.",
        "research": "Research areas: biochemistry, biophysics, structural biology, cell biology, developmental biology, physiology, genetics, genomics, evolutionary biology, immunology, molecular medicine, molecular therapeutics, neurobiology, tumor biology, microbiology, bioinformatics. Model systems from viruses and microbes to plants, worms, flies, fish, amphibians, and mammals."
    },
    "berkeley-metabolic-phd": {
        "id": "berkeley-metabolic-phd",
        "s": "berkeley",
        "n": "代谢生物学博士",
        "en": "PhD in Metabolic Biology (UC Berkeley Department of Metabolic Biology & Nutrition)",
        "dept": "Department of Metabolic Biology & Nutrition",
        "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; application opens Sep 24, 2026).",
        "lang": "TOEFL iBT 90 / IELTS 7.0 (with 6.5 min Speaking/Writing). Application fee $135 US / $155 international.",
        "test": {
            "cls": "GRE NOT required and will NOT be considered. No minimum score. Note: Endocrinology PhD (same department) is paused for Fall 2026 admission cycle."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Lab rotations during first semester; advisor placement finalized by end of first year. Interview weekend Jan 21-23, 2027.",
        "url": "details/berkeley-metabolic-phd.html",
        "school": "UC Berkeley",
        "website": "https://mbn.berkeley.edu/graduate-programs/metabolic-biology/met-bio-admissions/application-requirements",
        "overview": "The Metabolic Biology PhD is offered through the Department of Metabolic Biology & Nutrition. Students are admitted to the program rather than a specific lab, with lab rotations during the first semester and advisor placement finalized by the end of the first year. The department also offers an Endocrinology PhD, which is paused for Fall 2026 admission cycle. Admissions are holistic, using standardized evaluation rubrics and implicit bias training for the committee.",
        "requirements": "Required: bachelor's degree in biology, chemistry, or related field with lab experience. GPA minimum 3.0. 3 letters of recommendation (at least 2 from science faculty). Statement of Purpose. Personal History Statement. Resume/CV. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Expected background: general chemistry with lab, introductory biology with lab, physics, calculus and/or statistics.",
        "research": "Research areas: metabolic biology, nutrition, endocrinology, diabetes, obesity, metabolic disease, molecular metabolism, physiological regulation, genetic and environmental factors in metabolism, public health nutrition, aging, developmental metabolism."
    }
}

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