# -*- coding: utf-8 -*-
"""Stanford Explore Programs 目录级生成：剔遗传咨询/临床信息管理/动物科学/转化应用医学/继教硕士。"""
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 = "Stanford University"
SID = "stanford"

DROP = {
 "Clinical Informatics Management (MS)",
 "Human Genetics and Genetic Counseling (MS)",
 "Laboratory Animal Science (MS)",
 "Translational Research and Applied Medicine (MS)",
 "Master of Liberal Arts (MLA)",
}

# 去学位后缀的基础名 -> (cn, disc)
MAP = {
 "Aeronautics and Astronautics": ("航空航天工程", "eng"),
 "Anthropology": ("人类学", "soc"),
 "Applied Physics": ("应用物理", "sci"),
 "Art History": ("艺术史", "art"),
 "Art Practice": ("艺术实践", "art"),
 "Biochemistry": ("生物化学", "sci"),
 "Bioengineering": ("生物工程", "eng"),
 "Biology": ("生物学", "sci"),
 "Biomedical Data Science": ("生物医学数据科学", "cs"),
 "Biomedical Physics": ("生物医学物理", "sci"),
 "Biophysics": ("生物物理", "sci"),
 "Cancer Biology": ("癌症生物学", "sci"),
 "Chemical and Systems Biology": ("化学与系统生物学", "sci"),
 "Chemical Engineering": ("化学工程", "eng"),
 "Chemistry": ("化学", "sci"),
 "Civil and Environmental Engineering": ("土木与环境工程", "eng"),
 "Classics": ("古典学", "art"),
 "Communication": ("传播学", "soc"),
 "Community Health and Prevention Research": ("社区健康与预防研究", "med"),
 "Comparative Literature": ("比较文学", "art"),
 "Computational and Mathematical Engineering": ("计算与数学工程", "eng"),
 "Computer Science": ("计算机科学", "cs"),
 "Developmental Biology": ("发育生物学", "sci"),
 "Documentary Film and Video": ("纪录影视", "art"),
 "Earth and Planetary Sciences": ("地球与行星科学", "sci"),
 "Earth System Science": ("地球系统科学", "sci"),
 "East Asian Languages and Cultures": ("东亚语言文化", "art"),
 "East Asian Studies": ("东亚研究", "soc"),
 "Economics": ("经济学", "soc"),
 "Education": ("教育", "edu"),
 "Electrical Engineering": ("电气工程", "eng"),
 "Energy Science and Engineering": ("能源科学与工程", "eng"),
 "Design": ("设计（工程创新）", "eng"),
 "English": ("英语语言文学", "art"),
 "Environment and Resources": ("环境与资源", "sci"),
 "Environmental Social Sciences": ("环境社会科学", "soc"),
 "Epidemiology and Clinical Research": ("流行病学与临床研究", "med"),
 "French": ("法语", "art"),
 "French and Italian": ("法语与意大利语", "art"),
 "Genetics": ("遗传学", "sci"),
 "Geophysics": ("地球物理学", "sci"),
 "German Studies": ("德语研究", "art"),
 "Health Policy": ("健康政策", "med"),
 "History": ("历史学", "art"),
 "Iberian and Latin American Cultures": ("伊比利亚与拉美文化", "art"),
 "Immunology": ("免疫学", "sci"),
 "International Policy": ("国际政策", "soc"),
 "Italian": ("意大利语", "art"),
 "Latin American Studies": ("拉美研究", "soc"),
 "Linguistics": ("语言学", "art"),
 "Management Science and Engineering": ("管理科学与工程", "eng"),
 "Materials Science and Engineering": ("材料科学与工程", "eng"),
 "Mathematics": ("数学", "sci"),
 "Mechanical Engineering": ("机械工程", "eng"),
 "Microbiology and Immunology": ("微生物学与免疫学", "sci"),
 "Modern Thought and Literature": ("现代思想与文学", "art"),
 "Molecular and Cellular Physiology": ("分子与细胞生理学", "sci"),
 "Music": ("音乐", "art"),
 "Neurosciences": ("神经科学", "sci"),
 "Oceans": ("海洋科学", "sci"),
 "Philosophy": ("哲学", "art"),
 "Physics": ("物理学", "sci"),
 "Political Science": ("政治学", "soc"),
 "Psychology": ("心理学", "sci"),
 "Public Policy": ("公共政策", "soc"),
 "Religious Studies": ("宗教研究", "art"),
 "Russian, East European and Eurasian Studies": ("俄罗斯、东欧与欧亚研究", "soc"),
 "Slavic Languages and Literatures": ("斯拉夫语言文学", "art"),
 "Sociology": ("社会学", "soc"),
 "Statistics": ("统计学", "cs"),
 "Stem Cell Biology and Regenerative Medicine": ("干细胞生物学与再生医学", "sci"),
 "Structural Biology": ("结构生物学", "sci"),
 "Symbolic Systems": ("符号系统", "cs"),
 "Theater and Performance Studies": ("戏剧与表演研究", "art"),
}

