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-stat-phd": {
        "id": "berkeley-stat-phd",
        "s": "berkeley",
        "n": "统计学博士",
        "en": "PhD in Statistics (UC Berkeley Department of Statistics)",
        "dept": "Department of Statistics",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5 years full-time",
        "ddl": "Dec 1, 2026 (Fall admission only; no Spring admission)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "General GRE NO LONGER REQUIRED AND WILL NOT BE ACCEPTED. Math Subject Test optional (if available, may be submitted). ETS code 4833. No minimum score; admitted applicants typically score high percentiles (V 83%, Q 94%, AW 60% as reference distribution, not minimum threshold)."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Berkeley Graduate Division funding package.",
        "url": "details/berkeley-stat-phd.html",
        "school": "UC Berkeley",
        "website": "https://statistics.berkeley.edu/academics/phd/admissions",
        "overview": "The UC Berkeley Statistics PhD program is consistently ranked among the top two graduate programs nationally. Founded by Jerzy Neyman and David Blackwell, the program offers comprehensive training in theoretical and applied statistics. The five-year program begins with core coursework in advanced probability theory, applied and theoretical statistics, then transitions to independent dissertation research. Three Designated Emphasis tracks available: Computational and Data Science and Engineering, Computational Precision Health, Computational Science and Engineering.",
        "requirements": "Required: bachelor's degree in mathematics, statistics, or quantitative field. GPA minimum 3.0 (competitive applicants higher). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. Descriptive list of upper-division math courses. GRE not required. International students: TOEFL/IELTS required.",
        "research": "Research areas: theoretical statistics, probability, machine learning, data science, statistical computing, biostatistics, environmental statistics, financial statistics, social statistics, interdisciplinary applications across technology, medicine, finance, and public policy."
    },
    "berkeley-biophysics-phd": {
        "id": "berkeley-biophysics-phd",
        "s": "berkeley",
        "n": "生物物理学博士",
        "en": "PhD in Biophysics (UC Berkeley Biophysics Graduate Group, QB3)",
        "dept": "Biophysics Graduate Group, California Institute for Quantitative Biosciences (QB3)",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Nov 30, 2026 at 8:59pm PST (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "GRE General NOT required and will NOT be seen by the review committee even if submitted. Subject exams have never been required. No standardized tests considered."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). QB3/Graduate Division funding package.",
        "url": "details/berkeley-biophysics-phd.html",
        "school": "UC Berkeley",
        "website": "https://qb3.berkeley.edu/biophysics/admissions/",
        "overview": "The Biophysics Graduate Group is an interdisciplinary PhD program hosted by QB3 (California Institute for Quantitative Biosciences). Approximately 60 faculty members are affiliated, spanning over a dozen departments at UC Berkeley. The program trains students at the interface of biological and physical sciences. Students may work under the supervision of any faculty member in the group. First two years include self-selected coursework in biology, physics, and chemistry to fill foundational gaps.",
        "requirements": "Required: bachelor's degree in biological sciences, structural biology, physics, math, or chemistry. Laboratory research experience expected. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required and will not be reviewed. International students: TOEFL/IELTS required.",
        "research": "Research areas: structural biology, biophysics, single-molecule biophysics, membrane biophysics, computational biophysics, molecular biophysics, physical biology, quantitative biology, imaging. Interdisciplinary across biology, physics, chemistry, and engineering."
    },
    "berkeley-compbio-phd": {
        "id": "berkeley-compbio-phd",
        "s": "berkeley",
        "n": "计算生物学博士",
        "en": "PhD in Computational Biology (UC Berkeley Center for Computational Biology)",
        "dept": "Computational Biology Graduate Group, Center for Computational Biology",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5-6 years full-time",
        "ddl": "Nov 30, 2026 at 8:59pm PST (Fall admission only; no Master's degree offered)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "GRE General NOT required and will NOT be seen by the review committee. Subject tests NOT required. GRE scores are not a determining factor for application review."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). CCB/Graduate Division funding package.",
        "url": "details/berkeley-compbio-phd.html",
        "school": "UC Berkeley",
        "website": "https://ccb.berkeley.edu/academics/computational-biology-phd/phd-admissions",
        "overview": "The Computational Biology PhD program is offered through the Center for Computational Biology (CCB) Graduate Group. The program is intended for students who are passionate about being high-functioning in both computational and biological sciences. No Master's degree is offered through this program. The Designated Emphasis in Computational and Genomic Biology is also available for doctoral students in related programs.",
        "requirements": "Required: distinguished academic record, strong foundations in basic biological, physical, and computational sciences, significant computer programming and research experience. Bachelor's degree in related 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.",
        "research": "Research areas: computational genomics, systems biology, bioinformatics, machine learning for biology, computational structural biology, population genetics, evolutionary biology, single-cell analysis, genomic medicine, computational biology methods development."
    },
    "berkeley-astro-phd": {
        "id": "berkeley-astro-phd",
        "s": "berkeley",
        "n": "天体物理学博士",
        "en": "PhD in Astrophysics (UC Berkeley Department of Astronomy)",
        "dept": "Department of Astronomy",
        "college": "UC Berkeley",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "6 years normative time",
        "ddl": "Dec 4, 2026 at 8:59pm PST (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "Physics GRE Subject Test REQUIRED for all applicants. General GRE NOT required. Note: Department of Physics separately requires General GRE strongly recommended for Fall 2027; Astronomy department requires Physics Subject but not General GRE."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Astronomy Department funding package.",
        "url": "details/berkeley-astro-phd.html",
        "school": "UC Berkeley",
        "website": "https://astro.berkeley.edu/graduate/how-apply",
        "overview": "The Department of Astronomy offers a graduate program leading to the PhD in Astrophysics. Entering students need not have majored in astronomy, although some background is desirable; a strong background in physics is essential. The department offers opportunities in a wide variety of fields including theoretical and observational astrophysics, infrared/optical/radio astronomy, time-domain astronomy, high-energy astrophysics, cosmology, exoplanets, star formation, and stellar evolution. Six years is the normative time to degree.",
        "requirements": "Required: bachelor's degree with strong physics background. Some astronomy background desirable. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. Physics GRE Subject Test required. International students: TOEFL/IELTS required.",
        "research": "Research areas: observational astrophysics, theoretical astrophysics, cosmology, exoplanet discovery, star formation, stellar evolution, high-energy astrophysics, time-domain astronomy, radio astronomy, infrared astronomy, optical astronomy, galactic dynamics, extragalactic astronomy."
    },
    "berkeley-ieor-ms": {
        "id": "berkeley-ieor-ms",
        "s": "berkeley",
        "n": "工业工程与运筹学硕士",
        "en": "MS in Industrial Engineering and Operations Research (UC Berkeley)",
        "dept": "Department of Industrial Engineering & Operations Research",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "1 year full-time (terminal degree)",
        "ddl": "Dec 15, 2026 at 8:59pm PST (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "GRE REQUIRED for all applicants except: UC degree holders with 3.5+ cumulative/advanced GPA; current UC students with 3.5+ GPA; UC transfer students with 3.5+ advanced GPA. ETS code 4833. No minimum score required. Tests must be taken by application deadline."
        },
        "tui": "MS students typically self-funded or receive partial assistantships. Tuition: ~$20,000/year resident / ~$35,000/non-resident + fees. Ranked #3 in nation.",
        "url": "details/berkeley-ieor-ms.html",
        "school": "UC Berkeley",
        "website": "https://ieor.berkeley.edu/academics/master-of-science/",
        "overview": "The IEOR MS is a full-time, one-year technical master's degree program ranked #3 in the nation. The MS is a terminal degree - students are not expected to continue to the IEOR PhD. The program prepares students with the latest theory, computational tools, and methods for data-driven decision-making in domains such as AI, high-tech, healthcare, energy, finance, consulting, data science, management, robotics, and logistics.",
        "requirements": "Required: bachelor's degree in engineering, mathematics, or related quantitative field. GPA minimum 3.0 (competitive applicants higher). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE required (waiver for UC 3.5+ GPA holders). International students: TOEFL/IELTS required.",
        "research": "Areas of study: optimization, stochastic modeling, simulation, decision analytics, machine learning, data science, financial engineering, supply chain management, healthcare systems, energy systems, risk management, operations research methods."
    }
}

# 模板
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")

# 构建 PROGRAMS 记录
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())

# 定位 PROGRAMS 数组结束位置
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

# i 现在指向 ] 之后
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 Set
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!")
