# -*- coding: utf-8 -*-
"""Dartmouth Degree Finder 目录级生成：剔本科/MBA/MD双学位/在线在职；公卫与基础科学保留。"""
import io, sys, os, json, html, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

BASE = r"D:\work buddy\2026-11-05-14-15-52"
DET = os.path.join(BASE, "details")
TODAY = "2026-11-11"
SCHOOL_CN = "达特茅斯学院"
SCHOOL_EN = "Dartmouth College"
SID = "dartmouth"

# 明确剔除（临床执业/MBA/双学位/在线/在职继教/本科）
DROP = {
 "Business Administration (Master of Business Administration)",
 "Earth Sciences (Bachelor of Arts)",
 "Engineering Sciences (Bachelor of Engineering)",
 "Engineering, Computer Engineering (Master of Engineering)",
 "Health Care Delivery Science (Master of Health Care Delivery Science)",
 "Liberal Studies (Master of Arts in Liberal Studies)",
 "MD-MBA ", "MD-MS Program in Engineering", "MD-PhD",
 "MD-PhD Program in Biomedical Engineering", "Medicine (MD)", "PhD-MBA",
}

# title -> (cn, disc, college, slug, deg)
MAP = {
 "Biochemistry (PhD)": ("生物化学", "sci", "Guarini 研究生院", "biochemistry", "PhD"),
 "Biology (PhD)": ("生物学", "sci", "Guarini 研究生院", "biology", "PhD"),
 "Chemistry (Master of Science)": ("化学", "sci", "Guarini 研究生院", "chemistry-ms", "MS"),
 "Chemistry (PhD)": ("化学", "sci", "Guarini 研究生院", "chemistry-phd", "PhD"),
 "Cognitive Neuroscience (PhD)": ("认知神经科学", "sci", "Guarini 研究生院", "cognitive-neuroscience", "PhD"),
 "Comparative Literature (Master of Arts)": ("比较文学", "art", "Guarini 研究生院", "comparative-literature", "MA"),
 "Computer Science (Master of Science)": ("计算机科学", "cs", "Guarini 研究生院", "computer-science-ms", "MS"),
 "Computer Science (PhD)": ("计算机科学", "cs", "Guarini 研究生院", "computer-science-phd", "PhD"),
 "Digital Musics (Master of Arts)": ("数字音乐", "art", "Guarini 研究生院", "digital-musics", "MA"),
 "Earth Sciences (Master of Science)": ("地球科学", "sci", "Guarini 研究生院", "earth-sciences-ms", "MS"),
 "Earth Sciences (PhD)": ("地球科学", "sci", "Guarini 研究生院", "earth-sciences-phd", "PhD"),
 "Energy Transition (Master of Energy Transition)": ("能源转型", "eng", "Irving 能源与社会学院", "energy-transition", "MET"),
 "Engineering (Master of Engineering)": ("工程（工程硕士）", "eng", "Thayer 工程学院", "engineering-meng", "MEng"),
 "Engineering Management (Master of Engineering Management)": ("工程管理", "eng", "Thayer 工程学院", "engineering-management", "MEM"),
 "Engineering Sciences (Master of Science)": ("工程科学", "eng", "Thayer 工程学院", "engineering-sciences-ms", "MS"),
 "Engineering Sciences (PhD)": ("工程科学", "eng", "Thayer 工程学院", "engineering-sciences-phd", "PhD"),
 "Epidemiology (Master of Science)": ("流行病学", "med", "Geisel 医学院（公卫方向）", "epidemiology", "MS"),
 "Health Administration (Master of Health Administration)": ("医疗管理", "med", "Geisel 医学院（公卫方向）", "health-administration", "MHA"),
 "Health Data Science (Master of Science)": ("健康数据科学", "med", "Geisel 医学院（公卫方向）", "health-data-science", "MS"),
 "Health Policy & Clinical Practice (PhD)": ("健康政策与临床实践", "med", "Geisel 医学院（公卫方向）", "health-policy-clinical-practice", "PhD"),
 "Healthcare Research (Master of Science)": ("医疗研究", "med", "Geisel 医学院（公卫方向）", "healthcare-research", "MS"),
 "Implementation Science (Master of Science)": ("实施科学", "med", "Geisel 医学院（公卫方向）", "implementation-science", "MS"),
 "Mathematics (Master of Arts)": ("数学", "sci", "Guarini 研究生院", "mathematics-ma", "MA"),
 "Mathematics (PhD)": ("数学", "sci", "Guarini 研究生院", "mathematics-phd", "PhD"),
 "Medical Informatics (Master of Science)": ("医疗信息学", "med", "Geisel 医学院（公卫方向）", "medical-informatics", "MS"),
 "Microbiology and Immunology (PhD)": ("微生物学与免疫学", "sci", "Geisel 医学院（基础研究）", "microbiology-immunology", "PhD"),
 "Molecular and Systems Biology (MSB)": ("分子与系统生物学", "sci", "Guarini 研究生院", "molecular-systems-biology", "MSB"),
 "Physics and Astronomy (Master of Science)": ("物理与天文学", "sci", "Guarini 研究生院", "physics-astronomy-ms", "MS"),
 "Physics and Astronomy (PhD)": ("物理与天文学", "sci", "Guarini 研究生院", "physics-astronomy-phd", "PhD"),
 "Psychological and Brain Sciences (PhD)": ("心理与脑科学", "sci", "Guarini 研究生院", "psychological-brain-sciences", "PhD"),
 "Public Health (Master of Public Health)": ("公共卫生", "med", "Geisel 医学院（公卫方向）", "public-health", "MPH"),
 "Quantitative Biomedical Sciences (PhD)": ("定量生物医学", "sci", "Geisel 医学院（基础研究）", "quantitative-biomedical-sciences", "PhD"),
}

