#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第151轮批量写入：Emory×2 / Notre Dame / USC×2 共 5 条硕士（CS/DS/统计/BA/金融）"""
import os, re

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

projects = [
    {
        "id": "emory-ms-cs",
        "s": "emory",
        "n": "计算机科学硕士",
        "en": "Computer Science (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "约 2 年全日制（含夏季 practicum 实习；3 门核心课 + 4 门方向选修课）",
        "ddl": "待补（Laney Graduate School 常规 Fall 入学）",
        "lang": "TOEFL iBT ≥ 100 / IELTS ≥ 7.0",
        "test": {"cls": "待补（录取分布，非最低门槛）；不要求 CS 本科但需编程基础 + 线性代数 + 离散数学"},
        "tui": "待补",
        "url": "details/emory-ms-computer-science.html",
        "fields": ["Artificial Intelligence", "Machine Learning", "Natural Language Processing", "Data Mining & Data Science", "Human-Computer Interaction", "Visualization", "Systems & High Performance Computing", "Theory"],
        "school": "埃默里大学",
        "official": "https://computerscience.emory.edu/graduate-ms/cs-ms-programs.html",
        "note": "Laney Graduate School, Department of Computer Science；核心课 CS 526 Algorithms / CS 551 Systems Programming / CS 534 Machine Learning；所有 MS 学生须完成 practicum（通常为工业界实习），多数在第一学年后夏季完成；欢迎 CS/Math/Physics/Economics/Biology 等跨学科背景申请。",
    },
    {
        "id": "emory-ms-ds",
        "s": "emory",
        "n": "数据科学硕士（STEM）",
        "en": "Data Science (MS, DATASCIMS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "12 个月全日制（Fall + Spring + Summer 三学期；30 学分；on-campus residential）",
        "ddl": "优先 1 月 15 日 / 最终 4 月 15 日",
        "lang": "TOEFL iBT ≥ 100 / IELTS ≥ 7.0（英语为教学语言的本科可豁免）",
        "test": {"cls": "不要求 GRE（录取分布，非最低门槛）；先修：1 门微积分 + 1 门统计学"},
        "tui": "待补",
        "url": "details/emory-ms-data-science.html",
        "fields": ["统计建模", "因果推断", "研究设计", "统计计算", "AI 增强编程", "数据沟通与可视化", "Capstone 项目"],
        "school": "埃默里大学",
        "official": "https://datascience.emory.edu/graduate/index.html",
        "note": "Department of Data and Decision Sciences（DSc i）；2023 年秋季新设；STEM-designated；Capstone 与企业/政府/非营利合作完成真实数据项目；仅 1 封推荐信 + 简短 SOP；申请费 75 美元。",
    },
    {
        "id": "notre-ms-acms",
        "s": "notre",
        "n": "应用与计算数学统计学硕士（Professional）",
        "en": "Applied and Computational Mathematics and Statistics (MS, Professional)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "10 个月或 16 个月全日制（30 学分；on-campus；最少 1 学期住校）",
        "ddl": "1 月 15 日（晚申至 5 月 31 日，需联系项目主任）",
        "lang": "TOEFL iBT ≥ 100（口语 ≥ 23）/ IELTS / Duolingo",
        "test": {"cls": "GRE General optional（但强烈建议提交；录取分布，非最低门槛）；先修：线性代数 + 编程 + 概率 + 统计，B 以上"},
        "tui": "待补",
        "url": "details/notre-ms-applied-computational-math-statistics.html",
        "fields": ["Applied Statistics", "Applied & Computational Mathematics", "Predictive Analytics", "Computational Finance"],
        "school": "圣母大学",
        "official": "https://graduateschool.nd.edu/degree-programs/applied-and-computational-mathematics-and-statistics-ms---masters-professional/",
        "note": "Department of Applied and Computational Mathematics and Statistics；Professional 终端硕士，30 学分中 21 学分须在 ACMS 系内；申请时声明偏好 10 个月或 16 个月；3 封推荐信 + CV + Statement of Intent；与纯在线项目区分，本项目为 on-campus professional。",
    },
    {
        "id": "usc-msba",
        "s": "usc",
        "n": "商业分析硕士（STEM）",
        "en": "Business Analytics (MS, MSBA)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "约 2 年全日制（33 学分；Fall only；无在线选项）",
        "ddl": "待补（Marshall 常规滚动录取）",
        "lang": "TOEFL/IELTS 按 USC 英语水平政策",
        "test": {"cls": "不要求 GMAT/GRE（录取分布，非最低门槛）；不要求工作经验但偏好；先修：1 门大学统计"},
        "tui": "待补",
        "url": "details/usc-ms-business-analytics.html",
        "fields": ["统计学习", "SQL/NoSQL", "数据可视化", "优化", "营销分析", "金融分析", "运营分析", "Capstone"],
        "school": "南加州大学",
        "official": "https://www.marshall.usc.edu/programs/graduate-programs/specialized-masters/ms-business-analytics",
        "note": "Marshall School of Business；STEM-designated；2026 QS 商业分析全美 #8；申请含 KIRA 视频面试（邀请制）；申请费 175 美元；最多可凭相关硕士学位豁免 9 学分至 24 学分；不提供在线项目。",
    },
    {
        "id": "usc-msf",
        "s": "usc",
        "n": "金融硕士（STEM）",
        "en": "Finance (MS, MSF)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "16 个月全日制（36 学分；Fall only；3 学期：2 Fall + 1 Spring；无在线选项）",
        "ddl": "待补（Marshall 常规滚动录取）",
        "lang": "TOEFL/IELTS 按 USC 英语水平政策",
        "test": {"cls": "GMAT/GRE 要求（录取分布，非最低门槛）；不要求全职工作经验；3.5+ GPA 偏好"},
        "tui": "待补",
        "url": "details/usc-ms-finance.html",
        "fields": ["公司金融", "投资分析与投资组合", "财务预测与风险", "房地产", "并购", "对冲基金", "国际金融"],
        "school": "南加州大学",
        "official": "https://www.marshall.usc.edu/programs/graduate-programs/specialized-masters/ms-finance",
        "note": "Marshall School of Business；STEM-designated；Financial Times 2023 & 2024 全美 #1 金融硕士；面向投行/资管/Fintech/VC；课程与 CFA 内容高度重叠但不专门备考；所有课程在 USC 校园面授；无在线选项。",
    },
]

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