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

BASE = "https://www.duffield.cornell.edu"
URL = "https://www.duffield.cornell.edu/cbe/meng"

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

try:
    txt, status = fetch(URL)
    print("STATUS", status, "LEN", len(txt))
    open("_cornell_cbe_meng_raw.html", "w", encoding="utf-8").write(txt)
    # 链接矩阵
    links = sorted(set(html.unescape(h) for h in re.findall(r'href="([^"]+)"', txt)))
    rel = [l for l in links if "/cbe/" in l or "/meng" in l]
    print("=== CBE/MEng links ===")
    for l in rel:
        print(l)
    # 正文去标签
    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()
    open("_cornell_cbe_meng.txt", "w", encoding="utf-8").write(body)
    print("=== body len", len(body))
    print(body[:2500])
except Exception as e:
    print("ERR", type(e).__name__, e)
