# -*- coding: utf-8 -*-
import urllib.request, ssl, re, sys, io, 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
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"

def fetch(u):
    req = urllib.request.Request(u, headers={"User-Agent":UA})
    r = urllib.request.urlopen(req, timeout=15, context=ctx)
    return r.status, r.read()

cands = [
    ("Health Behavior MPH", "https://catalog.unc.edu/graduate/schools-departments/health-behavior/"),
    ("Maternal and Child Health", "https://catalog.unc.edu/graduate/schools-departments/maternal-child-health/"),
    ("Health Policy MHA", "https://catalog.unc.edu/graduate/schools-departments/health-management-policy/"),
    ("Nutrition MPH", "https://catalog.unc.edu/graduate/schools-departments/nutrition/"),
    ("Education", "https://catalog.unc.edu/graduate/schools-departments/education/"),
    ("Social Work", "https://catalog.unc.edu/graduate/schools-departments/social-work/"),
]
for name, u in cands:
    try:
        s, b = fetch(u)
        t = b.decode("utf-8", errors="ignore")
        t = htmllib.unescape(t)
        txt = re.sub(r"<script[\s\S]*?</script>", "", t, flags=re.I)
        txt = re.sub(r"<style[\s\S]*?</style>", "", txt, flags=re.I)
        txt = re.sub(r"<[^>]+>", " ", txt)
        txt = re.sub(r"\s+", " ", txt).strip()
        print(f"=== {name} ({s} {len(b)}B) ===")
        for m in re.finditer(r"(.{0,150}(?:Master of Public Health|M\.P\.H\.|Master of Health Administration|M\.H\.A\.|Master of Social Work|M\.S\.W\.|Master of Arts|M\.A\.|Master of Science|M\.S\.|terminal|professional|does not offer a terminal).{0,300})", txt, re.I):
            print("  >>", m.group(1)[:450])
            print()
    except Exception as e:
        print(f"=== {name}: FAIL {type(e).__name__} {str(e)[:80]} ===")
