# -*- coding: utf-8 -*-
"""MIT 目录级生成：读取 raw_mit.json，按口径甄别，生成目录页 + pending CATD。"""
import io, sys, os, json, re, 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"

# 剔除项（MBA / MBA 双学位 / 在职混合）
DROP = {
    "Leaders for Global Operations*",
    "MIT Sloan Evening MBA Program",
    "MIT Sloan Executive MBA Program",
    "MIT Sloan Fellows MBA Program",
    "MIT Sloan MBA Program",
    "Supply Chain Management Blended",
    "System Design and Management",
}

COLLEGE = {
    "arch": "建筑与规划学院",
    "eng": "工程学院",
    "cs": "施瓦茨曼计算学院",
    "hass": "人文艺术与社会科学学院",
    "biz": "斯隆管理学院",
    "sci": "理学院",
    "inter": "跨学科研究项目",
}

# text -> (cn, deg, disc, slug)
MAP = {
    "Architecture": ("建筑学", "MArch", "art", "architecture"),
    "Center for Real Estate": ("房地产理学硕士", "MS", "biz", "center-for-real-estate"),
    "Media Arts and Sciences": ("媒体艺术与科学", "MAS", "art", "media-arts-sciences"),
    "Urban Studies and Planning": ("城市研究与规划", "MCP", "soc", "urban-studies-planning"),
    "Aeronautics and Astronautics": ("航空航天", "SM/MEng/PhD", "eng", "aeronautics-astronautics"),
    "Biological Engineering": ("生物工程", "MEng/PhD/ScD", "eng", "biological-engineering"),
    "Chemical Engineering": ("化学工程", "SM/PhD", "eng", "chemical-engineering"),
    "Civil and Environmental Engineering": ("土木与环境工程", "SM/MEng/PhD", "eng", "civil-environmental-engineering"),
    "Computational Science and Engineering PhD*": ("计算科学与工程博士", "PhD", "cs", "computational-science-engineering"),
    "Electrical Engineering and Computer Science": ("电气工程与计算机科学", "SM/MEng/PhD", "cs", "eecs"),
    "Health Sciences and Technology (Joint Harvard-MIT Program)": ("健康科学与技术（哈佛-MIT 联合项目）", "PhD/ScD", "med", "health-sciences-technology"),
    "Materials Science and Engineering": ("材料科学与工程", "SM/PhD", "eng", "materials-science-engineering"),
    "Mechanical Engineering": ("机械工程", "SM/MEng/PhD", "eng", "mechanical-engineering"),
    "Nuclear Science and Engineering": ("核科学与工程", "SM/PhD", "eng", "nuclear-science-engineering"),
    "Institute for Data, Systems, and Society": ("数据、系统与社会", "SM/PhD", "cs", "idss"),
    "Data, Economics, and Design of Policy": ("数据、经济与政策设计", "MASc", "soc", "data-economics-design-policy"),
    "Economics": ("经济学", "PhD", "soc", "economics"),
    "History, Anthropology, and Science, Technology, and Society": ("历史、人类学与科学技术社会研究", "PhD", "art", "hasts"),
    "Linguistics": ("语言学", "PhD", "art", "linguistics"),
    "Music Technology and Computation": ("音乐技术与计算", "SM", "art", "music-technology-computation"),
    "Philosophy": ("哲学", "PhD", "art", "philosophy"),
    "Political Science": ("政治学", "PhD", "soc", "political-science"),
    "Science Writing": ("科学写作", "MS", "art", "science-writing"),
    "MIT Sloan Master of Business Analytics": ("商业分析硕士", "MBAn", "biz", "business-analytics"),
    "MIT Sloan Master of Finance": ("金融硕士", "MFin", "biz", "finance"),
    "MIT Sloan Master of Science in Management Studies": ("管理研究理学硕士", "MS", "biz", "management-studies"),
    "MIT Sloan PhD Program": ("斯隆管理博士", "PhD", "biz", "sloan-phd"),
    "Biology": ("生物学", "PhD", "sci", "biology"),
    "Brain and Cognitive Sciences": ("脑与认知科学", "PhD", "sci", "brain-cognitive-sciences"),
    "Chemistry": ("化学", "PhD", "sci", "chemistry"),
    "Computational and Systems Biology*": ("计算与系统生物学", "PhD", "sci", "computational-systems-biology"),
    "Earth, Atmospheric, and Planetary Sciences": ("地球、大气与行星科学", "PhD", "sci", "eaps"),
    "Mathematics": ("数学", "PhD", "sci", "mathematics"),
    "Microbiology": ("微生物学", "PhD", "sci", "microbiology"),
    "Physics": ("物理学", "PhD", "sci", "physics"),
    "MIT-WHOI Joint Program in Oceanography / Applied Ocean Science and Engineering": ("海洋学与应用海洋科学工程（WHOI 联合项目）", "SM/PhD", "sci", "whoi-oceanography"),
    "Operations Research Center": ("运筹学", "SM/PhD", "cs", "operations-research"),
    "Program in Polymers and Soft Matter": ("聚合物与软物质", "PhD", "sci", "polymers-soft-matter"),
    "Supply Chain Management Residential": ("供应链管理（住宿制）", "MS", "biz", "supply-chain-management-residential"),
    "Technology and Policy Program": ("技术与政策", "SM", "soc", "technology-policy"),
    "Transportation": ("交通运输", "SM/PhD", "eng", "transportation"),
}

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

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} · 麻省理工学院 · 项目详情 | 美加硕士项目查询系统</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">麻省理工学院 Massachusetts Institute of Technology · {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">本项目为 MIT 研究生院官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：MIT Office of Graduate Education 官方项目页 <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">本条目来自 MIT 官网研究生项目总目录；逐项核验（截止 / 语言 / 标化 / 学费 / 就业）完成后，本页将升级为完整核验详情页。</div></div>
</div>
<div class="foot">
  <div class="yellow">📋 数据说明：本页名称 / 学院 / 学位均摘自 MIT 官方页面（抓取日期 {TODAY}，对应 2027 申请季）。申请截止、语言、标化、学费等字段待逐项核验后补充展示，核验前不做估算填充；官网未公布的字段整项不展示。</div>
</div>
</body>
</html>
"""

for item in raw:
    t = item["text"].strip()
    if t in DROP:
        dropped.append(t); continue
    if t in seen:
        continue
    seen.add(t)
    if t not in MAP:
        missing.append(t); continue
    cn, deg, disc, slug = MAP[t]
    college = COLLEGE[item["group"]]
    det = f"details/mit-{slug}.html"
    url = item["href"]
    catd.append(["mit", college, t, cn, deg, url, disc, det])
    pages.append({"det": det, "cn": cn, "en": t, "college": college, "deg": deg, "url": url})
    htmlname = f"mit-{slug}.html"
    with open(os.path.join(DET, htmlname), "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), TODAY=TODAY))

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

print("保留条目:", len(catd))
print("剔除:", len(dropped), dropped)
print("未映射(需补):", missing)
from collections import Counter
print("disc 分布:", dict(Counter(c[6] for c in catd)))
print("学院分布:", dict(Counter(c[1] for c in catd)))
