# -*- coding: utf-8 -*-
import sys, io, os, requests, re, concurrent.futures as cf
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
BASE = r"D:\work buddy\2026-11-05-14-15-52"
H = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"}
URLS = {
 "wlu-fin-home": "https://uwaterloo.ca/finance",
 "wlu-gs-dates": "https://uwaterloo.ca/graduate-studies-post-doctoral-studies/important-dates",
 "brown-aiml-track": "https://cs.brown.edu/degrees/masters/aiml-track/",
 "brown-handbook": "https://cs.brown.edu/degrees/masters/masters-program-handbook/",
}
def go(kv):
    k, u = kv
    try:
        r = requests.get(u, headers=H, timeout=22, allow_redirects=True)
        b = r.text
        open(BASE + "\\cache\\r348-" + k + ".html", "w", encoding="utf-8", errors="replace").write(b)
        return k, r.status_code, len(b), r.url
    except Exception as e:
        return k, "ERR", str(e)[:70], u
with cf.ThreadPoolExecutor(max_workers=4) as ex:
    for k, st, ln, u in ex.map(go, URLS.items()):
        print(f"{st} {ln:7} {k:16s} {u}")

def txt(p):
    h = open(p, encoding="utf-8", errors="replace").read()
    h = re.sub(r"<script.*?</script>", " ", h, flags=re.S)
    h = re.sub(r"<style.*?</style>", " ", h, flags=re.S)
    h = re.sub(r"<[^>]+>", "\n", h)
    h = re.sub(r"&nbsp;", " ", h); h = re.sub(r"&amp;", "&", h)
    return re.sub(r"\n\s*\n+", "\n", h)

for k in ["wlu-fin-home", "wlu-gs-dates"]:
    p = BASE + "\\cache\\r348-" + k + ".html"
    if os.path.exists(p):
        t = txt(p)
        print("\n=====", k, len(t))
        for kw in ["tuition", "Tuition", "deadline", "Deadline"]:
            i = t.find(kw)
            if i > 0:
                print("  --", kw, re.sub(r"\s+", " ", t[i:i+200]))
        ln = re.findall(r'href="([^"]*(?:tuition|fees)[^"]*)"[^>]*>([^<]{0,40})', open(p, encoding="utf-8", errors="replace").read(), re.I)
        print("  links:", ln[:12])
