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 = {
    "bme_admit": "/bme/meng/meng-admission-requirements/",
    "bme_degree": "/bme/degree/biomedical-engineering-meng-ithaca-campus-requirements/",
    "bme_faq": "/bme/meng/meng-faqs/",
    "bme_design": "/bme/meng/meng-design-projects/",
    "bme_precept": "/bme/meng/preceptorship/",
}

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 '-')}")
    except Exception as e:
        print(f"[{tag}] FAIL {type(e).__name__}: {e}")
