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

u = "https://www.duffield.cornell.edu/mae/meng/"
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")
open("_cornell_mae_meng.html", "w", encoding="utf-8").write(raw)

txt = re.sub(r"<script[\s\S]*?</script>", " ", raw, flags=re.I)
txt = re.sub(r"<style[\s\S]*?</style>", " ", txt, flags=re.I)
txt = re.sub(r"<[^>]+>", " ", txt)
txt = htmllib.unescape(txt)
txt = re.sub(r"\s+", " ", txt).strip()
open("_cornell_mae_meng.txt", "w", encoding="utf-8").write(txt)
print("HTTP", r.status, "bytes", len(b), "text", len(txt))

# links on page
links = re.findall(r'href="([^"]+)"', raw)
keep = [h for h in links if any(k in h.lower() for k in ["meng", "admiss", "tuition", "deadline", "requirement", "degree", "curriculum", "funding", "international", "english"])]
print("=== relevant links ===")
for h in dict.fromkeys(keep):
    print(" ", h)

print("\n=== keyword context ===")
for kw in ["credit", "Credit", "semester", "year", "deadline", "Deadline", "GRE", "TOEFL", "IELTS", "Duolingo", "tuition", "Tuition", "application fee", "recommend", "statement", "resume", "resume", "STEM", "part-time", "online", "part time", "co-op", "coop", "concentration", "track", "capstone", "project"]:
    for m in re.finditer(re.escape(kw), txt):
        s = max(0, m.start()-120); e = min(len(txt), m.end()+160)
        print(f"[{kw}] ...{txt[s:e]}...")
        break
