#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""第一百四十六轮：批量落库 5 条半核验详情页（UCSD 数据工程/生医工/控制机电/电力能源/计算工程 方向）"""

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": "ucsd-dse-ms",
        "s": "ucsd",
        "n": "数据科学与工程硕士",
        "en": "M.S. in Data Science and Engineering",
        "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（Jacobs 工程学院标准）"},
        "tui": "待补（UCSD 研究生院学费）",
        "url": "details/ucsd-dse-ms.html",
        "official_url": "https://dse.ucsd.edu/graduate-programs/degree-programs/ms-data-science-engineering",
        "card_fields": {
            "学院": "Jacobs 工程学院计算机科学与工程系",
            "方向": "大数据系统、机器学习、数据挖掘、分布式计算、数据可视化",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；DS+工程交叉；偏工业界数据工程；适合 CS/统计/数学背景"
        }
    },
    {
        "id": "ucsd-bioe-med-ms",
        "s": "ucsd",
        "n": "生物工程硕士（医学方向）",
        "en": "M.S. in Bioengineering with a Medical Specialization",
        "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（Jacobs 工程学院标准）"},
        "tui": "待补（UCSD 研究生院学费）",
        "url": "details/ucsd-bioe-med-ms.html",
        "official_url": "https://bioengineering.ucsd.edu/graduate-programs/degree-programs/ms-medical-specialization",
        "card_fields": {
            "学院": "Jacobs 工程学院生物工程系",
            "方向": "医学影像、生物材料、组织工程、医疗器械、转化医学",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；保留方向（BME）；偏医学转化；适合生物/工程/医学背景"
        }
    },
    {
        "id": "ucsd-es-cm-ms",
        "s": "ucsd",
        "n": "工程科学硕士（控制与机电方向）",
        "en": "M.S. in Engineering Sciences with Specialization in Controls and Mechatronics",
        "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（Jacobs 工程学院标准）"},
        "tui": "待补（UCSD 研究生院学费）",
        "url": "details/ucsd-es-cm-ms.html",
        "official_url": "https://mae.ucsd.edu/graduate-programs/degree-programs/ms-controls-mechatronics",
        "card_fields": {
            "学院": "Jacobs 工程学院机械与航空工程系",
            "方向": "控制系统、机器人、机电一体化、自动驾驶、工业自动化",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏机械与控制交叉；适合 ME/EE/自动化背景"
        }
    },
    {
        "id": "ucsd-es-pe-ms",
        "s": "ucsd",
        "n": "工程科学硕士（电力与能源系统方向）",
        "en": "M.S. in Engineering Sciences with Specialization in Power and Energy Systems",
        "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（Jacobs 工程学院标准）"},
        "tui": "待补（UCSD 研究生院学费）",
        "url": "details/ucsd-es-pe-ms.html",
        "official_url": "https://mae.ucsd.edu/graduate-programs/degree-programs/ms-power-energy-systems",
        "card_fields": {
            "学院": "Jacobs 工程学院机械与航空工程系",
            "方向": "电力系统、新能源、储能、智能电网、电动汽车",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏能源与电力；适合 EE/ME/能源背景"
        }
    },
    {
        "id": "ucsd-es-ce-ms",
        "s": "ucsd",
        "n": "工程科学硕士（计算工程与科学方向）",
        "en": "M.S. in Engineering Sciences with Specialization in Computational Engineering and Science",
        "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（Jacobs 工程学院标准）"},
        "tui": "待补（UCSD 研究生院学费）",
        "url": "details/ucsd-es-ce-ms.html",
        "official_url": "https://mae.ucsd.edu/graduate-programs/degree-programs/ms-computational-engineering-science",
        "card_fields": {
            "学院": "Jacobs 工程学院机械与航空工程系",
            "方向": "计算力学、数值模拟、高性能计算、CFD、有限元分析",
            "学分": "待补（36 学分）",
            "课程": "待补（系站不可达）",
            "材料": "待补（系站不可达）",
            "备注": "STEM 认证；偏工程计算与仿真；适合 ME/CE/CS 背景"
        }
    },
]

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