# -*- coding: utf-8 -*-
"""Yale GSAS 目录级生成：剔护理/药理；医学转化类列边界；计算生物硕博合并。"""
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 = "Yale University"
SID = "yale"

DROP = {"Nursing", "Pharmacology"}
BOUNDARY = {"Investigative Medicine", "Pathology & Molecular Medicine", "Translational Biomedicine"}
# 同一项目两个学位条目合并到首条
MERGE_DUP = {"Computational Biology & Biomedical Informatics (PhD Program)"}

# text -> (cn, deg, disc, slug)
MAP = {
    "African Studies": ("非洲研究", "MA", "soc", "african-studies"),
    "American Studies": ("美国研究", "PhD/MA", "art", "american-studies"),
    "Anthropology": ("人类学", "PhD", "soc", "anthropology"),
    "Applied & Computational Mathematics": ("应用与计算数学", "PhD", "sci", "applied-computational-mathematics"),
    "Applied Physics": ("应用物理", "PhD/MS", "sci", "applied-physics"),
    "Archaeological Studies": ("考古研究", "MA", "soc", "archaeological-studies"),
    "Architecture": ("建筑学", "PhD", "art", "architecture"),
    "Astronomy": ("天文学", "PhD", "sci", "astronomy"),
    "Biological & Biomedical Sciences (BBS)": ("生物与生物医学科学", "PhD", "sci", "biological-biomedical-sciences-bbs"),
    "Biomedical Engineering": ("生物医学工程", "PhD/MS", "eng", "biomedical-engineering"),
    "Black Studies": ("黑人研究", "PhD", "soc", "black-studies"),
    "Cell Biology": ("细胞生物学", "PhD", "sci", "cell-biology"),
    "Cellular & Molecular Physiology": ("细胞与分子生理学", "PhD", "sci", "cellular-molecular-physiology"),
    "Chemical & Environmental Engineering": ("化学与环境工程", "PhD/MS", "eng", "chemical-environmental-engineering"),
    "Chemistry": ("化学", "PhD", "sci", "chemistry"),
    "Classics": ("古典学", "PhD", "art", "classics"),
    "Comparative Literature": ("比较文学", "PhD", "art", "comparative-literature"),
    "Computational Biology & Biomedical Informatics (MS Program)": ("计算生物学与生物医学信息", "MS/PhD", "cs", "computational-biology-biomedical-informatics"),
    "Computational Biology & Biomedical Informatics (PhD Program)": ("计算生物学与生物医学信息", "MS/PhD", "cs", "computational-biology-biomedical-informatics"),
    "Computer Science": ("计算机科学", "PhD/MS", "cs", "computer-science"),
    "Early Modern Studies": ("早期现代研究", "PhD", "art", "early-modern-studies"),
    "Earth & Planetary Sciences": ("地球与行星科学", "PhD", "sci", "earth-planetary-sciences"),
    "East Asian Languages & Literatures": ("东亚语言文学", "PhD", "art", "east-asian-languages-literatures"),
    "East Asian Studies": ("东亚研究", "MA", "soc", "east-asian-studies"),
    "Ecology & Evolutionary Biology": ("生态与进化生物学", "PhD", "sci", "ecology-evolutionary-biology"),
    "Economics": ("经济学", "PhD", "soc", "economics"),
    "Electrical & Computer Engineering": ("电气与计算机工程", "PhD/MS", "eng", "electrical-computer-engineering"),
    "English Language & Literature": ("英语语言文学", "PhD/MA", "art", "english-language-literature"),
    "Environment": ("环境研究", "PhD", "sci", "environment"),
    "European & Russian Studies": ("欧洲与俄罗斯研究", "MA", "soc", "european-russian-studies"),
    "Film & Media Studies": ("电影与媒体研究", "PhD", "art", "film-media-studies"),
    "French": ("法语", "PhD", "art", "french"),
    "Genetics": ("遗传学", "PhD", "sci", "genetics"),
    "Germanic Languages & Literatures": ("日耳曼语言文学", "PhD", "art", "germanic-languages-literatures"),
    "History": ("历史学", "PhD/MA", "art", "history"),
    "History of Art": ("艺术史", "PhD", "art", "history-art"),
    "History of Science & Medicine": ("科学与医学史", "PhD/MA", "art", "history-science-medicine"),
    "Immunobiology": ("免疫生物学", "PhD", "sci", "immunobiology"),
    "Interdepartmental Neuroscience Program": ("跨系神经科学", "PhD", "sci", "interdepartmental-neuroscience-program"),
    "International & Development Economics": ("国际与发展经济学", "MA", "soc", "international-development-economics"),
    "Italian Studies": ("意大利研究", "PhD", "art", "italian-studies"),
    "Jewish Studies": ("犹太研究", "PhD", "art", "jewish-studies"),
    "Law": ("法学（研究型博士）", "PhD", "soc", "law"),
    "Linguistics": ("语言学", "PhD", "soc", "linguistics"),
    "Management": ("管理学（研究型博士）", "PhD", "biz", "management"),
    "Materials Science": ("材料科学", "PhD", "eng", "materials-science"),
    "Mathematics": ("数学", "PhD", "sci", "mathematics"),
    "Mechanical Engineering": ("机械工程", "PhD/MS", "eng", "mechanical-engineering"),
    "Medieval Studies": ("中世纪研究", "PhD/MA", "art", "medieval-studies"),
    "Microbiology": ("微生物学", "PhD", "sci", "microbiology"),
    "Molecular Biophysics & Biochemistry": ("分子生物物理与生物化学", "PhD", "sci", "molecular-biophysics-biochemistry"),
    "Molecular, Cellular, & Developmental Biology": ("分子、细胞与发育生物学", "PhD", "sci", "molecular-cellular-developmental-biology"),
    "Music": ("音乐", "PhD/MA", "art", "music"),
    "Near Eastern Languages & Civilizations": ("近东语言文明", "PhD/MA", "art", "near-eastern-languages-civilizations"),
    "Personalized Medicine & Applied Engineering": ("个性化医学与应用工程", "MS", "eng", "personalized-medicine-applied-engineering"),
    "Philosophy": ("哲学", "PhD", "art", "philosophy"),
    "Physics": ("物理学", "PhD", "sci", "physics"),
    "Political Science": ("政治学", "PhD", "soc", "political-science"),
    "Psychology": ("心理学", "PhD", "soc", "psychology"),
    "Public Health": ("公共卫生", "PhD/MS", "med", "public-health"),
    "Religious Studies": ("宗教学", "PhD", "art", "religious-studies"),
    "Slavic Languages and Literatures": ("斯拉夫语言文学", "PhD", "art", "slavic-languages-literatures"),
    "Sociology": ("社会学", "PhD", "soc", "sociology"),
    "Spanish & Portuguese": ("西班牙语与葡萄牙语", "PhD", "art", "spanish-portuguese"),
    "Statistics": ("统计学", "MA", "cs", "statistics"),
    "Statistics & Data Science": ("统计学与数据科学", "PhD/MS", "cs", "statistics-data-science"),
    "Women’s, Gender, & Sexuality Studies": ("女性、性别与性研究", "PhD", "art", "womens-gender-sexuality-studies"),
}

