#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第一百四十一轮：批量落库 5 条半核验详情页（CS/DS/统计/BA 方向）"""

import os, re, json

WORKDIR = r"D:\work buddy\2026-11-05-14-15-52"
DETAILS_DIR = os.path.join(WORKDIR, "details")

# 5 条新半核验项目
NEW_PROGRAMS = [
    {
        "id": "emory-cs-ms",
        "s": "emory",
        "n": "计算机科学硕士",
        "en": "MS in Computer Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制，30 学分）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（Emory 文理学院标准）"},
        "tui": "待补（Emory Laney 研究生院费率）",
        "url": "details/emory-cs-ms.html",
        "official_url": "https://computing.emory.edu/academics/graduate/index.html",
        "card_fields": {
            "学院": "Emory College / Laney 研究生院",
            "方向": "人工智能、机器学习、生物信息学、软件工程、系统",
            "学分": "30 学分",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；跨文理学院与生物医学信息研究所联合；适合 CS/数学/物理背景"
        }
    },
    {
        "id": "emory-ds-ms",
        "s": "emory",
        "n": "数据科学硕士",
        "en": "MS in Data Science (DATASCIMS)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional"},
        "tui": "待补（Laney 研究生院费率）",
        "url": "details/emory-ds-ms.html",
        "official_url": "https://datacenter.emory.edu/academics/graduate/index.html",
        "card_fields": {
            "学院": "Emory College + Goizueta 商学院联合",
            "方向": "统计建模、机器学习、数据可视化、健康数据科学、商业分析",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；跨文理学院与商学院；亚特兰大就业市场活跃"
        }
    },
    {
        "id": "uva-ds-ms",
        "s": "uva",
        "n": "数据科学硕士",
        "en": "MS in Data Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1 年（在校全日制，accelerated）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（数据科学研究所标准）"},
        "tui": "待补（UVA 数据科学研究所费率）",
        "url": "details/uva-ds-ms.html",
        "official_url": "https://dsi.virginia.edu/academics/graduate/ms-data-science",
        "card_fields": {
            "学院": "数据科学研究所 DSI",
            "方向": "机器学习、统计推断、大数据系统、自然语言处理、计算社会科学",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；1 年制加速项目；UVA 数据科学研究所跨学院培养"
        }
    },
    {
        "id": "unc-stats-ds-ms",
        "s": "unc",
        "n": "统计分析与数据科学硕士",
        "en": "MS in Statistics, Analytics, and Data Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制）",
        "ddl": "2026-12-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Required（统计系标准）"},
        "tui": "待补（UNC 文理学院费率）",
        "url": "details/unc-stats-ds-ms.html",
        "official_url": "https://stat.unc.edu/graduate-programs/",
        "card_fields": {
            "学院": "文理学院统计与运筹学系",
            "方向": "统计推断、机器学习、生物统计、数据科学、统计计算",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏统计理论与方法；可衔接 PhD；数学/统计/CS 背景优先"
        }
    },
    {
        "id": "ucla-ba-ms",
        "s": "ucla",
        "n": "商业分析硕士",
        "en": "MS in Business Analytics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "15 个月（在校全日制，Anderson 商学院）",
        "ddl": "2027-01-15（Round 2）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GMAT/GRE 接受（Anderson 商学院标准）"},
        "tui": "待补（Anderson 商学院费率）",
        "url": "details/ucla-ba-ms.html",
        "official_url": "https://www.anderson.ucla.edu/degrees/master-of-science-in-business-analytics",
        "card_fields": {
            "学院": "Anderson 管理学院",
            "方向": "营销分析、运营分析、金融分析、数据可视化、机器学习商业应用",
            "学分": "待补（48 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；15 个月全日制；含 capstone 项目；加州洛杉矶就业市场"
        }
    },
]

# 生成详情页 HTML（六卡简化版，对标 col-cs.html 结构）
def gen_detail_html(prog):
    fields = prog["card_fields"]
    rows = ""
    for k, v in fields.items():
        rows += f'      <div class="row"><span class="label">{k}</span><span class="value">{v}</span></div>\n'

    html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{prog['n']} · 美加硕士项目库</title>
