# -*- coding: utf-8 -*-
"""Round 181: generate 5 detail pages + append PROGRAMS + VD"""
import os, re, json

BASE = r"D:\work buddy\2026-11-05-14-15-52"
DET = os.path.join(BASE, "details")
IDX = os.path.join(BASE, "index_main.html")

# ---------- Detail page templates ----------
def page(title, school, en, deg, body_cards):
    cards_html = "\n".join(body_cards)
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title} | {school}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{font-size:26px;border-bottom:3px solid #1a4480;padding-bottom:10px}}
h2{{font-size:18px;color:#1a4480;margin-top:28px}}
.meta{{background:#f4f7fb;padding:14px 18px;border-radius:8px;margin:16px 0}}
.card{{background:#fff;border:1px solid #e0e6ed;border-radius:8px;padding:16px 20px;margin:14px 0}}
.card h3{{margin-top:0;color:#1a4480;font-size:16px}}
table{{border-collapse:collapse;width:100%;margin:8px 0}}
th,td{{border:1px solid #d0d7e0;padding:6px 10px;text-align:left;font-size:14px}}
th{{background:#eef3f9}}
.tag{{display:inline-block;background:#e3f0e3;color:#1a6b1a;padding:2px 8px;border-radius:4px;font-size:12px;margin-right:6px}}
.warn{{background:#fff8e1;color:#8a6d00;padding:8px 12px;border-radius:6px;font-size:13px;margin:8px 0}}
</style>
</head>
<body>
<h1>{title}</h1>
<div class="meta"><strong>{school}</strong> &middot; {en} &middot; Degree: {deg}</div>
{cards_html}
<p style="color:#888;font-size:12px;margin-top:30px">Source: official university websites. Fields marked TBD are not yet published by the department and will be updated on re-verification.</p>
</body>
</html>"""

# 1. JHU MA Economics
jhu_econ = page(
    "MA in Economics", "Johns Hopkins University",
    "Master of Arts in Economics (Department of Economics, Homewood Campus)",
    "MA",
    [
    '<div class="card"><h3>Program Overview</h3><p>Full-time, two-year, fully in-person terminal MA at the Homewood Campus in Baltimore. Math-intensive curriculum designed to prepare students for PhD programs in economics or for quantitative research careers. <span class="tag">STEM-designated</span> <span class="tag">F-1 eligible</span></p></div>',
    '<div class="card"><h3>Degree Requirements</h3><ul><li>46 academic credits (14 courses over 2 years)</li><li>25 credits required core + 21 credits approved electives</li><li>No master\'s thesis required</li><li>First year: Micro I/II + Macro I/II + Statistics/Econometrics I/II + Mathematical Methods</li><li>Second year: 7 electives</li></ul></div>',
    '<div class="card"><h3>Application</h3><table><tr><th>Item</th><th>Detail</th></tr><tr><td>Entry term</td><td>Fall only</td></tr><tr><td>Priority deadline</td><td>March 1 (decision ~2 months earlier)</td></tr><tr><td>Final deadline</td><td>May 1</td></tr><tr><td>Prerequisites</td><td>2 semesters calculus + linear algebra; strong math background</td></tr></table></div>',
    '<div class="card"><h3>Tuition & Financial Aid</h3><div class="warn">Tuition per credit not separately published on department page; JWH graduate rate applies. TBD on re-verification.</div></div>',
    '<div class="card"><h3>Career Outcomes</h3><p>Graduates advance to top PhD programs in economics or take quantitative research roles. STEM designation qualifies F-1 students for 24-month OPT extension.</p></div>',
    ])

# 2. UPenn MSE Electrical Engineering
up_ece = page(
    "MSE in Electrical Engineering", "University of Pennsylvania",
    "Master of Science in Engineering in Electrical Engineering (ESE Department, SEAS)",
    "MSE",
    [
    '<div class="card"><h3>Program Overview</h3><p>Full-time residential terminal master\'s in Penn Engineering. Theoretically grounded with interdisciplinary skills; students tailor electives across electromagnetics/photonics, sensors/MEMS, VLSI/nanotechnology, circuits, signal processing, robotics, and data science.</p></div>',
    '<div class="card"><h3>Degree Requirements</h3><ul><li>10 course units (CU)</li><li>Minimum 2.7 GPA to graduate</li><li>Theory + research opportunities; interdisciplinary collaboration across Penn</li></ul></div>',
    '<div class="card"><h3>Application</h3><table><tr><th>Item</th><th>Detail</th></tr><tr><td>Application opens</td><td>September 15, 2026</td></tr><tr><td>Regular deadline</td><td>February 1, 2027</td></tr><tr><td>Prerequisites</td><td>Undergraduate EE or physics background + strong mathematics</td></tr><tr><td>Application fee</td><td>$95 (fee waivers for eligible categories)</td></tr></table></div>',
    '<div class="card"><h3>Tuition</h3><div class="warn">SEAS graduate tuition per CU not shown on department landing page; TBD on re-verification.</div></div>',
    '<div class="card"><h3>Research Areas</h3><p>Electromagnetics & Photonics &middot; Quantum Engineering &middot; Sensors & MEMS &middot; VLSI & Nanotechnology &middot; Circuits &middot; Signal Processing &middot; Robotics &middot; Data Science</p></div>',
    ])

# 3. Duke MA Economics
duke_mae = page(
    "MA in Economics", "Duke University",
    "Master of Arts in Economics (Department of Economics, MAE)",
    "MA",
    [
    '<div class="card"><h3>Program Overview</h3><p>Full-time quantitative master\'s completed in 3-4 semesters. Combines theoretical rigor with flexible electives; students frequently enroll in PhD-level economics courses and cross-departmental courses (Political Science, Public Policy, Finance, Statistics, Mathematics). <span class="tag">STEM-designated</span> <span class="tag">CIP 45.0603</span></p></div>',
    '<div class="card"><h3>Degree Requirements</h3><ul><li>Minimum 30 graded credit hours</li><li>Econometrics requirement (one course from ECON 608/612/613/623/672/703/7xx)</li><li>Portfolio evaluation; students may take PhD-level courses</li></ul></div>',
    '<div class="card"><h3>Application</h3><table><tr><th>Item</th><th>Detail</th></tr><tr><td>Entry term</td><td>Fall</td></tr><tr><td>Deadline</td><td>January 14, 2027</td></tr><tr><td>GRE General</td><td>Required (GRE Subject optional; GMAT not accepted)</td></tr><tr><td>Recommendations</td><td>3 letters</td></tr><tr><td>Prerequisites</td><td>Undergraduate math/engineering/CS/stats/economics background recommended</td></tr></table></div>',
    '<div class="card"><h3>Tuition</h3><table><tr><th>Item</th><th>Rate</th></tr><tr><td>Full-time research master\'s tuition</td><td>$34,940 per academic semester (2026-27)</td></tr></table></div>',
    '<div class="card"><h3>Career Outcomes</h3><p>Graduates are competitive on the finance sector job market, in applied research, and are well-positioned for top PhD programs. STEM designation qualifies for 24-month OPT extension.</p></div>',
    ])

# 4. UPenn MSMP Medical Physics
up_medphys = page(
    "MS in Medical Physics", "University of Pennsylvania",
    "Master of Science in Medical Physics (Perelman School of Medicine, MSMP)",
    "MS",
    [
    '<div class="card"><h3>Program Overview</h3><p>Full-time CAMPEP-accredited professional master\'s completed in 2 academic years plus one summer term. Bridges physics and clinical medicine; prepares students for medical physics residencies or PhD research in radiation oncology, diagnostic imaging, nuclear medicine, and health physics. <span class="tag">CAMPEP-accredited</span></p></div>',
    '<div class="card"><h3>Degree Requirements</h3><ul><li>15 course units</li><li>Faculty-mentored applied research project (thesis) with paper and presentation</li><li>Clinical experience through Penn Medicine Health System (part-time clinical work possible, hourly wage)</li><li>MPHY 6000 Professional Development (two-term, 0 CU)</li></ul></div>',
    '<div class="card"><h3>Application</h3><table><tr><th>Item</th><th>Detail</th></tr><tr><td>Entry term</td><td>Fall 2027</td></tr><tr><td>Deadline</td><td>January 15, 2027</td></tr><tr><td>Prerequisites</td><td>Bachelor\'s in physics/engineering/physical sciences; undergraduate minor in physics; one semester of CS/programming</td></tr><tr><td>Recommendations</td><td>3 letters</td></tr></table></div>',
    '<div class="card"><h3>Tuition (estimated, published)</h3><table><tr><th>Term</th><th>Tuition</th><th>Fees</th><th>Total</th></tr><tr><td>Fall 2026</td><td>$26,565</td><td>$3,179</td><td>$29,744</td></tr><tr><td>Spring 2027</td><td>$26,565</td><td>$3,179</td><td>$29,744</td></tr><tr><td>Summer 2027</td><td>$7,886</td><td>$779</td><td>$8,665</td></tr><tr><td>Fall 2027</td><td>$31,544</td><td>$3,303</td><td>$34,847</td></tr><tr><td>Spring 2028</td><td>$23,658</td><td>$3,303</td><td>$26,961</td></tr></table></div>',
    '<div class="card"><h3>Specialty Areas</h3><p>Radiation Therapy &middot; Diagnostic Imaging &middot; Nuclear Medicine &middot; Health Physics</p></div>',
    ])

# 5. Duke MSEC
duke_msec = page(
    "MS in Economics & Computation", "Duke University",
    "Master of Science in Economics and Computation (Joint: Economics + CS)",
    "MS",
    [
    '<div class="card"><h3>Program Overview</h3><p>Full-time joint degree between the Department of Economics and Department of Computer Science. Trains computational skills linked to economics, finance, and policy; prepares students for PhD studies or careers in tech/data science. <span class="tag">STEM-designated</span></p></div>',
    '<div class="card"><h3>Degree Requirements</h3><ul><li>30 credit hours (10 courses)</li><li>At least 12 credits in economics and computational science</li><li>Up to 6 credits may be independent capstone research (independent study)</li><li>Final portfolio exam administered by faculty committee</li><li>Normally 4 semesters (or 3 semesters + summer); first 3 semesters must be full-time (9 credits)</li></ul></div>',
    '<div class="card"><h3>Application</h3><table><tr><th>Item</th><th>Detail</th></tr><tr><td>Entry term</td><td>Fall</td></tr><tr><td>Deadline</td><td>February 1, 2027</td></tr><tr><td>Prerequisites</td><td>Undergraduate CS/applied math/engineering/stats/economics background recommended; strong quantitative background</td></tr></table></div>',
    '<div class="card"><h3>Tuition</h3><table><tr><th>Item</th><th>Rate</th></tr><tr><td>Full-time research master\'s tuition</td><td>$34,940 per academic semester (2026-27)</td></tr></table></div>',
    '<div class="card"><h3>Career Outcomes</h3><p>Graduates pursue PhD studies or careers in tech, data science, finance, government, and consulting. Interdisciplinary research opportunities with Fuqua School of Business, Nicholas School, Sanford School of Public Policy, NISS, and SAMS.</p></div>',
    ])

pages = {
    "jhu-ma-econ.html": jhu_econ,
    "up-mse-ece.html": up_ece,
    "duke-mae.html": duke_mae,
    "up-msmp.html": up_medphys,
    "duke-msec.html": duke_msec,
}

for fname, content in pages.items():
    p = os.path.join(DET, fname)
    with open(p, "w", encoding="utf-8") as f:
        f.write(content)
    print("Wrote", fname, len(content), "bytes")

# ---------- Append PROGRAMS ----------
new_programs = [
    '{id:"jhu-ma-econ",s:"jhu",n:"\u7ecf\u6d4e\u5b66\u827a\u672f\u7855\u58eb",en:"MA in Economics (Homewood)",deg:"MA",lvl:"m",stem:1,dur:"2 years in-person",ddl:"Priority 2027-03-01 / Final 2027-05-01",lang:"TOEFL/IELTS (JHU GSAS standard)",test:{cls:"GRE required for PhD-bound (admitted range, not minimum threshold)"},tui:"TBD",url:"details/jhu-ma-econ.html"}',
    '{id:"up-mse-ece",s:"up",n:"\u7535\u6c14\u5de5\u7a0b\u79d1\u5b66\u7855\u58eb",en:"MSE in Electrical Engineering (SEAS)",deg:"MSE",lvl:"m",stem:1,dur:"1-2 years (10 CUs)",ddl:"2027-02-01",lang:"TOEFL/IELTS (Penn SEAS standard)",test:{cls:"GRE not required (per SEAS residential master)"},tui:"TBD",url:"details/up-mse-ece.html"}',
    '{id:"duke-mae",s:"duke",n:"\u7ecf\u6d4e\u5b66\u827a\u672f\u7855\u58eb",en:"MA in Economics (MAE)",deg:"MA",lvl:"m",stem:1,dur:"3-4 semesters",ddl:"2027-01-14",lang:"TOEFL/IELTS (Duke GS standard)",test:{cls:"GRE General required (Subject optional, admitted range, not minimum threshold)"},tui:"$34,940/semester",url:"details/duke-mae.html"}',
    '{id:"up-msmp",s:"up",n:"\u533b\u5b66\u7269\u7406\u79d1\u5b66\u7855\u58eb",en:"MS in Medical Physics (Perelman, CAMPEP)",deg:"MS",lvl:"m",stem:1,dur:"2 years + 1 summer (15 CUs)",ddl:"2027-01-15",lang:"TOEFL/IELTS (Penn Perelman standard)",test:{cls:"GRE not required (per program page)"},tui:"~$129,961 total (5 published terms)",url:"details/up-msmp.html"}',
    '{id:"duke-msec",s:"duke",n:"\u7ecf\u6d4e\u4e0e\u8ba1\u7b97\u79d1\u5b66\u7855\u58eb",en:"MS in Economics & Computation (Econ x CS)",deg:"MS",lvl:"m",stem:1,dur:"3-4 semesters (30 credits)",ddl:"2027-02-01",lang:"TOEFL/IELTS (Duke GS standard)",test:{cls:"GRE required (admitted range, not minimum threshold)"},tui:"$34,940/semester",url:"details/duke-msec.html"}',
]

html = open(IDX, "r", encoding="utf-8").read()

# Locate PROGRAMS array end via bracket-depth matching
m = re.search(r'(?:const|let|var)\s+PROGRAMS\s*=\s*\[', html)
assert m, "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_pos = i - 1  # points at ]
j = insert_pos - 1
while j >= 0 and html[j] in ' \t\n\r': j -= 1
print("Last char before ]:", repr(html[j]))
if html[j] == '}':
    prefix = ","
elif html[j] == ',':
    prefix = ""
else:
    prefix = ","
new_block = prefix + "\n  " + ",\n  ".join(new_programs)
html = html[:insert_pos] + new_block + "\n" + html[insert_pos:]

# ---------- Append VERIFIED_DETAILS ----------
vd_new = ['details/jhu-ma-econ.html', 'details/up-mse-ece.html', 'details/duke-mae.html', 'details/up-msmp.html', 'details/duke-msec.html']
m2 = re.search(r'(?:const|let|var)\s+VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(', html)
assert m2, "VD Set not found"
vstart = m2.end()
# vstart points just after ( of Set(
vdepth = 1
vi = vstart
while vi < len(html) and vdepth > 0:
    c = html[vi]
    if c == '(': vdepth += 1
    elif c == ')': vdepth -= 1
    vi += 1
vinsert = vi - 1  # points at ) of Set(
# Find last non-whitespace before )
vj = vinsert - 1
while vj >= 0 and html[vj] in ' \t\n\r': vj -= 1
print("Last char before VD ):", repr(html[vj]))
# Need to insert before the closing ). If last char is " or , handle.
if html[vj] == '"':
    vprefix = ","
elif html[vj] == ',':
    vprefix = ""
else:
    vprefix = ","
# Build VD insert: , "details/xxx.html", "details/yyy.html"
vd_block = vprefix + '"' + '","'.join(vd_new) + '"'
html = html[:vinsert] + vd_block + html[vinsert:]

open(IDX, "w", encoding="utf-8").write(html)
print("OK: 5 PROGRAMS + 5 VD appended")
