# -*- coding: utf-8 -*-
"""Round 199: add 3 confirmed USC Viterbi/Dornsife MS - HSM / SEDA / ME-EM Dual."""
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": "usc-hsme-ms",
        "s": "usc",
        "n": "Health Systems Management Engineering (MS)",
        "en": "Master of Science in Health Systems Management Engineering (Viterbi, Epstein Dept. of Industrial & Systems Engineering)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "On-campus, Los Angeles CA; Viterbi ISE; designed for engineers transitioning to healthcare management",
        "ddl": "Fall 2027 scholarship: Dec 15, 2026; Fall 2027 final (HSM only): May 1, 2027; Spring 2027: Oct 15, 2026",
        "lang": "TOEFL / IELTS required for non-native English speakers (USC grad admission rules)",
        "test": "GRE: Not required for 2027 applications; 3 letters of recommendation (highly recommended); transcripts; resume/CV; personal statement. Bachelor's in engineering / information science / hard science / math / business administration with strong quantitative coursework.",
        "tui": "待补 (see USC Viterbi tuition; dedicated Health Systems Management Scholarship $10k-$50k available for US-resident students)",
        "url": "details/usc-hsme-ms.html",
    },
    {
        "id": "usc-seda-ms",
        "s": "usc",
        "n": "Spatial Economics and Data Analysis (MS, SEDA)",
        "en": "Master of Science in Spatial Economics and Data Analysis (Dornsife, Spatial Sciences Institute x Dept. of Economics)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "Residential, ~20 months / 2 years; 32 units (8 courses, 4 units each); CIP 45.0702 (Geographic Information Science & Cartography) STEM-designated",
        "ddl": "Fall 2027: Jun 5, 2027 (per GIS admissions calendar; classes start Aug 23, 2027)",
        "lang": "TOEFL / IELTS required for non-native English speakers (USC Dornsife rules)",
        "test": "GRE: Not required (per Dornsife admission rules); joint program of Dept of Economics and Spatial Sciences Institute; quantitative curriculum blending economics + data science + spatial science; international students eligible",
        "tui": "待补 (see USC Dornsife tuition)",
        "url": "details/usc-seda-ms.html",
    },
    {
        "id": "usc-me-em-dual",
        "s": "usc",
        "n": "Mechanical Engineering / Engineering Management (MS Dual)",
        "en": "Master of Science in Mechanical Engineering / Master of Science in Engineering Management (Viterbi, AME x ISE dual degree)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "On-campus, Los Angeles CA; 48 units; designed for mechanical engineers moving into technical management roles",
        "ddl": "Fall 2027 scholarship: Dec 15, 2026; Fall 2027 final: Jan 15, 2027; Spring 2027: Oct 15, 2026",
        "lang": "TOEFL / IELTS required for non-native English speakers (USC Viterbi rules)",
        "test": "GRE: Not required for 2027 applications; transcripts; resume/CV; personal statement; 3 letters of recommendation (highly recommended). Bachelor's in engineering / aerospace / mechanical / mechatronics; strong background in computer engineering, linear systems, programming expected",
        "tui": "待补 (see USC Viterbi tuition)",
        "url": "details/usc-me-em-dual.html",
    },
]

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 #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></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: USC Viterbi / Dornsife / Spatial Sciences Institute official admissions pages (viterbigradadmission.usc.edu, gis.usc.edu, catalogue.usc.edu).</li>
<li>Fields marked 待补 will be filled when the official bulletin / bulletin PDF is reachable.</li>
<li>USC Viterbi policy: GRE not required for 2027 master's applications.</li>
<li>Official pages may update; always confirm on the school's admissions site before applying.</li>
</ul>
</body></html>"""

details_meta = [
    ("usc-hsme-ms.html", "University of Southern California (Viterbi)", "Epstein Dept. of Industrial & Systems Engineering"),
    ("usc-seda-ms.html", "University of Southern California (Dornsife)", "Spatial Sciences Institute x Dept. of Economics"),
    ("usc-me-em-dual.html", "University of Southern California (Viterbi)", "Aerospace & Mechanical Engineering x ISE dual degree"),
]

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