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

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

projects = [
    {
        "id": "uva-msacc",
        "s": "uva",
        "n": "会计硕士",
        "en": "Accounting (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "9 个月（8 月入学，次年 5 月毕业）",
        "ddl": "滚动录取（通常秋季入学）",
        "lang": "TOEFL 100 / IELTS 7.5",
        "test": {"cls": "GMAT/GRE 可选（不提交则综合评估；录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/uva-accounting-ms.html",
        "fields": ["Financial Reporting & Assurance", "Tax Consulting"],
        "school": "弗吉尼亚大学",
        "official": "https://www.commerce.virginia.edu/ms-accounting",
        "note": "McIntire 商学院；30 学分；STEM-designated；全日制在校；可满足多数州 CPA 150 学分要求；小班教学；要求会计先修课。",
    },
    {
        "id": "gatech-msbcfm",
        "s": "gatech",
        "n": "建筑施工与设施管理硕士",
        "en": "Building Construction and Facility Management (MSBCFM)",
        "deg": "MS",
        "lvl": "m", "stem": 1,
        "dur": "1-2 年（非论文/论文选项）",
        "ddl": "Fall / Spring 入学",
        "lang": "TOEFL iBT ≥ 90（各项 ≥ 19）/ IELTS ≥ 7（读写 6.5，写作 5.5）",
        "test": {"cls": "GRE 优先但不强制（录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/gatech-building-construction-and-facility-management-ms.html",
        "fields": ["Program & Facility Management", "Technology", "No Concentration", "Thesis Option"],
        "school": "佐治亚理工学院",
        "official": "https://bc.gatech.edu/master-science-building-construction-and-facility-management",
        "note": "ABET 认证设施管理方向；STEM-designated；面向建造/土木/建筑/ME/EE/设施管理本科或相关领域 2 年经验者；含 capstone；有 evening part-time 选项但也支持 full-time。",
    },
    {
        "id": "uchicago-ssl",
        "s": "uchicago",
        "n": "社会部门领导力与非营利管理硕士",
        "en": "Social Sector Leadership and Nonprofit Management (SSL)",
        "deg": "AM",
        "lvl": "m", "stem": 0,
        "dur": "1 年全日制（也有 part-time 选项）",
        "ddl": "待补（通常 12 月/1 月）",
        "lang": "TOEFL/IELTS 待补",
        "test": {"cls": "待补（录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/uchicago-social-sector-leadership.html",
        "fields": ["Nonprofit Finance", "Nonprofit Operations & Management", "Measuring and Monitoring Impact"],
        "school": "芝加哥大学",
        "official": "https://crownschool.uchicago.edu/about/school-glance",
        "note": "Crown Family School of Social Work, Policy, and Practice；面向 3-5 年经验的 early-to-mid career professionals；组织管理/治理/分析技能；可与 AM/SW 或 MPP 联合学位。",
    },
    {
        "id": "nyu-hcm",
        "s": "nyu",
        "n": "人力资本管理硕士",
        "en": "Human Capital Management (MS)",
        "deg": "MS",
        "lvl": "m", "stem": 0,
        "dur": "1 年全日制（30 学分；也有 5 年 part-time）",
        "ddl": "滚动录取（Fall/Spring 入学）",
        "lang": "TOEFL/IELTS 待补",
        "test": {"cls": "待补（录取分布，非最低门槛）"},
        "tui": "待补",
        "url": "details/nyu-human-capital-management-ms.html",
        "fields": ["Core: Foundations of HCM", "Quantitative Methods and Metrics",
                   "HR Analytics", "Organizational Behavior", "Capstone"],
        "school": "纽约大学",
        "official": "https://www.sps.nyu.edu/homepage/academics/masters-degrees/ms-in-human-capital-management.html",
        "note": "SPS 学院；SHRM-aligned；30 学分；含 5 天 immersion 课程；capstone 可选商业模拟/应用项目/论文；也有 MS/MS 双学位（HCM + Human Capital Analytics and Technology，STEM）。",
    },
    {
        "id": "gatech-mseem",
        "s": "gatech",
        "n": "可持续能源与环境管理硕士",
        "en": "Sustainable Energy and Environmental Management (MSEEM)",
        "deg": "MSEEM",
        "lvl": "m", "stem": 0,
        "dur": "1 年全日制（30 学分；也有 part-time 2 年）",
        "ddl": "优先 2 月 15 日 / 最终 3 月 15 日（Fall 入学）",
        "lang": "TOEFL/IELTS 待补（按 Georgia Tech 研究生院标准）",
        "test": {"cls": "GRE general required（录取分布，非最低门槛）"},
        "tui": "申请费 $75（国际生 $85）",
        "url": "details/gatech-sustainable-energy-and-environmental-management-ms.html",
        "fields": ["Energy Policy & Markets", "Climate Policy", "Environmental Law",
                   "Utility Regulation", "GIS for Environmental Analysis", "Cost-Benefit Analysis"],
        "school": "佐治亚理工学院",
        "official": "https://spp.gatech.edu/masters/mseem",
        "note": "School of Public Policy 跨学科项目；课程来自公共政策/商学院/ISyE/城市规划/土木/经济；含 2 门定量课 + 3 门 SEEM 课 + 1 门政策管理课；毕业生去向政府/NGO/私营部门可持续能源与环境领域。",
    },
]

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)

# PROGRAMS 追加
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)} 条")

# VD 追加
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)")
