#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第147轮批量写入：Brown/UChicago/Vanderbilt/NYU/Emory 各 1 条硕士"""
import os, re, json

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

# 5 条项目
projects = [
    {
        "id": "brown-eng-scm",
        "s": "brown",
        "n": "工程硕士（多方向）",
        "en": "Engineering (ScM)",
        "deg": "ScM",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 年",
        "ddl": "待补（通常 12 月/1 月）",
        "lang": "TOEFL/IELTS 待补",
        "test": {"cls": "GRE optional（录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/brown-engineering-scm.html",
        "fields": ["Chemical Engineering", "Environmental Engineering", "Electrical and Computer Engineering",
                   "Materials Science and Engineering", "Mechanical Engineering & Applied Mechanics",
                   "Biomedical Engineering", "DECES（数据驱动计算工程）", "Sustainable Energy"],
        "school": "布朗大学",
        "official": "https://engineering.brown.edu/graduate/programs-guide/scm-requirements",
        "note": "Thesis 选项，8 门研究生课 + 论文；跨学科方向丰富；5th-year ScM 可 1 年完成，常规学生通常 1.5-2 年。",
    },
    {
        "id": "uchicago-chem-ms",
        "s": "uchicago",
        "n": "化学硕士",
        "en": "Chemistry MS",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "9 个月-2 年（最快 3 学季）",
        "ddl": "5 月 15 日（秋季入学）",
        "lang": "TOEFL/IELTS（英语能力证明）",
        "test": {"cls": "待补（不提供硕士奖学金）"},
        "tui": "待补（无申请费）",
        "url": "details/uchicago-chemistry-ms.html",
        "fields": ["Physical Chemistry", "Organic Chemistry", "Inorganic Chemistry",
                   "Materials Chemistry", "Chemical Biology"],
        "school": "芝加哥大学",
        "official": "https://chemistry.uchicago.edu/ms-in-chemistry",
        "note": "2026 秋首次招生的全新 terminal MS；研究导向，5 个方向；STEM OPT 资格；适合工业界或博士申请跳板；不提供硕士学费资助。",
    },
    {
        "id": "vandy-msmp",
        "s": "vanderbilt",
        "n": "医学物理硕士",
        "en": "Medical Physics (MSMP)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 年（5 学期）",
        "ddl": "12 月 15 日",
        "lang": "TOEFL/IELTS（国际生需外部学位认证）",
        "test": {"cls": "GRE required（建议总分 312，Quant 159；录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/vanderbilt-medical-physics-ms.html",
        "fields": ["Radiation Therapy Physics", "Diagnostic Imaging Physics"],
        "school": "范德堡大学",
        "official": "https://medschool.vanderbilt.edu/medical-physics/msmp/",
        "note": "CAMPEP 认证项目；小班教学（3-6 人）；200+ 小时临床实习；位于 Vanderbilt University Medical Center；有 thesis 选项；毕业后通常进入 residency。",
    },
    {
        "id": "nyu-a3sr",
        "s": "nyu",
        "n": "社会科学研究应用统计硕士",
        "en": "Applied Statistics for Social Science Research (A3SR)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1-2 年（34-44 学分）",
        "ddl": "2 月 1 日（秋季入学）",
        "lang": "TOEFL/IELTS 待补",
        "test": {"cls": "待补（录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/nyu-a3sr-ms.html",
        "fields": ["General Applied Statistics", "Computational Methods",
                   "Data Science for Social Impact", "Measurement, Methodology, and Design"],
        "school": "纽约大学",
        "official": "https://steinhardt.nyu.edu/degree/ms-applied-statistics-social-science-research",
        "note": "Steinhardt 学院；变量学分制（34-44）；因果推断/缺失数据/多层次建模/网络分析为强项；含统计咨询研究研讨课和实习；可 full-time 或 part-time。",
    },
    {
        "id": "emory-math-ms",
        "s": "emory",
        "n": "数学硕士",
        "en": "Mathematics MS",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 年（30 学分）",
        "ddl": "1 月 31 日（MS 截止；PhD 为 12/15）",
        "lang": "TOEFL（自报成绩可，录取后需官方送分；Emory code 5187）",
        "test": {"cls": "GRE optional（不要求，录取分布，非最低门槛）"},
        "tui": "提供 50% 学费奖学金（学生自理剩余 50% 及学杂费；无 TA 岗位）",
        "url": "details/emory-mathematics-ms.html",
        "fields": ["Pure Mathematics", "Computational Mathematics"],
        "school": "埃默里大学",
        "official": "https://mathematics.emory.edu/graduate/grad-info.html",
        "note": "Laney 研究生院；Thesis 或 course-only 两种选项；适合工业界就业或博士申请跳板；申请费 $75。",
    },
]

# 详情页模板
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>是</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"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"], tui=p["tui"],
        fields_html=fields_html, note=p["note"], official=p["official"]
    )
    det_path = os.path.join(BASE, p["url"])
    with open(det_path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] 生成: {p['url']} ({len(html)} chars)")

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

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

# 在 PROGRAMS 数组末尾追加（用括号深度匹配定位 ]）
# 找 const PROGRAMS=[ ... ];
m = re.search(r'(const PROGRAMS\s*=\s*\[)', idx)
if not m:
    raise SystemExit("未找到 PROGRAMS 数组起始")
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
# i 现在指向 ] 之后；插入点在 ] 前
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] != ',' and idx[j] != '[':
    # 前面是记录结尾 }，需要逗号
    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)} 条")

# 在 VERIFIED_DETAILS 集合追加
m2 = re.search(r'(VERIFIED_DETAILS\s*=\s*new Set\(\[)', idx)
if not m2:
    raise SystemExit("未找到 VERIFIED_DETAILS")
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_entries = ",".join(f'"{p["url"]}"' for p in projects)
if last_char == ',':
    vd_text = new_vd_entries
elif last_char == '"':
    vd_text = "," + new_vd_entries
else:
    vd_text = "," + new_vd_entries
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)")
