# -*- coding: utf-8 -*-
"""Vanderbilt 目录级生成：按 URL 精确映射；剔临床/法律/神学/护理/在线/MBA/遗传咨询/药理/病理免疫。"""
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="Vanderbilt University"; SID="vanderbilt"
raw = json.load(open(os.path.join(BASE,"raw_vanderbilt.json"),encoding="utf-8"))

# DROP：URL 子串黑名单
DROP = [
 "online-programs", "engineeringonline", "edd-programs", "engineering-management",
 "/mba/", "evening-mba", "/emba/", "msaci", "hearing-speech", "mstp", "/md-program/",
 "dnp", "nursing.vanderbilt.edu", "/llm-program", "/jd-program", "law.vanderbilt.edu/phd", "master-legal-studies",
 "/dmin.php", "ThM.php", "professionalprograms", "molecular-pathology-immunology",
 "master-of-management-in-healthcare", "/pharmacology/", "mgc/about", "/mis/",
 "ms-business-and-tech", "/rrr/", "doctor-of-education-edd",
]

# MAP: URL 子串 -> (cn, en, disc, deg, college)
MAP = {
 "masters-in-accounting/": ("会计", "Master of Accountancy", "biz", "MAcc", "Owen 商学院"),
 "masters-in-accounting-valuation": ("会计与估值", "Master of Accountancy in Valuation", "biz", "MAcc", "Owen 商学院"),
 "anthropology/graduate": ("人类学", "Anthropology", "soc", "PhD", "文理学院"),
 "applied-behavior-analysis-med": ("应用行为分析", "Applied Behavior Analysis (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "phd-astrophysics": ("天体物理", "Astrophysics", "sci", "PhD", "文理学院"),
 "biochemistry/graduate": ("生物化学", "Biochemistry", "sci", "PhD", "医学院（基础研究）"),
 "biological-sciences/graduate": ("生物科学", "Biological Sciences", "sci", "PhD", "文理学院"),
 "biomedical-engineering/graduate-programs": ("生物医学工程", "Biomedical Engineering", "eng", "MS/PhD", "工程学院"),
 "biomedical-sciences/": ("生物医学科学", "Biomedical Sciences", "sci", "MS", "文理学院"),
 "biostatistics-graduate": ("生物统计学", "Biostatistics", "cs", "MS/PhD", "研究生院"),
 "cancer-biology": ("癌症生物学", "Cancer Biology", "sci", "PhD", "医学院（基础研究）"),
 "/cdb/graduate-program": ("细胞与发育生物学", "Cell and Developmental Biology", "sci", "PhD", "医学院（基础研究）"),
 "/cpb/": ("化学与物理生物学", "Chemical and Physical Biology", "sci", "PhD", "医学院（基础研究）"),
 "chemical-biomolecular-engineering": ("化学与生物分子工程", "Chemical and Biomolecular Engineering", "eng", "MS/PhD", "工程学院"),
 "/chemistry/graduate": ("化学", "Chemistry", "sci", "PhD", "文理学院"),
 "child-studies-med": ("儿童研究", "Child Studies (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "civil-environmental-engineering/graduate-programs": ("土木与环境工程", "Civil and Environmental Engineering", "eng", "MS/PhD", "工程学院"),
 "cognitive-and-developmental-psychology": ("认知与发展心理学", "Cognitive and Developmental Psychology in Context", "edu", "MS", "Peabody 教育与人类发展学院"),
 "community-development-and-action-med": ("社区发展与行动", "Community Development and Action (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "community-research-action-phd": ("社区研究与行动", "Community Research and Action", "soc", "PhD", "Peabody 教育与人类发展学院"),
 "computer-science/graduate": ("计算机科学", "Computer Science", "cs", "MS", "工程学院"),
 "english/mfa": ("创意写作", "Creative Writing (MFA)", "art", "MFA", "文理学院"),
 "master-of-engineering-degree": ("工程硕士", "Master of Engineering", "eng", "MEng", "工程学院"),
 "datascience/msprogram": ("数据科学", "Data Science", "cs", "MS", "数据科学学院"),
 "earth-environmental-sciences": ("地球与环境科学", "Earth, Environmental and Planetary Sciences", "sci", "PhD", "文理学院"),
 "economics/about-ma-economics": ("经济学", "Economics (MA)", "soc", "MA", "文理学院"),
 "economics/phd-admissions": ("经济学", "Economics (PhD)", "soc", "PhD", "文理学院"),
 "education-policy-mpp": ("教育政策", "Education Policy (MPP)", "edu", "MPP", "Peabody 教育与人类发展学院"),
 "leadership-policy-studies-phd": ("领导与政策研究", "Leadership and Policy Studies", "edu", "PhD", "Peabody 教育与人类发展学院"),
 "electrical-computer-engineering": ("电气与计算机工程", "Electrical and Computer Engineering", "eng", "MS/PhD", "工程学院"),
 "elementary-education-med": ("初等教育", "Elementary Education (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "english/phd-admissions": ("英语语言文学", "English", "art", "PhD", "文理学院"),
 "masters-in-finance": ("金融学", "Finance (MFin)", "biz", "MFin", "Owen 商学院"),
 "higher-education-administration-med": ("高等教育管理", "Higher Education Administration (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "history/phd-admissions": ("历史学", "History", "art", "PhD", "文理学院"),
 "human-development-counseling-med": ("人类发展与咨询", "Human Development Counseling (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "humangenetics": ("人类遗传学", "Human Genetics", "sci", "PhD", "医学院（基础研究）"),
 "independent-school-leadership-med": ("独立学校领导", "Independent School Leadership (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "innovative-design-and-technology-in-education": ("创新设计与教育技术", "Innovative Design and Technology in Education", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "integrated-early-childhood-education": ("综合早期儿童教育", "Integrated Early Childhood Education (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "materials-science/graduate-program": ("材料科学", "Materials Science and Engineering", "eng", "MS/PhD", "工程学院"),
 "international-education-policy-and-management": ("国际教育政策与管理", "International Education Policy and Management (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "/mlas/": ("博雅研究", "Master of Liberal Arts", "art", "MLS", "文理学院"),
 "master-of-management/": ("管理学", "Master of Management", "biz", "MM", "Owen 商学院"),
 "master-of-marketing": ("市场营销", "Master of Marketing", "biz", "MMkt", "Owen 商学院"),
 "math/graduate": ("数学", "Mathematics", "sci", "PhD", "文理学院"),
 "mechanical-engineering/graduate-programs": ("机械工程", "Mechanical Engineering", "eng", "MS/PhD", "工程学院"),
 "medical-physics": ("医学物理", "Medical Physics", "sci", "MS/DMP", "医学院（基础研究）"),
 "medicine-health-society/ma": ("医学、健康与社会", "Medicine, Health and Society", "med", "MA", "文理学院"),
 "microbe-host-interactions": ("微生物-宿主相互作用", "Microbe-Host Interactions", "sci", "PhD", "医学院（基础研究）"),
 "/mpb/": ("分子生理学与生物物理", "Molecular Physiology and Biophysics", "sci", "PhD", "医学院（基础研究）"),
 "multilingual-and-multicultural-studies": ("多语言与多元文化研究", "Multilingual and Multicultural Studies", "edu", "MA", "Peabody 教育与人类发展学院"),
 "multilingual-education-med": ("多语言教育", "Multilingual Education (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "neuroscience/graduate-programs": ("神经科学", "Neuroscience", "sci", "PhD", "医学院（基础研究）"),
 "organizational-development-for-social-innovation": ("组织发展与社会创新", "Organizational Development for Social Innovation", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "philosophy/graduateprogram": ("哲学", "Philosophy", "art", "PhD", "文理学院"),
 "/physics/graduate": ("物理学", "Physics", "sci", "PhD", "文理学院"),
 "political-science/phd": ("政治学", "Political Science", "soc", "PhD", "文理学院"),
 "psychological_sciences": ("心理科学", "Psychological Sciences", "sci", "PhD", "文理学院"),
 "/mph/about": ("公共卫生", "Master of Public Health", "med", "MPH", "医学院（公共卫生）"),
 "quantitative-methods-and-data-analysis": ("量化方法与数据分析", "Quantitative Methods and Data Analysis", "edu", "MA", "Peabody 教育与人类发展学院"),
 "reading-education-med": ("阅读教育", "Reading Education (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "religious-studies/graduate": ("宗教研究", "Religious Studies", "art", "PhD", "文理学院"),
 "secondary-education-med": ("中等教育", "Secondary Education (M.Ed.)", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "sociology/graduate": ("社会学", "Sociology", "soc", "PhD", "文理学院"),
 "special-education-phd": ("特殊教育", "Special Education", "edu", "PhD", "Peabody 教育与人类发展学院"),
 "sped-high-incidence": ("特殊教育（高发障碍方向）", "Special Education - High Incidence Disabilities", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "sped-severe": ("特殊教育（重度障碍方向）", "Special Education - Severe Disabilities", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
 "sped-visual": ("特殊教育（视觉障碍方向）", "Special Education - Visual Impairments", "edu", "M.Ed.", "Peabody 教育与人类发展学院"),
}

from urllib.parse import urlparse
def slug_of(u):
    p=urlparse(u); host=p.hostname.split(".")[0]
    segs=[s for s in p.path.split("/") if s and not s.startswith("#")]
    tail=[s for s in segs if s not in ("graduate-programs","graduate-program","graduate-admissions","academic-curriculum-and-guidelines")]
    slug="-".join([host]+tail[-3:])
    return re.sub(r"[^a-z0-9]+","-",slug.lower()).strip("-") or "program"

def deg_of(u, default):
    if re.search(r"doctor-of-philosophy|/phd|phd-admissions|/phd/|doctoral", u, re.I): return "PhD"
    return default

catd, pages, missing, dropped = [], [], [], []
seen=set()
for x in raw:
    u=x["h"]
    if not re.search(r"vanderbilt\.edu", u): continue
    if any(b in u for b in DROP): dropped.append(u); continue
    hit=None
    for k,v in MAP.items():
        if k in u: hit=(k,v); break
    if not hit:
        missing.append(u); continue
    k,(cn,en,disc,deg,college)=hit
    deg=deg_of(u, deg)
    slug=slug_of(u)
    if slug in seen: continue
    seen.add(slug)
    det=f"details/{SID}-{slug}.html"
    catd.append([SID, college, en, cn, deg, u, disc, det])
    pages.append({"det":det,"cn":cn,"en":en,"college":college,"deg":deg,"url":u})

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">本项目为 Vanderbilt University 研究生院官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：Vanderbilt University 官方项目页 <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">📋 数据说明：本页名称 / 学院 / 学位均摘自 Vanderbilt University 官方页面（抓取日期 {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_vanderbilt_catd.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
json.dump(pages,open(os.path.join(BASE,"pending_vanderbilt_pages.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
from collections import Counter
print("保留:",len(catd)," 剔除:",len(dropped)," 未映射:",len(missing))
for m in missing: print("  MISS:",m)
print("disc:",dict(Counter(c[6] for c in catd)))
