# -*- coding: utf-8 -*-
"""第183轮批量落库 5 条全日制硕士：UCSD CSME / UCSD CSS / UNC STANDS / Dartmouth Med Info / USC Public Health DS"""
import re, os, sys
sys.stdout.reconfigure(encoding='utf-8')

BASE = r"D:\work buddy\2026-11-05-14-15-52"
IDX = os.path.join(BASE, "index_main.html")

with open(IDX, "r", encoding="utf-8") as f:
    html = f.read()

# ============ 5 条项目数据 ============
projects = [
    {
        "id": "ucsd-csme-ms",
        "s": "ucsd",
        "n": "计算科学、数学与工程理学硕士",
        "en": "MS in Computational Science, Mathematics and Engineering (CSME)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 年（4-5 个 quarter）",
        "ddl": "Fall：12 月 15 日（待补精确年份）",
        "lang": "TOEFL / IELTS（待补精确分数线）",
        "test": "GRE not required（待补官网确认）",
        "tui": "待补（self-supporting 项目）",
        "url": "details/ucsd-csme-ms.html",
        "school_cn": "加州大学圣地亚哥分校",
        "school_en": "UC San Diego",
        "college": "Physical Sciences × Jacobs School of Engineering",
        "website": "https://csme.ucsd.edu/csme-ms/index.html",
        "overview": "校园跨学科独立 MS 项目，由物理科学部与雅各布斯工程学院联合发起，面向希望在计算科学领域接受硕士级专业训练但不打算攻读博士学位的科学家和工程师。核心课程涵盖数值方法、数据结构与算法、偏微分方程数值解等，强调理论基础与实际计算能力结合。毕业生受工业界和政府机构青睐。",
        "req": "Bachelor's degree in a related quantitative field；基础能力要求：数值方法（MATH 174/274 或 MAE 290A）、数据结构与算法（CSE 100/101），可通过先修课程或入学后考试豁免；GPA 3.0+（待补官网确认）",
        "curriculum": "38 required units：基础能力 8 units（数值方法 + 数据结构）；核心课程 16 units（数值偏微分方程、线性代数、科学计算等）；研究/研讨 6 units；选修 8 units；需通过三门 Qualifying Exams",
        "deadline": "Fall admission：12 月 15 日（具体年份待补）",
        "funding": "待补（MS 为 self-supporting，funding 机会有限）",
        "career": "工业界计算科学家、政府科研机构、数据分析、工程仿真；可申请参与院系 PhD 项目继续深造"
    },
    {
        "id": "ucsd-css-ms",
        "s": "ucsd",
        "n": "计算社会科学理学硕士",
        "en": "MS in Computational Social Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1 年（Summer + Fall + Winter + Spring，全日制）",
        "ddl": "Fall：待补（通常 12 月-1 月）",
        "lang": "TOEFL / IELTS（待补精确分数线）",
        "test": "GRE not required（待补官网确认）",
        "tui": "待补（self-supporting 项目）",
        "url": "details/ucsd-css-ms.html",
        "school_cn": "加州大学圣地亚哥分校",
        "school_en": "UC San Diego",
        "college": "School of Social Sciences",
        "website": "https://css.ucsd.edu/masters/",
        "overview": "全日制 1 年制跨学科硕士，由社会科学学院主办，行政上隶属政治科学系。融合社会科学形式化模型与大规模自然数据采集、结构化和分析技术，培养学生运用因果推断、社会网络分析、自然语言处理、机器学习等方法解决社会问题的能力。Summer Bootcamp 提供数学、编程、分析基础。",
        "req": "Bachelor's degree；GPA typically 3.0+；建议先修统计或形式逻辑课程；无需正式数学/编程先修课（Bootcamp 补基础）；2 封推荐信；1000 字个人陈述；简历",
        "curriculum": "55 units（14 门课）：Summer Bootcamp 16 units（CSS 201S 导论 + CSS 202S 技术 Bootcamp）；核心课程 27 units（含 10 units Capstone）；选修 12 units（可从经济、GIS、视觉计算等领域选修）",
        "deadline": "Fall admission：待补",
        "funding": "待补（self-supporting，funding 机会有限）",
        "career": "公共政策分析、教育、非营利组织、数据科学家、市场研究；可继续攻读 PhD"
    },
    {
        "id": "unc-stands-ms",
        "s": "unc",
        "n": "统计、分析与数据科学理学硕士",
        "en": "MS in Statistics, Analytics, and Data Science (STANDS)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "3-4 个学期（全日制）",
        "ddl": "Fall：12 月 15 日",
        "lang": "TOEFL / IELTS / Duolingo（2 年内有效，待补精确分数线）",
        "test": "GRE not required",
        "tui": "待补",
        "url": "details/unc-stands-ms.html",
        "school_cn": "北卡罗来纳大学教堂山分校",
        "school_en": "UNC-Chapel Hill",
        "college": "Department of Statistics and Operations Research",
        "website": "https://stor.unc.edu/graduate-program/",
        "overview": "STOR 系开设的全日制 STEM 硕士项目，专注于高级定量思维训练，培养数据科学与分析领域专业人才或为进一步研究生学习做准备。核心课程涵盖概率、数理统计、机器学习、优化、随机建模、数据科学等方向。无在线课程，全部在校面授。",
        "req": "Bachelor's degree；扎实的技术准备背景（数学、统计、CS 或相关定量专业）；3 封推荐信（来自相关课程教授）；GRE not required；国际生需 TOEFL/IELTS/Duolingo",
        "curriculum": "30 credit hours + Master's Project；核心课程 5 门（从 8 门中选：数据科学、机器学习、应用统计、优化、随机建模、理论统计、概率、模拟分析）；选修课程；最多可转 6 学分",
        "deadline": "Fall admission：12 月 15 日（春季仅特殊情况考虑）",
        "funding": "待补",
        "career": "数据科学家、统计分析师、量化分析师、运筹分析师；可继续攻读 PhD"
    },
    {
        "id": "dartmouth-medinfo-ms",
        "s": "dartmouth",
        "n": "医学信息学理学硕士",
        "en": "MS in Medical Informatics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "12 个月（全日制）",
        "ddl": "待补（SOPHAS 申请，通常 12 月-1 月）",
        "lang": "TOEFL / IELTS（待补精确分数线）",
        "test": "待补",
        "tui": "待补",
        "url": "details/dartmouth-medinfo-ms.html",
        "school_cn": "达特茅斯学院",
        "school_en": "Dartmouth College",
        "college": "Geisel School of Medicine · The Dartmouth Institute",
        "website": "https://healthsciences.dartmouth.edu/education/degree-programs/master-science-medical-informatics/",
        "overview": "Geisel 医学院开设的全日制跨学科硕士，融合信息科学、数据科学、生物统计与医疗系统知识，培养医疗信息学专业人才。课程涵盖数据可视化、数据清洗、应用生物统计、流行病学、机器学习、电子健康记录（EHR）分析、决策分析等。2 单元 Capstone 真实项目。",
        "req": "Bachelor's degree（无特定本科专业要求）；建议先修微积分、计算机编程、统计学；无需工作经验；SOPHAS 申请；适合医疗、CS、工程、数据科学等背景学生",
        "curriculum": "10.5 units 核心课程 + 4.5 units 选修：数据可视化、数据清洗、应用生物统计、流行病学基础、健康信息学、决策与成本效果分析、高级健康方法等；2 单元 Capstone 真实项目；QBS 700 科研伦理（必修不计学分）",
        "deadline": "待补（SOPHAS 申请）",
        "funding": "待补",
        "career": "生物医学研究、政府机构、医疗信息产业、非营利组织；可继续攻读 PhD"
    },
    {
        "id": "usc-phds-ms",
        "s": "usc",
        "n": "公共卫生数据科学理学硕士",
        "en": "MS in Public Health Data Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "待补（通常 1.5-2 年）",
        "ddl": "待补",
        "lang": "TOEFL / IELTS（待补精确分数线）",
        "test": "GRE not required（待补官网确认）",
        "tui": "待补",
        "url": "details/usc-phds-ms.html",
        "school_cn": "南加州大学",
        "school_en": "University of Southern California",
        "college": "Price School of Public Policy · Department of Population and Public Health Sciences",
        "website": "https://pphs.usc.edu/academics/degree-programs/ms-in-public-health-data-science/",
        "overview": "Population and Public Health Sciences 系开设的 terminal 硕士项目，融合生物统计、流行病学与计算方法，培养专注于公共卫生数据的数据分析人才。课程涵盖数据科学基础、健康数据采集与管理、统计方法、机器学习在健康数据中的应用、结果沟通等。",
        "req": "Bachelor's degree in mathematics, statistics, biostatistics, computer science or related field；要求中级统计知识 + 至少一门编程语言熟悉；建议先修微积分、线性代数；简历、个人陈述、推荐信",
        "curriculum": "32 units：核心课程 16 units（数据科学基础、流行病学、高级统计计算、健康数据科学实践等）；选修课程；3 units Practicum（健康数据科学实习）",
        "deadline": "待补",
        "funding": "待补",
        "career": "公共卫生数据科学家、生物统计师、医疗数据分析、政策研究；可继续攻读 PhD in Biostatistics / Statistics / DS / CS"
    }
]

