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

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

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

slugs = [
    ("UT Econ", "https://www.sgs.utoronto.ca/programs/economics/"),
    ("UT CS", "https://www.sgs.utoronto.ca/programs/computer-science/"),
    ("UT Mgmt", "https://www.sgs.utoronto.ca/programs/management/"),
    ("UT Info", "https://www.sgs.utoronto.ca/programs/information/"),
]

for name, url in slugs:
    print("="*70)
    print(name, url)
    h = fetch(url)
    # 提取 title
    m = re.search(r"<title>([^<]+)</title>", h)
    if m: print("TITLE:", m.group(1).strip())
    # 提取 h1/h2
    for m in re.finditer(r"<h[12][^>]*>(.*?)</h[12]>", h, re.S):
        t = re.sub(r"<[^>]+>", "", m.group(1)).strip()
        if t: print("  H:", t[:120])
    # Quick Facts 表
    qf = re.search(r"Quick Facts([\s\S]{0,6000})", h)
    if qf:
        # 提取 table rows
        rows = re.findall(r"<tr[^>]*>(.*?)</tr>", qf.group(1), re.S)
        for row in rows[:30]:
            cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row, re.S)
            cells = [re.sub(r"<[^>]+>", "", c).strip() for c in cells]
            cells = [html.unescape(c) for c in cells if c]
            if cells: print("  ROW:", " | ".join(cells)[:200])
    # 查找 degree 关键词
    for kw in ["Master of", "MSc", "MA ", "MEng", "MEng", "MMSc", "MASc", "Meng", "PhD", "Doctor", "MBA", "LLM"]:
        if kw in h:
            # 找上下文
            idx = h.find(kw)
            ctx = re.sub(r"<[^>]+>", "", h[max(0,idx-80):idx+120]).strip()
            print(f"  KW[{kw}]:", html.unescape(ctx)[:200])
