# -*- coding: utf-8 -*-
"""Brown Graduate Programs 目录级生成：剔在线/MD/双学位/EMBA/在职职业硕士。"""
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 = "Brown University"
SID = "brown"

DROP_SLUG = {
 "biostatistics-online-scm", "business-analytics-online-scm",
 "data-science-policy-governance-society-online-scm", "management-online-mim",
 "organizational-leadership-online-scm", "public-health-online-mph", "public-policy-online-mpp",
 "doctor-medicine-md", "mdphd", "primary-care-population-medicine-program-md-scm",
 "public-health-and-public-affairs-dual-degree-mpa-mph", "ie-brown-executive-mba-executive-master",
 "healthcare-leadership-scm", "technology-leadership-scm",
 "innovation-management-and-entrepreneurship-scm",
 "innovation-management-and-entrepreneurship-online-scm", "medical-sciences-scm",
}

# slug -> (cn, disc, college)
MAP = {
 "africana-studies-phd": ("非裔研究", "art", "人文与科学学院"),
 "american-studies-phd": ("美国研究", "art", "人文与科学学院"),
 "anthropology-phd": ("人类学", "soc", "人文与科学学院"),
 "applied-mathematics-phd": ("应用数学", "sci", "人文与科学学院"),
 "archaeology-and-ancient-world-phd": ("考古与古代世界", "art", "人文与科学学院"),
 "computer-science-scm-ai-ml-track": ("计算机科学（AI 与机器学习方向）", "cs", "工程学院"),
 "behavioral-and-social-health-sciences-phd": ("行为与社会健康科学", "med", "公共卫生学院"),
 "biomed-ecology-evolution-and-organismal-biology-phd": ("生态、进化与有机生物学", "sci", "生物医学部"),
 "biomed-molecular-biology-cell-biology-and-biochemistry-phd": ("分子生物学、细胞生物学与生物化学", "sci", "生物医学部"),
 "biomed-neuroscience-phd": ("神经科学", "sci", "生物医学部"),
 "biomed-pathobiology-phd": ("病理生物学", "sci", "生物医学部"),
 "biomed-therapeutic-sciences-phd": ("治疗科学", "sci", "生物医学部"),
 "biomedical-engineering-meng-scm": ("生物医学工程", "eng", "工程学院"),
 "biomedical-engineering-phd": ("生物医学工程", "eng", "工程学院"),
 "biostatistics-am-scm": ("生物统计学", "cs", "公共卫生学院"),
 "biostatistics-phd": ("生物统计学", "cs", "公共卫生学院"),
 "biotechnology-am-scm": ("生物技术", "sci", "生物医学部"),
 "chemical-engineering-scm": ("化学工程", "eng", "工程学院"),
 "chemistry-phd": ("化学", "sci", "人文与科学学院"),
 "classics-phd": ("古典学", "art", "人文与科学学院"),
 "cognitive-science-phd": ("认知科学", "sci", "人文与科学学院"),
 "comparative-literature-phd": ("比较文学", "art", "人文与科学学院"),
 "computational-biology-phd": ("计算生物学", "sci", "生物医学部"),
 "computer-science-phd": ("计算机科学", "cs", "工程学院"),
 "computer-science-scm": ("计算机科学", "cs", "工程学院"),
 "cybersecurity-scm": ("网络安全", "cs", "工程学院"),
 "data-science-scm": ("数据科学", "cs", "工程学院"),
 "data-enabled-computational-engineering-and-science-scm": ("数据驱动计算工程与科学", "eng", "工程学院"),
 "design-engineering-am": ("设计工程", "art", "工程学院"),
 "earth-environmental-and-planetary-sciences-phd": ("地球、环境与行星科学", "sci", "人文与科学学院"),
 "economics-phd": ("经济学", "soc", "人文与科学学院"),
 "education-master-arts-teaching-mat": ("教育（教学文学硕士）", "edu", "教育学院"),
 "education-urban-education-policy-am": ("城市教育政策", "edu", "教育学院"),
 "egyptology-and-assyriology-phd": ("埃及学与亚述学", "art", "人文与科学学院"),
 "electrical-and-computer-engineering-scm": ("电气与计算机工程", "eng", "工程学院"),
 "engineering-am-meng-scm": ("工程", "eng", "工程学院"),
 "engineering-phd": ("工程", "eng", "工程学院"),
 "english-phd": ("英语语言文学", "art", "人文与科学学院"),
 "environmental-engineering-scm": ("环境工程", "eng", "工程学院"),
 "epidemiology-phd": ("流行病学", "med", "公共卫生学院"),
 "french-and-francophone-studies-phd": ("法语与法语区研究", "art", "人文与科学学院"),
 "german-studies-phd": ("德语研究", "art", "人文与科学学院"),
 "health-informatics-and-ai-scm": ("健康信息学与 AI", "med", "公共卫生学院"),
 "health-services-research-phd": ("健康服务研究", "med", "公共卫生学院"),
 "hispanic-studies-phd": ("西班牙语研究", "art", "人文与科学学院"),
 "history-phd": ("历史学", "art", "人文与科学学院"),
 "history-art-and-architecture-phd": ("艺术与建筑史", "art", "人文与科学学院"),
 "integrative-studies-am-scm": ("综合研究", "art", "人文与科学学院"),
 "italian-studies-phd": ("意大利研究", "art", "人文与科学学院"),
 "literary-arts-mfa": ("文学艺术", "art", "人文与科学学院"),
 "materials-science-and-engineering-scm": ("材料科学与工程", "eng", "工程学院"),
 "mathematics-phd": ("数学", "sci", "人文与科学学院"),
 "mechanical-engineering-and-applied-mechanics-scm": ("机械工程与应用力学", "eng", "工程学院"),
 "medical-physics-scm": ("医学物理", "sci", "生物医学部"),
 "modern-culture-and-media-phd": ("现代文化与媒体", "art", "人文与科学学院"),
 "music-and-multimedia-composition-phd": ("音乐与多媒体作曲", "art", "人文与科学学院"),
 "musicology-and-ethnomusicology-phd": ("音乐学与民族音乐学", "art", "人文与科学学院"),
 "philosophy-phd": ("哲学", "art", "人文与科学学院"),
 "physics-scm": ("物理学", "sci", "人文与科学学院"),
 "physics-phd": ("物理学", "sci", "人文与科学学院"),
 "political-science-phd": ("政治学", "soc", "人文与科学学院"),
 "portuguese-and-brazilian-studies-phd": ("葡萄牙与巴西研究", "art", "人文与科学学院"),
 "psychology-phd": ("心理学", "sci", "人文与科学学院"),
 "public-affairs-mpa": ("公共事务", "soc", "公共卫生学院"),
 "public-health-mph": ("公共卫生", "med", "公共卫生学院"),
 "public-health-accelerated-mph": ("公共卫生（加速项目）", "med", "公共卫生学院"),
 "public-humanities-integrative-studies-am": ("公共人文（综合研究）", "art", "人文与科学学院"),
 "religious-studies-phd": ("宗教研究", "art", "人文与科学学院"),
 "slavic-studies-phd": ("斯拉夫研究", "art", "人文与科学学院"),
 "social-data-analytics-scm": ("社会数据分析", "cs", "人文与科学学院"),
 "sociology-phd": ("社会学", "soc", "人文与科学学院"),
 "sustainable-energy-scm": ("可持续能源", "eng", "工程学院"),
 "theatre-arts-and-performance-studies-phd": ("戏剧艺术与表演研究", "art", "人文与科学学院"),
 "theatre-arts-and-performance-studies-mfa": ("戏剧艺术与表演研究", "art", "人文与科学学院"),
 "theatre-arts-and-performance-studies-playwriting-mfa": ("戏剧编剧", "art", "人文与科学学院"),
 "theatre-browntrinity-rep-acting-and-directing-mfa": ("布朗/Trinity Rep 表演与导演", "art", "人文与科学学院"),
}

