# -*- coding: utf-8 -*-
import urllib.request, ssl, gzip, io, sys, re, time
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 = ["environmental-studies-mes", "applied-positive-psychology-mapp"]
for s in slugs:
    url = f"https://catalog.upenn.edu/graduate/programs/{s}/"
    for attempt in range(3):
        req = urllib.request.Request(url, headers={
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Referer":"https://catalog.upenn.edu/graduate/programs/",
        })
        try:
            with urllib.request.urlopen(req, timeout=25, context=SCTX) as r:
                data = r.read()
                enc = r.headers.get("Content-Encoding","")
                if enc == "gzip":
                    data = gzip.decompress(data)
                txt = data.decode("utf-8", errors="replace")
                if r.status == 202 or len(txt) < 100:
                    print(f"== {s}  attempt{attempt+1}  RETRY")
                    time.sleep(2); continue
                title = txt.split("<title>")[1].split("</title>")[0][:120] if "<title>" in txt else ""
                print(f"== {s}  status={r.status}  len={len(txt)}  title={title}")
                m = re.search(r'<div id="texttab"[^>]*>([\s\S]*?)</div>\s*</div>\s*</div>', txt)
                body = m.group(1) if m else txt
                body = re.sub(r'<[^>]+>', ' ', body)
                body = re.sub(r'\s+', ' ', body).strip()
                for kw in ["course units","CU","online","working professional","part-time","full-time","MBA","dual","joint","for professionals","executive"]:
                    mm = re.search(r'.{40}'+re.escape(kw)+r'.{150}', body, re.I)
                    if mm:
                        print(f"  [{kw}] {mm.group(0)[:220]}")
                break
        except Exception as e:
            print(f"== {s}  attempt{attempt+1}  ERR {e}")
            time.sleep(2)
