# -*- coding: utf-8 -*-
"""Round 200: add 5 - USC MNLM / USC AEEC MS / UIUC MSPE / Cornell BEE MS / Cornell BME MEng."""
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-mnlm",
        "s": "usc",
        "n": "Nonprofit Leadership and Management (MNLM)",
        "en": "Master of Nonprofit Leadership and Management (USC Price School of Public Policy)",
        "deg": "MNLM",
        "lvl": "m",
        "stem": 0,
        "dur": "On-campus cohort, Fall admission only, Los Angeles CA; 40 units; 1-3 years flexible for working professionals",
        "ddl": "Fall 2027 scholarship: Dec 15, 2026; International final: May 1, 2027; Domestic final: July 1, 2027",
        "lang": "TOEFL / IELTS required (institution code 4852); scores dated within 24 months of entry",
        "test": "GRE: Not required per Price admission; 3 letters of recommendation (at least 1 academic); official transcripts; resume; $90 application fee; financial guarantee statement. Tuition ~$2,354/unit (2024-25) for 40 units.",
        "tui": "待补 (see USC Price tuition; ~$2,354/unit x 40 units per 2024-25 FAQ)",
        "url": "details/usc-mnlm.html",
    },
    {
        "id": "usc-aeec-ms",
        "s": "usc",
        "n": "Applied Economics and Econometrics (MS)",
        "en": "Master of Science in Applied Economics and Econometrics (Dornsife College, Department of Economics)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "On-campus, Los Angeles CA; Dornsife Economics; separate from Economics MA and MECDS joint MS with Viterbi",
        "ddl": "Master's: April 1 (Fall); PhD: December 1",
        "lang": "TOEFL / IELTS required for non-native English speakers (USC Dornsife rules); English placement exam may be required",
        "test": "GRE: Not required for master's per current Dornsife admission; prerequisite: intermediate micro/macro theory, one year calculus, one semester statistics. Typical applicant has economics undergraduate major.",
        "tui": "待补 (see USC Dornsife tuition)",
        "url": "details/usc-aeec-ms.html",
    },
    {
        "id": "illinois-mspe",
        "s": "illinois",
        "n": "Policy Economics (MS)",
        "en": "Master of Science in Policy Economics (University of Illinois Urbana-Champaign, Department of Economics)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "On-campus, Fall admission only (no Spring/Summer); Urbana-Champaign IL; designed for applied/policy economics",
        "ddl": "Fall: April 1 (decisions rolling from Feb 1)",
        "lang": "TOEFL / IELTS / Duolingo accepted (UIUC institution code 1836)",
        "test": "GRE: Not strictly required for MSPE (recommended to self-report; required only for PhD track); GMAT not required. Strong economics, quantitative methods, English background; calculus sequence, probability, statistics, econometrics.",
        "tui": "待补 (see UIUC Graduate College tuition; $90 application fee)",
        "url": "details/illinois-mspe.html",
    },
    {
        "id": "cornell-bee-ms",
        "s": "cornell",
        "n": "Biological and Environmental Engineering (MS)",
        "en": "Master of Science in Biological and Environmental Engineering (Cornell CALS / Duffield College of Engineering, Graduate Field)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "In-person, Ithaca NY; minimum 4 semesters; research MS with thesis; Special Committee design; concentration in bioenvironmental engineering",
        "ddl": "Fall: December 1 (fellowship priority); Spring: October 1",
        "lang": "TOEFL / IELTS required for international applicants (Cornell institution code 2098)",
        "test": "GRE: Not required; 3 letters of recommendation; resume; ORCID required. Bachelor's in engineering / physical science / biological science with strong math and physics; deficiencies must be made up early.",
        "tui": "待补 (see Cornell Graduate School tuition)",
        "url": "details/cornell-bee-ms.html",
    },
    {
        "id": "cornell-bme-meng",
        "s": "cornell",
        "n": "Biomedical Engineering (MEng)",
        "en": "Master of Engineering in Biomedical Engineering (Cornell Duffield College of Engineering, Meinig School of Biomedical Engineering)",
        "deg": "MEng",
        "lvl": "m",
        "stem": 1,
        "dur": "In-person professional master, Ithaca NY; 2 semesters + summer; concentrations in biomedical instrumentation / drug delivery / biomaterials / computational systems biology / medical biomechanics",
        "ddl": "Fall: May 3 (rolling); Spring: November 2",
        "lang": "TOEFL / IELTS required for international applicants (Cornell institution code 2098)",
        "test": "GRE: Not required (permanently eliminated since 2019-20); 2 letters of recommendation; resume; interview by invitation. Prerequisites: calculus I/II/III, linear algebra, differential equations, biology, chemistry, physics, statistics, anatomy/physiology.",
        "tui": "待补 (see Cornell Engineering MEng tuition)",
        "url": "details/cornell-bme-meng.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: official university / Price / Dornsife / Economics / CALS / Duffield admissions pages.</li>
<li>Fields marked 待补 will be filled when the official bulletin / bulletin PDF is reachable.</li>
<li>UChicago MS-TRM (executive one-weekend-per-month) and UChicago MS-BMI (fully remote one-year synchronous) were reviewed and excluded this round.</li>
<li>Official pages may update; always confirm on the school's admissions site before applying.</li>
</ul>
</body></html>"""

details_meta = [
    ("usc-mnlm.html", "University of Southern California (Price)", "Sol Price School of Public Policy"),
    ("usc-aeec-ms.html", "University of Southern California (Dornsife)", "Department of Economics"),
    ("illinois-mspe.html", "University of Illinois Urbana-Champaign", "Department of Economics"),
    ("cornell-bee-ms.html", "Cornell University (CALS x Duffield)", "Graduate Field of Biological and Environmental Engineering"),
    ("cornell-bme-meng.html", "Cornell University (Duffield Engineering)", "Meinig School of Biomedical Engineering, MEng"),
]

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