# -*- coding: utf-8 -*-
"""Round 307: USC Econ/Math/ChemE PhD + NYU Econ/Courant Math PhD."""
import re, os

ROOT = r"D:\work buddy\2026-11-05-14-15-52"
IDX = os.path.join(ROOT, "index_main.html")

PAGES = [
    {
        "id": "usc-econ-phd",
        "s": "usc",
        "n": "经济学博士",
        "en": "Economics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 年",
        "ddl": "2026-12-01",
        "lang": "TOEFL 100/IELTS 7.0",
        "test_cls": "GRE General REQUIRED（Verbal 150+ / Quant 160+ 基准，典型录取 Quant 165-170；GMAT 不接受）",
        "tui": "PhD 全额资助：学费全免 + stipend + 医保（每年约 12 个名额，竞争激烈）",
        "url": "details/usc-econ-phd.html",
        "school": "University of Southern California",
        "dept": "Department of Economics",
        "college": "Dornsife College of Letters, Arts and Sciences",
        "website": "https://dornsife.usc.edu/econ/doctoral/admissions/",
        "overview": "南加州大学经济学博士项目（Economics PhD）由 Dornsife 文理学院经济系开设，强调经济理论、计量经济学与应用经济分析。每年收到数百份申请，录取约 12 人，录取学生全额资助。STEM-designated，F-1 学生可申请 24 个月 OPT 延期。",
        "requirements": "要求经济学或相关本科背景；中级微观/宏观经济学、一年微积分、一学期统计学为最低先修；PhD 申请者通常需要更强的数学准备（实分析、复分析、微分方程、线性代数）；3 封推荐信；SOP（2-3 页 double-spaced）；CV；官方成绩单；TOEFL 100/IELTS 7.0。仅 Fall 入学。",
        "research": "研究方向包括：微观经济理论；宏观经济学；计量经济学；国际经济学与发展经济学；城市与区域经济学；政治经济学；劳动经济学；产业组织；行为经济学；计算经济学。",
    },
    {
        "id": "usc-math-phd",
        "s": "usc",
        "n": "数学博士",
        "en": "Mathematics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 年",
        "ddl": "2026-12-15",
        "lang": "TOEFL（国际生，USC 统一标准）",
        "test_cls": "GRE General 不要求也不审核；GRE Mathematics Subject Test 可选提交（非传统背景学生建议提交，提交后纳入审核）",
        "tui": "5 年资助包：1 年 Fellowship + 4 年 Teaching Assistantship + 全学费减免 + 医保与牙科保险",
        "url": "details/usc-math-phd.html",
        "school": "University of Southern California",
        "dept": "Department of Mathematics",
        "college": "Dornsife College of Letters, Arts and Sciences",
        "website": "https://dornsife.usc.edu/mathematics/admissions/",
        "overview": "南加州大学数学博士项目（Mathematics PhD）是 Dornsife 数学系开设的 5 年研究型博士，提供 Mathematics PhD 与 Applied Mathematics PhD 两个学位路径。项目以核心课程 + 笔试筛选 + 导师指导研究为特色，录取学生均获 5 年全额资助。",
        "requirements": "要求数学或相关本科背景；3 封推荐信（至少 2 封来自数学/理科课程教师）；SOP；CV；官方成绩单；TOEFL（国际生）。Screening Exam 需从 5 门核心科目（Algebra、Real/Complex Analysis、ODE/PDE、Geometry/Topology、Probability/Statistics）中通过 3 门，其中一门必须是 Algebra 或 Analysis。需修满 60 学分研究生课程（B- 以上）。外语要求：中文/法语/德语/日语/俄语数学阅读考试。",
        "research": "研究方向包括：代数几何；算术几何；组合数学；复几何；控制论；微分方程；微分几何；动力系统；泛函分析；几何分析；群论；数学物理；数值分析；概率与统计；拓扑学；应用数学。",
    },
    {
        "id": "usc-cheme-phd",
        "s": "usc",
        "n": "化学工程博士",
        "en": "Chemical Engineering PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 年",
        "ddl": "2026-12-15",
        "lang": "TOEFL/IELTS（USC Viterbi 统一标准）",
        "test_cls": "GRE General 不要求（USC Viterbi 2027 政策：除 ASTE 和 ISE 外所有 PhD 项目均不要求 GRE）",
        "tui": "PhD 全额资助：学费全免 + stipend + 医保（Mork Family Department）",
        "url": "details/usc-cheme-phd.html",
        "school": "University of Southern California",
        "dept": "Mork Family Department of Chemical Engineering and Materials Science",
        "college": "Viterbi School of Engineering",
        "website": "https://viterbigradadmission.usc.edu/doctoral/how-to-apply-phd/",
        "overview": "南加州大学化学工程博士项目（Chemical Engineering PhD）由 Viterbi 工程学院 Mork Family Department of Chemical Engineering and Materials Science 开设，涵盖能源、材料、反应工程、纳米技术、高分子、生物工程与先进计算等方向。仅 Fall 入学，录取学生需展示研究经历。",
        "requirements": "要求工程、数学或硬科学本科背景；3 封推荐信（来自了解研究能力的教师）；SOP；CV；官方成绩单；TOEFL/IELTS（国际生）；护照复印件（国际生）。需展示研究能力与经历。USC 本科毕业者免 TOEFL。",
        "research": "研究方向包括：能源与可持续城市；健康与医疗；数据科学与机器学习；量子材料与系统；先进材料与制造；半导体材料与纳米结构；先进陶瓷与金属复合材料；生物技术；膜分离；反应器设计；石油与天然气勘探。",
    },
    {
        "id": "nyu-econ-phd",
        "s": "nyu",
        "n": "经济学博士",
        "en": "Economics PhD (GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 年",
        "ddl": "2026-12-18",
        "lang": "TOEFL/IELTS（NYU GSAS 标准，非英语母语者需提交）",
        "test_cls": "GRE General REQUIRED（所有 PhD 项目均要求；MS Quantitative Economics 接受 GRE/GMAT 二选一）",
        "tui": "PhD 全额资助：学费全免 + stipend + 医保（MacCracken Fellowship 或 TA/RA）",
        "url": "details/nyu-econ-phd.html",
        "school": "New York University",
        "dept": "Department of Economics",
        "college": "Graduate School of Arts and Science (GSAS)",
        "website": "https://as.nyu.edu/departments/econ/graduate/phd.html",
        "overview": "纽约大学经济学博士项目（Economics PhD）由 GSAS 经济系开设，是全美顶尖经济学博士项目之一。系里有 7 位 Econometric Society Fellow 和 1 位诺贝尔奖得主，Tilburg 大学排名全美前十。项目要求 72 学分（至少 64 学分在 NYU 完成），通过微观和宏观两门资格考试，完成两个专业方向，撰写三年级论文并答辩博士论文。",
        "requirements": "要求经济学或相关本科背景；单变量与多变量微积分、线性代数、概率与统计学为先修；许多申请者有微分方程和拓扑学基础；3 封推荐信；SOP（不超过 2 页 double-spaced）；CV；官方成绩单；GRE General（必填）；TOEFL/IELTS（非英语母语者）。Writing sample 不要求但鼓励提交原创研究。仅全日制。",
        "research": "研究方向包括：经济理论（含博弈论）；货币理论与宏观经济学；政治经济学；计量经济学；产业组织；国际经济学；劳动经济学；发展经济学；实验经济学；行为经济学；金融学；公共经济学。",
    },
    {
        "id": "nyu-math-phd",
        "s": "nyu",
        "n": "数学博士（Courant研究所）",
        "en": "Mathematics PhD (Courant Institute)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 年",
        "ddl": "2027-01-04",
        "lang": "TOEFL 100+/IELTS（非英语母语者需提交；英语授课学位可豁免）",
        "test_cls": "GRE General + Mathematics Subject Test 均为可选提交（提交视为有用信息，不提交不会劣势；非传统背景学生建议提交）",
        "tui": "MacCracken Fellowship：9 个月 stipend + 全学费 + 医保，最长可续 5 年（基于学术 merit）",
        "url": "details/nyu-math-phd.html",
        "school": "New York University",
        "dept": "Courant Institute of Mathematical Sciences, Department of Mathematics",
        "college": "Graduate School of Arts and Science (GSAS)",
        "website": "https://math.nyu.edu/dynamic/graduate/phd-mathematics/admission-policies/",
        "overview": "纽约大学数学博士项目（Mathematics PhD）由 Courant Institute of Mathematical Sciences 开设，是全球应用数学与纯数学顶尖研究所。项目要求 72 学分（第 4 学年末完成），通过三门书面资格考试（Advanced Calculus、Linear Algebra、Complex Analysis），口试通过后撰写博士论文并公开答辩。学生可选择在纽约或 NYU Shanghai 做研究。",
        "requirements": "要求数学或相关本科背景；3 封推荐信（至少 2 封来自数学/理科课程教师）；SOP；CV；官方成绩单；TOEFL 100+/IELTS（非英语母语者）。ETS code: 2596 (GSAS)，dept code 0703 (GRE)，72 (TOEFL)。书面资格考试每年 5 月和 1 月各一次，每门 3 小时，覆盖本科水平内容。需保持 GPA 3.0+。",
        "research": "研究方向包括：纯数学（代数、分析、几何、拓扑、数论）；应用数学；数值分析；科学计算；数学物理；概率论；偏微分方程；动力系统；机器学习与数据科学；金融数学；生物学数学建模。",
    },
]

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} - {en} | {school}</title>
<style>
body{{font-family:-apple-system,"Segoe UI",sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{color:#8C1515;border-bottom:3px solid #8C1515;padding-bottom:8px}}
h2{{color:#2e0e0e;margin-top:28px;border-left:4px solid #8C1515;padding-left:10px}}
.cards{{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px;margin:18px 0}}
.card{{background:#faf7f3;border:1px solid #e6d9c8;border-radius:8px;padding:14px 16px}}
.card h3{{margin:0 0 8px;color:#8C1515;font-size:15px}}
.card .v{{font-size:14px}}
a{{color:#0066cc}}
</style>
</head>
<body>
<h1>{school} · {n}</h1>
<p><b>英文名：</b>{en}　|　<b>学位：</b>{deg}　|　<b>学院：</b>{college}　|　<b>系所：</b>{dept}</p>
<p><b>官网：</b><a href="{website}" target="_blank">{website}</a></p>

<div class="cards">
<div class="card"><h3>申请截止</h3><div class="v">{ddl}（2026-2027 入学季）</div></div>
<div class="card"><h3>语言要求</h3><div class="v">{lang}</div></div>
<div class="card"><h3>标化政策</h3><div class="v">{test_cls}</div></div>
<div class="card"><h3>学费与资助</h3><div class="v">{tui}</div></div>
<div class="card"><h3>学制</h3><div class="v">{dur}</div></div>
<div class="card"><h3>STEM</h3><div class="v">{stem_label}</div></div>
</div>

<h2>项目概览</h2>
<p>{overview}</p>

<h2>申请要求</h2>
<p>{requirements}</p>

<h2>研究方向</h2>
<p>{research}</p>

<p><i>数据来源：{school} 官方项目页 / Graduate Admissions；2026-12-01 核验。录取分数分布仅作参考，非最低门槛。</i></p>
</body>
</html>
"""

def render_page(p):
    stem_label = "STEM-designated，符合 36 个月 OPT 延期资格" if p["stem"] == 1 else "非 STEM"
    return TEMPLATE.format(
        n=p["n"], en=p["en"], school=p["school"], deg=p["deg"],
        college=p["college"], dept=p["dept"], website=p["website"],
        ddl=p["ddl"], lang=p["lang"], test_cls=p["test_cls"],
        tui=p["tui"], dur=p["dur"], stem_label=stem_label,
        overview=p["overview"], requirements=p["requirements"], research=p["research"],
    )

def main():
    with open(IDX, "r", encoding="utf-8") as f:
        html = f.read()
    before = len(html.encode("utf-8"))

    new_prog = []
    for p in PAGES:
        out = os.path.join(ROOT, p["url"].replace("/", os.sep))
        os.makedirs(os.path.dirname(out), exist_ok=True)
        with open(out, "w", encoding="utf-8") as f:
            f.write(render_page(p))
        print(f"Written: {p['url']}")
        new_prog.append(
            '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},tui:"{tui}",url:"{url}"}}'.format(
                id=p["id"], s=p["s"], n=p["n"], en=p["en"], deg=p["deg"],
                lvl=p["lvl"], stem=p["stem"], dur=p["dur"], ddl=p["ddl"],
                lang=p["lang"], test_cls=p["test_cls"], tui=p["tui"], url=p["url"],
            )
        )

    m = re.search(r"const PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS not found")
    depth = 1
    i = m.end()
    while i < len(html) and depth > 0:
        c = html[i]
        if c == "[": depth += 1
        elif c == "]": depth -= 1
        i += 1
    prog_end = i - 1
    insert_block = "," + ",".join(new_prog) + "\n"
    html = html[:prog_end] + insert_block + html[prog_end:]

    m2 = re.search(r"const VERIFIED_DETAILS\s*=\s*new\s*Set\(\[", html)
    if not m2:
        raise RuntimeError("VD not found")
    depth = 1
    j = m2.end()
    while j < len(html) and depth > 0:
        c = html[j]
        if c == "[": depth += 1
        elif c == "]": depth -= 1
        j += 1
    vd_close_bracket = j - 1
    vd_new_urls = ",".join(f'"{p["url"]}"' for p in PAGES)
    html = html[:vd_close_bracket] + "," + vd_new_urls + html[vd_close_bracket:]

    after = len(html.encode("utf-8"))
    with open(IDX, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Before size: {before} bytes")
    print(f"After size: {after} bytes")
    print(f"Delta: +{after-before} bytes")
    print(f"PROGRAMS appended: {len(PAGES)} entries")
    print(f"VD appended: {len(PAGES)} urls")
    print("Done!")

if __name__ == "__main__":
    main()
