#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第一百四十四轮：批量落库 5 条半核验详情页（AI教育/医疗信息/IT管理/数学/化学 方向）"""

import os, re, json

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

NEW_PROGRAMS = [
    {
        "id": "cmu-le-ms",
        "s": "cmu",
        "n": "学习工程硕士",
        "en": "Master of Science in Learning Engineering (MSLE)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（CMU 工程学院标准）"},
        "tui": "待补（CMU 研究生学费）",
        "url": "details/cmu-le-ms.html",
        "official_url": "https://www.cmu.edu/engage/academics/degrees/learning-engineering.html",
        "card_fields": {
            "学院": "CMU 迪特里希人文与社会科学学院 + 软件工程学院联合",
            "方向": "学习科学、教育技术、AI 教育、课程设计、教育数据挖掘",
            "学分": "待补（36–48 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；跨学科项目（教育+CS+认知科学）；偏教育科技就业方向；适合教育学/CS/心理背景"
        }
    },
    {
        "id": "dartmouth-mi-ms",
        "s": "dartmouth",
        "n": "医疗信息学硕士",
        "en": "Master of Science in Medical Informatics (MSMI)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Required（Geisel 医学院标准）"},
        "tui": "待补（Dartmouth 研究生学费）",
        "url": "details/dartmouth-mi-ms.html",
        "official_url": "https://geiselmed.dartmouth.edu/education/graduate-programs/medical-informatics/",
        "card_fields": {
            "学院": "Geisel 医学院 + 工程学院联合",
            "方向": "健康信息学、医学数据科学、临床决策支持、医疗 AI、电子病历系统",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；保留方向（医疗信息）；跨医学与 CS；适合医学/CS/信息背景"
        }
    },
    {
        "id": "uva-mit-ms",
        "s": "uva",
        "n": "信息技术管理硕士",
        "en": "Master of Science in Management of Information Technology (MS-MIT)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GMAT/GRE Optional（McIntire 商学院标准）"},
        "tui": "待补（UVA McIntire 商学院学费）",
        "url": "details/uva-mit-ms.html",
        "official_url": "https://comm.virginia.edu/graduate/ms-in-management-of-information-technology",
        "card_fields": {
            "学院": "McIntire 商学院",
            "方向": "IT 战略、数字转型、产品管理、数据分析、信息安全管理",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；商学院下的技术管理项目；偏管理咨询/IT 战略方向；适合工科/商科背景"
        }
    },
    {
        "id": "emory-math-ms",
        "s": "emory",
        "n": "数学硕士",
        "en": "Master of Science in Mathematics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Required（数学与统计系标准）"},
        "tui": "待补（Emory Laney 研究生院学费）",
        "url": "details/emory-math-ms.html",
        "official_url": "https://math.emory.edu/graduate-program/index.html",
        "card_fields": {
            "学院": "Emory College 数学与统计系",
            "方向": "纯数学、应用数学、计算数学、概率统计、数学物理",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏研究型，可衔接 PhD；数学/物理/CS 背景优先"
        }
    },
    {
        "id": "dartmouth-chem-ms",
        "s": "dartmouth",
        "n": "化学硕士",
        "en": "Master of Science in Chemistry",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Required（化学系标准）"},
        "tui": "待补（Dartmouth 研究生院学费）",
        "url": "details/dartmouth-chem-ms.html",
        "official_url": "https://chemistry.dartmouth.edu/graduate-program",
        "card_fields": {
            "学院": "艺术与科学学院化学系",
            "方向": "有机化学、无机化学、物理化学、分析化学、生物化学",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；注意：部分文理学院化学系为 PhD-only，terminal MS 名额极少，需系站确认是否招收外部 terminal MS"
        }
    },
]

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

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

    # 追加 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:]

    # 追加 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

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

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