# -*- coding: utf-8 -*-
import sys, io, re, os, requests, pathlib
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"}
def fetch(k, u):
    try:
        r = requests.get(u, headers=H, timeout=25)
        print(k, r.status_code, len(r.text))
        if r.status_code == 200:
            open(BASE + "\\cache\\r347-" + k + ".html", "w", encoding="utf-8", errors="replace").write(r.text)
    except Exception as e:
        print(k, "ERR", str(e)[:60])
fetch("nd-mscse", "https://cse.nd.edu/graduate/ms-in-computer-science-and-engineering/")
fetch("rice-mcs-adm", "https://www.cs.rice.edu/academics/graduate-programs/master-computer-science/admissions")
# dump visible text of existing detail pages
CODE = re.compile(r"\b\d{2}[\-]\d{3}\b|\b[A-Z]{2,8}[\s\-]?\d{3,4}[A-Z]?\b")
for fn in ["emory-computer-science-ms", "rice-computer-science", "rice-data-science", "notre-computer-science-and-engineering-mscse---masters-professional"]:
    p = pathlib.Path(BASE) / "details" / (fn + ".html")
    if not p.exists():
        print("MISS", fn)
        continue
    t = p.read_text(encoding="utf-8", errors="replace")
    t = re.sub(r"<script.*?</script>|<style.*?</style>", " ", t, flags=re.S)
    txt = re.sub(r"<[^>]+>", "\n", t)
    txt = re.sub(r"\n{2,}", "\n", txt)
    lines = [l.strip() for l in txt.split("\n") if len(l.strip()) > 2]
    out = "\n".join(lines)
    open(BASE + "\\_r347-old-" + fn + ".txt", "w", encoding="utf-8").write(out)
    print("OLD", fn, len(out), "codes", len(set(CODE.findall(out))))
