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

PAGES = {
    "admit": "https://www.duffield.cornell.edu/cbe/meng/meng-admission-requirements/",
    "degree": "https://www.duffield.cornell.edu/cbe/degree/chemical-engineering-meng-ithaca-campus-requirements/",
    "faq": "https://www.duffield.cornell.edu/cbe/meng/meng-faqs/",
    "projects": "https://www.duffield.cornell.edu/cbe/meng/meng-projects/",
}

def fetch(u):
    req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"})
    r = urllib.request.urlopen(req, context=ctx, timeout=25)
    b = r.read()
    return b.decode("utf-8", errors="replace"), r.status

for key, url in PAGES.items():
    try:
        txt, status = fetch(url)
        body = re.sub(r"<script[\s\S]*?</script>", " ", txt)
        body = re.sub(r"<style[\s\S]*?</style>", " ", body)
        body = re.sub(r"<[^>]+>", " ", body)
        body = html.unescape(re.sub(r"\s+", " ", body)).strip()
        fn = f"_cornell_cbe_{key}.txt"
        open(fn, "w", encoding="utf-8").write(body)
        print(f"=== {key} STATUS {status} LEN {len(body)} ===")
        print(body[:1800])
        print()
    except Exception as e:
        print(f"=== {key} ERR {type(e).__name__} {e} ===")
