# -*- 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()

# UNC catalog 系页候选（生物/理科热门）
cands = [
    ("Biochemistry & Biophysics", "https://catalog.unc.edu/graduate/schools-departments/biochemistry-biophysics/"),
    ("Microbiology & Immunology", "https://catalog.unc.edu/graduate/schools-departments/microbiology-immunology/"),
    ("Genetics", "https://catalog.unc.edu/graduate/schools-departments/genetics/"),
    ("Pharmacology", "https://catalog.unc.edu/graduate/schools-departments/pharmacology/"),
    ("Cell Biology & Physiology", "https://catalog.unc.edu/graduate/schools-departments/cell-biology-physiology/"),
    ("Neuroscience", "https://catalog.unc.edu/graduate/schools-departments/neuroscience/"),
    ("Environment-Ecology", "https://catalog.unc.edu/graduate/schools-departments/environment-ecology/"),
    ("Geography", "https://catalog.unc.edu/graduate/schools-departments/geography/"),
    ("Sociology", "https://catalog.unc.edu/graduate/schools-departments/sociology/"),
    ("Exercise & Sport Science", "https://catalog.unc.edu/graduate/schools-departments/exercise-sport-science/"),
]
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()
        # 找 master/terminal/MS 关键词
        has_ms = bool(re.search(r"Master of Science|M\.S\.|terminal master|does not offer a terminal", txt, re.I))
        has_phd_only = bool(re.search(r"PhD only|does not offer a terminal|M\.S\..*PhD|doctoral only", txt, re.I))
        print(f"=== {name} ({s} {len(b)}B) ms={has_ms} phd_only={has_phd_only} ===")
        # 找 master 相关段
        for m in re.finditer(r"(.{0,200}(?:Master of Science|M\.S\.|terminal master|PhD only|does not offer a terminal).{0,300})", txt, re.I):
            print("  >>", m.group(1)[:400])
            print()
    except Exception as e:
        print(f"=== {name}: FAIL {type(e).__name__} {str(e)[:80]} ===")