def college_of(school):
    s = school or ""
    if "engineering" in s: return "工程学院（School of Engineering）"
    if "med.stanford" in s: return "医学院（研究 / 公共卫生方向）"
    if "ed.stanford" in s: return "教育研究生院（Graduate School of Education）"
    if "sustainability" in s: return "可持续发展学院（Doerr School of Sustainability）"
    return "人文与科学学院（School of Humanities and Sciences）"

raw = json.load(open(os.path.join(BASE, "raw_stanford.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">本项目为 Stanford University 研究生院官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：Stanford 官方项目页 / Bulletin <a href="{url}" target="_blank">{url}</a>（抓取日期 {TODAY}）。</div></div>
<div class="card"><h2>官方链接</h2><div class="links"><a href="{pw}" target="_blank">🔗 项目官网（申请要求 / 课程）</a><a href="{bl}" target="_blank">📘 Stanford Bulletin 学位说明</a></div><div class="note">本条目来自学校官方研究生项目目录；逐项核验（截止 / 语言 / 标化 / 学费 / 就业）完成后，本页将升级为完整核验详情页。</div></div>
</div>
<div class="foot">
  <div class="yellow">📋 数据说明：本页名称 / 学院 / 学位均摘自 Stanford University 官方页面（抓取日期 {TODAY}，对应 2027 申请季）。申请截止、语言、标化、学费等字段待逐项核验后补充展示，核验前不做估算填充；官网未公布的字段整项不展示。</div>
</div>
</body>
</html>
"""

DEG_MAP = {"MS":"MS","PhD":"PhD","MA":"MA","MFA":"MFA","Eng":"Eng","DMA":"DMA","MPP":"MPP","MLA":"MLA"}

for item in raw:
    t = item["t"].strip()
    if t in DROP:
        dropped.append(t); continue
    m = re.match(r"^(.*?)\s*\(([^)]+)\)\s*$", t)
    base, deg_suf = m.group(1).strip(), m.group(2).strip()
    deg = DEG_MAP.get(deg_suf, deg_suf)
    if base not in MAP:
        missing.append(t); continue
    cn, disc = MAP[base]
    college = college_of(item["school"])
    code = (item["bl"] or "").rstrip("/").split("/")[-1].lower().replace("%20","-")
    slug = f"{SID}-{code}"
    det = f"details/{slug}.html"
    url = item["bl"]
    catd.append([SID, college, base, cn, deg, url, disc, det])
    pages.append({"det": det, "cn": cn, "en": base, "college": college, "deg": deg, "url": url})
    with open(os.path.join(DET, f"{slug}.html"), "w", encoding="utf-8", newline="") as f:
        f.write(TPL.format(cn=html.escape(cn), en=html.escape(base), college=html.escape(college),
                          deg=html.escape(deg), url=html.escape(url, quote=True),
                          pw=html.escape(item["pw"] or url, quote=True),
                          bl=html.escape(item["bl"] or url, quote=True),
                          school_cn=SCHOOL_CN, school_en=SCHOOL_EN, TODAY=TODAY))

json.dump(catd, open(os.path.join(BASE, "pending_stanford_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_stanford_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)))
print("剔除:", dropped)
