# -*- coding: utf-8 -*-
"""UNC 目录级生成。剔除临床执业/牙科/护理/远程/社工/运动机能/病理药理毒理等。"""
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="UNC Chapel Hill"; SID="unc"
LIST_URL="https://catalog.unc.edu/graduate/degree-programs/"
rows=json.load(open(os.path.join(BASE,"raw_unc.json"),encoding="utf-8"))

COLLEGE_CN={
 "African, African-American, and Diaspora Studies":"非裔与非洲流散研究系",
 "American Studies":"美国研究系","Anthropology":"人类学系","Applied Physical Sciences":"应用物理科学研究所",
 "Art and Art History":"艺术与艺术史系","Asian and Middle Eastern Studies":"亚洲与中东研究系",
 "Biochemistry and Biophysics":"生化与生物物理系","Bioinformatics and Computational Biology":"生物信息与计算生物学项目",
 "Biology":"生物系","Biomedical Engineering":"生物医学工程系","Business Administration":"凯南-弗拉格勒商学院",
 "Cell Biology and Physiology":"细胞生物与生理系","Chemistry":"化学系","City and Regional Planning":"城市与区域规划系",
 "Classics":"古典学系","Clinical Rehabilitation and Mental Health Counseling":"康复与心理健康咨询系",
 "Communication":"传播系","Computer Science":"计算机科学系","Data and Information Science":"数据与信息学院",
 "Dentistry":"牙医学院","Dramatic Art":"戏剧艺术系","Earth, Marine, and Environmental Sciences":"地球海洋与环境科学系",
 "Economics":"经济系","Education":"教育学院","English and Comparative Literature":"英语与比较文学系",
 "Environment, Ecology and Energy":"环境生态与能源项目","Exercise and Sport Science":"运动与体育科学系",
 "Genetics and Molecular Biology":"遗传与分子生物学项目","Geography and Environment":"地理与环境系",
 "Germanic and Slavic Languages and Literature":"日耳曼与斯拉夫语言文学系","Global Studies":"全球研究项目",
 "Government":"政府系","History":"历史系","Human Movement Science":"人类运动科学系",
 "Journalism and Media":"新闻与媒体系","Linguistics":"语言学系","Mathematics":"数学系",
 "Microbiology and Immunology":"微生物与免疫系","Musicology":"音乐学系","Neuroscience":"神经科学项目",
 "Nursing":"护理学院","Occupational Science":"职业科学项目","Occupational Therapy":"职业治疗系",
 "Pathology":"病理系","Pharmacy":"药学院","Pharmacology":"药理系","Philosophy":"哲学系",
 "Physics and Astronomy":"物理与天文系","Political Science":"政治科学系","Psychology and Neuroscience":"心理与神经科学系",
 "Public Health":"公共卫生学院","Health Policy and Management":"公共卫生学院","Maternal and Child Health":"公共卫生学院",
 "Religious Studies":"宗教研究系","Romance Studies":"罗曼语研究系","Social Work":"社会工作系","Sociology":"社会学系",
 "Speech and Hearing Sciences":"言语与听力科学系","Statistics and Operations Research":"统计与运筹系",
 "Toxicology":"毒理系","Materials Science":"应用物理科学研究所","Applied Professional Studies":"应用专业研究项目",
}

DROP_NAME=[
 r"Dental|Endodontics|Operative Dentistry|Oral |Orthodontics|Pediatric Dentistry|Periodontology|Prosthodontics",  # 牙科临床
 r"Nursing|D\.N\.P\.|M\.S\.N\.",                                   # 护理
 r"Occupational Therapy|Speech and Hearing|Counseling|Rehabilitation|School Psychology|School Counseling",  # 治疗/咨询执业
 r"M\.A\.T\.|Master of Arts in Teaching",                          # 教师资格
 r"Exercise and Sport|Human Movement|Kinesiology",                  # 运动机能
 r"Pathology|Pharmacology|Toxicology|Physiology|Cell Biology and Physiology",  # 病理/药理/毒理/生理
 r"distance|Site-based",                                            # 名称标注远程
 r"Social Work|M\.S\.W\.",                                          # 社工执业
 r"Regulatory Science|Applied Professional Studies|M\.A\.P\.S\.",  # 应用职业/监管科学
 r"Public Health Leadership and Practice|Educational Leadership",  # 实践型领导/在职 EdD
]
DROP_DEG=[r"Trans-Atlantic", r"Executive Leadership"]              # 学位标注的远程/在职分支

