"""r284: add 5 independent PhD — UofT CS / UBC ME / UBC Civil / UofT Statistics / Yale Statistics."""
import re
import json
from pathlib import Path

ROOT = Path(r"D:\work buddy\2026-11-05-14-15-52")
IDX = ROOT / "index_main.html"
DETAILS = ROOT / "details"

PAGES = {
    "ut-cs-phd": {
        "id": "ut-cs-phd",
        "s": "ut",
        "n": "多伦多大学计算机科学博士",
        "en": "PhD in Computer Science",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4 years (5 years direct-entry from bachelor's)",
        "ddl": "Dec 1, 2026 (firm, Fall 2027 entry)",
        "lang": "TOEFL iBT 93 (min 22 Writing & Speaking) / IELTS Academic 7.0 (min 6.5 each)",
        "test": "GRE: not required (per SGS Calendar); Vector Institute application does NOT substitute for department application",
        "tui": "Funding: 4 years guaranteed (direct-entry 5 years); ETS code 0982",
        "url": "details/ut-cs-phd.html",
        "school": "University of Toronto",
        "dept": "Department of Computer Science (Faculty of Arts & Sciences)",
        "website": "https://web.cs.toronto.edu/graduate/phd",
        "overview": "The PhD in Computer Science at the University of Toronto is a research-intensive doctoral program offered by the Department of Computer Science (part of the Faculty of Arts & Sciences). It prepares students for research careers in academia and industry. The department offers three graduate degrees: research-stream MSc, PhD, and the professional Master of Science in Applied Computing (MScAC). The PhD program is a core member of the U of T / Vector Institute ecosystem. Direct-entry PhD (PhD U) is available to applicants with a bachelor's degree and an A- equivalent average in relevant courses.",
        "requirements": "Master's degree (or direct-entry bachelor's) with minimum A- equivalent average in computer science or closely related discipline; 2.0 full-course equivalents (FCEs) + thesis; English proficiency per SGS standard (TOEFL 93 with 22 in W/S, IELTS 7.0 with 6.5 each); supervisor assigned by graduate unit before admission; Vector Institute application is NOT an application to the department — all applicants must apply directly through the School of Graduate Studies (SGS) by Dec 1, 2026; application fee CAD 135.",
        "research": "Research groups span algorithms & complexity, artificial intelligence, computational biology, computer graphics, computer vision, databases, language technologies, machine learning, numerical analysis, operating systems, programming languages, robotics, security & privacy, software engineering, and theoretical computer science. The department hosts the Vector Institute (deep learning) and the Schwartz Reisman Institute for Technology & Society."
    },
    "ubc-me-phd": {
        "id": "ubc-me-phd",
        "s": "ubc",
        "n": "UBC机械工程博士",
        "en": "PhD in Mechanical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "36-48 months",
        "ddl": "Jan 31, 2027 (Sept 2027 intake; awards priority Dec 1, 2026 round 1)",
        "lang": "TOEFL iBT 90 (22 R / 21 W / 22 L / 21 S) / IELTS Academic 6.5 (no band < 6.0)",
        "test": "GRE: optional",
        "tui": "Tuition ~CAD 9,884/year international; guaranteed funding min CAD 40,000/year from Sep 2026 (median ~CAD 39,763 before tuition)",
        "url": "details/ubc-me-phd.html",
        "school": "University of British Columbia (Vancouver)",
        "dept": "Department of Mechanical Engineering (Faculty of Applied Science)",
        "website": "https://mech.ubc.ca/graduate/prospective/applications-admissions/",
        "overview": "The PhD in Mechanical Engineering at UBC Vancouver is a thesis-based doctoral program designed for engineering graduates who want to advance knowledge through rigorous research. The program requires coursework, a qualifying examination, a research thesis proposal defence, and a final thesis defence. September intake is primary; January intake is not common as most research positions are filled in September.",
        "requirements": "Thesis-based master's degree in Mechanical Engineering or related field; minimum B+ (UBC) standing; English proficiency per G+PS standard (TOEFL 90 with 22/21/22/21, IELTS 6.5 with no band below 6.0); connect with faculty supervisor before application; online application opens Sep 15, 2026; priority awards deadline Sep 15 (NSERC/G+PS Affiliated Awards for PhD) and Dec 1 (round 1 Departmental Entrance Awards); final deadline Jan 31, 2027; documents due Feb 15; no deferrals normally accepted.",
        "research": "Research areas include advanced manufacturing and materials, bio-mechanical engineering, combustion and energy systems, control and robotics, fluid mechanics and thermal sciences, mechatronics, micro/nano engineering, and sustainable energy. UBC Mech hosts the clean energy and advanced propulsion research clusters."
    },
    "ubc-cen-phd": {
        "id": "ubc-cen-phd",
        "s": "ubc",
        "n": "UBC土木工程博士",
        "en": "PhD in Civil Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "36-48 months",
        "ddl": "Jan 31, 2027 (Sept 2027 intake; application opens Jul 1, 2026)",
        "lang": "TOEFL iBT 90 (22 R / 21 W / 22 L / 21 S) / IELTS Academic 6.5 (no band < 6.0)",
        "test": "GRE: optional",
        "tui": "Tuition CAD 5,626 domestic / CAD 9,884 international (first year); guaranteed funding min CAD 40,000/year from Sep 2026 (median ~CAD 39,763 before tuition)",
        "url": "details/ubc-cen-phd.html",
        "school": "University of British Columbia (Vancouver)",
        "dept": "Department of Civil Engineering (Faculty of Applied Science)",
        "website": "https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/phd-civil-engineering",
        "overview": "The PhD in Civil Engineering at UBC Vancouver is a thesis-based doctoral program requiring coursework, a qualifying exam, a research proposal defence, and a final thesis defence. The program is intended for engineering graduates who want to magnify their knowledge through rigorous research related to civil, geological, and environmental engineering problems.",
        "requirements": "Thesis-based master's degree in Civil Engineering or related field; minimum B+ (UBC) standing; English proficiency per G+PS standard (TOEFL 90 with 22/21/22/21, IELTS 6.5 with no band below 6.0); connect with faculty supervisor before application; application opens Jul 1, 2026; final deadline Jan 31, 2027; transcripts and references due Feb 15, 2027.",
        "research": "Research areas include applied microbiology in water treatment, biological treatment of water & wastewater, drinking water treatment & distribution, construction materials, geohazards assessment & mitigation, life-cycle management in construction, solid waste management, structural design & strengthening, sustainable transportation, and sustainable urban development."
    },
    "ut-stat-phd": {
        "id": "ut-stat-phd",
        "s": "ut",
        "n": "多伦多大学统计学博士",
        "en": "PhD in Statistics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4 years (5 years direct-entry from bachelor's)",
        "ddl": "Nov 22, 2026 (Fall 2027 entry; application opens Sep 22)",
        "lang": "TOEFL iBT 93 (min 22 Writing & Speaking) / IELTS Academic 7.0 (min 6.5 each)",
        "test": "GRE: not required (per SGS Calendar)",
        "tui": "Funding: 4 years guaranteed (direct-entry 5 years); ETS code 0982; CGS D / NSERC PGS D $35,000/year top awards",
        "url": "details/ut-stat-phd.html",
        "school": "University of Toronto",
        "dept": "Department of Statistical Sciences (Faculty of Arts & Sciences)",
        "website": "https://www.statistics.utoronto.ca/graduate/phd-application-information",
        "overview": "The PhD in Statistics at the University of Toronto is a research-intensive doctoral program offered by the Department of Statistical Sciences. It trains students for careers in academia, industry research, government, and data science leadership. The department also offers MSc (full & part-time), Master of Financial Insurance (MFI), and MScAC Data Science Concentration. The PhD deadline is notably earlier than most U of T doctoral programs (Nov 22 vs. typical Dec 1 - Jan 7).",
        "requirements": "Master's degree (or direct-entry bachelor's) with minimum B+ (U of T = 77-79%) standing; direct-entry from bachelor's requires A- equivalent average in statistics/mathematics/related field; English proficiency per SGS standard (TOEFL 93 with 22 in W/S, IELTS 7.0 with 6.5 each); supervisor identified before admission; application opens Sep 22 and closes Nov 22 each year; ETS institution code 0982; TOEFL/IELTS scores must be within 24 months of application.",
        "research": "Research areas span theoretical statistics, probability, high-dimensional data analysis, statistical computing, machine learning, Bayesian methodology, biostatistics, environmental statistics, financial statistics, official statistics, and statistical graphics. Notable named awards include the Donald S. Fraser Doctoral Award for theoretical statistics contributions."
    },
    "yale-stat-phd": {
        "id": "yale-stat-phd",
        "s": "yale",
        "n": "耶鲁大学统计学博士",
        "en": "PhD in Statistics & Data Science",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years (typical)",
        "ddl": "Dec 1, 2026 (11:59pm ET, Fall 2027 entry)",
        "lang": "TOEFL iBT or IELTS Academic required; IELTS General Training, IELTS Online, and IELTS One Skill Retake not accepted",
        "test": "GRE General: optional; GRE Mathematics Subject Test: optional (per GSAS Standardized Testing Requirements, last updated Jun 29, 2026)",
        "tui": "Yale PhD: fully funded (tuition + stipend) for 5 years through fellowships, TA/RA appointments; ETS code 2174 (Yale GSAS)",
        "url": "details/yale-stat-phd.html",
        "school": "Yale University",
        "dept": "Department of Statistics & Data Science (Yale Graduate School of Arts & Sciences)",
        "website": "https://gsas.yale.edu/programs-of-study/statistics-data-science",
        "overview": "The PhD in Statistics & Data Science at Yale University is offered through the Yale Graduate School of Arts & Sciences (GSAS). The field of study covers statistical theory, probability, information theory, bioinformatics & genetics, classification, data mining & machine learning, neural nets, network science, optimization, statistical computing, and graphical models. The terminal degree offered is the PhD (MS is also offered but PhD is the research track).",
        "requirements": "Bachelor's or master's degree in statistics, mathematics, computer science, or related quantitative field; English proficiency required unless applicant has 3 years of residence at an undergraduate institution where English is the primary language of instruction (no exemption based on advanced degrees); application deadline Dec 1 at 11:59pm ET; letters of recommendation have no separate deadline but should be submitted promptly; IELTS must be Academic only — General Training, Online, and One Skill Retake are not accepted; ETS code 2174.",
        "research": "Research strengths include Bayesian theory, decision theory, nonparametric statistics, stochastic processes & asymptotics, weak convergence, bioinformatics, machine learning, neural nets, network science, optimization, and statistical graphics. The department is part of the Yale Institute for Foundations of Data Science."
    },
}

TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title} — {school}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6;}}
h1{{color:#1a3a6c;border-bottom:2px solid #1a3a6c;padding-bottom:8px;}}
h2{{color:#1a3a6c;margin-top:28px;}}
.badge{{display:inline-block;background:#1a3a6c;color:#fff;padding:2px 10px;border-radius:12px;font-size:13px;margin-right:6px;}}
.card{{background:#f7f9fc;border-left:4px solid #1a3a6c;padding:14px 18px;margin:12px 0;border-radius:4px;}}
a{{color:#1a6fc4;}}
</style>
</head>
<body>
<h1>{title}</h1>
<p><span class="badge">{deg}</span><span class="badge">{stem_label}</span><span class="badge">{lvl_label}</span></p>
<div class="card"><strong>School:</strong> {school}<br>
<strong>Department:</strong> {dept}<br>
<strong>Website:</strong> <a href="{website}" target="_blank">{website}</a></div>

<h2>Overview</h2>
<p>{overview}</p>

<h2>Degree Requirements</h2>
<div class="card">
<strong>Duration:</strong> {duration}<br>
<strong>Application Deadline:</strong> {ddl}<br>
<strong>English Language:</strong> {lang}<br>
<strong>Standardized Tests:</strong> {test_cls}<br>
<strong>Tuition &amp; Funding:</strong> {tui}
</div>
<p>{requirements}</p>

<h2>Research Areas</h2>
<p>{research}</p>

<p style="color:#888;font-size:12px;margin-top:32px;">Verified against official department / graduate school source. Not a minimum-threshold guarantee; admitted class distributions reflect competitive review.</p>
</body>
</html>
"""


def render(p):
    stem_label = "STEM" if p["stem"] == 1 else "Non-STEM"
    lvl_label = "Doctoral" if p["lvl"] == "d" else "Master"
    return TEMPLATE.format(
        title=p["n"],
        school=p["school"],
        deg=p["deg"],
        stem_label=stem_label,
        lvl_label=lvl_label,
        dept=p["dept"],
        website=p["website"],
        overview=p["overview"],
        duration=p["dur"],
        ddl=p["ddl"],
        lang=p["lang"],
        test_cls=p["test"],
        tui=p["tui"],
        requirements=p["requirements"],
        research=p["research"],
    )


def append_program(html, entry):
    """Insert one PROGRAMS record before the closing ]; of PROGRAMS array."""
    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
        elif c == "[" and depth == 1:
            depth += 1
        elif c == "]" and depth == 1:
            break
        i += 1
    else:
        raise RuntimeError("PROGRAMS end not found")
    insert_at = i
    # ensure previous entry ends with comma
    j = insert_at - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[insert_at:]
    if not prefix.endswith(","):
        prefix += ","
    block = ('{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
             'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}').format(
        id=entry["id"], s=entry["s"], n=entry["n"], en=entry["en"], deg=entry["deg"],
        lvl=entry["lvl"], stem=entry["stem"], dur=entry["dur"], ddl=entry["ddl"],
        lang=entry["lang"], test=entry["test"], tui=entry["tui"], url=entry["url"])
    return prefix + "\n" + block + "\n" + suffix


def append_vd(html, urls):
    """Insert new VD entries into VERIFIED_DETAILS Set."""
    m = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\[", html)
    if not m:
        raise RuntimeError("VERIFIED_DETAILS 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:
                break
        i += 1
    else:
        raise RuntimeError("VD end not found")
    # insert before the closing ] at i
    j = i - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[i:]
    if not prefix.endswith(",") and not prefix.endswith("["):
        prefix += ","
    additions = ",".join('"{}"'.format(u) for u in urls)
    return prefix + "\n" + additions + "\n" + suffix


def main():
    html = IDX.read_text(encoding="utf-8")
    before = len(html.encode("utf-8"))
    new_urls = []
    for pid, p in PAGES.items():
        out = DETAILS / (pid + ".html")
        out.write_text(render(p), encoding="utf-8")
        print("wrote", out)
        html = append_program(html, p)
        new_urls.append(p["url"])
    html = append_vd(html, new_urls)
    after = len(html.encode("utf-8"))
    IDX.write_text(html, encoding="utf-8")
    print(f"index_main.html: {before} -> {after} bytes (delta +{after - before})")
    print("done.")


if __name__ == "__main__":
    main()