# ============ 详情页 HTML 模板 ============
def make_detail(p):
    stem_label = "STEM" if p["stem"] else "Non-STEM"
    return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{p['n']} - {p['school_en']}</title>
<style>
* {{ margin:0; padding:0; box-sizing:border-box; }}
body {{ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif; background:#f5f7fa; color:#333; line-height:1.7; }}
.container {{ max-width:960px; margin:0 auto; padding:20px; }}
.header {{ background:linear-gradient(135deg,#1a3a6b 0%,#2d5a9e 100%); color:#fff; padding:30px; border-radius:12px; margin-bottom:20px; }}
.header h1 {{ font-size:24px; margin-bottom:8px; }}
.header .school {{ font-size:16px; opacity:0.9; }}
.header .college {{ font-size:14px; opacity:0.75; margin-top:4px; }}
.badge {{ display:inline-block; background:rgba(255,255,255,0.2); padding:3px 12px; border-radius:20px; font-size:13px; margin-right:8px; margin-top:8px; }}
.cards {{ display:grid; grid-template-columns:1fr 1fr; gap:16px; }}
.card {{ background:#fff; border-radius:10px; padding:20px; box-shadow:0 2px 8px rgba(0,0,0,0.06); }}
.card h3 {{ font-size:16px; color:#1a3a6b; margin-bottom:12px; padding-bottom:8px; border-bottom:2px solid #e8eef5; }}
.card p, .card li {{ font-size:14px; color:#555; }}
.card ul {{ padding-left:20px; }}
.full {{ grid-column:1/-1; }}
.website {{ display:inline-block; background:#1a3a6b; color:#fff; padding:8px 16px; border-radius:6px; text-decoration:none; font-size:14px; margin-top:10px; }}
.website:hover {{ background:#2d5a9e; }}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>{p['n']}</h1>
    <div class="school">{p['school_en']} · {p['school_cn']}</div>
    <div class="college">{p['college']}</div>
    <div>
      <span class="badge">{p['deg']}</span>
      <span class="badge">{stem_label}</span>
      <span class="badge">{p['dur']}</span>
    </div>
  </div>
  <div class="cards">
    <div class="card full">
      <h3>项目概述</h3>
      <p>{p['overview']}</p>
      <a class="website" href="{p['website']}" target="_blank">官网项目页 →</a>
    </div>
    <div class="card">
      <h3>申请要求</h3>
      <p>{p['req']}</p>
    </div>
    <div class="card">
      <h3>课程设置</h3>
      <p>{p['curriculum']}</p>
    </div>
    <div class="card">
      <h3>截止日期</h3>
      <p>{p['deadline']}</p>
    </div>
    <div class="card">
      <h3>语言要求</h3>
      <p>{p['lang']}</p>
    </div>
    <div class="card">
      <h3>标化要求</h3>
      <p>{p['test']}</p>
    </div>
    <div class="card">
      <h3>学费与资助</h3>
      <p>{p['tui']}</p>
      <p>{p['funding']}</p>
    </div>
    <div class="card full">
      <h3>职业发展</h3>
      <p>{p['career']}</p>
    </div>
  </div>
</div>
</body>
</html>"""

# ============ 写入详情页 ============
for p in projects:
    path = os.path.join(BASE, p["url"])
    with open(path, "w", encoding="utf-8") as f:
        f.write(make_detail(p))
    print(f"Wrote: {p['url']}")

# ============ 追加 PROGRAMS ============
# 找到 PROGRAMS 数组结束位置（括号深度匹配）
prog_start = html.find("const PROGRAMS=[")
if prog_start == -1:
    prog_start = html.find("PROGRAMS=[")
# 从 [ 后开始扫描
bracket_start = html.find("[", prog_start)
depth = 1
i = bracket_start + 1
while i < len(html) and depth > 0:
    if html[i] == "[":
        depth += 1
    elif html[i] == "]":
        depth -= 1
    i += 1
prog_end = i  # 指向 ] 后

# 构建新条目
new_entries = []
for p in projects:
    entry = f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",deg:"{p["deg"]}",lvl:"{p["lvl"]}",stem:{p["stem"]},dur:"{p["dur"]}",ddl:"{p["ddl"]}",lang:"{p["lang"]}",test:{{cls:"{p["test"]}"}},tui:"{p["tui"]}",url:"{p["url"]}"}}'
    new_entries.append(entry)

# 检查插入位置前一个字符是否是 ]（如果数组为空）或 }（如果有元素）
# 需要确保前一个条目后有逗号
insert_pos = prog_end - 1  # 指向 ]
before = html[insert_pos-1]
if before == "]":
    # 空数组，直接在 ] 前插入
    new_block = ",".join(new_entries)
    html = html[:insert_pos] + new_block + html[insert_pos:]
else:
    # 非空数组，检查前一个条目结尾是否有逗号
    # 往前找，跳过空白
    j = insert_pos - 1
    while j >= 0 and html[j] in " \t\n\r":
        j -= 1
    if html[j] == "}":
        # 前一个条目结尾没有逗号，加上
        new_block = "," + ",".join(new_entries)
        html = html[:insert_pos] + new_block + html[insert_pos:]
    else:
        # 已经有逗号了
        new_block = ",".join(new_entries)
        html = html[:insert_pos] + new_block + html[insert_pos:]

print(f"Appended {len(projects)} PROGRAMS entries")

# ============ 追加 VD ============
vd_start = html.find("const VERIFIED_DETAILS=new Set(")
if vd_start == -1:
    vd_start = html.find("VERIFIED_DETAILS=new Set(")
paren_start = html.find("(", vd_start)
depth = 1
i = paren_start + 1
while i < len(html) and depth > 0:
    if html[i] == "(":
        depth += 1
    elif html[i] == ")":
        depth -= 1
    i += 1
vd_end = i  # 指向 ) 后

# 找到 [ 位置（Set( 后面的数组）
bracket_start = html.find("[", paren_start)
# 从 [ 后扫描找 ]
depth2 = 1
j = bracket_start + 1
while j < len(html) and depth2 > 0:
    if html[j] == "[":
        depth2 += 1
    elif html[j] == "]":
        depth2 -= 1
    j += 1
vd_arr_end = j  # 指向 ] 后

# 构建新 VD 条目
new_vd = [f'"{p["url"]}"' for p in projects]

# 检查数组最后一个元素后是否有逗号或引号
k = vd_arr_end - 2  # 指向 ] 前一个字符
while k >= 0 and html[k] in " \t\n\r":
    k -= 1
if html[k] == '"':
    # 最后一个元素是引号结尾，加逗号
    vd_block = "," + ",".join(new_vd)
    html = html[:vd_arr_end-1] + vd_block + html[vd_arr_end-1:]
else:
    vd_block = ",".join(new_vd)
    html = html[:vd_arr_end-1] + vd_block + html[vd_arr_end-1:]

print(f"Appended {len(projects)} VD entries")

# ============ 写回 ============
with open(IDX, "w", encoding="utf-8") as f:
    f.write(html)

print(f"Done. File size: {len(html)}")
