# -*- coding: utf-8 -*-
import sys, io, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
import requests
requests.packages.urllib3.disable_warnings()

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36",
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
      "Accept-Language": "en-US,en;q=0.9"}

def to_text(h):
    h = re.sub(r'<(script|style|noscript)[^>]*>[\s\S]*?</\1>', ' ', h, flags=re.I)
    h = re.sub(r'</t[dh]>', ' | ', h, flags=re.I)
    h = re.sub(r'</tr>', '\n', h, flags=re.I)
    h = re.sub(r'<br\s*/?>', '\n', h, flags=re.I)
    h = re.sub(r'<[^>]+>', ' ', h)
    for a,b in (('&nbsp;',' '),('&amp;','&'),('&#36;','$'),('&lt;','<'),('&gt;','>'),('&quot;','"')):
        h = h.replace(a,b)
    h = re.sub(r'&#(\d+);', lambda m: chr(int(m.group(1))) if int(m.group(1))<0x10000 else ' ', h)
    h = re.sub(r'[ \t\r\f\v]+', ' ', h)
    h = re.sub(r'\n\s*\n+', '\n', h)
    return h

def show(u, maxlines=60):
    print(f"\n########## {u} ##########")
    try:
        r = requests.get(u, headers=UA, timeout=30, verify=False)
        print("status", r.status_code, "rawlen", len(r.text))
        t = to_text(r.text)
        lines = [l.strip() for l in t.split('\n') if re.search(r'\$|tuition|fee|quarter|semester|unit|credit', l, re.I) and len(l.strip())<400]
        print("textlen", len(t), "hit", len(lines))
        for l in lines[:maxlines]: print("  ", l)
        return t
    except Exception as e:
        print("ERR", type(e).__name__, str(e)[:150])
        return ""

show("https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html")
show("https://bursar.rice.edu/graduate-programs")

print("\n########## BERKELEY: 逐处 Graduate ##########")
r = requests.get("https://registrar.berkeley.edu/tuition-fees/fee-schedule/", headers=UA, timeout=30, verify=False)
t = to_text(r.text)
for n, m in enumerate(re.finditer(r'Graduate', t)):
    i = m.start()
    ctx = re.sub(r'\n+',' | ', t[i:i+180])
    print(f"[{n}] idx={i} :: {ctx}")