def drop(name, deg):
    for rx in DROP_NAME:
        if re.search(rx, name, re.I): return rx
    for rx in DROP_DEG:
        if re.search(rx, deg, re.I): return rx
    return None

def split_deg(degstr):
    if re.search(r"Dr\.?P\.?H\.?|DrPH", degstr): return "DrPH"
    if re.search(r"Ph\.?D\.|PhD", degstr): return "PhD"
    if re.search(r"Ed\.D\.|Doctor of Education", degstr): return "EdD"
    if re.search(r"M\.P\.H\.|M\.S\.P\.H\.|M\.H\.A\.|M\.P\.A\.|M\.C\.R\.P\.|M\.F\.A\.|M\.A\.|M\.A\.D\.S\.", degstr): return "MA"
    return "MS"

def disc_of(name, college):
    n=name
    if re.search(r"Public Health|MPH|MSPH|Health Policy|Health Behavior|Epidemiology|Biostatistics|Nutrition|Maternal and Child|Environmental Sciences and Engineering",n): return "med"
    if re.search(r"Computer Science|Data Science|Statistics|Information Science|Library|Information and Library|Health Informatics|Bioinformatics|Computational",n): return "cs"
    if re.search(r"Engineering|Biomedical Engineering|Materials Science|Environmental Sciences and Engineering",n): return "eng"
    if re.search(r"Business|Commerce|Finance|Real Estate|Marketing",n): return "biz"
    if re.search(r"Biology|Biochemistry|Biophysics|Chemistry|Physics|Astronomy|Microbiology|Immunology|Cell|Neuroscience|Molecular|Genetics|Earth|Marine|Environmental|Mathematics|Occupational Science|Psychology|Pharmaceutical|Ecology|Energy",n): return "sci"
    if re.search(r"Economics|Government|Political|Sociology|Anthropology|Public Policy|City and Regional Planning|Geography|Global Studies|Asian|Middle Eastern|Religious|Linguistics|Communication|Media|Journalism|African|American Studies|Folklore|Gender",n): return "soc"
    if re.search(r"Education|Curriculum|Educational|School",n): return "edu"
    return "art"

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

catd,pages,dropped=[],[],[]; seen=set()
for r in rows:
    name,degstr,college_en,url=r["name"],r["deg"],r["college"],r["url"]
    dr=drop(name,degstr)
    if dr: dropped.append((name,degstr,dr)); continue
    deg=split_deg(degstr)
    disc=disc_of(name,college_en)
    college=COLLEGE_CN.get(college_en, college_en or "研究生院")
    slug=slugify(name)+("-phd" if deg=="PhD" else "-ms")
    if slug in seen: continue
    seen.add(slug)
    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 North Carolina at Chapel Hill 官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：UNC-Chapel Hill Graduate Catalog 官方目录 <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">📋 数据说明：本页名称 / 学院 / 学位均摘自 UNC 官方页面（抓取日期 {TODAY}，对应 2027 申请季）。申请截止、语言、标化、学费等字段待逐项核验后补充展示，核验前不做估算填充；官网未公布的字段整项不展示。</div></div>
</body></html>"""

if "--write" in sys.argv:
    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_unc_catd.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
    json.dump(pages,open(os.path.join(BASE,"pending_unc_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 c in catd:
    print(f"{c[6]:4}|{c[4]:5}|{c[1][:20]:20}|{c[2]}")
print("--- 剔除 ---")
for d in dropped: print("  ",d[2],"|",d[0],"|",d[1])
