# -*- coding: utf-8 -*-
import io, sys, re, ssl, urllib.request, html as H
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
u = "https://www.duffield.cornell.edu/cee/meng/"
req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
b = urllib.request.urlopen(req, context=ctx, timeout=25).read()
open("_cornell_cee_raw.html", "wb").write(b)
print("总览页 bytes:", len(b))

t = re.sub(r"<script.*?</script>", " ", b.decode("utf-8","ignore"), flags=re.S)
t = re.sub(r"<style.*?</style>", " ", t, flags=re.S)
t = H.unescape(re.sub(r"<[^>]+>", " ", t))
t = re.sub(r"[ \t]+", " ", t)
t = re.sub(r"\n\s*\n+", "\n", t)
open("_cornell_cee.txt", "w", encoding="utf-8").write(t)

links = re.findall(r'href="([^"]+)"', b.decode("utf-8","ignore"))
cee_links = sorted(set(l for l in links if "cee" in l.lower() or "meng" in l.lower()))
print("=== CEE 相关链接 ===")
for l in cee_links:
    print(l)

print("\n=== 正文关键词切片 ===")
for kw in ["Master of Engineering", "M.Eng", "credit", "Focus", "track", "concentration",
           "specialization", "deadline", "Fall", "Spring", "recommend", "GRE", "prerequisite",
           "STEM", "OPT", "tuition", "degree requirement", "On-Campus", "Distance", "Project",
           "Environmental", "Structural", "Transportation", "Water", "Geotech", "Sustainable",
           "career", "employment", "three-semester", "two-semester"]:
    idx = 0; cnt = 0
    while True:
        i = t.lower().find(kw.lower(), idx)
        if i < 0 or cnt >= 2:
            break
        print(f"\n--- [{kw}] @{i} ---")
        print(t[max(0, i-180):i+340].strip())
        idx = i + len(kw); cnt += 1
