# -*- 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 = [
 "statistics-measurement-assessment-research-technology-msed",
 "learning-sciences-technologies-msed",
 "education-culture-society-msed",
]
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)
                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+1500] if i>=0 else plain[:1500]
                print(f"\n=== {s} OK {len(text)} ===")
                print(snippet)
                # online/executive check
                for kw in ["online","executive","part-time","working professional","evening","fully online","not currently accepting","residency"]:
                    for m in re.finditer(kw, plain, re.IGNORECASE):
                        j = m.start()
                        print(f"  [KW {kw}] ...{plain[max(0,j-80):j+180]}...")
                        break
                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")
