# -*- coding: utf-8 -*-
"""Round 195: add 5 programs - Cornell MPS AEM, UVA MSA, CMU MSPM, UCLA Biostat MS, UBC MPPGA."""
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")

# ---------- 5 new program records ----------
new_programs = [
    {
        "id": "cornell-mps-aem",
        "s": "cornell",
        "n": "Applied Economics and Management (MPS)",
        "en": "Master of Professional Studies in Applied Economics and Management",
        "deg": "MPS",
        "lvl": "m",
        "stem": 1,
        "dur": "1 year full-time, Ithaca NY",
        "ddl": "Round 1 Dec 1 / Round 2 Jan 15 / Round 3 Mar 1 / Round 4 Apr 15 (Fall entry)",
        "lang": "TOEFL iBT min sub-scores (S22/R20/L15); IELTS 7.0; waiver possible",
        "test": "GMAT/GRE required (waiver available by application); no minimum; code 5811 / ETS 2098",
        "tui": "待补 (see Dyson cost of attendance)",
        "url": "details/cornell-mps-aem.html",
    },
    {
        "id": "uva-msa",
        "s": "uva",
        "n": "Accounting (MS)",
        "en": "Master of Science in Accounting (McIntire School of Commerce)",
        "deg": "MS",
        "lvl": "m",
        "stem": 0,
        "dur": "~1 year, Fall only, Charlottesville VA",
        "ddl": "Rolling Fall admission (check McIntire deadlines page)",
        "lang": "TOEFL 100 iBT / IELTS 7.5",
        "test": "GMAT/GRE accepted but not required",
        "tui": "待补 (see McIntire MSA tuition)",
        "url": "details/uva-msa.html",
    },
    {
        "id": "cmu-mspm",
        "s": "cmu",
        "n": "Product Management (MS)",
        "en": "Master of Science in Product Management (Tepper x School of Computer Science)",
        "deg": "MSPM",
        "lvl": "m",
        "stem": 1,
        "dur": "1 calendar year, Pittsburgh PA; Fall (Aug/Sep) & Spring (Jan) entry",
        "ddl": "Multiple rounds (R1 ~ Jun, R2 ~ Jul, R3 ~ Aug for Fall; Spring ~ Aug/Sep)",
        "lang": "TOEFL 2074 / IELTS 7.0 (all bands 7.0) / Duolingo accepted",
        "test": "GMAT/GRE required (waiver possible); GMAT code 69H-XH-84 / GRE 4883",
        "tui": "待补 (see Tepper MSPM cost)",
        "url": "details/cmu-mspm.html",
    },
    {
        "id": "ucla-biostat-ms",
        "s": "ucla",
        "n": "Biostatistics (MS)",
        "en": "Master of Science in Biostatistics (Fielding School of Public Health)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "On-campus, Fall only, Los Angeles CA",
        "ddl": "Dec 1, 2026 (Fall 2027); rolling after, but Dec 1 strongly preferred",
        "lang": "TOEFL 87 min (W25/S24/R21/L17); IELTS accepted",
        "test": "GRE optional",
        "tui": "待补 (see Fielding tuition)",
        "url": "details/ucla-biostat-ms.html",
    },
    {
        "id": "ubc-mppga",
        "s": "ubc",
        "n": "Public Policy and Global Affairs (MPPGA)",
        "en": "Master of Public Policy and Global Affairs (School of Public Policy and Global Affairs)",
        "deg": "MPPGA",
        "lvl": "m",
        "stem": 0,
        "dur": "2 years, Vancouver BC; September intake",
        "ddl": "Primary Jan 26, 2027 (Sep 2027); Secondary Mar 16, 2027",
        "lang": "TOEFL 100 (min 22 each) / IELTS 7.0 (min 7.0 each) / DET 130",
        "test": "GRE/GMAT not required",
        "tui": "待补 (see SPPGA tuition)",
        "url": "details/ubc-mppga.html",
    },
]

# ---------- detail page templates ----------
def detail_html(p, school_cn, tagline):
    stem_badge = "STEM" if p["stem"] else "Non-STEM"
    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 #1a5fb4;padding-bottom:8px}}
h2{{font-size:16px;color:#1a5fb4;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:#1a5fb4;color:#fff;padding:2px 8px;border-radius:10px;font-size:12px;margin-left:8px}}
.back{{display:inline-block;margin-bottom:16px;color:#1a5fb4;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></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']}. Score distributions (when published) reflect admitted cohort, not minimum thresholds.</div>
<div class="card"><h3>Tuition / Funding</h3>{p['tui']}.</div>
<div class="card"><h3>Curriculum</h3>待补 - course list, credits, concentrations to be filled from official bulletin.</div>
</div>
<h2>Notes</h2>
<ul>
<li>Source: official university / school admissions page (see program page for URL).</li>
<li>Fields marked 待补 will be filled when the official bulletin / bulletin 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 = [
    ("cornell-mps-aem.html", "Cornell University", "Dyson School / SC Johnson College of Business"),
    ("uva-msa.html", "University of Virginia", "McIntire School of Commerce"),
    ("cmu-mspm.html", "Carnegie Mellon University", "Tepper School x School of Computer Science"),
    ("ucla-biostat-ms.html", "UCLA", "Fielding School of Public Health"),
    ("ubc-mppga.html", "University of British Columbia", "School of Public Policy and Global Affairs"),
]

# ---------- write detail pages ----------
for fname, scn, tag in details_meta:
    # find matching program
    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)

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

# Build new PROGRAMS entry string (no quoted keys, matching existing style)
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)

# Locate PROGRAMS array end with bracket-depth matching (initial depth=1 after [)
m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
if not m:
    raise SystemExit("PROGRAMS array not found")
start = m.end()  # position just after [
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[':
        depth += 1
    elif c == ']':
        depth -= 1
    i += 1
# i is now just past the closing ]
insert_at = i - 1  # position of closing ]
# Insert before the closing ]
new_html = html[:insert_at] + new_block + "\n" + html[insert_at:]

# ---------- append to VERIFIED_DETAILS set ----------
vd_new = [p["url"] for p in new_programs]
# Find const VERIFIED_DETAILS = new Set([ ... ])
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
# j is just past closing ]; insert before it
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))
