# -*- 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
H = {"User-Agent": "Mozilla/5.0"}

def fetch(u):
    req = urllib.request.Request(u, headers=H)
    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

pages = {
    "home": "https://publicpolicy.cornell.edu/masters/dspp/",
    "apply": "https://publicpolicy.cornell.edu/masters/dspp/apply/",
    "faq": "https://publicpolicy.cornell.edu/masters/dspp/apply/faq/",
    "curr": "https://publicpolicy.cornell.edu/masters/msdsp/residential/curriculum/",
}
all_links = {}
for k, u in pages.items():
    st, txt, n = fetch(u)
    print("=" * 90); print(k, u, st, n)
    if st == 200:
        links = sorted(set(re.findall(r'href="([^"]+)"', txt)))
        kw = [l for l in links if re.search(r'cost|fund|tuition|aid|scholar|english|toefl|ielts|language|requirement|admiss|deadline|fees|waiver', l, re.I)]
        for l in kw:
            print("  ", l)
        all_links[k] = links

# 研究生院语言要求候选
for u in [
    "https://gradschool.cornell.edu/admissions/requirements/english-language-proficiency/",
    "https://gradschool.cornell.edu/admissions/requirements/",
    "https://publicpolicy.cornell.edu/masters/msdsp/residential/cost-and-funding/",
    "https://publicpolicy.cornell.edu/masters/dspp/cost-and-funding/",
]:
    st, txt, n = fetch(u)
    print("=" * 90); print(u, st, n)
    if st == 200:
        body = html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<script.*?</script>|<style.*?</style>", " ", txt, flags=re.S)))
        body = re.sub(r"\s+", " ", body)
        for kw in ["TOEFL", "IELTS", "Duolingo", "score", "fee", "Fee", "tuition", "Tuition", "$"]:
            m = re.search(re.escape(kw), body)
            if m:
                s=max(0,m.start()-100); e=min(len(body),m.end()+180)
                print(f"  [{kw}] ...{body[s:e]}...")