COLLEGE_BY_DISC = {
    "cs": "工程与应用科学学院（SEAS）", "eng": "工程与应用科学学院（SEAS）",
    "biz": "管理学院（研究型博士）", "med": "公共卫生学院 / 文理研究生院",
    "soc": "社会科学部", "art": "人文部", "sci": "自然科学部",
}

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

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">本项目为 Yale University 研究生院官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学部与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：Yale GSAS 官方项目页 <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">📋 数据说明：本页名称 / 学部 / 学位均摘自 Yale University 官方页面（抓取日期 {TODAY}，对应 2027 申请季）。申请截止、语言、标化、学费等字段待逐项核验后补充展示，核验前不做估算填充；官网未公布的字段整项不展示。</div>
</div>
</body>
</html>
"""

for item in raw:
    t = item["text"].strip().replace("​", "")
    if t in DROP:
        dropped.append(t); continue
    if t in BOUNDARY:
        boundary.append(t); continue
    if t in MERGE_DUP:
        merged.append(t); continue
    if t not in MAP:
        missing.append(t); continue
    cn, deg, disc, slug = MAP[t]
    if slug in seen_slug:
        merged.append(t); continue
    seen_slug.add(slug)
    college = COLLEGE_BY_DISC[disc]
    url = item["href"].replace("/index%2Ephp/", "/")
    en = re.sub(r"\s*\((MS|PhD) Program\)", "", t)
    det = f"details/{SID}-{slug}.html"
    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_yale_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_yale_pages.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

from collections import Counter
print("保留:", len(catd), " 剔除:", len(dropped), " 边界:", len(boundary), " 合并/重复:", len(merged), " 未映射:", missing)
print("disc:", dict(Counter(c[6] for c in catd)))
print("剔除:", dropped, " 边界:", boundary)
