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

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": "ucla-applied-stats-ds-ms",
        "s": "ucla",
        "n": "应用统计与数据科学硕士",
        "en": "Master of Applied Statistics and Data Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制，36 学分）",
        "ddl": "2026-12-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Required（统计系标准）"},
        "tui": "待补（UCLA 研究生院费率）",
        "url": "details/ucla-applied-stats-ds-ms.html",
        "official_url": "https://statistics.ucla.edu/graduate-programs/master-of-applied-statistics-and-data-science",
        "card_fields": {
            "学院": "文理学院统计系",
            "方向": "统计推断、机器学习、数据科学、生物统计、统计计算",
            "学分": "36 学分",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏应用统计与数据科学；可衔接 PhD；数学/统计/CS 背景优先"
        }
    },
    {
        "id": "cornell-aem-mps",
        "s": "cornell",
        "n": "应用经济学与管理硕士",
        "en": "MPS in Applied Economics and Management",
        "deg": "MPS",
        "lvl": "m",
        "stem": 1,
        "dur": "1 年（在校全日制，康奈尔约翰逊商学院）",
        "ddl": "2027-01-15（Round 2）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GMAT/GRE 接受（约翰逊商学院标准）"},
        "tui": "待补（约翰逊商学院费率）",
        "url": "details/cornell-aem-mps.html",
        "official_url": "https://www.johnson.cornell.edu/programs/masters-programs/mps-applied-economics-management/",
        "card_fields": {
            "学院": "SC Johnson 商学院",
            "方向": "金融、市场营销、策略管理、农业经济、资源经济",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；1 年制专业硕士；偏应用就业导向；含实习项目"
        }
    },
    {
        "id": "notre-cse-mscse",
        "s": "notre",
        "n": "计算机科学与工程硕士",
        "en": "MSCSE in Computer Science and Engineering",
        "deg": "MSCSE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5–2 年（在校全日制，30 学分）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（工程学院标准）"},
        "tui": "待补（Notre Dame 工程学院费率）",
        "url": "details/notre-cse-mscse.html",
        "official_url": "https://cse.nd.edu/graduate-programs/graduate-programs/",
        "card_fields": {
            "学院": "工程学院计算机科学与工程系",
            "方向": "人工智能、机器学习、系统、理论、生物计算",
            "学分": "30 学分",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；研究型硕士，可衔接 PhD；Notre Dame 工程学院跨学科培养"
        }
    },
    {
        "id": "unc-bmi-ms",
        "s": "unc",
        "n": "生物医学与健康信息学硕士",
        "en": "MS in Biomedical and Health Informatics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制）",
        "ddl": "2026-12-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（医学院信息学院标准）"},
        "tui": "待补（UNC 医学院费率）",
        "url": "details/unc-bmi-ms.html",
        "official_url": "https://www.med.unc.edu/healthsciences/biomedical-and-health-informatics/",
        "card_fields": {
            "学院": "医学院信息学院 + Gillings 公卫学院联合",
            "方向": "临床信息学、基因组学、健康数据科学、医学 NLP",
            "学分": "待补（30+ 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；跨医学与信息学院；适合 CS/生物/医学背景学生"
        }
    },
    {
        "id": "jhu-gis-ms",
        "s": "jhu",
        "n": "地理信息系统硕士",
        "en": "MS in Geographic Information Systems",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1–2 年（在校全日制）",
        "ddl": "2027-01-15（秋季入学优先）",
        "lang": "TOEFL iBT 100+ / IELTS 7.0",
        "test": {"cls": "GRE Optional（KSAS AAP 标准）"},
        "tui": "待补（KSAS AAP 费率）",
        "url": "details/jhu-gis-ms.html",
        "official_url": "https://e-catalogue.jhu.edu/arts-sciences/advanced-academic-programs/programs/geographic-information-systems-master-science/",
        "card_fields": {
            "学院": "KSAS 文理学院高级学术项目（AAP）",
            "方向": "空间分析、地理空间数据科学、遥感、GIS 软件开发",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏应用 GIS 与空间数据科学；适合地理/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()