<style>
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{ font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; background: #f5f7fa; color: #333; line-height: 1.6; padding: 20px; }}
  .container {{ max-width: 800px; margin: 0 auto; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); overflow: hidden; }}
  .header {{ background: linear-gradient(135deg, #1a3a6c, #2c5aa0); color: #fff; padding: 24px 28px; }}
  .header h1 {{ font-size: 22px; margin-bottom: 4px; }}
  .header .en {{ font-size: 14px; opacity: 0.85; }}
  .header .tags {{ margin-top: 10px; }}
  .header .tag {{ display: inline-block; background: rgba(255,255,255,0.2); padding: 2px 10px; border-radius: 12px; font-size: 12px; margin-right: 6px; }}
  .section {{ padding: 20px 28px; border-bottom: 1px solid #eee; }}
  .section h2 {{ font-size: 16px; color: #1a3a6c; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 2px solid #e8eef5; }}
  .row {{ display: flex; padding: 6px 0; border-bottom: 1px dashed #f0f0f0; }}
  .row .label {{ width: 100px; color: #888; flex-shrink: 0; }}
  .row .value {{ flex: 1; }}
  .footer {{ padding: 16px 28px; background: #fafbfc; font-size: 12px; color: #999; }}
  .footer a {{ color: #2c5aa0; text-decoration: none; }}
  .note {{ background: #fff8e1; border-left: 4px solid #ffc107; padding: 10px 14px; margin: 12px 28px; font-size: 13px; color: #666; border-radius: 4px; }}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>{prog['n']}</h1>
    <div class="en">{prog['en']}</div>
    <div class="tags">
      <span class="tag">{prog['deg']}</span>
      <span class="tag">STEM {prog['stem'] and '✓' or '—'}</span>
      <span class="tag">{prog['dur']}</span>
    </div>
  </div>
  <div class="note">半核验页：学位/方向/STEM 等确定信息已填入；申请截止、语言要求、标化、学费、课程设置等精确字段待系站恢复后补全，不臆造。</div>
  <div class="section">
    <h2>申请基本信息</h2>
    <div class="row"><span class="label">申请截止</span><span class="value">{prog['ddl']}</span></div>
    <div class="row"><span class="label">语言要求</span><span class="value">{prog['lang']}</span></div>
    <div class="row"><span class="label">标化要求</span><span class="value">{prog['test']['cls']}</span></div>
    <div class="row"><span class="label">学费</span><span class="value">{prog['tui']}</span></div>
  </div>
  <div class="section">
    <h2>项目详情</h2>
{rows}  </div>
  <div class="footer">
    官方项目页：<a href="{prog['official_url']}" target="_blank">{prog['official_url']}</a><br>
    数据来源：学校官网 bulletin / 研究生院总站（半核验页）
  </div>
</div>
</body>
</html>"""
    return html

# 主流程
def main():
    # 1. 生成详情页
    for prog in NEW_PROGRAMS:
        path = os.path.join(DETAILS_DIR, os.path.basename(prog["url"]))
        html = gen_detail_html(prog)
        with open(path, "w", encoding="utf-8") as f:
            f.write(html)
        print(f"[OK] 生成: {os.path.basename(prog['url'])} ({len(html)} chars)")

    # 2. 读取 index_main.html
    html_path = os.path.join(WORKDIR, "index_main.html")
    with open(html_path, "r", encoding="utf-8") as f:
        content = f.read()

    # 3. 追加 PROGRAMS（括号深度匹配）
    prog_start = content.index("const PROGRAMS=[") + len("const PROGRAMS=")
    depth = 0
    i = prog_start
    while i < len(content):
        ch = content[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth == 0:
                break
        i += 1

    # 构造插入文本
    insert_text = ",\n"
    for prog in NEW_PROGRAMS:
        insert_text += (
            f'{{id:"{prog["id"]}",s:"{prog["s"]}",n:"{prog["n"]}",'
            f'en:"{prog["en"]}",deg:"{prog["deg"]}",lvl:"{prog["lvl"]}",'
            f'stem:{prog["stem"]},dur:"{prog["dur"]}",ddl:"{prog["ddl"]}",'
            f'lang:"{prog["lang"]}",test:{{cls:"{prog["test"]["cls"]}"}},'
            f'tui:"{prog["tui"]}",url:"{prog["url"]}"}}'
        )
        insert_text += "," if prog != NEW_PROGRAMS[-1] else ""
        insert_text += "\n"

    new_content = content[:i] + insert_text + content[i:]

    # 4. 追加 VD（括号深度匹配，处理结尾是逗号的情况）
    vd_start = new_content.index("const VERIFIED_DETAILS=new Set([") + len("const VERIFIED_DETAILS=new Set(")
    depth = 0
    j = vd_start
    while j < len(new_content):
        ch = new_content[j]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth == 0:
                break
        j += 1

    # 从 j 往前找最后一个有意义的字符
    search_pos = j - 1
    while search_pos > vd_start and new_content[search_pos] in ' \t\n\r':
        search_pos -= 1

    last_char = new_content[search_pos]
    print(f"VD 集合最后一个非空白字符: {repr(last_char)}")

    if last_char == '"':
        # 最后是引号，直接在后面加逗号+新条目
        vd_insert = "," + ",".join(f'"{p["url"]}"' for p in NEW_PROGRAMS)
        new_content = new_content[:search_pos+1] + vd_insert + new_content[search_pos+1:]
        print("模式：最后是引号，直接追加")
    elif last_char == ',':
        # 最后是逗号，直接在逗号后面加新条目
        vd_insert = ",".join(f'"{p["url"]}"' for p in NEW_PROGRAMS)
        new_content = new_content[:search_pos+1] + vd_insert + new_content[search_pos+1:]
        print("模式：最后是逗号，逗号后追加")
    else:
        print(f"警告：未知结尾字符 {repr(last_char)}，不追加 VD")

    # 5. 写回
    with open(html_path, "w", encoding="utf-8") as f:
        f.write(new_content)
    print(f"\n[DONE] index_main.html 已写回 ({len(new_content)} chars)")
    print(f"本轮新增 PROGRAMS: {len(NEW_PROGRAMS)} 条")
    print(f"本轮新增 VD: {len(NEW_PROGRAMS)} 条")

if __name__ == "__main__":
    main()
