#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第152轮批量写入：Notre CSE / NYU×2 / UPenn EE / Cornell BME 共 5 条硕士"""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
IDX = os.path.join(BASE, 'index_main.html')

projects = [
    {
        "id": "notre-mscse",
        "s": "notre",
        "n": "计算机科学与工程硕士",
        "en": "Computer Science and Engineering (MSCSE)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "11 个月-2 年全日制（30 学分：24 学分 60000 级课程 + 6 学分研究/thesis；well-prepared 学生 2 学期+夏季可完成）",
        "ddl": "Fall 12 月 15 日 / Spring 10 月 15 日",
        "lang": "TOEFL iBT ≥ 100 / IELTS / Duolingo（按 Notre Dame Graduate School 标准）",
        "test": {"cls": "GRE 不强制（录取分布，非最低门槛）；3 封推荐信；欢迎 CS 或相关本科；非 CS 本科走 TTC 过渡路径"},
        "tui": "待补",
        "url": "details/notre-mscse-computer-science-engineering.html",
        "fields": ["AI & Machine Learning", "Algorithms & Theory", "Computer Architecture & Systems", "Computer Vision", "Human-Computer Interaction", "Natural Language Processing", "Data Science", "Security & Privacy", "Software Engineering", "Visualization"],
        "school": "圣母大学",
        "official": "https://graduateschool.nd.edu/degree-programs/computer-science-and-engineering-mscse---masters-professional/",
        "note": "College of Engineering, Department of Computer Science and Engineering；terminal MS 与 PhD 分池招生；所有合格 MS 自动考虑 TA 职位（带 stipend），但无学费减免；TTC（Transition to Computing）路径为非 CS 本科学生提供 12 学分过渡学期（Software Design/Data Structures/Computer Systems/Integrative Practicum），GPA 3.0 后直接进入 MSCSE。",
    },
    {
        "id": "nyu-ma-econ",
        "s": "nyu",
        "n": "经济学文学硕士",
        "en": "Economics (MA)",
        "deg": "MA",
        "lvl": "m", "stem": 1,
        "dur": "3-4 学期全日制（32 学分：5 门核心 + 5 门选修 + Special Project；最长 5 年完成）",
        "ddl": "待补（GSAS 常规 Fall 入学）",
        "lang": "TOEFL iBT ≥ 105（国际生；录取分布，非最低门槛）",
        "test": {"cls": "GRE Quant > 80 百分位（≈159）/ AW > 80 百分位（≈5.0）/ Verbal > 50 百分位（≈150）；先修：2 门微积分 + 1 门统计 + 1 门计量 + 中级微观/宏观 + 4 门其他经济学；GPA 3.5+"},
        "tui": "待补",
        "url": "details/nyu-ma-economics.html",
        "fields": ["Microeconomic Theory", "Macroeconomic Theory", "Applied Statistics & Econometrics", "Math for Economists", "Special Project in Economic Research", "跨修 Stern/Courant/CDS 课程"],
        "school": "纽约大学",
        "official": "https://gsas.nyu.edu/academics/bulletin/economics/ma-economics.html",
        "note": "Graduate School of Arts and Science, Department of Economics；MA 为应用/实证/政策导向，与 10 个月加速 MS（Quantitative Economics）区分；允许跨修 Stern（金融）、Courant（数学）、Center for Data Science、政治系课程；少数优秀生可修 PhD 级课程；多数毕业生进入金融/银行/咨询/政府/国际组织。",
    },
    {
        "id": "nyu-ms-a3sr",
        "s": "nyu",
        "n": "社会科学研究应用统计学硕士",
        "en": "Applied Statistics for Social Science Research (MS, A3SR)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "3-4 学期全日制（34-44 学分可变；依先修背景加速可减学分；最多 6 学期 part-time）",
        "ddl": "2 月 1 日（Fall 入学）",
        "lang": "TOEFL/IELTS 按 NYU Steinhardt 标准",
        "test": {"cls": "GRE 待补（录取分布，非最低门槛）；要求定量与统计背景"},
        "tui": "待补",
        "url": "details/nyu-ms-applied-statistics-social-science.html",
        "fields": ["General Applied Statistics", "Computational Methods", "Data Science for Social Impact", "Measurement Methodology and Design", "Causal Inference", "Multilevel Modeling", "Machine Learning", "Survey Sampling"],
        "school": "纽约大学",
        "official": "https://steinhardt.nyu.edu/degree/ms-applied-statistics-social-science-research",
        "note": "Steinhardt School of Culture, Education, and Human Development；4 个 concentration 必选其一；Faculty 强项：因果推断、人口学、缺失数据、模型选择、多变量分析、多层模型、网络、调查抽样；毕业生去向：应用统计师/数据科学家（公共或私营部门）或 PhD 继续深造。",
    },
    {
        "id": "upenn-mse-ee",
        "s": "up",
        "n": "电气工程硕士",
        "en": "Electrical Engineering (MSE)",
        "deg": "MSE",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（10 course units：5 EE core + 2 ESE elective + 1 SEAS elective + 2 open elective；夏修可 1 年完成）",
        "ddl": "2 月 1 日（Fall 入学；申请 9 月 15 日开放）",
        "lang": "TOEFL/IELTS 按 Penn SEAS Graduate Admissions 标准",
        "test": {"cls": "GRE 待补（录取分布，非最低门槛）；先修：本科 EE 或物理 + 强数学背景"},
        "tui": "待补",
        "url": "details/upenn-mse-electrical-engineering.html",
        "fields": ["Electromagnetics & Photonics", "VLSI & Nanotechnology", "Sensors & MEMS", "Signal Processing", "Robotics", "Data Science", "Information & Decision Systems", "Feedback Control"],
        "school": "宾夕法尼亚大学",
        "official": "https://www.ese.upenn.edu/academics/masters/electrical-engineering-program/",
        "note": "School of Engineering and Applied Science, Department of Electrical and Systems Engineering；open elective 可跨修 SEAS/SAS/Medicine/Law/Wharton MBA/Social Policy/Education 研究生课程（需 technical/scientific 内容并经 ESE 审批）；国际生每学期至少注册 3 门课；提供 thesis 与 non-thesis 选项；与 GRASP 实验室、Singh 纳米技术中心等合作。",
    },
    {
        "id": "cornell-ms-bme",
        "s": "cornell",
        "n": "生物医学工程硕士（论文）",
        "en": "Biomedical Engineering (MS, Thesis)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "2 年全日制（Ithaca in-person；research-focused；须完成 master's thesis）",
        "ddl": "12 月 1 日（Fall 入学；无 Spring 入学）",
        "lang": "TOEFL/IELTS 按 Cornell Graduate School 标准",
        "test": {"cls": "GRE 待补（录取分布，非最低门槛）；self-funded 学位；到校后 10 月双向选择导师"},
        "tui": "待补",
        "url": "details/cornell-ms-biomedical-engineering.html",
        "fields": ["Biomechanics", "Biomaterials", "Drug/Gene Delivery", "Molecular & Cellular Bioengineering", "Medical Imaging", "Tissue Engineering", "Systems Biology", "Neuroengineering"],
        "school": "康奈尔大学",
        "official": "https://www.duffield.cornell.edu/bme/ms-program/",
        "note": "Meinig School of Biomedical Engineering（Duffield College of Engineering）；与 MEng（professional 终端硕士，已在库）区分：MS 为 research track，须完成 Foundations in BME 课程 + 2 学期 seminar + 4-5 门工程/生命科学课程 + thesis；跨学院合作：CALS/Engineering/Human Ecology/Vet Medicine/Weill Cornell Medicine；录取决定通常 2 月底-3 月初通知，最晚 5 月中。",
    },
]

