import ssl, json, io, sys, re, urllib.request, html as htmllib
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

URLS = {
    "cornell-mae-meng": "https://www.duffield.cornell.edu/mae/meng/",
    "cornell-bme-meng": "https://www.duffield.cornell.edu/bme/meng/",
    "cornell-cbe-meng": "https://www.duffield.cornell.edu/cbe/meng",
    "jhu-bio-scm": "https://e-catalogue.jhu.edu/public-health/departments/biostatistics/biostatistics-scm/",
    "jhu-bio-mhs": "https://e-catalogue.jhu.edu/public-health/departments/biostatistics/biostatistics-mhs/",
    "notre-msae": "https://graduateschool.nd.edu/degree-programs/aerospace-engineering-msae---masters-traditional/",
}

def strip(t):
    t = re.sub(r"<script[\s\S]*?</script>", " ", t, flags=re.I)
    t = re.sub(r"<style[\s\S]*?</style>", " ", t, flags=re.I)
    t = re.sub(r"<[^>]+>", " ", t)
    t = htmllib.unescape(t)
    t = re.sub(r"\s+", " ", t)
    return t.strip()

for tag, u in URLS.items():
    try:
        req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"})
        r = urllib.request.urlopen(req, timeout=20, context=ctx)
        b = r.read()
        txt = strip(b.decode("utf-8", errors="replace"))
        title = re.search(r"<title>(.*?)</title>", b.decode("utf-8", errors="replace"), re.I | re.S)
        print(f"[{tag}] HTTP {r.status} bytes={len(b)} text={len(txt)}")
        print("  title:", (title.group(1).strip()[:90] if title else "-"))
        print("  text:", txt[:380])
        print()
    except Exception as e:
        print(f"[{tag}] FAIL {type(e).__name__}: {e}")
        print()
