# -*- coding: utf-8 -*-
import urllib.request, ssl, re, io, sys, os, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")

SCTX = ssl.create_default_context()
SCTX.check_hostname = False
SCTX.verify_mode = ssl.CERT_NONE

def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0"})
    r = urllib.request.urlopen(req, timeout=20, context=SCTX)
    return r.read().decode("utf-8", errors="replace")

def clean(html):
    t = re.sub(r"<script[\s\S]*?</script>", "", html)
    t = re.sub(r"<style[\s\S]*?</style>", "", t)
    t = re.sub(r"<[^>]+>", " ", t)
    t = re.sub(r"&#8217;", "'", t)
    t = re.sub(r"&#8211;", "-", t)
    t = re.sub(r"&#8220;", '"', t)
    t = re.sub(r"&#8221;", '"', t)
    t = re.sub(r"&amp;", "&", t)
    t = re.sub(r"\s+", " ", t)
    return t

def extract(url, label):
    html = fetch(url)
    text = clean(html)
    out = {"url": url, "label": label}
    # Program requirements / credits
    for kw in ["requires", "credit", "thesis", "comprehensive", "degree", "option", "track", "concentration", "specialization"]:
        idx = text.lower().find(kw.lower())
        if idx >= 0:
            snippet = text[max(0,idx-80):idx+400]
            out[kw] = snippet
            break
    # Admission
    idx = text.lower().find("admission")
    if idx >= 0:
        out["admission"] = text[idx:idx+500]
    # Department / area
    idx = text.lower().find("department")
    if idx >= 0:
        out["dept"] = text[max(0,idx-50):idx+200]
    return out

items = [
    ("nyu-math", "https://bulletins.nyu.edu/graduate/arts-science/programs/mathematics-ms/"),
    ("nyu-econ", "https://bulletins.nyu.edu/graduate/arts-science/programs/economics-ma/"),
    ("nyu-phys", "https://bulletins.nyu.edu/graduate/arts-science/programs/physics-ms/"),
    ("nyu-psych", "https://bulletins.nyu.edu/graduate/arts-science/programs/psychology-ma/"),
    ("ut-mpacc", "https://www.sgs.utoronto.ca/programs/management-and-professional-accounting/"),
]

results = {}
for tag, url in items:
    try:
        r = extract(url, tag)
        results[tag] = r
        print(f"\n===== {tag} =====")
        for k, v in r.items():
            if k in ("url","label"): continue
            print(f"[{k}] {v[:350]}")
    except Exception as e:
        print(f"{tag} ERROR: {e}")

json.dump(results, open("_round70_data.json","w",encoding="utf-8"), ensure_ascii=False, indent=2)
print("\nSAVED _round70_data.json")