DETAIL_TPL = """<!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:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7;}}
h1{{font-size:24px;border-bottom:3px solid #1a5fb4;padding-bottom:8px;}}
h2{{font-size:18px;color:#1a5fb4;margin-top:28px;}}
.meta{{background:#f5f7fa;padding:14px 18px;border-radius:8px;margin:16px 0;}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:10px 24px;}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a5fb4;padding:2px 10px;border-radius:12px;font-size:13px;margin:2px 4px 2px 0;}}
a{{color:#1a5fb4;}}
.note{{background:#fff8e1;padding:12px 16px;border-left:4px solid #f9a825;margin:16px 0;font-size:14px;}}
</style>
</head>
<body>
<h1>{school} · {n}</h1>
<div class="meta">
<div class="grid">
<div><b>英文名：</b>{en}</div>
<div><b>学位：</b>{deg}</div>
<div><b>学制：</b>{dur}</div>
<div><b>STEM：</b>{stem_yn}</div>
<div><b>申请截止：</b>{ddl}</div>
<div><b>语言要求：</b>{lang}</div>
<div><b>标化：</b>{test_cls}</div>
<div><b>学费：</b>{tui}</div>
</div>
</div>
<h2>方向 / Concentration</h2>
{fields_html}
<h2>项目说明</h2>
<div class="note">{note}</div>
<h2>官方链接</h2>
<p><a href="{official}" target="_blank">{official}</a></p>
<p><a href="index_main.html">← 返回项目库首页</a></p>
</body>
</html>
"""

