# -*- coding: utf-8 -*-
"""Round 209: add 5 Canadian ECE/CS PhDs - UBC ECE / McGill ECE / UW ECE / UofT CS / UBC CS."""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
INDEX = os.path.join(BASE, "index_main.html")
DETAILS_DIR = os.path.join(BASE, "details")

new_programs = [
    {
        "id": "ubc-ece-phd",
        "s": "ubc",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (University of British Columbia, Vancouver, Faculty of Applied Science, Department of Electrical and Computer Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Vancouver BC; Fall (September) admission; applications open October 15; requires recognized course-and-thesis-based Master's degree with graduate-level courses and written thesis in ECE or closely related field; minimum overall GPA 76% (3.3/4.0), preferred 80%+ (3.7/4.0); research areas include communications/signal processing, controls, electronics/photonics, energy, integrated circuits, ML, micro/nanoelectronics, power, robotics, VLSI.",
        "ddl": "January 15, 2027 (international and Canadian applicants; transcripts and referee reports due January 31, 2027).",
        "lang": "TOEFL iBT or IELTS Academic required per UBC Graduate and Postdoctoral Studies minimum English requirement.",
        "test": "GRE General: not required per UBC ECE graduate admissions. Required: UBC graduate online application; PDF transcripts from every post-secondary institution; CV/resume; UBC-specified Statement of Purpose; three confidential reference reports (at least one detailing academic achievement); PR card if applicable. All full-time UBC Vancouver PhD students receive guaranteed minimum funding of at least CAD $18,000 per year for the first four years (combination of fellowship, RA, TA, external awards). Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Guaranteed minimum funding CAD $18,000/year for first 4 years (fellowship + RA + TA + external awards such as NSERC, OGS, Vanier).",
        "url": "details/ubc-ece-phd.html",
    },
    {
        "id": "mcg-ece-phd",
        "s": "mcg",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (Doctor of Philosophy in Electrical Engineering) (McGill University, Faculty of Engineering, Department of Electrical and Computer Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Montreal QC; Fall (September) and Winter (January) intakes (no Summer); requires suitable Master's degree from recognized university in ECE or closely related field; minimum CGPA 3.0/4.0 (75%); admission is highly competitive; research areas include intelligent systems, photonics, power, software engineering, systems and control, telecommunications and signal processing, integrated circuits, electromagnetics.",
        "ddl": "Fall: open September 15, deadline December 15 (international and Canadian). Winter: open February 15, deadline August 1 (international) / October 15 (Canadian/PR). No Summer intake.",
        "lang": "English proficiency required per McGill GPS (waived for mother-tongue English or degrees from recognized English-medium institutions in US/Canada/UK/Australia/NZ); TOEFL/IELTS accepted.",
        "test": "GRE General: not required per McGill ECE catalogue (older archive page mentions GRE if applicable; current catalogue does not list GRE as required). Required: McGill GPS online application; transcripts; 2 reference letters; CV; SOP; application fee CAD $60. Funding: Graduate Assistantship (RA from supervisor research grant) + Teaching Assistantship; no separate funding application; all applicants indicating need are considered. External awards: NSERC CGS-D (Canadian/PR only), OGS, Vanier. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "RA + TA package; external awards (NSERC CGS-D, OGS, Vanier) on top; no prior department funding commitment.",
        "url": "details/mcg-ece-phd.html",
    },
    {
        "id": "uw-ece-phd",
        "s": "uw",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (University of Waterloo, Faculty of Engineering, Department of Electrical and Computer Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus thesis-based research PhD, Waterloo ON; three intakes: Fall (September), Winter (January), Spring (May); expected duration 48 months full-time; minimum 80% standing in relevant thesis-based Master's or Waterloo MEng with completed ECE 699 project; must have faculty supervisor who has endorsed admission at time of application; direct PhD entry from bachelor's considered for exceptional MASc applicants. Research fields: antennas/microwaves, biomedical circuits, communications, computer hardware/software, nanotechnology, pattern analysis and machine intelligence (PAMI), power/energy, quantum information, silicon devices/IC, systems and control, VLSI, wireless.",
        "ddl": "Fall (September admission): February 1; Winter (January admission): June 1; Spring (May admission): October 1. Begin application at least two weeks before deadline to allow referees time to submit.",
        "lang": "TOEFL iBT: writing 4.5, speaking 4, reading 4, listening 4; IELTS Academic: overall 6.5, writing 6.0, speaking 6.0.",
        "test": "GRE General: not required per Waterloo ECE admissions. Required: Waterloo graduate application; transcripts; three letters of reference (at least two academic); proof of English proficiency; faculty supervisor endorsement. All international and domestic PhD students are guaranteed minimum funding of CAD $25,000 per year through a Graduate Research Studentship (GRS) paid by the supervisor, except those funded by external scholarship/sponsorship; no separate application. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Guaranteed minimum funding CAD $25,000/year via GRS (supervisor-paid); external awards (NSERC, OGS, Vanier) on top.",
        "url": "details/uw-ece-phd.html",
    },
    {
        "id": "ut-cs-phd",
        "s": "ut",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (University of Toronto, Faculty of Arts and Science, Department of Computer Science / School of Graduate Studies)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Toronto ON; two entry routes: (1) after appropriate master's degree (minimum B+ standing), or (2) direct entry after bachelor's degree (minimum A- standing, exceptional applicants); coursework total 2.0 full-course equivalents (FCEs) satisfying breadth across four research areas of CS; thesis; qualifying oral (supervisory committee meeting) required by the 16th month; research strengths across ML, systems, theory, HCI, graphics, NLP, robotics, security, databases.",
        "ddl": "Early-to-mid December annually (around December 15; department admissions deadline; verify on cs.utoronto.ca for the current cycle).",
        "lang": "TOEFL iBT minimum 93/120 with 22/30 on writing and speaking; TOEFL paper 580 with TWE 4; IELTS Academic accepted per SGS English facility requirement.",
        "test": "GRE General: not required per current U of T CS / SGS calendar (older faculty pages mention scores considered but not required). Required: SGS online application; transcripts; 3 reference letters; statement of purpose; CV; English proficiency. All admitted PhD students are guaranteed funding for the normal time to completion (17 months master's + 43 months PhD if continuing), consisting of student scholarships, central university funds, and supervisor research grants. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Guaranteed funding package for normal time to completion (scholarships + central support + RA/TA from supervisor).",
        "url": "details/ut-cs-phd.html",
    },
    {
        "id": "ubc-cs-phd",
        "s": "ubc",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (University of British Columbia, Vancouver, Faculty of Science, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Vancouver BC; three research programs: research MSc (2-year), PhD (usually for students with a master's), and PhD Track (direct from bachelor's); all three fully funded; application portal opens September 15; comprehensive course requirement: 6 courses covering at least 4 research areas, at least 4 in CS department, at least 4 at graduate level, minimum grade 72%, overall average 80%; 24 research groups; strengths: AI/ML, graphics, HCI, software engineering, programming languages, formal methods, systems, security & privacy, data science, theory/scientific computing.",
        "ddl": "December 15, 2026 (hard deadline for programs beginning September 2027 or January 2028; portal opens September 15, 2026; all applicant documents and references must be submitted by this date).",
        "lang": "TOEFL iBT or IELTS Academic required per UBC Graduate and Postdoctoral Studies.",
        "test": "GRE General: not required per UBC CS graduate admissions. Required: UBC graduate online application; transcripts; three mandatory reference letters; statement of interest; CV; English proficiency scores (if applicable). All three research programs (MSc, PhD, PhD Track) are fully funded and qualify for substantial awards toward tuition. Application fee waived for applicants from UN-designated least-developed countries. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "All PhD and PhD Track students fully funded (combination of fellowship, RA, TA, external awards); substantial awards toward tuition.",
        "url": "details/ubc-cs-phd.html",
    },
]

def detail_html(p, school_cn, tagline):
    stem_badge = "STEM" if p["stem"] else "Non-STEM"
    lvl_badge = "PhD" if p["lvl"] == "d" else "Master's"
    return f"""<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8">
<title>{p['en']} - {school_cn}</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.6}}
h1{{font-size:22px;border-bottom:2px solid #8c641a;padding-bottom:8px}}
h2{{font-size:16px;color:#8c641a;margin-top:24px}}
.grid{{display:grid;grid-template-columns:1fr 1fr;gap:12px}}
.card{{border:1px solid #ddd;border-radius:8px;padding:14px;background:#fafafa}}
.card h3{{margin:0 0 6px;font-size:14px;color:#444}}
.badge{{display:inline-block;background:#8c641a;color:#fff;padding:2px 8px;border-radius:10px;font-size:12px;margin-left:8px}}
.back{{display:inline-block;margin-bottom:16px;color:#8c641a;text-decoration:none}}
</style></head><body>
<a class="back" href="../index_main.html">&larr; Back to Program Library</a>
<h1>{p['en']}<span class="badge">{stem_badge}</span><span class="badge">{lvl_badge}</span></h1>
<p><strong>{school_cn}</strong> &middot; {p['deg']} &middot; {tagline}</p>
<div class="grid">
<div class="card"><h3>Degree / Format</h3>{p['deg']}, on-campus. {p['dur']}.</div>
<div class="card"><h3>Application Deadline</h3>{p['ddl']}.</div>
<div class="card"><h3>English Proficiency</h3>{p['lang']}.</div>
<div class="card"><h3>Standardized Tests</h3>{p['test']}.</div>
<div class="card"><h3>Tuition / Funding</h3>{p['tui']}.</div>
<div class="card"><h3>Curriculum</h3>待补 - qualifying exam, course distribution, thesis handbook to be filled from graduate program guide.</div>
</div>
<h2>Notes</h2>
<ul>
<li>Source: UBC ECE / McGill ECE / Waterloo ECE / U of T CS / UBC CS official admissions pages.</li>
<li>All five are Canadian research PhDs fully funded; none require GRE for the current cycle.</li>
<li>Waterloo ECE offers three intakes (Fall/Winter/Spring) and guaranteed CAD $25,000/year GRS; UBC guarantees minimum CAD $18,000/year for 4 years.</li>
<li>UBC CS offers a PhD Track for direct bachelor's entry; U of T CS also allows direct entry from bachelor's (A-).</li>
<li>Fields marked 待补 will be filled when the official graduate handbook PDF is reachable.</li>
<li>Official pages may update; always confirm on the school's admissions site before applying.</li>
</ul>
</body></html>"""

details_meta = [
    ("ubc-ece-phd.html", "University of British Columbia (Vancouver, Faculty of Applied Science)", "PhD in Electrical and Computer Engineering"),
    ("mcg-ece-phd.html", "McGill University (Faculty of Engineering)", "PhD in Electrical and Computer Engineering"),
    ("uw-ece-phd.html", "University of Waterloo (Faculty of Engineering)", "PhD in Electrical and Computer Engineering"),
    ("ut-cs-phd.html", "University of Toronto (Faculty of Arts & Science, Dept. of Computer Science)", "PhD in Computer Science"),
    ("ubc-cs-phd.html", "University of British Columbia (Vancouver, Faculty of Science, Dept. of Computer Science)", "PhD in Computer Science"),
]

for fname, scn, tag in details_meta:
    p = next(p for p in new_programs if p["url"].endswith(fname))
    out = os.path.join(DETAILS_DIR, fname)
    with open(out, "w", encoding="utf-8") as f:
        f.write(detail_html(p, scn, tag))
    print("Wrote:", fname)

with open(INDEX, "r", encoding="utf-8") as f:
    html = f.read()

def fmt_prog(p):
    return (
        '{{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(**p)

new_block = ",\n" + ",\n".join(fmt_prog(p) for p in new_programs)

m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
if not m:
    raise SystemExit("PROGRAMS array not found")
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[':
        depth += 1
    elif c == ']':
        depth -= 1
    i += 1
insert_at = i - 1
new_html = html[:insert_at] + new_block + "\n" + html[insert_at:]

vd_new = [p["url"] for p in new_programs]
m2 = re.search(r'const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[', new_html)
if not m2:
    raise SystemExit("VD Set not found")
start2 = m2.end()
depth2 = 1
j = start2
while j < len(new_html) and depth2 > 0:
    c = new_html[j]
    if c == '[':
        depth2 += 1
    elif c == ']':
        depth2 -= 1
    j += 1
insert_at2 = j - 1
vd_block = "," + ",".join('"{}"'.format(u) for u in vd_new)
new_html = new_html[:insert_at2] + vd_block + new_html[insert_at2:]

with open(INDEX, "w", encoding="utf-8") as f:
    f.write(new_html)

print("Appended {} PROGRAMS entries and {} VD entries".format(len(new_programs), len(vd_new)))
print("Done. File size:", os.path.getsize(INDEX))
