# -*- 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/apply/",
    BASE + "/masters/dspp/apply/faq/",
    BASE + "/masters/msdsp/residential/curriculum/",
]

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("=" * 90)
    print(u, "->", st, "len", n)
    if st == 200:
        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()
        # 找关键词上下文
        for kw in ["Residential", "Executive", "tuition", "Tuition", "deadline", "Deadline", "TOEFL", "IELTS", "Duolingo", "GRE", "credit", "Credit", "semester", "STEM", "language", "English"]:
            for m in re.finditer(re.escape(kw), body):
                s = max(0, m.start()-120); e = min(len(body), m.end()+160)
                print(f"  [{kw}] ...{body[s:e]}...")
                break
