# -*- 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")

base = "https://www.duffield.cornell.edu/mem/"
try:
    st, raw = fetch(base)
    print("STATUS", st, "LEN", len(raw))
    open("_cornell_mem_raw.html", "w", encoding="utf-8").write(raw)
    # links
    links = re.findall(r'href="([^"]+)"', raw)
    mem = sorted({H.unescape(l) for l in links if "/mem/" in l or "mem" in l.lower()})
    print("--- mem links ---")
    for l in mem:
        print(l)
    # text strip
    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("_cornell_mem.txt", "w", encoding="utf-8").write(txt)
    print("--- text head ---")
    print(txt[:2500])
except Exception as e:
    print("ERR", type(e).__name__, e)
