# -*- coding: utf-8 -*-
"""Georgetown 目录级生成：剔 MBA/EMBA/本科/LLM/证书/护理执业/临床转化/在职在线 MPS·MSF。"""
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="Georgetown University"; SID="geo"
LIST_URL="https://grad.georgetown.edu/programs/"
raw=json.load(open(os.path.join(BASE,"raw_georgetown.json"),encoding="utf-8"))

# 1-based 显式剔除索引（在职在线 / MBA / 本科 / LLM / 证书 / 护理执业 / 临床转化 / 职业型 MPS·MSF）
DROP_IDX={2,3,6,12,16,22,24,25,26,27,30,31,32,33,35,39,44,48,51,57,58,59,64,70,74}

SCHOOL_CN_MAP={
 "College of Arts & Sciences":"文理学院","Walsh School of Foreign Service":"外交学院（SFS）",
 "McDonough School of Business":"麦克多诺商学院","McCourt School of Public Policy":"麦考特公共政策学院",
 "School of Health":"健康学院","School of Medicine":"医学院（生物医学）",
 "School of Continuing Studies":"继续教育学院","Georgetown Law":"法学院",
 "Berkley School of Nursing":"护理学院",
 "McDonough School of Business, Walsh School of Foreign Service":"商学院·外交学院联合",
}

CN={
 "Addiction Policy & Practice":"成瘾政策与实践","American Government":"美国政府与政治学","Applied Economics":"应用经济学",
 "Applied Mathematics":"应用数学","Arab Studies":"阿拉伯研究","Arabic & Islamic Studies":"阿拉伯语与伊斯兰研究",
 "Art & Museum Studies":"艺术与博物馆研究","Asian Studies":"亚洲研究","Biochemistry & Molecular Biology":"生物化学与分子生物学",
 "Biochemistry and Molecular & Cellular Biology":"生物化学与分子细胞生物学","Biohazardous Threat Agents & Emerging Infectious Diseases":"生物威胁因子与新发传染病",
 "Bioinformatics":"生物信息学","Biology":"生物学","Biostatistics":"生物统计学","Biotechnology":"生物技术",
 "Chemistry":"化学","Climate, Environment and Health":"气候、环境与健康","Communication, Culture & Technology":"传播、文化与技术",
 "Computer Science":"计算机科学","Conflict Resolution":"冲突解决","Cybersecurity Risk Management":"网络安全风险管理",
 "Data Science & Analytics":"数据科学与分析","Data Science for Public Policy":"公共政策数据科学","Democracy & Governance":"民主与治理",
 "Economics":"经济学","Educational Transformation":"教育转型","Engaged & Public Humanities":"参与式公共人文",
 "English":"英语语言文学","Environment & International Affairs":"环境与国际事务","Environment & Sustainability Management":"环境与可持续管理",
 "Epidemiology":"流行病学","Eurasian, Russian & East European Studies":"欧亚、俄罗斯与东欧研究","European Studies":"欧洲研究",
 "Foreign Service":"外交研究","German":"德语语言文学","Global Health":"全球健康","Global Human Development":"全球人类发展",
 "Global Infectious Disease":"全球传染病","Global Real Assets":"全球不动产与实物资产","Global, International & Comparative History":"全球、国际与比较历史",
 "Government":"政治学","Health Informatics & Data Science":"健康信息学与数据科学","Higher Education Administration":"高等教育管理",
 "Financial Economics":"金融经济学",
}

def disc_of(name):
    n=name
    if re.search(r"Computer Science|Data Science|Analytics|Bioinformatics|Cybersecurity|Health Informatics",n): return "cs"
    if re.search(r"Real Assets|Sustainability Management|Environment & Sustainability",n): return "biz"
    if re.search(r"Epidemiology|Global Health|Infectious Disease|Climate, Environment|Addiction",n): return "med"
    if re.search(r"Biology|Biochemistry|Biostatistics|Biotechnology|Chemistry|Mathematics|Biohazardous|Molecular",n): return "sci"
    if re.search(r"Government|Economics|Conflict Resolution|Democracy|Foreign Service|International Affairs|Human Development|Eurasian|European Studies|Asian Studies|Arab Studies|Financial Economics",n): return "soc"
    if re.search(r"Educational|Higher Education",n): return "edu"
    return "art"

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

catd,pages,dropped=[],[],[]
seen=set()
for i,x in enumerate(raw, start=1):
    title=x["title"].strip()
    # 拆学位后缀
    m=re.match(r"^(.*?),\s*(Master's|Doctorate|Graduate Certificate|Certificate|LLM|Bachelor's|Master’s|Executive [^,]*)$", title)
    if not m:
        dropped.append((i,title,"后缀未识别")); continue
    name,deg_suf=m.group(1).strip(),m.group(2)
    if i in DROP_IDX:
        dropped.append((i,title,"显式剔除")); continue
    if "Certificate" in deg_suf or "LLM" in deg_suf or "Bachelor" in deg_suf:
        dropped.append((i,title,"证书/法律职业/本科")); continue
    is_phd = deg_suf=="Doctorate"
    disc=disc_of(name)
    deg="PhD" if is_phd else ("MS" if disc in ("cs","eng","biz","sci","med") else "MA")
    school=x["school"]; college=SCHOOL_CN_MAP.get(school, school)
    slug=slugify(name)+("-phd" if is_phd else "-ms")
    if slug in seen: continue
    seen.add(slug)
    url=x.get("url") or LIST_URL
    if not url or url=="": url=LIST_URL
    det=f"details/{SID}-{slug}.html"
    cn=CN.get(name,name)
    catd.append([SID, college, name, cn, deg, url, disc, det])
    pages.append({"det":det,"cn":cn,"en":name,"college":college,"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">本项目为 Georgetown University 官方招生项目，授予所列学位方向；具体课程设置、研究领域与申请要求详见官方项目页。目录层先收录项目名称、所属学院与学位类别，字段级信息待逐项核验后补充。</div><div class="note">来源：Georgetown University Graduate Studies 官方项目目录 <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">📋 数据说明：本页名称 / 学院 / 学位均摘自 Georgetown 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_geo_catd.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=1)
json.dump(pages,open(os.path.join(BASE,"pending_geo_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[0],d[1][:40],"|",d[2])