for p in projects:
    fields_html = "\n".join(f'<span class="tag">{f}</span>' for f in p["fields"])
    html = DETAIL_TPL.format(
        school=p["school"], n=p["n"], en=p["en"], deg=p["deg"],
        dur=p["dur"], stem_yn="是" if p["stem"] else "否",
        ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"], tui=p["tui"],
        fields_html=fields_html, note=p["note"], official=p["official"]
    )
    with open(os.path.join(BASE, p["url"]), "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] 生成: {p['url']} ({len(html)} chars)")

with open(IDX, "r", encoding="utf-8") as f:
    idx = f.read()

def esc(s):
    return s.replace("\\", "\\\\").replace('"', '\\"')

prog_records = []
for p in projects:
    rec = (
        '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
        'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},tui:"{tui}",'
        'url:"{url}"}}'
    ).format(
        id=p["id"], s=p["s"], n=esc(p["n"]), en=esc(p["en"]), deg=p["deg"],
        lvl=p["lvl"], stem=p["stem"], dur=esc(p["dur"]), ddl=esc(p["ddl"]),
        lang=esc(p["lang"]), test_cls=esc(p["test"]["cls"]), tui=esc(p["tui"]),
        url=p["url"]
    )
    prog_records.append(rec)

m = re.search(r'(const PROGRAMS\s*=\s*\[)', idx)
start = m.end()
depth = 1; i = start
while i < len(idx) and depth > 0:
    if idx[i] == '[': depth += 1
    elif idx[i] == ']': depth -= 1
    i += 1
insert_pos = i - 1
j = insert_pos - 1
while j >= 0 and idx[j] in ' \t\n\r': j -= 1
if j >= 0 and idx[j] not in ',[':
    insert_text = "," + ",".join(prog_records)
else:
    insert_text = ",".join(prog_records)
idx = idx[:insert_pos] + insert_text + idx[insert_pos:]
print(f"[OK] PROGRAMS 追加 {len(prog_records)} 条")

m2 = re.search(r'(VERIFIED_DETAILS\s*=\s*new Set\(\[)', idx)
vd_start = m2.end()
depth = 1; i = vd_start
while i < len(idx) and depth > 0:
    if idx[i] == '[': depth += 1
    elif idx[i] == ']': depth -= 1
    i += 1
vd_insert = i - 1
j = vd_insert - 1
while j >= 0 and idx[j] in ' \t\n\r': j -= 1
last_char = idx[j] if j >= 0 else ''
new_vd = ",".join(f'"{p["url"]}"' for p in projects)
if last_char == ',':
    vd_text = new_vd
elif last_char == '"':
    vd_text = "," + new_vd
else:
    vd_text = "," + new_vd
idx = idx[:vd_insert] + vd_text + idx[vd_insert:]
print(f"[OK] VERIFIED_DETAILS 追加 {len(projects)} 条")

with open(IDX, "w", encoding="utf-8") as f:
    f.write(idx)
print(f"\n[DONE] index_main.html 已写回 ({len(idx)} chars)")
