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

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

pages = {
    "oncampus": "https://www.duffield.cornell.edu/mae/on-campus-meng-aerospace-engineering/",
}
for key, url in pages.items():
    try:
        st, raw = fetch(url)
        print("====", key, "STATUS", st, "LEN", len(raw))
        open(f"_cornell_aero_{key}.html", "w", encoding="utf-8").write(raw)
        links = re.findall(r'href="([^"]+)"', raw)
        rel = sorted({H.unescape(l) for l in links if "/mae/" in l or "/meng/" in l})
        for l in rel:
            print("  ", l)
        txt = re.sub(r"<script[\s\S]*?</script>", " ", raw)
        txt = re.sub(r"<style[\s\S]*?</style>", " ", txt)
        txt = re.sub(r"<[^>]+>", " ", txt)
        txt = H.unescape(re.sub(r"\s+", " ", txt)).strip()
        open(f"_cornell_aero_{key}.txt", "w", encoding="utf-8").write(txt)
        print("--- text ---")
        print(txt[:3500])
    except Exception as e:
        print("ERR", key, type(e).__name__, e)
