# -*- coding: utf-8 -*-
"""Round 205: add 5 CS PhDs - UVA CpE / UNC / Notre CSE / UCLA / NYU Courant."""
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": "uva-cpe-phd",
        "s": "uva",
        "n": "Computer Engineering (PhD)",
        "en": "PhD in Computer Engineering (University of Virginia, School of Engineering and Applied Science, Charles L. Brown Department of ECE)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Charlottesville VA; admits Fall and a small Spring cohort; no application fee; strong expected background in both computing and electronic systems (a degree in EE/CpE/CS is not strictly required); contact cpe-support@virginia.edu for transfer questions.",
        "ddl": "Fall: December 15 (fellowship priority); Spring: September 29 (previous cycle; confirm current cycle)",
        "lang": "TOEFL iBT 90+ minimum (most admitted score 24 on each section); OR IELTS Academic 7.0 with 7.0 in each band; waiver for applicants who earned a 4-year degree at an English-speaking institution (a 4-year non-English degree plus an English-taught master's does not waive).",
        "test": "GRE General: OPTIONAL for 2026 applications (UVA Engineering has waived the GRE requirement; if self-reported, official scores required upon matriculation; institution code 5820). Required: online application; transcripts; 3 letters of recommendation; SOP/essay. PhD students considered for assistantships and fellowships by January 15 for Fall. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Assistantships and fellowships available for PhD applicants; consider by January 15 for Fall",
        "url": "details/uva-cpe-phd.html",
    },
    {
        "id": "unc-cs-phd",
        "s": "unc",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (University of North Carolina at Chapel Hill, College of Arts and Sciences, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Chapel Hill NC; Fall admission only (other semesters only in unusual circumstances after consulting the Director of Graduate Studies); entering students expected to have substantial math and CS background (at least 6 semester courses in math and 6 in CS); admitted PhD profile: strong research record, SOP, CV, 3 letters.",
        "ddl": "Graduate School fellowship priority: December 15, 2026; department RA/TA priority: January 5, 2027; final Graduate School deadline: March 9, 2027 (Fall entry)",
        "lang": "TOEFL iBT 90 minimum (tests before Jan 26, 2026) OR new scale 5 (tests on/after Jan 26, 2026); OR IELTS Academic 7.0; OR Duolingo English Test 110; scores valid within 2 years; waiver for English-medium institutions per Graduate School.",
        "test": "GRE General: NOT required (no penalty for not submitting; holistic review). Required: online Graduate School application; transcripts; SOP; CV/resume; 3 letters of recommendation; areas of interest / faculty matches. Majority of PhD students receive fellowship, RA, or TA covering tuition + health insurance + stipend. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Majority of PhD students funded via fellowship / RA / TA covering tuition + health insurance + stipend",
        "url": "details/unc-cs-phd.html",
    },
    {
        "id": "notre-cse-phd",
        "s": "notre",
        "n": "Computer Science and Engineering (PhD)",
        "en": "PhD in Computer Science and Engineering (University of Notre Dame, College of Engineering, Department of Computer Science and Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Notre Dame IN; degree can be completed in 3-5 years; minimum 2 years residency; open to B.S. or M.S. applicants (master's not required); research areas: AI/ML, algorithms, assistive tech, computer architecture, computer vision, medical imaging, NLP, networks/data science, HPC, security, software engineering, visualization, wireless/embedded.",
        "ddl": "Fall: December 15; Spring: October 15 (small spring cohort)",
        "lang": "TOEFL iBT 80 minimum pre-Feb 2026 (23 speaking) OR new scale 4.5 average with no section below 4.0; OR IELTS Academic 7.0; OR Duolingo English Test 120; TOEFL ITP Plus for China accepted for mainland applicants unable to test standard iBT.",
        "test": "GRE General: NOT required (recommended but not required). Required: online application; bachelor's degree in CS or related; SOP/statement of intent; CV; 3 letters of recommendation (from faculty who can judge research potential); unofficial transcripts. PhD support: 12-month stipend + full tuition scholarship + 100% health insurance premium + conference/travel funding; engineering stipend ~$42,435 (up to $50,000 for select fellows). Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "Full tuition + 12-month stipend + 100% health insurance + travel funding (fellowship / TA / RA)",
        "url": "details/notre-cse-phd.html",
    },
    {
        "id": "ucla-cs-phd",
        "s": "ucla",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (University of California Los Angeles, Samueli School of Engineering, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Los Angeles CA; Fall admission only (no Winter/Spring); expected GPA 3.0+; admitted profile includes strong undergraduate research; students apply directly to PhD (master's not required); separate from the ECE PhD program in the Samueli School.",
        "ddl": "December 15, 2026, 11:59 PM Pacific Time (Fall 2027 entry; application window mid-September to December 15)",
        "lang": "TOEFL iBT minimum per UCLA Graduate Division (ECE department uses 87 pre-2026 / 4.5 new scale); OR IELTS Academic 7.0; UCLA does not accept MyBest TOEFL; conditional admission and transitional pre-master's programs are not offered.",
        "test": "GRE General: NOT required for 2027-2028 cycle (optional; voluntary submission receives no greater weight); institution code 4837. Required: UCLA graduate application; bachelor's degree (4 years) with above-average scholarship; transcripts; SOP; 3 letters of recommendation. PhD admits generally receive full funding package. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "PhD admits generally receive full funding (tuition + stipend + insurance)",
        "url": "details/ucla-cs-phd.html",
    },
    {
        "id": "nyu-cs-phd",
        "s": "nyu",
        "n": "Computer Science (PhD, Courant)",
        "en": "PhD in Computer Science (New York University, Graduate School of Arts and Science, Courant Institute of Mathematical Sciences / CIMS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus full-time research PhD, New York NY; 72 graduate credits; GPA must stay 3.5+ from the fifth class onward; PhD-JD dual degree available in Computer Science/Law (two separate applications); optional research abroad at NYU Shanghai or NYU Abu Dhabi; research strengths: data management, cybersecurity, computer games, visualization, web search, graphics, vision, theory.",
        "ddl": "December 12, 5:00 PM Eastern Time (Fall admission only; if deadline falls on weekend/holiday, next business day)",
        "lang": "TOEFL or IELTS required for applicants whose native language or undergraduate medium of instruction is not English; waiver for US citizens/permanent residents, native English speakers, or applicants completing a bachelor's/master's at an English-instruction institution.",
        "test": "GRE General: NOT required (optional; if submitted, official scores not needed at application). Required: online GSAS application; SOP; CV; 3 letters of recommendation; transcripts; evidence of original research capability (publications welcome as links, not as attachments). All full-time CS PhD students in good standing receive MacCracken fellowship or RA support: 9-month stipend + tuition + health insurance; external fellowship winners receive a 25% stipend supplement. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "All full-time PhD students funded: MacCracken fellowship / RA / TA covering tuition + 9-month stipend + health insurance",
        "url": "details/nyu-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: UVA Engineering / UNC CS Graduate School / Notre Dame Graduate School / UCLA Samueli / NYU GSAS Courant official admissions pages.</li>
<li>All five programs are research PhDs with full or near-full funding; none require GRE for the current cycle.</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 = [
    ("uva-cpe-phd.html", "University of Virginia (SEAS)", "PhD in Computer Engineering"),
    ("unc-cs-phd.html", "UNC Chapel Hill (College of Arts & Sciences)", "PhD in Computer Science"),
    ("notre-cse-phd.html", "University of Notre Dame (College of Engineering)", "PhD in Computer Science and Engineering"),
    ("ucla-cs-phd.html", "UCLA (Samueli School of Engineering)", "PhD in Computer Science"),
    ("nyu-cs-phd.html", "New York University (Courant Institute / GSAS)", "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))
