# -*- coding: utf-8 -*-
import urllib.request, ssl, sys, io, time, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
SCTX = ssl.create_default_context(); SCTX.check_hostname=False; SCTX.verify_mode=ssl.CERT_NONE
slugs = [
 "education-studies-msed",
 "learning-analytics-artificial-intelligence-msed",
 "government-administration-mpaf",
 "international-impact-evaluation-mpa",
]
for s in slugs:
    url = f"https://catalog.upenn.edu/graduate/programs/{s}/"
    saved = False
    for attempt in range(5):
        try:
            req = urllib.request.Request(url, headers={
                "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36",
                "Referer":"https://catalog.upenn.edu/graduate/programs/",
            })
            r = urllib.request.urlopen(req, timeout=25, context=SCTX)
            body = r.read()
            if r.status == 200 and len(body) > 5000:
                text = body.decode("utf-8","ignore")
                open(f"_raw_{s}.html","w",encoding="utf-8").write(text)
                # quick overview
                plain = re.sub(r"<script[\s\S]*?</script>"," ",text)
                plain = re.sub(r"<style[\s\S]*?</style>"," ",plain)
                plain = re.sub(r"<[^>]+>"," ",plain)
                plain = re.sub(r"\s+"," ",plain).strip()
                i = plain.lower().find("overview")
                snippet = plain[i:i+1200] if i>=0 else plain[:1200]
                print(f"\n=== {s} OK {len(text)} ===")
                print(snippet)
                saved = True
                break
            else:
                print(s, "attempt", attempt, r.status, len(body))
                time.sleep(3)
        except Exception as e:
            print(s, "attempt", attempt, "ERR", repr(e)[:100]); time.sleep(3)
    if not saved:
        print(s, "GIVE UP")
