import ssl, 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

BASE = "https://www.duffield.cornell.edu"
PAGES = {
    "meng_guide": "/meng/admissions-meng-students/application-guide/",
}

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)
    return re.sub(r"\s+", " ", t).strip()

for tag, path in PAGES.items():
    u = BASE + path
    try:
        req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"})
        r = urllib.request.urlopen(req, timeout=25, context=ctx)
        b = r.read()
        raw = b.decode("utf-8", errors="replace")
        txt = strip(raw)
        open(f"_cornell_{tag}.txt", "w", encoding="utf-8").write(txt)
        title = re.search(r"<title>(.*?)</title>", raw, re.I | re.S)
        print(f"[{tag}] HTTP {r.status} bytes={len(b)} text={len(txt)} title={(title.group(1).strip()[:80] if title else '-')}")
        for kw in ["TOEFL", "IELTS", "application fee", "Fee", "recommend", "2098", "waiver", "English"]:
            for m in re.finditer(r"[^.]*" + kw + r"[^.]*\.?", txt):
                print("  ·", m.group(0).strip()[:240])
    except Exception as e:
        print(f"[{tag}] FAIL {type(e).__name__}: {e}")
