# -*- coding: utf-8 -*-
"""UVA 目录级生成。学院分组继承；整组剔除继续职业教育/护理/法律。"""
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="UVA"; SID="uva"
LIST_URL="https://records.ureg.virginia.edu/content.php?catoid=44&navoid=3134"
raw=json.load(open(os.path.join(BASE,"raw_uva.json"),encoding="utf-8"))

COLLEGE_MAP={
 "Curry Graduate School of Education":"教育学院",
 "Darden Graduate School of Business Administration":"达顿商学院",
 "Data Science Institute":"数据科学研究所",
 "Frank Batten School of Leadership and Public Policy":"巴腾公共政策与领导学院",
 "Graduate School of Architecture":"建筑学院",
 "Graduate School of Arts and Sciences":"文理研究生院",
 "Graduate School of Commerce":"商学院",
 "Graduate School of Continuing and Professional Studies":"继续与职业教育学院",
 "Graduate School of Engineering and Applied Science":"工程与应用科学学院",
 "Graduate School of Nursing":"护理学院",
 "School of Law":"法学院",
 "School of Medicine":"医学院",
}
# 整组剔除
DROP_GROUP={"Graduate School of Continuing and Professional Studies","Graduate School of Nursing","School of Law"}

# 项目级剔除关键词
DROP_RES=[
 r"CERT|CRT",                                   # 证书/资格证
 r"M\.B\.A\.|D\.B\.A\.|Executive",             # MBA/DBA/高管
 r"J\.D\.|L\.L\.M\.|S\.J\.D\.",                # 法律职业学位
 r"M\.S\.N\.|D\.N\.P\.|Nursing",               # 护理
 r"\bM\.T\.",                                  # 教师资格硕士
 r"Ed\.S\.",                                   # 教育专家资格
 r"Clinical Psychology|Counselor Education|Communication Sciences",  # 临床心理/咨询/言语
 r"Kinesiology",                               # 运动机能学（边界剔除）
 r"Clinical Research|Experimental Pathology|Pharmacology|Physiology|Medicine\b",  # 临床/病理/药理/生理/MD
]

def drop(title, deg, college_key):
    if college_key in DROP_GROUP: return "整组剔除"
    for rx in DROP_RES:
        if re.search(rx, title+" "+deg, re.I): return rx
    return None

def split_deg(title, degstr):
    deg="MS"
    if re.search(r"Ed\.D\.|Doctor of Education", degstr): deg="EdD"
    elif re.search(r"Ph\.?D\.|PH\.D\.", degstr): deg="PhD"
    elif re.search(r"M\.P\.H\.|M\.P\.P\.|M\.F\.A\.|M\.A\.|M\.Ar\.H\.|M\.Arch\.|M\.L\.A\.|M\.U\.E\.P\.", degstr): deg="MA"
    name=re.sub(r",?\s*(M\.E\.|M\.S\.|M\.A\.|M\.P\.H\.|M\.P\.P\.|M\.F\.A\.|M\.C\.S\.|M\.Ar\.H\.|M\.Arch\.|M\.L\.A\.|M\.U\.E\.P\.|M\.M\.S\.E\.|M\.E\.P\.|Ph\.?D\.|PH\.D\.|Ed\.D\.|Ed\.S\.|M\.T\.|D\.B\.A\.|M\.B\.A\.|J\.D\.|L\.L\.M\.|S\.J\.D\.|M\.S\.N\.|D\.N\.P\.|M\.A\.P\.E\.|CERT-G?|CERT)(,?\s*[A-Za-z.]+)*$","",title).strip(" ,–-")
    if not name: name=title
    return name, deg

def disc_of(name, college_cn):
    n=name
    if re.search(r"Public Health|MPH|Health Policy|Epidemiology|Biostatistics",n): return "med"
    if re.search(r"Business|Commerce|Accounting|Global Commerce|Finance|Real Estate|Marketing|Management of Information",n): return "biz"
    if re.search(r"Computer Science|Data Science|Statistics|Cybersecurity",n): return "cs"
    if re.search(r"Engineering|Bioengineering|Civil|Mechanical|Aerospace|Electrical|Chemical|Materials|Systems Engineering|Engineering Physics|Biomolecular",n): return "eng"
    if re.search(r"Education|Educational|Higher Education|Curriculum|Special Education",n): return "edu"
    if re.search(r"Biology|Biochemistry|Biophysics|Chemistry|Physics|Astronomy|Astrophysics|Microbiology|Cell Biology|Neuroscience|Molecular|Environmental Sciences|Mathematics|Biological and Physical|Psychology",n): return "sci"
    if re.search(r"Economics|Government|Political|Sociology|Anthropology|Foreign Affairs|Public Policy|Urban|Planning|European Studies|East Asian|Middle Eastern|Gender|Religious|Linguistics|Social",n): return "soc"
    return "art"

def slugify(name):
    return re.sub(r"[^a-z0-9]+","-",name.lower()).strip("-")

catd,pages,dropped=[],[],[]
seen=set(); current=None
for i,x in enumerate(raw):
    if len(x)==1:
        key=x[0].strip()
        if key in COLLEGE_MAP: current=key
        continue
    if len(x)<4: continue
    title,degstr,credits,code=x[0],x[1],x[2],x[3]
    if not re.search(r"[A-Z]+-[A-Z0-9]",code): continue
    dr=drop(title,degstr,current)
    if dr: dropped.append((i,title,degstr,dr)); continue
    name,deg=split_deg(title,degstr)
    disc=disc_of(name,COLLEGE_MAP.get(current,""))
    slug=slugify(name)+("-phd" if deg=="PhD" else "-ms")
    if slug in seen: continue
    seen.add(slug)
    college=COLLEGE_MAP.get(current,current or "研究生院")
    det=f"details/{SID}-{slug}.html"
    catd.append([SID,college,name,name,deg,LIST_URL,disc,det])
    pages.append({"det":det,"cn":name,"en":name,"college":college,"deg":deg,"url":LIST_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 Virginia 官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：UVA Graduate Record 官方目录 <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">📋 数据说明：本页名称 / 学院 / 学位均摘自 UVA 官方页面（抓取日期 {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_uva_catd.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
json.dump(pages,open(os.path.join(BASE,"pending_uva_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)))
print("--- 剔除清单 ---")
for d in dropped: print("  ",d[3],"|",d[1],"|",d[2])
