# -*- coding: utf-8 -*-
"""Round 206: add 5 CS PhDs - CMU / Columbia / UChicago / Duke / JHU."""
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": "cmu-cs-phd",
        "s": "cmu",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Carnegie Mellon University, School of Computer Science, Computer Science Department)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Pittsburgh PA; expected completion ~5 years; 72 university units of graduate courses plus directed research (at least 24 research units per semester); admits Fall only; strong CS/math background expected; SCS houses 7 research departments (CSD, LTI, RI, MLD, Cylab C>S, HCII, ISR) but CSD PhD is the canonical CS PhD.",
        "ddl": "Early deadline November 29 (3pm EST, $80 fee); Final deadline December 13 (3pm EST, $100 fee); all supporting documents and letters of recommendation due by final deadline.",
        "lang": "TOEFL iBT required for applicants whose native language is not English (no exceptions; institution code 4256, dept 78); IELTS accepted in lieu of TOEFL; TOEFL may be waived if the applicant has completed a bachelor's or master's degree at a US institution.",
        "test": "GRE General: OPTIONAL for CSD PhD (a no-GRE application is not disadvantaged; applicants who took the GRE are encouraged to self-report; GRE at-home test is NOT accepted; institution code 2074, dept 0402; GRE must be less than 5 years old). Required: online SCS application; transcripts from every university attended; 3 letters of recommendation; SOP; current resume. PhD students receive tuition + fees + monthly stipend via RA/TA/fellowship/NSF grants. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "All admitted PhD students receive financial support: tuition + fees + monthly stipend via research assistantships, outside fellowships (NSF / NDSEG / Hertz), or teaching assistantships.",
        "url": "details/cmu-cs-phd.html",
    },
    {
        "id": "col-cs-phd",
        "s": "col",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Columbia University, Fu Foundation School of Engineering and Applied Science, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, New York NY; Fall and Spring admission (Spring is small); students apply to the department at large and are nominated by faculty; MS/PhD track and direct PhD track both exist; PAR (Pre-submission Application Review) program offered Oct-Nov for PhD applicants to get one-time feedback from a current PhD student.",
        "ddl": "Fall: December 15; Spring: October 15. Late applications may be reviewed but are less likely to receive department funding.",
        "lang": "TOEFL iBT (incl. Home Edition), IELTS Academic, PTE Academic, or Duolingo English Test accepted; institution code 2111 for SEAS; scores required for applicants whose undergraduate degree is from a country where English is not the official and widely spoken language.",
        "test": "GRE General: OPTIONAL for 2026 admission cycle (school code 2111). Required: online SEAS application; $85 non-refundable application fee (waivers available for eligible US citizens/PRs, veterans, and certain program participants); transcripts from every post-secondary institution; 3 letters of recommendation; personal statement; CV/resume; publications optional; interview may be requested. PhD students are funded via RA/TA/fellowship covering tuition + stipend. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "PhD students are funded via department RA/TA/fellowship covering tuition + stipend (apply before the priority deadline for best funding chance).",
        "url": "details/col-cs-phd.html",
    },
    {
        "id": "uchicago-cs-phd",
        "s": "uchicago",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (University of Chicago, Physical Sciences Division, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Chicago IL; three phases: Qualifying (core coursework) → Candidacy (admit to candidacy) → Dissertation; expected ~6 years; research advisor by end of Spring Quarter of first year; qualifying exam by end of Autumn Quarter of third year; thesis defense by Spring of year 6; separate from the professional MPCS (9-course / 12-course MS) program.",
        "ddl": "December 10, 2026 (all application materials; $90 application fee; fee waivers available from the Physical Sciences Division); admissions decisions early-to-mid February; April 15 reply date.",
        "lang": "English proficiency required for non-native speakers (TOEFL/IELTS per Graduate Division policy; check current UChicago GSPE minimums).",
        "test": "GRE General: OPTIONAL / NOT REQUIRED for this PhD application cycle. Required: online UChicago graduate application; $90 fee; 3 letters of recommendation; SOP; transcripts; CV. PhD students are funded via RA/TA/fellowship; industry external fellowships (NVIDIA, Google PhD, etc.) are available on top. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "PhD students funded via RA/TA/fellowship covering tuition + stipend + insurance; external industry fellowships (NVIDIA, Google PhD, Hertz) supplement.",
        "url": "details/uchicago-cs-phd.html",
    },
    {
        "id": "duke-cs-phd",
        "s": "duke",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Duke University, Trinity College of Arts and Sciences / Pratt School of Engineering, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Durham NC; Fall admission only; ~8 courses (24 credits) in CS or related field; 6 semesters of full-time study; breadth requirement (3 of 6 core areas); research initiation project then dissertation defense; 37 faculty, ~80 PhD students; 100% of PhD students receive financial aid.",
        "ddl": "December 15, 2026, 11:59:59 PM Eastern Standard Time (Fall 2027 entry).",
        "lang": "TOEFL iBT, IELTS Academic, or Duolingo English Test required for applicants whose first language is not English; test waiver may apply for some applicants.",
        "test": "GRE General: OPTIONAL for PhD admission (GRE is REQUIRED for the terminal MS program). Required: online Duke Graduate School application; unofficial transcripts at submission (official upon admission); 3 letters of recommendation; SOP; CV/resume; undergraduate GPA on 4.0 scale. PhD funding: tuition + fees + insurance + stipend guaranteed for 5 years in good standing; year 1-2 via grad fellowship + TA, year 3+ via advisor research grant; summer research fellowship available. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "100% of PhD students funded: tuition + fees + health insurance + stipend, guaranteed 5 years (typically extended when needed).",
        "url": "details/duke-cs-phd.html",
    },
    {
        "id": "jhu-cs-phd",
        "s": "jhu",
        "n": "Computer Science (PhD)",
        "en": "PhD in Computer Science (Johns Hopkins University, Whiting School of Engineering, Department of Computer Science)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "On-campus research PhD, Baltimore MD; Fall admission only (no Spring cohort); application window opens ~August 15; must complete at least one semester of TA as a degree requirement; faculty match based on mutual research interest; VTSI (Vivien Thomas Scholars Initiative) supplemental fellowship available for students from eligible HBCUs / community colleges / regional Maryland-Virginia-DC institutions.",
        "ddl": "December 15, 2026 (Fall 2027 entry; VTSI supplemental deadline December 1); application opens ~August 15.",
        "lang": "TOEFL iBT preferred 100 (paper 600 / computer 250); OR IELTS Academic band 7.0; no hard minimum but preferred scores are stated.",
        "test": "GRE General: NOT REQUIRED (Whiting School of Engineering does not require GRE for PhD programs; no minimum scores). Required: online application; $75 application fee; transcripts; 3 letters of recommendation; SOP; CV. All full-time CS PhD students in good standing receive full funding: ~$50,000/year stipend (AY26-27 advisor stipend ~$52,000) + tuition + health insurance; primarily RA, with some TA time. Score distributions reflect admitted cohort, not minimum thresholds.",
        "tui": "All full-time PhD students in good standing receive full funding: ~$50,000/year stipend (AY26-27 ~$52,000) + tuition + health insurance; summer industry internships pay significantly more.",
        "url": "details/jhu-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: CMU SCS CSD / Columbia SEAS CS / UChicago CS / Duke Graduate School / JHU Whiting CS official admissions pages.</li>
<li>All five programs are research PhDs with full funding; none require GRE for the current cycle; CMU rejects at-home GRE.</li>
<li>JHU stipend ~$50k (AY26-27 ~$52k); Duke guarantees 5-year funding; UChicago offers 3-phase qualifying/candidacy/dissertation structure.</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 = [
    ("cmu-cs-phd.html", "Carnegie Mellon University (School of Computer Science)", "PhD in Computer Science"),
    ("col-cs-phd.html", "Columbia University (Fu Foundation SEAS)", "PhD in Computer Science"),
    ("uchicago-cs-phd.html", "University of Chicago (Physical Sciences Division)", "PhD in Computer Science"),
    ("duke-cs-phd.html", "Duke University (Trinity / Pratt)", "PhD in Computer Science"),
    ("jhu-cs-phd.html", "Johns Hopkins University (Whiting School of Engineering)", "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))
