#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第150轮批量写入：UCLA×2/UMich/McGill/UVA 各 1 条硕士"""
import os, re

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

projects = [
    {
        "id": "ucla-mse-ece",
        "s": "ucla",
        "n": "电气与计算机工程硕士",
        "en": "Electrical and Computer Engineering (MSE)",
        "deg": "MSE",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（Fall only 入学）",
        "ddl": "12 月 15 日（Fall 入学，太平洋时间 23:59）",
        "lang": "TOEFL iBT ≥ 87 / IELTS ≥ 7.0",
        "test": {"cls": "2027-2028 申请季 GRE 不要求（录取分布，非最低门槛）；建议 GPA 3.5+"},
        "tui": "待补",
        "url": "details/ucla-mse-electrical-computer-engineering.html",
        "fields": ["Circuits & VLSI", "Communications", "Controls", "Electromagnetics", "Photonics", "Signal & Image Processing", "Solid-State", "Systems"],
        "school": "加州大学洛杉矶分校",
        "official": "https://www.ee.ucla.edu/graduate-application-requirements/",
        "note": "Henry Samueli 工程学院 ECE 系；Fall only 入学；3 封推荐信 + SOP；PhD 未录取者会自动转入 MS 池；2028 Fall 起 GRE 豁免重新评估。",
    },
    {
        "id": "ucla-ms-me",
        "s": "ucla",
        "n": "机械工程硕士",
        "en": "Mechanical Engineering (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（Fall only 入学）",
        "ddl": "12 月 1 日（Fall 入学）",
        "lang": "TOEFL iBT ≥ 87 / IELTS ≥ 7.0",
        "test": {"cls": "GRE General required（录取分布，非最低门槛）；3 封推荐信 + SOP + CV"},
        "tui": "待补",
        "url": "details/ucla-ms-mechanical-engineering.html",
        "fields": ["Aerodynamics", "Biomechanical Engineering", "Controls", "Design", "Dynamics", "Energy", "Fluids", "Manufacturing", "Materials", "Robotics", "Thermal Sciences"],
        "school": "加州大学洛杉矶分校",
        "official": "https://www.mae.ucla.edu/graduate-admissions-2/",
        "note": "Mechanical and Aerospace Engineering (MAE) 系；Fall only；截止严格 12/1；4 月 15 日前必出录取决定；terminal MS 与 PhD 同池招生，无 MS 学位者通常按 MS 录取。",
    },
    {
        "id": "umich-mse-me",
        "s": "umich",
        "n": "机械工程硕士",
        "en": "Mechanical Engineering (MSE)",
        "deg": "MSE",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年全日制（30 学分；Fall only；三种选项：coursework-only / coursework+research / thesis）",
        "ddl": "Fall 1 月 15 日（冬季仅限 U-M 本校学生 8 月 1 日）",
        "lang": "TOEFL iBT ≥ 84 / IELTS 按 Rackham 标准",
        "test": {"cls": "Fall 2027 GRE 可选（录取分布，非最低门槛）；无 GPA 最低线但竞争激烈"},
        "tui": "待补",
        "url": "details/umich-mse-mechanical-engineering.html",
        "fields": ["Automotive", "Biomechanics & Biosystems", "Controls", "Design", "Dynamics & Vibrations", "Energy", "Fluids", "Manufacturing", "Mechanics & Materials", "Mechatronics", "Robotics", "Thermal Sciences"],
        "school": "密歇根大学安娜堡分校",
        "official": "https://me.engin.umich.edu/admissions/graduate/",
        "note": "Rackham 研究生院；ME 系；30 学分毕业，累计 GPA 需 ≥ 3.0；3 封推荐信 + SOP + Personal Statement；外招 PhD 建议 12/1 前提交；MEng Automotive/Game/Mfg 另有 6/15 延期截止。",
    },
    {
        "id": "mcg-msc-cs",
        "s": "mcg",
        "n": "计算机科学理学硕士（非论文）",
        "en": "Computer Science (MSc, Non-Thesis)",
        "deg": "MSc",
        "lvl": "m", "stem": 1,
        "dur": "1.5-2 年全日制（Fall only；course-based 非论文）",
        "ddl": "12 月 15 日（Fall 入学，国际生）",
        "lang": "TOEFL/IELTS 按 McGill GPS 标准",
        "test": {"cls": "GRE 不要求（录取分布，非最低门槛）；本科 CGPA ≥ 3.2/4.0"},
        "tui": "申请费含最多 2 个项目",
        "url": "details/mcgill-msc-computer-science-non-thesis.html",
        "fields": ["Applications", "Theory", "Systems"],
        "school": "麦吉尔大学",
        "official": "https://www.mcgill.ca/gradapplicants/program/computer-science-msc-non-thesis",
        "note": "Faculty of Science, School of Computer Science；course-based 强调实践与严谨学习；申请时选 Applications/Theory/Systems 一个研究方向；无需提前联系导师；申请问卷含动机陈述。",
    },
    {
        "id": "uva-ms-cs",
        "s": "uva",
        "n": "计算机科学硕士（论文）",
        "en": "Computer Science (MS, Thesis)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "1.5-2 年全日制（31 学分；含 6 学分 CS 8999 论文 + 1 学分 CS 6190）",
        "ddl": "1 月 30 日（Fall 入学）",
        "lang": "TOEFL iBT ≥ 90 / IELTS ≥ 7.0",
        "test": {"cls": "2026 申请季 GRE optional（录取分布，非最低门槛）；不要求 CS 本科但需先修课"},
        "tui": "待补",
        "url": "details/uva-ms-computer-science.html",
        "fields": ["Algorithms", "Artificial Intelligence", "Computer Architecture", "Cryptography", "Databases", "Human-Computer Interaction", "Programming Languages", "Software Engineering", "Systems"],
        "school": "弗吉尼亚大学",
        "official": "https://engineering.virginia.edu/department/computer-science/academics/graduate-programs/ms-computer-science",
        "note": "School of Engineering and Applied Science；MS 学位需 coursework + 正式 thesis + oral defense；与 MCS（coursework-only）区分；Fall only；PhD 未录取可转 MS；与 ECE 系合办 Computer Engineering 学位。",
    },
]

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