# -*- 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 = [
    ("Kenan-Flagler", "https://catalog.unc.edu/graduate/schools-departments/kenan-flagler-business-school/"),
    ("Business", "https://catalog.unc.edu/graduate/schools-departments/business/"),
    ("Accounting", "https://catalog.unc.edu/graduate/schools-departments/accounting/"),
    ("Business Analytics", "https://catalog.unc.edu/graduate/schools-departments/business-analytics/"),
    ("Management", "https://catalog.unc.edu/graduate/schools-departments/management/"),
    ("Social Work", "https://catalog.unc.edu/graduate/schools-departments/social-work/"),
    ("Education MEITE", "https://catalog.unc.edu/graduate/schools-departments/education/"),
    ("Environment-Ecology", "https://catalog.unc.edu/graduate/schools-departments/environment-ecology/"),
]
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) ===")
        # 找 master/MAcc/MSBA/MSM 关键词
        for m in re.finditer(r"(.{0,120}(?:Master of Accounting|M\.Acc\.|Master of Science in Business Analytics|MSBA|Master of Management|M\.M\.|Master of Business Administration|MBA|Master of Social Work|M\.S\.W\.|Master of Arts in Educational Innovation|MEITE|Environment and Ecology).{0,300})", txt, re.I):
            seg = m.group(1)[:420]
            print("  >>", seg)
            print()
    except Exception as e:
        print(f"=== {name}: FAIL {type(e).__name__} {str(e)[:80]} ===")
