# -*- coding: utf-8 -*-
import ssl, re, html, io, sys, urllib.request
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

BASE = "https://publicpolicy.cornell.edu"
URLS = [
    BASE + "/masters/dspp/",
    BASE + "/masters/dspp/admissions/",
    BASE + "/masters/dspp/curriculum/",
    BASE + "/masters/dspp/admissions/requirements/",
    BASE + "/masters/dspp/tuition/",
]

def fetch(u):
    req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(req, context=ctx, timeout=20) as r:
            b = r.read()
            return r.status, b.decode("utf-8", "ignore"), len(b)
    except Exception as e:
        return None, repr(e), 0

for u in URLS:
    st, txt, n = fetch(u)
    print("=" * 80)
    print(u, "->", st, "len", n)
    if st == 200:
        links = sorted(set(re.findall(r'href="([^"]+)"', txt)))
        rel = [l for l in links if ("dspp" in l.lower() or "admission" in l.lower() or "tuition" in l.lower() or "curric" in l.lower() or "degree" in l.lower())]
        for l in rel[:30]:
            print("  link:", l)
        body = re.sub(r"<script.*?</script>", " ", txt, flags=re.S)
        body = re.sub(r"<style.*?</style>", " ", body, flags=re.S)
        body = html.unescape(re.sub(r"<[^>]+>", " ", body))
        body = re.sub(r"\s+", " ", body).strip()
        print("  TEXT:", body[:900])