raw = json.load(open(os.path.join(BASE, "raw_dartmouth.json"), encoding="utf-8"))
catd, pages, missing, dropped = [], [], [], []

TPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{cn} · {school_cn} · 项目详情 | 美加硕士项目查询系统</title>
<style>
:root{{--navy1:#0b2447;--navy2:#19376d;--navy3:#2b5ba8;--gold:#f0a500;--bg:#f5f7fa;--card:#fff;--line:#e3e8f0;--text:#1f2937;--muted:#6b7280;--green:#1e8449;--blue:#2563eb}}
*{{margin:0;padding:0;box-sizing:border-box}}
body{{font-family:"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;background:var(--bg);color:var(--text);font-size:14px}}
a{{color:var(--blue)}}
.hero{{background:linear-gradient(135deg,var(--navy1) 0%,var(--navy2) 55%,var(--navy3) 100%);color:#fff;padding:24px 30px 20px}}
.hero h1{{font-size:21px}}
.hero .en{{font-size:13px;opacity:.85;margin-top:4px}}
.hero .school{{margin-top:8px;font-size:14px;font-weight:600;color:#ffd77a}}
.badges{{margin-top:12px;display:flex;gap:8px;flex-wrap:wrap}}
.badge{{font-size:12px;border-radius:5px;padding:3px 10px;font-weight:700;background:rgba(240,165,0,.25);color:#ffe1a1}}
.wrap{{max-width:900px;margin:20px auto 60px;padding:0 16px}}
.card{{background:var(--card);border-radius:12px;box-shadow:0 2px 10px rgba(15,35,80,.08);border:1px solid var(--line);padding:20px 24px;margin-bottom:16px}}
.card h2{{font-size:16px;color:var(--navy2);border-left:4px solid var(--gold);padding-left:10px;margin-bottom:14px}}
.pdesc{{font-size:13px;line-height:1.95;color:#263244}}
.links a{{display:inline-block;margin:4px 8px 4px 0;padding:8px 14px;background:var(--navy2);color:#fff;border-radius:8px;font-size:13px;text-decoration:none;font-weight:600}}
.links a:hover{{background:var(--navy3)}}
.note{{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.7}}
.foot{{max-width:900px;margin:0 auto 40px;padding:0 16px}}
.yellow{{background:#fff8e1;border-left:4px solid var(--gold);border-radius:8px;padding:12px 16px;font-size:12px;line-height:1.8}}
.back{{display:inline-block;margin-bottom:14px;color:var(--navy2);text-decoration:none;font-size:13px;font-weight:600}}
</style>
</head>
<body>
<div class="hero">
  <h1>{cn}</h1>
  <div class="en">{en}</div>
  <div class="school">{school_cn} {school_en} · {college}</div>
  <div class="badges"><span class="badge">🎓 {deg}</span></div>
</div>
<div class="wrap">
  <a class="back" href="../index_main.html">← 返回项目库</a>
<div class="card"><h2>培养方案与项目描述（官方项目页）</h2><div class="pdesc">本项目为 Dartmouth College 研究生院官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：Dartmouth Degree Finder / 官方项目页 <a href="{url}" target="_blank">{url}</a>（抓取日期 {TODAY}）。</div></div>
<div class="card"><h2>官方链接</h2><div class="links"><a href="{url}" target="_blank">🔗 项目官方页（申请要求 / 课程 / 费用）</a></div><div class="note">本条目来自学校官方研究生项目目录；逐项核验（截止 / 语言 / 标化 / 学费 / 就业）完成后，本页将升级为完整核验详情页。</div></div>
</div>
<div class="foot">
  <div class="yellow">📋 数据说明：本页名称 / 学院 / 学位均摘自 Dartmouth College 官方页面（抓取日期 {TODAY}，对应 2027 申请季）。申请截止、语言、标化、学费等字段待逐项核验后补充展示，核验前不做估算填充；官网未公布的字段整项不展示。</div>
</div>
</body>
</html>
"""

for item in raw:
    t = item["t"].strip()
    if not re.search(r"PhD|Master|MPH|MHA|MSB|MEng|MEM|MET", t):
        continue  # 导航/本科/分页噪声
    if t in DROP:
        dropped.append(t); continue
    if t not in MAP:
        missing.append(t); continue
    cn, disc, college, slug, deg = MAP[t]
    en = re.sub(r"\s*\([^)]*\)", "", t).strip()
    det = f"details/{SID}-{slug}.html"
    url = item["h"]
    catd.append([SID, college, en, cn, deg, url, disc, det])
    pages.append({"det": det, "cn": cn, "en": en, "college": college, "deg": deg, "url": url})
    with open(os.path.join(DET, f"{SID}-{slug}.html"), "w", encoding="utf-8", newline="") as f:
        f.write(TPL.format(cn=html.escape(cn), en=html.escape(en), college=html.escape(college),
                          deg=html.escape(deg), url=html.escape(url, quote=True),
                          school_cn=SCHOOL_CN, school_en=SCHOOL_EN, TODAY=TODAY))

json.dump(catd, open(os.path.join(BASE, "pending_dartmouth_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_dartmouth_pages.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

from collections import Counter
print("保留:", len(catd), " 剔除:", len(dropped), " 未映射:", missing)
print("disc:", dict(Counter(c[6] for c in catd)))
