# -*- coding: utf-8 -*-
"""Harvard GSAS 目录级生成：剔非学位身份/JD·MD-PhD/MS-MBA 双学位；学位不明列边界。"""
import io, sys, os, json, html
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 = "Harvard University"
SID = "harvard"

DROP = {
    "Exchange Scholar", "Harvard AB/AM and AB/SM", "JD/PhD", "MD/PhD", "MS/MBA",
    "Research Scholar Initiative", "Special Students",
    "Summer Research Opportunities at Harvard", "Visiting Fellows",
}
BOUNDARY = {"Byzantine Studies", "Inner Asian and Altaic Studies", "Philosophy"}

# text -> (cn, deg, disc)
MAP = {
    "African and African American Studies": ("非裔与非裔美国人研究", "PhD", "art"),
    "American Studies": ("美国研究", "PhD", "art"),
    "Anthropology": ("人类学", "PhD", "soc"),
    "Applied Mathematics": ("应用数学", "PhD", "sci"),
    "Applied Physics": ("应用物理", "PhD", "sci"),
    "Architecture, Landscape Architecture, and Urban Planning": ("建筑、景观建筑与城市规划", "PhD", "art"),
    "Astronomy": ("天文学", "PhD", "sci"),
    "Bioengineering": ("生物工程", "PhD", "eng"),
    "Biological and Biomedical Sciences": ("生物与生物医学科学", "PhD", "sci"),
    "Biological Sciences in Public Health": ("公共卫生生物科学", "PhD", "med"),
    "Biomedical Informatics": ("生物医学信息学", "PhD", "med"),
    "Biophysics": ("生物物理", "PhD", "sci"),
    "Biostatistics": ("生物统计学", "PhD", "cs"),
    "Business Administration": ("工商管理（研究型博士）", "PhD", "biz"),
    "Business Economics": ("商业经济学", "PhD", "biz"),
    "Celtic Languages and Literatures": ("凯尔特语言文学", "PhD", "art"),
    "Chemical Biology": ("化学生物学", "PhD", "sci"),
    "Chemical Physics": ("化学物理", "PhD", "sci"),
    "Chemistry and Chemical Biology": ("化学与化学生物学", "PhD", "sci"),
    "Classics": ("古典学", "PhD", "art"),
    "Comparative Literature": ("比较文学", "PhD", "art"),
    "Computational Science and Engineering": ("计算科学与工程", "ME", "eng"),
    "Computer Science": ("计算机科学", "PhD", "cs"),
    "Data Science": ("数据科学", "SM", "cs"),
    "Earth and Planetary Sciences": ("地球与行星科学", "PhD", "sci"),
    "East Asian Languages and Civilizations": ("东亚语言文明", "PhD", "art"),
    "Economics": ("经济学", "PhD", "soc"),
    "Education": ("教育学", "PhD", "edu"),
    "Electrical and Computer Engineering": ("电气与计算机工程", "PhD", "eng"),
    "Engineering and Applied Sciences": ("工程与应用科学", "SM", "eng"),
    "English": ("英语语言文学", "PhD", "art"),
    "Environmental Science and Engineering": ("环境科学与工程", "PhD", "eng"),
    "Film and Visual Studies": ("电影与视觉研究", "PhD", "art"),
    "Germanic Languages and Literatures": ("日耳曼语言文学", "PhD", "art"),
    "Government": ("政府学", "PhD", "soc"),
    "Health Policy": ("健康政策", "PhD", "med"),
    "History": ("历史学", "PhD", "art"),
    "History of Art and Architecture": ("艺术与建筑史", "PhD", "art"),
    "History of Science": ("科学史", "PhD", "art"),
    "Human Evolutionary Biology": ("人类进化生物学", "PhD", "sci"),
    "Immunology": ("免疫学", "PhD", "sci"),
    "Linguistics": ("语言学", "PhD", "art"),
    "Materials Science and Mechanical Engineering": ("材料科学与机械工程", "PhD", "eng"),
    "Mathematics": ("数学", "PhD", "sci"),
    "Middle Eastern Studies": ("中东研究", "PhD/AM", "art"),
    "Molecular and Cellular Biology": ("分子与细胞生物学", "PhD", "sci"),
    "Music": ("音乐", "PhD", "art"),
    "Near Eastern Languages and Civilizations": ("近东语言文明", "PhD", "art"),
    "Neuroscience": ("神经科学", "PhD", "sci"),
    "Organismic and Evolutionary Biology": ("机体与进化生物学", "PhD", "sci"),
    "Organizational Behavior": ("组织行为学", "PhD", "biz"),
    "Physics": ("物理学", "PhD", "sci"),
    "Population Health Sciences": ("人口健康科学", "PhD", "med"),
    "Psychology": ("心理学", "PhD", "sci"),
    "Public Policy": ("公共政策", "PhD", "soc"),
    "Quantum Science and Engineering": ("量子科学与工程", "PhD", "eng"),
    "Regional Studies–East Asia": ("东亚区域研究", "AM", "art"),
    "Regional Studies–Russia, Eastern Europe, and Central Asia": ("俄罗斯、东欧与中亚区域研究", "AM", "art"),
    "Religion": ("宗教学", "PhD", "art"),
    "Romance Languages and Literatures": ("罗曼语言文学", "PhD", "art"),
    "Slavic Languages and Literatures": ("斯拉夫语言文学", "PhD", "art"),
    "Social Policy": ("社会政策", "PhD", "soc"),
    "Sociology": ("社会学", "PhD", "soc"),
    "South Asian Studies": ("南亚研究", "PhD", "art"),
    "Speech and Hearing Bioscience and Technology": ("言语听力生物科学与技术", "PhD", "med"),
    "Statistics": ("统计学", "PhD", "cs"),
    "Systems, Synthetic, and Quantitative Biology": ("系统、合成与定量生物学", "PhD", "sci"),
    "Virology": ("病毒学", "PhD", "sci"),
}

COLLEGE_BY_DISC = {
    "cs": "工程与应用科学学院（SEAS）", "eng": "工程与应用科学学院（SEAS）",
    "biz": "商学院（研究型博士）", "edu": "教育研究生院", "med": "公共卫生学院 / 文理研究生院",
    "soc": "文理研究生院（GSAS）", "art": "文理研究生院（GSAS）", "sci": "文理研究生院（GSAS）",
}

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

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

for item in raw:
    t = item["text"].strip().replace("​", "").replace("\u200b", "")
    if t in DROP:
        dropped.append(t); continue
    if t in BOUNDARY:
        boundary.append(t); continue
    if t not in MAP:
        missing.append(t); continue
    cn, deg, disc = MAP[t]
    college = COLLEGE_BY_DISC[disc]
    slug = item["href"].rstrip("/").split("/program/")[1]
    det = f"details/{SID}-{slug}.html"
    url = item["href"]
    catd.append([SID, college, t, cn, deg, url, disc, det])
    pages.append({"det": det, "cn": cn, "en": t, "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(t), 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_harvard_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_harvard_pages.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

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