# -*- 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 费率段落 ##########")
r = requests.get("https://registrar.berkeley.edu/tuition-fees/fee-schedule/", headers=UA, timeout=30, verify=False)
t = to_text(r.text)
pos = [m.start() for m in re.finditer(r'Graduate', t)]
print("Graduate 出现次数:", len(pos))
if pos:
    start = pos[0]
    seg = t[start-200:start+3000]
    print(re.sub(r'\n+','\n',seg))

print("\n\n########## UCSD grad tuition-fees ##########")
for u in ["https://grad.ucsd.edu/financial/tuition-fees.html"]:
    try:
        r2 = requests.get(u, headers=UA, timeout=30, verify=False)
        print("URL:", u, "status", r2.status_code, "len", len(r2.text))
        t2 = to_text(r2.text)
        lines = [l.strip() for l in t2.split('\n') if re.search(r'\$|tuition|fee|quarter|semester', l, re.I) and len(l.strip())<400]
        print("textlen", len(t2))
        for l in lines[:40]: print("  ", l)
    except Exception as e:
        print("ERR", type(e).__name__, str(e)[:150])

print("\n\n########## RICE tuition_fee_rates ##########")
try:
    r3 = requests.get("https://bursar.rice.edu/tuition_fee_rates", headers=UA, timeout=30, verify=False)
    print("status", r3.status_code, "len", len(r3.text))
    t3 = to_text(r3.text)
    lines = [l.strip() for l in t3.split('\n') if re.search(r'\$|tuition|fee|semester', l, re.I) and len(l.strip())<400]
    print("textlen", len(t3), "hit", len(lines))
    for l in lines[:45]: print("  ", l)
except Exception as e:
    print("ERR", type(e).__name__, str(e)[:150])

print("\n\n########## UCLA annual fees ##########")
for u in ["https://registrar.ucla.edu/fees-residence"]:
    try:
        r4 = requests.get(u, headers=UA, timeout=30, verify=False)
        print("URL:", u, "status", r4.status_code, "len", len(r4.text))
        raw = re.findall(r'href="([^"]+)"', r4.text)
        seen=[]
        for h in raw:
            if re.search(r'annual|fee|tuition', h, re.I):
                if h.startswith('/'): h = "https://registrar.ucla.edu" + h
                if h not in seen: seen.append(h)
        print("\n".join(seen[:12]))
    except Exception as e:
        print("ERR", type(e).__name__, str(e)[:150])
