#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第149轮批量写入：UCLA/UIUC/Northwestern/UBC/UMich 各 1 条硕士"""
import os, re

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

projects = [
    {
        "id": "ucla-ms-cs",
        "s": "ucla",
        "n": "计算机科学硕士",
        "en": "Computer Science (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（Fall only 入学）",
        "ddl": "12 月 15 日（Fall 入学）",
        "lang": "TOEFL iBT ≥ 87 / IELTS ≥ 7.0",
        "test": {"cls": "2027-2028 申请季 GRE 不要求（录取分布，非最低门槛）；建议本科 GPA 3.5+"},
        "tui": "待补",
        "url": "details/ucla-ms-computer-science.html",
        "fields": ["Systems", "Software", "Algorithms", "Machine Learning", "Computer Architecture", "Graphics/HCI"],
        "school": "加州大学洛杉矶分校",
        "official": "https://www.cs.ucla.edu/graduate-admissions/",
        "note": "Henry Samueli School of Engineering and Applied Science；CS 系 regular MS 项目；Fall 入学 only；3 封推荐信；不提供 conditional admission 或 pre-master's；可与 Anderson MBA 读 concurrent 3 年双学位。",
    },
    {
        "id": "uiuc-oncampus-mcs",
        "s": "illinois",
        "n": "在校计算机科学专业硕士",
        "en": "Professional Master of Computer Science (MCS, On-Campus)",
        "deg": "MCS",
        "lvl": "m", "stem": 1,
        "dur": "最短 1 年（最多 3 学期；32 学分 coursework-only）",
        "ddl": "滚动录取（Fall/Spring 入学）",
        "lang": "TOEFL iBT ≥ 102 / IELTS ≥ 6.5（单项 ≥ 6.0）",
        "test": {"cls": "GRE 不要求（录取分布，非最低门槛）；建议本科 GPA 3.2+；不要求推荐信"},
        "tui": "申请费 $90",
        "url": "details/uiuc-oncampus-mcs.html",
        "fields": ["Algorithms", "Data Structures", "Machine Learning", "Databases", "Programming Languages", "Systems"],
        "school": "伊利诺伊大学厄巴纳-香槟分校",
        "official": "https://cs.illinois.edu/academics/graduate/professional-mcs/campus-master-computer-science",
        "note": "Siebel School of Computing and Data Science；non-thesis coursework-only；32 学分；至少 4 门 core 课程；非 CS 本科需补先修（OOP/数据结构/算法/线代/概率统计）；UIUC 本校 CS 本科满足条件可 guaranteed admission。",
    },
    {
        "id": "nu-msai",
        "s": "nu",
        "n": "人工智能硕士",
        "en": "Master of Science in Artificial Intelligence (MSAI)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "15 个月全日制（traditional track；MSAI+X track 12 个月）",
        "ddl": "推荐 12 月 15 日 / 最终 4 月 15 日（9 月入学）",
        "lang": "TOEFL iBT ≥ 100 / IELTS ≥ 7.0",
        "test": {"cls": "GRE 可选（不强制；录取分布，非最低门槛）；偏好 2 年以上相关工作经验"},
        "tui": "待补",
        "url": "details/northwestern-ms-artificial-intelligence.html",
        "fields": ["Machine Learning", "Deep Learning", "AI Systems", "Human-AI Interaction", "Ethics in AI", "Capstone"],
        "school": "西北大学",
        "official": "https://www.mccormick.northwestern.edu/artificial-intelligence/",
        "note": "Robert R. McCormick School of Engineering；Evanston 校区；班级规模约 45 人；要求 CS/相关背景或相当工程经验；3 封推荐信 + 简历 + 个人陈述 + 可选 video；Python 从第一天即用，不教基础语法。",
    },
    {
        "id": "ubc-meng-ece",
        "s": "ubc",
        "n": "电气与计算机工程硕士",
        "en": "Master of Engineering in Electrical and Computer Engineering (MEng)",
        "deg": "MEng",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（9 月入学，in person at UBC Vancouver）",
        "ddl": "12 月 12 日（2027 年 9 月入学，国际生）",
        "lang": "TOEFL iBT ≥ 100（阅读22/写作21/口语21/听力22）/ IELTS ≥ 7.0（单项 ≥ 6.0）",
        "test": {"cls": "GRE 不要求；建议本科 GPA 76%（4 分制约 3.3+），偏好 80%"},
        "tui": "待补",
        "url": "details/ubc-meng-electrical-computer-engineering.html",
        "fields": ["Communications", "Microelectronics", "Photonics", "Power Systems", "Controls", "Computer Engineering"],
        "school": "英属哥伦比亚大学",
        "official": "https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/master-of-engineering-electrical-computer-engineering",
        "note": "Faculty of Applied Science；Vancouver 校区 in person；4 年工程或相关本科；3 封推荐信 + CV + SOP；授课型硕士（professional），非论文导向；MEng 学位 alone 不能作为加拿大专业工程师协会认证基础。",
    },
    {
        "id": "umich-ms-ece",
        "s": "umich",
        "n": "电气与计算机工程硕士",
        "en": "Electrical and Computer Engineering (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（day-time；Fall/Winter 入学）",
        "ddl": "Fall 1 月 15 日 / Winter 9 月 15 日",
        "lang": "TOEFL/IELTS 按 Rackham 研究生院标准",
        "test": {"cls": "国际本科需 GRE；美国本科 GRE 可选（录取分布，非最低门槛）；建议本科 GPA 3.5+"},
        "tui": "待补",
        "url": "details/umich-ms-electrical-computer-engineering.html",
        "fields": ["Circuits & VLSI", "Communications", "Controls", "Electromagnetics", "Photonics", "Solid-State", "Systems", "Signal & Image Processing"],
        "school": "密歇根大学安娜堡分校",
        "official": "https://ece.engin.umich.edu/academics/graduate-programs/prospective-grad-students/apply-for-grad/apply/",
        "note": "Rackham Graduate School；ECE 系；3 封推荐信 + Academic SOP（1-3 页）+ Personal Statement（1 页）；本科 EE 背景可选 MS 或 MSE 学位，非 EE 本科授 MS；系里不给 master's 奖学金；偶尔允许 domestic 学生 part-time 一学期一门课。",
    },
]

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