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-biostat-phd": {
        "id": "berkeley-biostat-phd",
        "s": "berkeley",
        "n": "生物统计学博士",
        "en": "PhD in Biostatistics (UC Berkeley School of Public Health)",
        "dept": "School of Public Health, Division of Biostatistics",
        "college": "UC Berkeley",
        "disc": "med",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "4-6 semesters coursework; PhD typically 5 years",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum; dept may require higher)",
        "test": {
            "cls": "GRE General REQUIRED. ETS code 4833. Waiver available if: 2 semesters calculus (B+), 1 semester linear algebra (B+), 1 semester statistics (B+), undergrad GPA 3.0+, quantitative GPA 3.0+. Scores must be within 5 years. No minimum score; competitive applicants ~50th percentile and above."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Berkeley Graduate Division funding package.",
        "url": "details/berkeley-biostat-phd.html",
        "school": "UC Berkeley",
        "website": "https://publichealth.berkeley.edu/academics/programs/biostatistics-phd",
        "overview": "The Biostatistics PhD program at UC Berkeley trains students in the theory of statistics and biostatistics, computer implementation of analytic methods, and application to biological/medical research. Curriculum is jointly taught by the Division of Biostatistics (School of Public Health) and the Department of Statistics (College of Letters & Science). All PhD students are required to hold a master's degree in Biostatistics or a related field.",
        "requirements": "Required: master's degree in Biostatistics or related field. Strongly recommended prerequisites: calculus, linear algebra, statistics. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE General scores required (waiver available per criteria above). No minimum GPA; competitive applicants ~3.5+.",
        "research": "Research areas: statistical methodology, bioinformatics, genomics, environmental statistics, epidemiological methods, causal inference, machine learning for health. Joint faculty appointment with Department of Statistics."
    },
    "berkeley-econ-phd": {
        "id": "berkeley-econ-phd",
        "s": "berkeley",
        "n": "经济学博士",
        "en": "PhD in Economics (UC Berkeley Department of Economics)",
        "dept": "Department of Economics",
        "college": "UC Berkeley",
        "disc": "soc",
        "lvl": "d",
        "deg": "PhD",
        "stem": 0,
        "dur": "5-6 years full-time",
        "ddl": "Dec 1, 2026 at 8:59pm PT (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "GRE General REQUIRED. No exceptions. ETS code 4833. Scores valid 5 years. We recommend taking GRE by October for timely score arrival. 3 letters of recommendation must also be received by Dec 12, 2026."
        },
        "tui": "Fully funded for PhD students (5 years guarantee: stipend + tuition + fees + summer support). Berkeley Graduate Division funding.",
        "url": "details/berkeley-econ-phd.html",
        "school": "UC Berkeley",
        "website": "https://econ.berkeley.edu/graduate/admissions",
        "overview": "The Economics PhD program at UC Berkeley is designed for students pursuing advanced study and original research in economics. New admissions are restricted to PhD only; there is no external terminal MA program. Students may earn an MA en route to the PhD. The program is consistently ranked among the top economics departments worldwide.",
        "requirements": "Required: bachelor's degree (economics major preferred but not required). Prerequisites: intermediate math-based micro/macro theory, multivariate calculus, basic matrix algebra, differential equations. Knowledge of statistics and elementary probability highly desirable. 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE General required (no exceptions).",
        "research": "Fields: microeconomic theory, macroeconomics, econometrics, labor economics, public economics, industrial organization, international trade, development economics, behavioral economics, political economy, environmental economics."
    },
    "berkeley-cee-phd": {
        "id": "berkeley-cee-phd",
        "s": "berkeley",
        "n": "土木与环境工程博士",
        "en": "PhD in Civil and Environmental Engineering (UC Berkeley)",
        "dept": "Department of Civil and Environmental Engineering",
        "college": "UC Berkeley College of Engineering",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "~5 years full-time",
        "ddl": "Dec 15, 2026 (Fall admission only; no Spring admission)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum)",
        "test": {
            "cls": "GRE NO LONGER REQUIRED NOR ACCEPTED. CEE department explicitly states: 'The CEE department no longer requires, nor accepts, the GRE.' No subject test required either."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Research assistantships and teaching assistantships available.",
        "url": "details/berkeley-cee-phd.html",
        "school": "UC Berkeley",
        "website": "https://ce.berkeley.edu/grad/admissions",
        "overview": "The Department of Civil and Environmental Engineering (CEE) at Berkeley offers PhD programs across seven areas of study. The PhD typically takes 5 years to complete. Students with only a bachelor's degree earn a master's degree while progressing toward the PhD. Admission requires faculty research adviser support.",
        "requirements": "Required: bachelor's or master's degree in Civil/Environmental Engineering or 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": "Seven programs of study: structural engineering, geotechnical engineering, transportation engineering, environmental engineering, hydrology/water resources, construction engineering and management, engineering mechanics. Designated Emphasis options available."
    },
    "berkeley-bioe-joint-phd": {
        "id": "berkeley-bioe-joint-phd",
        "s": "berkeley",
        "n": "生物工程联合博士（Berkeley×UCSF）",
        "en": "Joint PhD in Bioengineering (UC Berkeley × UCSF)",
        "dept": "Department of Bioengineering (Berkeley) × Dept of Bioengineering & Therapeutic Sciences (UCSF)",
        "college": "UC Berkeley / UCSF",
        "disc": "eng",
        "lvl": "d",
        "deg": "Joint 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)",
        "test": {
            "cls": "GRE OPTIONAL (since Fall 2020 admission cycle). Applicants may submit scores but are not required to. ETS code 4833. Scores must be within 5 years."
        },
        "tui": "Fully funded for PhD students (stipend + tuition + fees). Joint Berkeley-UCSF funding package.",
        "url": "details/berkeley-bioe-joint-phd.html",
        "school": "UC Berkeley × UCSF",
        "website": "https://bioegrad.berkeley.edu/prospectivegrads/application",
        "overview": "The Berkeley-UCSF Graduate Program in Bioengineering awards a joint PhD degree granted by both institutions. The interdisciplinary program combines biomedical and clinical sciences at UCSF with engineering, physical and life sciences at Berkeley. Students are simultaneously enrolled in both graduate divisions and may take courses and conduct research on both campuses. Interview visits held February 17-19 and 24-26, 2027.",
        "requirements": "Required: bachelor's degree or equivalent in bioengineering or related field (engineering, biology, physics, chemistry). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE optional. GPA competitive applicants ~3.5+. International students: TOEFL/IELTS required.",
        "research": "Research areas: medical imaging, biomaterials, tissue engineering, biomechanics, bioinformatics, computational biology, neural engineering, molecular/cellular bioengineering, drug delivery. Faculty from both Berkeley and UCSF campuses."
    },
    "berkeley-eecs-cs-ms": {
        "id": "berkeley-eecs-cs-ms",
        "s": "berkeley",
        "n": "电子工程与计算机科学硕士（CS方向）",
        "en": "MS in EECS - Computer Science (UC Berkeley)",
        "dept": "Department of Electrical Engineering and Computer Sciences",
        "college": "UC Berkeley College of Engineering",
        "disc": "cs",
        "lvl": "m",
        "deg": "MS",
        "stem": 1,
        "dur": "2 years full-time (research-oriented)",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL 90 / IELTS 7.0 (Graduate Division minimum; dept may require higher)",
        "test": {
            "cls": "GRE NO LONGER REQUIRED NOR ACCEPTED. EECS department explicitly states: 'The GRE is no longer required nor accepted.' No subject test either."
        },
        "tui": "MS students typically self-funded or receive partial assistantships. Tuition: ~$20,000/year resident / ~$35,000/non-resident + fees. Research assistantships competitive.",
        "url": "details/berkeley-eecs-cs-ms.html",
        "school": "UC Berkeley",
        "website": "https://eecs.berkeley.edu/academics/graduate/research-programs/admissions",
        "overview": "The EECS MS in Computer Science emphasizes research preparation and experience. For most students, it is a chance to lay the groundwork for pursuing a PhD. The MS is a research-oriented degree, distinct from the professional MEng. Note: Berkeley EECS does not offer a terminal professional MS; the MS is primarily for students who will continue to the PhD.",
        "requirements": "Required: bachelor's degree in CS, EECS, or related field. GPA minimum 3.0 (competitive applicants ~3.7+). 3 letters of recommendation. Statement of Purpose. Personal History Statement. Official transcripts. GRE not required. International students: TOEFL/IELTS required (IELTS Indicator and One Skill Retake NOT accepted).",
        "research": "Research areas: artificial intelligence, machine learning, computer vision, natural language processing, systems, networking, security, databases, programming languages, theory, HCI, graphics, robotics. Faculty are among the most cited in CS."
    }
}

# 模板
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 数组结束位置
# 格式: const 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
# j 现在是最后一个非空白字符
if html[j] != ',':
    # 没有逗号，需要加逗号
    new_block = "," + new_records
else:
    new_block = new_records

html = html[:insert_pos] + new_block + html[insert_pos:]

# 现在重新定位 VD Set
# 格式: const VERIFIED_DETAILS=new Set(["details/xxx.html", ...]);
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

# i 指向 ] 之后
vd_insert_pos = i - 1  # 指向 ]

# 构建 VD 新元素
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!")
