# -*- coding: utf-8 -*-
"""Round 282: add 5 independent PhD programs.
MIT HASTS / MIT IDSS SES / Princeton QCB / Harvard Health Policy / UBC Statistics
Note: MIT Media Arts and Sciences PhD is excluded (internal promotion only, no external PhD admission).
"""
import re, pathlib

ROOT = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52")
INDEX = ROOT / "index_main.html"
DET = ROOT / "details"
DET.mkdir(exist_ok=True)

PAGES = {
    "mit-hasts-phd": {
        "id": "mit-hasts-phd", "s": "mit",
        "n": "历史、人类学与科学技术社会研究 PhD",
        "en": "PhD in History, Anthropology, and Science, Technology, and Society (HASTS, MIT SHASS)",
        "deg": "PhD", "lvl": "d", "stem": 0,
        "dur": "5 years full-time",
        "ddl": "Dec 1, 11:59 PM ET (Fall 2027 admission)",
        "lang": "TOEFL iBT 100 minimum (iBT26: 5); IELTS Academic 7.0; MIT ELP waivers only via automatic eligibility; ETS institute code 3514.",
        "test": {"cls": "GRE General NOT ACCEPTED — HASTS does not accept GRE scores and will not consider them in evaluation."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students (SHASS funding); application fee $90.",
        "url": "details/mit-hasts-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Program in Science, Technology, and Society (School of Humanities, Arts, and Social Sciences)",
        "website": "https://oge.mit.edu/programs/history-anthropology-and-science-technology-and-society/",
        "overview": "MIT HASTS is a small, selective doctoral program that trains scholars to study science and technology as activities situated in social and cultural contexts. It is the flagship STS program in the MIT School of Humanities, Arts, and Social Sciences. Research spans history of science and medicine, anthropology of science and technology, and technology studies, with strong connections to STS, STS, and the social study of computing, energy, and the life sciences.",
        "requirements": "Strong preparation in humanities or social sciences; demonstrated interest in historical, anthropological, or social study of science and technology. Three letters of recommendation; statement of objectives; personal statement; transcripts; CV. No GRE required or accepted. Interviews by invitation during admissions review.",
        "research": "History of science and medicine; anthropology of science and technology; science and technology policy; social studies of computing, energy, and the environment; STS; history and anthropology of the life sciences; technology and global development."
    },
    "mit-idss-ses-phd": {
        "id": "mit-idss-ses-phd", "s": "mit",
        "n": "社会与工程系统 PhD",
        "en": "PhD in Social and Engineering Systems (SES, MIT Institute for Data, Systems, and Society)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "4.5–6 years full-time",
        "ddl": "Dec 15, 11:59 PM ET (Fall 2027 admission; applications open Sep 15)",
        "lang": "TOEFL iBT 110 minimum (iBT26: 5.5); IELTS Academic 7.5; Duolingo English Test 140; MIT ELP waivers only via automatic eligibility; ETS institute code 3514.",
        "test": {"cls": "GRE General OPTIONAL. If submitted, IDSS recommends meeting or exceeding 157 Verbal (150 for non-native English speakers), 159 Quantitative, and 4.0 Analytical Writing; these are minimum expectations, not hard thresholds."},
        "tui": "Full tuition + stipend + health insurance for all admitted PhD students; application fee $90. Affiliated programs include TPP and IDPS.",
        "url": "details/mit-idss-ses-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Institute for Data, Systems, and Society (Schwarzman College of Computing)",
        "website": "https://idss.mit.edu/academics/ses/",
        "overview": "The MIT SES doctoral program is a unique research degree that combines methods from computing, data science, statistics, engineering, and the social sciences to address concrete, societally significant problems. It is housed in the Institute for Data, Systems, and Society (IDSS) and is the only PhD offered directly by IDSS. Students work at the interface of engineering and social science, with research spanning autonomous systems, energy systems, finance, social networks, and urban systems.",
        "requirements": "Strong quantitative preparation in engineering, computer science, mathematics, statistics, operations research, or a related quantitative social science. Three letters of recommendation; statement of objectives; transcripts; CV. Coursework and research must include breadth and depth in engineering/quantitative methods, the social sciences, and a particular application domain. Full-time, residential; no part-time track.",
        "research": "Autonomous systems and decision making; energy and climate systems; finance and financial technology; social networks and network science; urban systems and transportation; data science for public health; statistics and machine learning for societal problems."
    },
    "princeton-qcb-phd": {
        "id": "princeton-qcb-phd", "s": "princeton",
        "n": "定量与计算生物学 PhD",
        "en": "PhD in Quantitative and Computational Biology (Lewis-Sigler Institute, Princeton University)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5 years",
        "ddl": "Dec 1, 11:59 PM ET (Fall 2027 admission)",
        "lang": "TOEFL iBT required; students scoring below 27 on the speaking subsection must take an English placement test (non-passing requires ELP courses). IELTS speaking below 8.0 triggers placement. ETS code 2672 (no department code).",
        "test": {"cls": "GRE General Test NOT ACCEPTED — QCB will not consider GRE scores. Subject tests not required."},
        "tui": "Full tuition + stipend + student health plan coverage for all admitted PhD students for 5 years; application fee $90 (fee waivers available).",
        "url": "details/princeton-qcb-phd.html",
        "school": "Princeton University",
        "dept": "Lewis-Sigler Institute for Integrative Genomics; Program in Quantitative and Computational Biology",
        "website": "https://lsi.princeton.edu/education/quantitative-computational-biology-graduate-program",
        "overview": "Princeton QCB is a degree-granting PhD program administered from the Lewis-Sigler Institute for Integrative Genomics. It is a cross-departmental collaboration among 40+ faculty from Chemistry, Chemical and Biological Engineering, Computer Science, Ecology and Evolutionary Biology, Molecular Biology, and Physics. The program covers genomics, computational biology, systems biology, quantitative genetics, molecular evolution, and microbial interactions.",
        "requirements": "Particularly welcomes undergraduates with degrees in computer science, chemistry, operations research, statistics, applied math, or physics. Three letters of recommendation; statement of academic purpose; transcripts; CV. No GRE required or accepted. Lab sizes are modest (6–16 researchers) with close faculty mentorship. Thesis must be defended according to Graduate School rules.",
        "research": "Genomics and multi-omics; systems biology; quantitative and statistical genetics; molecular evolution; computational biology; microbiome and microbial interactions; biophysics; mathematical biology; data science for the life sciences."
    },
    "harvard-health-policy-phd": {
        "id": "harvard-health-policy-phd", "s": "harvard",
        "n": "健康政策 PhD",
        "en": "PhD in Health Policy (Harvard Griffin GSAS, jointly with HKS, HBS, Harvard Chan, and HMS)",
        "deg": "PhD", "lvl": "d", "stem": 0,
        "dur": "5 years (5 years tuition + 3 years stipend guaranteed)",
        "ddl": "Dec 1, 5:00 PM Boston time (Fall 2027 admission; decisions by early March)",
        "lang": "TOEFL iBT required for non-native English speakers whose undergraduate degree was not earned at an English-instruction institution; minimum 80 iBT (GSAS baseline). IELTS not accepted by GSAS. ETS code 3451.",
        "test": {"cls": "Management track: GRE General or GMAT REQUIRED (GRE preferred). Decision Sciences / Economics / Methods for Policy Research / Political Analysis tracks: GRE/GMAT OPTIONAL. No minimum score; successful applicants typically score above the 80th percentile (admission distribution, not a threshold)."},
        "tui": "5 years of tuition plus 3 years of stipend guaranteed for all admitted PhD students; application fee $105.",
        "url": "details/harvard-health-policy-phd.html",
        "school": "Harvard University",
        "dept": "PhD Program in Health Policy (Harvard Kenneth C. Griffin GSAS; cross-school with HKS, HBS, Harvard Chan, HMS)",
        "website": "https://healthpolicy.fas.harvard.edu/apply",
        "overview": "The Harvard PhD Program in Health Policy is a cross-school doctoral program based in Harvard Griffin GSAS. Students apply to one of five concentrations: Management, Decision Sciences, Economics, Methods for Policy Research, or Political Analysis. The program is jointly staffed by faculty from Harvard Kennedy School, Harvard Business School, Harvard T.H. Chan School of Public Health, and Harvard Medical School. Up to two concentration areas may be specified in the application.",
        "requirements": "Three letters of recommendation (four permitted); statement of purpose specifying concentration(s) and policy area(s) of interest; personal statement; CV; transcripts. GRE/GMAT required only for the Management concentration. Applications reviewed by both concentration faculty and a general admissions committee. Master's degree does not exempt English proficiency requirement.",
        "research": "Health economics and financing; health care management and organizational behavior; decision science and medical decision making; political analysis of health policy; quantitative methods for policy research; comparative health systems; pharmaceuticals and regulatory policy; mental health and health services research."
    },
    "ubc-statistics-phd": {
        "id": "ubc-statistics-phd", "s": "ubc",
        "n": "统计学 PhD",
        "en": "PhD in Statistics (University of British Columbia, Department of Statistics)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "4 years (September entry only; no part-time)",
        "ddl": "Dec 1, 2026 (application deadline for September 2027 entry); letters due Dec 15, 2026",
        "lang": "TOEFL iBT 90 overall (minimum 22 reading, 22 listening, 21 writing, 21 speaking); IELTS Academic 7.0 overall (no band below 6.5); Duolingo 130; ETS institution code 0965.",
        "test": {"cls": "GRE not required; not listed on current UBC Statistics admissions requirements."},
        "tui": "Guaranteed minimum funding package of at least CAD 40,000 per year for the first four years (from September 2026); historical mean funding $50,862 / median $50,973.",
        "url": "details/ubc-statistics-phd.html",
        "school": "University of British Columbia (Vancouver)",
        "dept": "Department of Statistics, Faculty of Science",
        "website": "https://www.stat.ubc.ca/graduate-admissions",
        "overview": "UBC Statistics is one of Canada's leading statistics departments, located on the Vancouver Point Grey campus. The PhD program trains researchers in statistical theory, methodology, and interdisciplinary applications. It admits students to a September-only cohort and does not offer part-time or off-cycle entry. The department has strong research groups in biostatistics, environmental statistics, statistical computing, and statistical theory.",
        "requirements": "Strong undergraduate preparation in statistics, mathematics, or a related quantitative field; master's degree preferred for PhD admission. Application opens October 1, 2026. All materials (application, transcripts, references) due by Dec 1, 2026; letter writers have until Dec 15, 2026. Scores expire two years after test date; expired scores not accepted.",
        "research": "Statistical theory and methodology; biostatistics and bioinformatics; environmental and spatial statistics; statistical computing and machine learning; data science; probability; statistical genetics; statistical finance and actuarial science."
    },
}

PAGE_TMPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} · {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI','PingFang SC',sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{font-size:24px;margin-bottom:4px}}
h2{{font-size:18px;color:#1a4480;border-bottom:1px solid #d8dde6;padding-bottom:6px;margin-top:28px}}
.meta{{background:#f4f7fb;border-left:4px solid #1a4480;padding:12px 16px;border-radius:4px;margin:14px 0}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:10px 24px}}
.kv{{font-size:14px}}
.kv b{{color:#1a4480}}
.badge{{display:inline-block;background:#e6efff;color:#1a4480;padding:2px 8px;border-radius:10px;font-size:12px;margin-right:6px}}
ul{{margin:6px 0 6px 22px}}
</style>
</head>
<body>
<h1>{n}</h1>
<div style="color:#666;margin-bottom:14px">{en}</div>
<div class="meta">
<div><span class="badge">{school}</span><span class="badge">{dept}</span><span class="badge">stem_label</span></div>
<div class="grid" style="margin-top:10px">
<div class="kv"><b>学位</b>：{deg}</div>
<div class="kv"><b>学制</b>：{duration}</div>
<div class="kv"><b>截止</b>：{ddl}</div>
<div class="kv"><b>语言</b>：{lang}</div>
<div class="kv"><b>标化</b>：{test_cls}</div>
<div class="kv"><b>学费/资助</b>：{tui}</div>
</div>
</div>
<h2>项目概览</h2><p>{overview}</p>
<h2>申请要求</h2><p>{requirements}</p>
<h2>研究方向</h2><p>{research}</p>
<p style="margin-top:24px;color:#888;font-size:12px">官网：<a href="{website}">{website}</a></p>
</body></html>"""


def render(p):
    p = dict(p)
    p["lvl_label"] = "Doctoral" if p["lvl"] == "d" else "Master's"
    p["duration"] = p["dur"]
    p["test_cls"] = p["test"]["cls"]
    return PAGE_TMPL.format(**p)


def append_program(html, rec):
    m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                end = i
                break
        i += 1
    else:
        raise RuntimeError("PROGRAMS end not found")
    block = (
        f',{{id:"{rec["id"]}",s:"{rec["s"]}",n:"{rec["n"]}",en:"{rec["en"]}",'
        f'deg:"{rec["deg"]}",lvl:"{rec["lvl"]}",stem:{rec["stem"]},dur:"{rec["dur"]}",'
        f'ddl:"{rec["ddl"]}",lang:"{rec["lang"]}",test:{{cls:"{rec["test"]["cls"]}"}},'
        f'tui:"{rec["tui"]}",url:"{rec["url"]}"}}'
    )
    return html[:end] + block + html[end:]


def append_vd(html, det_path):
    m = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[', html)
    if not m:
        raise RuntimeError("VD Set not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                end = i
                break
        i += 1
    else:
        raise RuntimeError("VD end not found")
    existing = html[start:end]
    stripped = existing.rstrip()
    if not stripped.endswith(','):
        stripped = stripped + ','
    new_block = stripped + f'"{det_path}"'
    return html[:start] + new_block + html[end:]


def main():
    html = INDEX.read_text(encoding="utf-8")
    size_before = len(html.encode("utf-8"))
    for key, p in PAGES.items():
        out = DET / (key + ".html")
        out.write_text(render(p), encoding="utf-8")
        print(f"wrote {out.relative_to(ROOT)}")
        html = append_program(html, p)
        html = append_vd(html, p["url"])
    size_after = len(html.encode("utf-8"))
    INDEX.write_text(html, encoding="utf-8")
    print(f"index_main.html: {size_before} -> {size_after} bytes (delta +{size_after-size_before})")
    print("done.")


if __name__ == "__main__":
    main()