def norm_deg(slug, deg_raw):
    if slug.endswith("-phd"): return "PhD"
    d = (deg_raw or "")
    d = d.replace("Ph.D.", "PhD").replace("Sc.M.", "ScM").replace("A.M.", "AM").replace("M.Eng.", "MEng")
    d = re.sub(r"\s*,\s*", "/", d).strip()
    return d or "ScM"

raw = json.load(open(os.path.join(BASE, "raw_brown.json"), encoding="utf-8"))
catd, pages, missing, dropped = [], [], [], []

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

for item in raw:
    slug = item["h"].rstrip("/").split("/")[-1]
    if slug in DROP_SLUG:
        dropped.append(slug); continue
    if slug not in MAP:
        missing.append(slug); continue
    cn, disc, college = MAP[slug]
    deg = norm_deg(slug, item.get("deg", ""))
    en = item["t"].strip() or slug.replace("-", " ").title()
    det = f"details/{SID}-{slug}.html"
    url = item["h"]
    catd.append([SID, college, en, cn, deg, url, disc, det])
    pages.append({"det": det, "cn": cn, "en": en, "college": college, "deg": deg, "url": url})
    with open(os.path.join(DET, f"{SID}-{slug}.html"), "w", encoding="utf-8", newline="") as f:
        f.write(TPL.format(cn=html.escape(cn), en=html.escape(en), college=html.escape(college),
                          deg=html.escape(deg), url=html.escape(url, quote=True),
                          school_cn=SCHOOL_CN, school_en=SCHOOL_EN, TODAY=TODAY))

json.dump(catd, open(os.path.join(BASE, "pending_brown_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_brown_pages.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

from collections import Counter
print("保留:", len(catd), " 剔除:", len(dropped), " 未映射:", missing)
print("disc:", dict(Counter(c[6] for c in catd)))
