# -*- coding: utf-8 -*-
"""Notre Dame 目录级生成：剔辅修/Prep/REU/部门锚点/MD-PhD/MDiv/在职创业。"""
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="University of Notre Dame"; SID="notre"
raw = json.load(open(os.path.join(BASE,"raw_notre.json"),encoding="utf-8"))

DROP = ["Minor","Prep","REU","?id=","MD/PhD","MDiv","Echo/Theology","Entrepreneurship","Weekend",
        "Summer Research","Joint","Degree Programs","Faculty","Postdocs","Alumni","Inquire","Apply",
        "Admissions","Applicants","Incoming","Current Students","News","About","Funding","Policies",
        "Graduate Training","Handbook","Program Handbook","apply","@nd.edu","drive.google"]

CN = {
 "Anthropology":"人类学","Applied and Computational Mathematics and Statistics":"应用计算数学与统计",
 "Biochemistry":"生物化学","Bioengineering":"生物工程","Biological Sciences":"生物科学","Biophysics":"生物物理学",
 "Chemical Engineering":"化学工程","Chemistry":"化学","Civil and Environmental Engineering and":"土木与环境工程",
 "Civil and Environmental Engineering":"土木与环境工程","Civil Engineering":"土木工程","Classics":"古典学",
 "Computational Science and Engineering":"计算科学与工程","Computer Science and Engineering":"计算机科学与工程",
 "Data Science":"数据科学","Economics":"经济学","Electrical Engineering":"电气工程","English":"英语语言文学",
 "English (Creative Writing)":"创意写作（MFA）","French and Francophone Studies":"法语与法语区研究",
 "History and Philosophy of Science":"科学史与科学哲学","History":"历史学","Integrated Biomedical Sciences":"综合生物医学",
 "Interdisciplinary Mathematics":"跨学科数学","International Peace Studies":"国际和平研究","Italian":"意大利语",
 "Italian Studies":"意大利研究","Management":"管理学（研究型博士）","Materials Science and Engineering":"材料科学与工程",
 "Mathematics":"数学","Mechanical Engineering":"机械工程","Medieval Studies":"中世纪研究","Philosophy":"哲学",
 "Physics":"物理学","Political Science":"政治学","Psychology, Research and Experimental":"研究与实验心理学",
 "Sociology":"社会学","Spanish":"西班牙语","Theology":"神学研究","Earth Sciences":"地球科学",
 "Aerospace and Mechanical Engineering":"航空航天与机械工程","Aerospace Engineering":"航空工程",
 "Analytics":"分析学","Design":"设计（MFA）","Early Christian Studies":"早期基督教研究",
 "History and Philosophy of Science, Technology and Society":"科学、技术与社会史哲学",
 "Peace Studies and Anthropology":"和平研究与人类学","Peace Studies and History":"和平研究与历史学",
 "Peace Studies and Political Science":"和平研究与政治学","Peace Studies and Psychology":"和平研究与心理学",
 "Peace Studies and Sociology":"和平研究与社会学","Peace Studies and Theology":"和平研究与神学",
 "Sustainable Development":"可持续发展","Advanced Quantitative Social Science":"高级量化社会科学",
 "Conducting (Sacred Music)":"指挥（圣乐）","Organ (Sacred Music)":"管风琴（圣乐）","Sacred Music":"圣乐",
 "Studio Art":"工作室艺术","Screen Cultures":"屏幕文化",
}

def disc_of(t):
    if re.search(r"ACE|Teaching Fellows|Education|Leadership Program",t): return "edu"
    if re.search(r"Computer Science|Data Science|Statistics|Computational Science|Analytics",t): return "cs"
    if re.search(r"Engineering|Aerospace|Mechanical|Electrical|Materials|Civil|Chemical|Bioengineering|Architecture|Robotics",t): return "eng"
    if re.search(r"Management|Marketing|Business|Finance",t): return "biz"
    if re.search(r"Biomedical|Biochemistry|Biological|Biophysics|Chemistry|Physics|Mathematics|Earth Sciences|Psychology|Sustainable",t): return "sci"
    if re.search(r"Anthropology|Economics|Political Science|Sociology|Peace Studies|Global Affairs|Quantitative Social",t): return "soc"
    return "art"

def college_of(disc):
    return {"cs":"工程学院","eng":"工程学院","biz":"Mendoza 商学院","sci":"理学院",
            "med":"理学院","soc":"文理学院","art":"文理学院","edu":"教育学院"}[disc]

catd, pages, dropped = [], [], []
seen=set()
for x in raw:
    t=x["t"].replace("\u200b","").strip()
    if any(b in t for b in DROP): dropped.append(t); continue
    h=x["h"]
    if "/degree-programs/" not in h: dropped.append(t); continue
    if ":" in t:
        name, deg = t.split(":",1)
        deg=deg.strip()
    else:
        name, deg = t, ""
    name=name.strip()
    if not deg: dropped.append(t); continue
    slug=h.split("/degree-programs/")[-1].split("?")[0].strip("/")
    if slug in seen: continue
    seen.add(slug)
    disc=disc_of(name)
    cn=CN.get(name, name)
    url=h if h.startswith("http") else "https://graduateschool.nd.edu"+h
    det=f"details/{SID}-{slug}.html"
    catd.append([SID, college_of(disc), name, cn, deg, url, disc, det])
    pages.append({"det":det,"cn":cn,"en":name,"college":college_of(disc),"deg":deg,"url":url})

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

for p in pages:
    with open(os.path.join(DET, os.path.basename(p["det"])),"w",encoding="utf-8",newline="") as f:
        f.write(TPL.format(cn=html.escape(p["cn"]),en=html.escape(p["en"]),college=html.escape(p["college"]),
            deg=html.escape(p["deg"]),url=html.escape(p["url"],quote=True),school_cn=SCHOOL_CN,school_en=SCHOOL_EN,TODAY=TODAY))

json.dump(catd,open(os.path.join(BASE,"pending_notre_catd.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
json.dump(pages,open(os.path.join(BASE,"pending_notre_pages.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
from collections import Counter
print("保留:",len(catd)," 剔除:",len(dropped))
print("disc:",dict(Counter(c[6] for c in catd)))
