# -*- coding: utf-8 -*-
"""Round 283: add 5 independent PhD programs.
UBC CS / UBC ECE / UofT ECE / McGill CS / Northwestern IBiS
"""
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 = {
    "ubc-cs-phd": {
        "id": "ubc-cs-phd", "s": "ubc",
        "n": "计算机科学 PhD",
        "en": "PhD in Computer Science (University of British Columbia, Department of Computer Science)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "4–5 years full-time",
        "ddl": "Dec 15, 2026 (application deadline for September 2027 or January 2028 entry; referee deadline Jan 15, 2027)",
        "lang": "TOEFL iBT 100 (22 reading, 22 listening, 21 writing, 21 speaking); IELTS Academic 7.0 overall (no band below 6.5); MELAB 85; PTE Academic 71-72; Oxford ELLT 8.0 overall (CS-specific, no component below 7.0). ETS institution code 0965.",
        "test": {"cls": "GRE not required; not listed on current UBC CS admissions requirements."},
        "tui": "Fully funded. 2026-2027 package: CAD 41,653 domestic / CAD 46,236 international (department stipend + tuition award + international tuition award + PAEIPA); median funding ~CAD 44,526 over first four years.",
        "url": "details/ubc-cs-phd.html",
        "school": "University of British Columbia (Vancouver)",
        "dept": "Department of Computer Science, Faculty of Science",
        "website": "https://www.cs.ubc.ca/students/grad/admissions",
        "overview": "UBC CS is one of Canada's top computer science departments, located on the Point Grey campus overlooking Vancouver. The department has around 280 graduate students organized into 24 research groups spanning AI, machine learning, graphics, HCI, software engineering, programming languages, formal methods, systems, security, data science, and theory. Three research programs are offered: research MSc, PhD (for students with a master's), and PhD Track (direct entry from bachelor's).",
        "requirements": "Strong undergraduate preparation in computer science or a closely related quantitative field. Three references; statement of interest; transcripts; CV. PhD Track option available for exceptional bachelor's holders. No GRE required. Applications open September 15; deadline December 15. Scores expire two years after test date.",
        "research": "Artificial intelligence and machine learning; computer graphics and vision; human-computer interaction; programming languages and software engineering; formal methods and security; systems, networks, and databases; data science and mining; theory of computing; scientific computing; natural language processing."
    },
    "ubc-ece-phd": {
        "id": "ubc-ece-phd", "s": "ubc",
        "n": "电子与计算机工程 PhD",
        "en": "PhD in Electrical and Computer Engineering (University of British Columbia, Faculty of Applied Science)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "~48 months average (max 6 years)",
        "ddl": "September entry only; historical deadline around January 15 (current department page to re-verify each cycle).",
        "lang": "TOEFL iBT 100 minimum (22 reading, 22 listening, 21 writing, 21 speaking); IELTS Academic 7.0 overall (minimum 6.0 each component); ETS institution code 0965. Language score cannot be waived even if prior degree was English-instructed unless completed within 5 years at an approved country.",
        "test": {"cls": "GRE not required; not listed on current UBC ECE admissions requirements."},
        "tui": "Guaranteed minimum funding package of at least CAD 40,000 per year for the first four years (from September 2026 UBC-wide minimum funding policy), via scholarships, RA, TA, and supervisor awards; 30–50 students admitted per year.",
        "url": "details/ubc-ece-phd.html",
        "school": "University of British Columbia (Vancouver)",
        "dept": "Department of Electrical and Computer Engineering, Faculty of Applied Science",
        "website": "https://engineering.ubc.ca/electrical-computer-engineering",
        "overview": "UBC ECE is one of Canada's leading electrical and computer engineering departments, with strengths in microelectronics, photonics, signals and systems, communications, controls, power, biomedical engineering, and computer engineering. The PhD program trains students for independent research and typically admits 30–50 new graduate students per year. The department offers MASc and PhD research degrees (no coursework-only MEng).",
        "requirements": "Strong undergraduate preparation in electrical engineering, computer engineering, physics, or a related quantitative field. Three references; statement of interest; transcripts; CV. High scholastic standing and demonstrated research aptitude required. No conditional admission pending English language training; language score must be on file before application processing.",
        "research": "Microelectronics and VLSI; photonics and electromagnetics; communications and signal processing; controls and robotics; power and energy systems; biomedical engineering; computer engineering; machine learning and AI; quantum engineering."
    },
    "ut-ece-phd": {
        "id": "ut-ece-phd", "s": "ut",
        "n": "电子与计算机工程 PhD",
        "en": "PhD in Electrical and Computer Engineering (University of Toronto, Edward S. Rogers Sr. Department)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "~48 months expected (4 years guaranteed funding)",
        "ddl": "January 7, 2027 (for September 2027 / January 2028 entry; domestic and international applicants same deadline)",
        "lang": "TOEFL iBT 93 overall (minimum 22 writing, 22 speaking); IELTS Academic 7.0 overall (minimum 6.5 each component); COPE 76 (22 each component, 32 writing). ETS institution code 0982. TOEFL MyBest and IELTS One Skill Retake not accepted.",
        "test": {"cls": "GRE not required; not listed on current UofT ECE admissions requirements."},
        "tui": "4 years guaranteed funding package for PhD students in good standing (5 years for direct-entry PhD); minimum package = ECE stipend (~CAD 20,000) + tuition and fees; supervisor may pay above minimum; external awards (OGS, NSERC, QEII) enhance package.",
        "url": "details/ut-ece-phd.html",
        "school": "University of Toronto (St. George)",
        "dept": "Edward S. Rogers Sr. Department of Electrical and Computer Engineering, Faculty of Applied Science & Engineering",
        "website": "https://www.ece.toronto.edu/graduates/",
        "overview": "The University of Toronto ECE department is one of Canada's largest and most engineering-focused doctoral programs. It offers MEng (coursework), MASc (research master's), and PhD. The PhD program expects students to complete relevant coursework, pass a qualifying examination, and make novel and significant research contributions under the supervision of one or more faculty. Research spans communications, computer engineering, signals, systems, controls, power, photonics, biomedical, and applied electromagnetics.",
        "requirements": "Strong undergraduate or master's preparation in electrical or computer engineering, physics, mathematics, or a related quantitative field. Three references; statement of research interest; transcripts; CV. Direct-entry PhD option available for exceptional bachelor's holders. Qualifying examination required. Admissions decisions typically released February–April.",
        "research": "Communications and signal processing; computer engineering and VLSI; controls, robotics, and MEMS; photonics and applied electromagnetics; power and energy systems; biomedical engineering; machine learning; quantum engineering; internet of things; nanotechnology."
    },
    "mcg-cs-phd": {
        "id": "mcg-cs-phd", "s": "mcg",
        "n": "计算机科学 PhD",
        "en": "PhD in Computer Science (McGill University, School of Computer Science)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "4–5 years full-time",
        "ddl": "December 15 (scholarship consideration, recommended); January 1 (financial support deadline); March 1 (final application deadline). Fall entry only; Winter entry September 1.",
        "lang": "TOEFL iBT 100 (minimum 20 in each of four components); IELTS Academic 6.5 overall (no band below 6.0); ETS institution code 0935. IELTS Online and One Skill Retake not accepted; scores must be sent electronically by test center.",
        "test": {"cls": "GRE not required; not listed on current McGill CS admissions requirements."},
        "tui": "All PhD students and most MSc students funded via personal scholarships, McGill awards, research assistantships, or teaching assistantships. Applying by December 15 ensures automatic consideration for funding. Canadian/Québec residents encouraged to apply for NSERC and FRQNT.",
        "url": "details/mcg-cs-phd.html",
        "school": "McGill University (Montréal)",
        "dept": "School of Computer Science, Faculty of Science",
        "website": "https://cs.mcgill.ca/graduate/future/phdadmission/",
        "overview": "McGill's School of Computer Science is one of Canada's oldest and most respected CS departments, located in downtown Montréal. The PhD program trains students to become independent researchers. Normally applicants should hold an MSc in Computer Science or a closely related field; exceptionally strong BSc holders may be admitted directly to the PhD. The department requires applicants to list at least three proposed supervisors.",
        "requirements": "Strong undergraduate (and preferably master's) preparation in computer science or a closely related quantitative field. Three proposed supervisors listed on application; statement of research interest; transcripts; CV; three references. No GRE required. McGill does not offer a qualifying program for students with weak CS background; equivalent courses must be completed externally before applying.",
        "research": "Algorithms and complexity; artificial intelligence and machine learning; computational linguistics; computer graphics and vision; databases and data mining; human-computer interaction; numerical analysis; programming languages; robotics; scientific computing; security and cryptography; systems and networks."
    },
    "nu-ibis-phd": {
        "id": "nu-ibis-phd", "s": "nu",
        "n": "跨学科生物科学 PhD",
        "en": "PhD in Interdisciplinary Biological Sciences (IBiS, Northwestern University Weinberg College of Arts and Sciences)",
        "deg": "PhD", "lvl": "d", "stem": 1,
        "dur": "5–6 years full-time",
        "ddl": "December 2026 cycle (IBiS fall admission; exact date per TGS application page; typical mid-December deadline)",
        "lang": "TOEFL iBT 90 minimum (TGS PhD baseline); ETS institution code 1565. IBiS FAQ specifies iBT 90. TGS also accepts TOEFL at-home; scores must be within two years of entry.",
        "test": {"cls": "GRE General NOT REQUIRED; GRE Subject NOT REQUIRED (IBiS FAQ explicitly states no GRE required)."},
        "tui": "Full tuition and stipend for all admitted PhD students (2026-27 tuition $47,748); typical TGS bioscience package includes tuition, stipend, and health insurance.",
        "url": "details/nu-ibis-phd.html",
        "school": "Northwestern University",
        "dept": "Interdisciplinary Biological Sciences Graduate Program (Weinberg College of Arts and Sciences)",
        "website": "https://ibis.northwestern.edu/graduate/prospective/",
        "overview": "Northwestern IBiS is a cross-departmental biology PhD program based in the Weinberg College of Arts and Sciences. It admits a cohort of students who rotate through faculty labs and then choose a thesis advisor. Upon successful completion, the degree awarded is a PhD in Biological Sciences. IBiS is the Weinberg-side bioscience PhD program, distinct from the Feinberg-side DGP (Driskill Graduate Program).",
        "requirements": "Strong undergraduate preparation in biology, chemistry, biochemistry, or a related quantitative life science. Three letters of recommendation; statement of purpose; personal statement; transcripts; CV. No GRE required. Fall admission only. Rotations in the first year before thesis advisor selection.",
        "research": "Molecular and cellular biology; genetics and genomics; biochemistry and biophysics; neurobiology; developmental biology; cell signaling; structural biology; computational biology; microbial sciences; chemical biology."
    },
}

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()
