# -*- coding: utf-8 -*-
"""Round 208: add 5 CS/ECE PhDs - Rice / Cornell CS / UCSD CSE / UCSD ECE / UofT ECE."""
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": "rice-cs-phd",
        "s": "rice",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Rice University, School of Engineering, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Houston TX; Fall admission; applications open around September 1; after the January 1 priority deadline applications continue to be reviewed on a rolling basis; no standalone external thesis MS (PhD is the research route; MCS/MAI are professional course-based); strong CS/math background expected.",
        "ddl": "January 1, 2027 (PhD priority deadline for Fall 2027 entry; rolling review after; decisions by April 15).",
        "lang": "TOEFL iBT, IELTS Academic, or Duolingo English Test accepted for non-native speakers.",
        "test": "GRE General: OPTIONAL / not required (school code 6609; subject test not required; applicants may self-report). Required: online Rice Graduate and Postdoctoral Studies application; electronic transcripts from every institution attended; at least 3 letters of recommendation; SOP; CV. All enrolled full-time PhD students receive full tuition + stipend; first-year students supported by department fellowship, thereafter by advisor RA; external fellows encouraged. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Full tuition + stipend; first-year department fellowship, thereafter advisor RA; external fellowships encouraged.",
        "url": "details/rice-cs-phd.html",
    },
    {
        "id": "cornell-cs-phd",
        "s": "cornell",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Cornell University, Cornell Bowers College of Computing and Information Science, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Ithaca NY + NYC; Fall admission only; first two semesters spent in Ithaca, thereafter based at the principal advisor's location (Ithaca or NYC); typically 5-7 years; MS awarded after A Exam, PhD after B Exam; course requirements determined by the Special Committee.",
        "ddl": "December 15, 2026 (hard deadline; no Spring admission; apply early strongly advised; TOEFL/IELTS scores may arrive after deadline but delay review).",
        "lang": "TOEFL iBT or IELTS Academic required for international applicants per Cornell Graduate School.",
        "test": "GRE General: NOT REQUIRED (submitted scores are masked and not reviewed). Required: online Cornell Graduate School application; scanned transcripts (no paper); 3 letters of recommendation; SOP; CV; English proficiency scores. Full support for duration of degree in good standing via TA + GRA + fellowship: tuition + health insurance + stipend; students may not use paid agents / credentials services. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Full support for duration of degree: tuition + health insurance + stipend via TA / GRA / fellowship.",
        "url": "details/cornell-cs-phd.html",
    },
    {
        "id": "ucsd-cse-phd",
        "s": "ucsd",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science / Computer Engineering (University of California San Diego, Jacobs School of Engineering, Department of Computer Science and Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, La Jolla CA; Fall quarter admission only (no Spring); total university support cannot exceed 7 years; TA requirement: 50% TA plus CSE 500 (Teaching Assistantship); PhD and master's admissions are made separately (current UCSD MS students must petition to transfer).",
        "ddl": "December 16, 2026, 11:59 PM Pacific Time (application opens September 2, 2026; hard deadline; no late exceptions; final offers typically by beginning of April).",
        "lang": "TOEFL iBT or IELTS Academic required per UCSD Graduate Division.",
        "test": "GRE General: NOT REQUIRED for Fall 2027 (PhD and MS; applicants may still submit valid scores; UCSD institution code 4836; no department code needed). Required: online UCSD graduate application; transcripts; letters; SOP; CV. Limited CSE fee waivers for international students based on diversity / social justice / overcoming adversity criteria (not financial need alone). PhD students funded via fellowship / RA / TA. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "PhD students funded via fellowship / RA / TA; total university support capped at 7 years.",
        "url": "details/ucsd-cse-phd.html",
    },
    {
        "id": "ucsd-ece-phd",
        "s": "ucsd",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (University of California San Diego, Jacobs School of Engineering, Department of Electrical and Computer Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, La Jolla CA; Fall admission only (once per year); B.S. and/or M.S. in engineering, physical sciences, or math from accredited institution; minimum cumulative GPA 3.0 (4.0 scale); research areas: communications, circuits, computing, control, energy, photonics, signals, systems.",
        "ddl": "December 16, 2026, 11:59 PM Pacific Time (PhD; MS deadline January 6, 2027; application opens September 2, 2026).",
        "lang": "TOEFL iBT or IELTS Academic required per UCSD Graduate Division; institution code 4836 (ECE dept code 66 optional for TOEFL).",
        "test": "GRE General: NOT REQUIRED for Fall 2027 (both MS and PhD; school code 4836, ECE dept code 1203 optional; scores valid up to 5 years). Required: online UCSD graduate application; transcripts; 3 letters; SOP; CV. PhD students funded via fellowship / RA / TA. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "PhD students funded via fellowship / RA / TA.",
        "url": "details/ucsd-ece-phd.html",
    },
    {
        "id": "ut-ece-phd",
        "s": "ut",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (University of Toronto, Faculty of Applied Science and Engineering, Edward S. Rogers Sr. Department of ECE)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Toronto ON; entry in September (Fall) and January (Winter); expected completion within 48 months; requires equivalent of U of T MASc with thesis in ECE or related field (CS/math/physics); direct entry for exceptionally qualified 4-year bachelor's holders; current MASc students may fast-track to PhD; must complete TWO applications (SGS system + ECE system).",
        "ddl": "Priority: December 1; Regular: January 7 (for September or January entry; both SGS and ECE applications plus 2 references must be fully completed).",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo per U of T SGS English facility requirement.",
        "test": "GRE General: not required per U of T ECE admissions. Required: SGS online application + ECE application; 2 references; statement of intent; CV; transcripts. Guaranteed funding: 4 years for MASc-entry PhD, 5 years for direct-entry PhD; minimum package = ECE stipend + tuition & fees (PhD stipend ~CAD $20,000, 2023-24; direct-entry typically higher); supervisors may pay more. External awards (OGS CAD $5,000/session, NSERC, Indigenous and Black Engineering Fellowship $25,000/year for 4 years) enhance package. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Guaranteed 4-year (MASc-entry) / 5-year (direct-entry) funding: ECE stipend (~CAD $20,000) + tuition + fees; external awards (OGS, NSERC, Indigenous/Black Fellowship) on top.",
        "url": "details/ut-ece-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: Rice CS / Cornell Bowers CS / UCSD CSE / UCSD ECE / U of T ECE official admissions pages.</li>
<li>All five are research PhDs fully funded; none require GRE for Fall 2027.</li>
<li>UCSD CSE/ECE deadline is December 16 (later than most US Dec 15); U of T ECE requires TWO applications and has a January Winter intake.</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 = [
    ("rice-cs-phd.html", "Rice University (George R. Brown School of Engineering)", "PhD in Computer Science"),
    ("cornell-cs-phd.html", "Cornell University (Bowers CIS)", "PhD in Computer Science"),
    ("ucsd-cse-phd.html", "UC San Diego (Jacobs School of Engineering)", "PhD in Computer Science / Computer Engineering"),
    ("ucsd-ece-phd.html", "UC San Diego (Jacobs School of Engineering)", "PhD in Electrical and Computer Engineering"),
    ("ut-ece-phd.html", "University of Toronto (Faculty of Applied Science and Engineering)", "PhD in Electrical and Computer Engineering"),
]

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