# -*- coding: utf-8 -*-
"""Caltech 研究生选项目录级生成：sitemap 31 项；无 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 = "California Institute of Technology"
SID = "caltech"

# slug -> (cn, disc, college, short_slug, deg_override)
MAP = {
 "aerospace-ae": ("航空航天工程", "eng", "工程与应用科学分部", "aerospace", None),
 "applied-and-computational-mathematics-acm": ("应用与计算数学", "sci", "工程与应用科学分部", "applied-computational-mathematics", None),
 "applied-mechanics-am": ("应用力学", "eng", "工程与应用科学分部", "applied-mechanics", None),
 "applied-physics-aph": ("应用物理", "sci", "工程与应用科学分部", "applied-physics", None),
 "astrophysics-ay": ("天体物理学", "sci", "物理、数学与天文分部", "astrophysics", None),
 "biochemistry-and-molecular-biophysics-bmb": ("生物化学与分子生物物理", "sci", "生物与生物工程分部", "biochemistry-molecular-biophysics", None),
 "bioengineering-be": ("生物工程", "eng", "生物与生物工程分部", "bioengineering", None),
 "biology-bi": ("生物学", "sci", "生物与生物工程分部", "biology", None),
 "chemical-engineering-che": ("化学工程", "eng", "化学与化学工程分部", "chemical-engineering", None),
 "chemistry-ch": ("化学", "sci", "化学与化学工程分部", "chemistry", None),
 "civil-engineering-ce": ("土木工程", "eng", "工程与应用科学分部", "civil-engineering", None),
 "computation-and-neural-systems-cns": ("计算与神经系统", "cs", "工程与应用科学分部", "computation-neural-systems", None),
 "computational-science-and-engineering-cse": ("计算科学与工程", "eng", "工程与应用科学分部", "computational-science-engineering", None),
 "computer-science-cs": ("计算机科学", "cs", "工程与应用科学分部", "computer-science", None),
 "computing-and-mathematical-science-cms": ("计算与数学科学", "cs", "工程与应用科学分部", "computing-mathematical-science", None),
 "control-and-dynamical-systems-cds": ("控制与动力系统", "eng", "工程与应用科学分部", "control-dynamical-systems", None),
 "electrical-engineering-ee": ("电气工程", "eng", "工程与应用科学分部", "electrical-engineering", None),
 "environmental-science-and-engineering-ese": ("环境科学与工程", "eng", "工程与应用科学分部", "environmental-science-engineering", None),
 "geological-and-planetary-sciences-gps-geology-geobiology-geochemistry-geophysics-planetary-science": ("地质与行星科学", "sci", "地质与行星科学分部", "geological-planetary-sciences", None),
 "history-and-philosophy-of-science-hps": ("科学史与科学哲学", "art", "人文与社会科学分部", "history-philosophy-science", None),
 "history-h": ("历史学", "art", "人文与社会科学分部", "history", None),
 "information-and-data-science-ids": ("信息与数据科学", "cs", "工程与应用科学分部", "information-data-science", None),
 "materials-science-ms": ("材料科学", "eng", "工程与应用科学分部", "materials-science", None),
 "mathematics-ma": ("数学", "sci", "物理、数学与天文分部", "mathematics", None),
 "mechanical-engineering-me": ("机械工程", "eng", "工程与应用科学分部", "mechanical-engineering", None),
 "medical-engineering-mede": ("医学工程", "eng", "生物与生物工程分部", "medical-engineering", None),
 "neurobiology-nb": ("神经生物学", "sci", "生物与生物工程分部", "neurobiology", None),
 "physics-ph": ("物理学", "sci", "物理、数学与天文分部", "physics", None),
 "quantum-science-and-engineering-qse": ("量子科学与工程", "eng", "物理、数学与天文分部", "quantum-science-engineering", None),
 "social-and-decision-neuroscience-sdn": ("社会与决策神经科学", "soc", "人文与社会科学分部", "social-decision-neuroscience", None),
 "social-science-ss": ("社会科学", "soc", "人文与社会科学分部", "social-science", "PhD"),
}

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

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

for item in raw:
    slug = item["href"].rstrip("/").split("/")[-1]
    if slug not in MAP:
        missing.append(slug); continue
    cn, disc, college, short, deg_ov = MAP[slug]
    deg = deg_ov or item["deg"]
    en = re.sub(r"\s*\([A-Z][A-Za-z/ ]*\)$", "", item["text"]).replace(" and Minor", "").strip()
    det = f"details/{SID}-{short}.html"
    url = item["href"]
    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}-{short}.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_caltech_catd.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(pages, open(os.path.join(BASE, "pending_caltech_pages.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

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