# -*- coding: utf-8 -*-
"""Round 202: add 5 - Princeton ECE PhD / Harvard ECE PhD / Stanford CS PhD / Caltech CS PhD / Berkeley EECS PhD."""
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": "princeton-ece-phd",
        "s": "princeton",
        "n": "Electrical and Computer Engineering (PhD)",
        "en": "PhD in Electrical and Computer Engineering (Princeton University, Department of Electrical and Computer Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, Princeton NJ; nominal 5 years; first semester coursework, thesis advisor selected start of spring semester; students earn a Masters of Arts (MA) en route to PhD; 5-to-1 student-faculty ratio, ~170 total graduate students.",
        "ddl": "December 15, 11:59 PM ET (Fall admission only; decisions emailed by mid-February; program starts August)",
        "lang": "TOEFL / IELTS required of non-native English speakers (Princeton GSAS rule)",
        "test": "GRE General: Optional/not required (not disadvantage if omitted). Required: bachelor's in EE/CS/Physics/related; resume/CV; statement of academic purpose; transcripts (English); 3 letters of recommendation; select research area at application. Full financial support throughout the program: generous stipend + tuition waiver + health fees. Score distributions (when published) reflect admitted cohort, not minimum thresholds.",
        "tui": "Fully funded: stipend + tuition waiver + health fees for 5 years (good progress)",
        "url": "details/princeton-ece-phd.html",
    },
    {
        "id": "harvard-ece-phd",
        "s": "harvard",
        "n": "Electrical Engineering (PhD)",
        "en": "PhD in Engineering Sciences: Electrical Engineering (Harvard John A. Paulson School of Engineering and Applied Sciences, SEAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, Cambridge MA; conferred through Harvard Griffin GSAS; select 'Engineering and Applied Sciences' then 'PhD Engineering Sciences: Electrical Engineering' on the application; fields include sensing/systems, IoT, photonics, quantum, applied physics, signal processing.",
        "ddl": "December 15, 5:00 PM ET (Fall admission only; no late applications)",
        "lang": "TOEFL iBT / IELTS Academic required of non-native English speakers (Harvard Griffin GSAS rule)",
        "test": "GRE General: NOT ACCEPTED (do not submit official or unofficial scores; do not mention in materials). Required: bachelor's in natural sciences/math/CS/engineering; transcripts; CV/resume; personal statement; 3 letters of recommendation; Supplemental SEAS Application Form. PhD students fully funded (stipend + tuition + health fees). Score distributions (when published) reflect admitted cohort, not minimum thresholds.",
        "tui": "Fully funded: stipend + tuition fellowship + health insurance",
        "url": "details/harvard-ece-phd.html",
    },
    {
        "id": "stanford-cs-phd",
        "s": "stanford",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Stanford University, Computer Science Department, School of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, Stanford CA; Autumn quarter entry only; 135 course units required (up to 45 transferable); must take courses from at least 4 different Academic Council faculty; 8-10 units per quarter; 1-unit CS300 seminar + CS499 research required each quarter; minimum 3.0 GPA for conferral.",
        "ddl": "December 8, 2026 (Autumn 2027 entry; decisions February 2027; application opens September 15, 2026)",
        "lang": "TOEFL / IELTS required of non-native English speakers (Stanford Graduate Admissions rule)",
        "test": "GRE: NOT required and NOT considered for PhD applicants. Required: SOP (max 2 pages single-spaced / 8,000 chars); 3 recommendation letters (online only, no mail/email/fax); transcripts; $125 application fee. All incoming PhD students supported by teaching and/or research assistantships; strongly encouraged to apply for external fellowships (KHS up to 3 years full funding). Score distributions (when published) reflect admitted cohort, not minimum thresholds.",
        "tui": "Fully funded: RA/TA + tuition + stipend for duration of PhD (good progress)",
        "url": "details/stanford-cs-phd.html",
    },
    {
        "id": "caltech-cs-phd",
        "s": "caltech",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (California Institute of Technology, Computing + Mathematical Sciences / CMS Department)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, Pasadena CA; Fall entry only; CMS department also offers PhD in Applied + Computational Mathematics, Computing + Mathematical Sciences, Control + Dynamical Systems; small research groups / individual work with faculty advisor.",
        "ddl": "December 1, 2026 (Fall 2027 entry; late applications considered with lower priority; decisions by end of March / April 1)",
        "lang": "TOEFL / IELTS required of international students (Caltech institution code 4034)",
        "test": "GRE General: NOT required for 2026-2027 admissions. Required: bachelor's in science/engineering related to CS; transcripts; 3 letters of recommendation; statement of purpose; research interests match with faculty. Applicants automatically considered for financial aid (no separate application). PhD students receive tuition + living stipend. Score distributions (when published) reflect admitted cohort, not minimum thresholds.",
        "tui": "Fully funded: tuition + living stipend + health insurance",
        "url": "details/caltech-cs-phd.html",
    },
    {
        "id": "berkeley-eecs-phd",
        "s": "berkeley",
        "n": "Electrical Engineering and Computer Sciences (PhD)",
        "en": "PhD in Electrical Engineering and Computer Sciences (UC Berkeley, Department of Electrical Engineering and Computer Sciences, College of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, Berkeley CA; Fall entry only; combines coursework + original research; MS/PhD and PhD tracks available (external PhD applicants apply directly); institution code 4833 for ETS score reports.",
        "ddl": "December 1, 2026, 8:59 PM PST (Fall 2027 entry; no late applications)",
        "lang": "TOEFL iBT: 90 minimum total (tests June 1, 2025 - Jan 20, 2026) OR 5 minimum total with 4.5 speaking/writing (tests on/after Jan 21, 2026); IELTS Academic accepted (no IELTS Indicator).",
        "test": "GRE: NO LONGER REQUIRED NOR ACCEPTED. Required: minimum 3.0 GPA (B) on 4.0 scale (do not convert non-4.0 scales); 3 letters of recommendation (PDF upload through application); transcripts; SOP. All incoming doctoral students (MS/PhD and PhD) offered support; external fellowship applications encouraged. Score distributions (when published) reflect admitted cohort, not minimum thresholds.",
        "tui": "Fully funded: RA/TA + tuition + stipend for doctoral students",
        "url": "details/berkeley-eecs-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>待补 - course list, qualifying exams, thesis requirements to be filled from graduate handbook.</div>
</div>
<h2>Notes</h2>
<ul>
<li>Source: Princeton ECE / Harvard SEAS / Stanford CS / Caltech CMS / Berkeley EECS official admissions pages.</li>
<li>All five programs are research PhDs with full funding; none require or accept GRE for the 2026-27 cycle.</li>
<li>Fields marked 待补 will be filled when the official graduate handbook / student 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 = [
    ("princeton-ece-phd.html", "Princeton University (ECE)", "PhD in Electrical and Computer Engineering"),
    ("harvard-ece-phd.html", "Harvard University (SEAS)", "PhD in Engineering Sciences: Electrical Engineering"),
    ("stanford-cs-phd.html", "Stanford University (Computer Science)", "PhD in Computer Science"),
    ("caltech-cs-phd.html", "California Institute of Technology (CMS)", "PhD in Computer Science"),
    ("berkeley-eecs-phd.html", "UC Berkeley (EECS)", "PhD in Electrical Engineering and Computer Sciences"),
]

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