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

print("########## BERKELEY: 搜 'Graduate Fee Schedule' ##########")
r = requests.get("https://registrar.berkeley.edu/tuition-fees/fee-schedule/", headers=UA, timeout=30, verify=False)
t = to_text(r.text)
for key in ["Graduate Fee Schedule", "Graduate Academic", "Graduate Professional"]:
    i = t.find(key)
    print(f"[{key}] idx={i}")
    if i > 0:
        print(re.sub(r'\n+','\n', t[i:i+1800]))
        print("-----")

print("\n########## UCSD: registrar 链接 ##########")
r2 = requests.get("https://grad.ucsd.edu/financial/tuition-fees.html", headers=UA, timeout=30, verify=False)
raw = re.findall(r'href="([^"]+)"', r2.text)
seen=[]
for h in raw:
    if re.search(r'registrar|tuition|fee', h, re.I):
        if h.startswith('/'): h = "https://grad.ucsd.edu" + h
        if h not in seen: seen.append(h)
print("\n".join(seen[:20]))

print("\n########## RICE: tuition_fee_rates 链接 ##########")
r3 = requests.get("https://bursar.rice.edu/tuition_fee_rates", headers=UA, timeout=30, verify=False)
raw = re.findall(r'href="([^"]+)"', r3.text)
seen=[]
for h in raw:
    if re.search(r'tuition_fee_rates|graduate', h, re.I):
        if h.startswith('/'): h = "https://bursar.rice.edu" + h
        if h not in seen: seen.append(h)
print("\n".join(seen[:15]))
