# -*- 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 fee-schedule 上下文（$11,640 附近）##########")
r = requests.get("https://registrar.berkeley.edu/tuition-fees/fee-schedule/", headers=UA, timeout=30, verify=False)
t = to_text(r.text)
idx = t.find("$11,640")
if idx > 0:
    seg = t[max(0, idx-2500): idx+2500]
    print(re.sub(r'\n+', '\n', seg))
else:
    print("not found, show head:")
    print(t[:3000])

print("\n########## RICE bursar 链接 ##########")
r2 = requests.get("https://bursar.rice.edu", headers=UA, timeout=25, verify=False)
raw = re.findall(r'href="([^"]+)"', r2.text)
seen=[]
for h in raw:
    if re.search(r'tuition|fee|cost', 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]))

print("\n########## JHU sfs graduate ##########")
r3 = requests.get("https://sfs.jhu.edu/cost-tuition/", headers=UA, timeout=25, verify=False)
raw = re.findall(r'href="([^"]+)"', r3.text)
seen=[]
for h in raw:
    if re.search(r'graduate|tuition|cost', h, re.I):
        if h.startswith('/'): h = "https://sfs.jhu.edu" + h
        if h not in seen: seen.append(h)
print("\n".join(seen[:20]))

print("\n########## UCLA registrar public fees ##########")
try:
    r4 = requests.get("https://sa.ucla.edu/RO/Fees/Public/public-fees", headers=UA, timeout=25, verify=False)
    t4 = to_text(r4.text)
    print("status", r4.status_code, "textlen", len(t4))
    print(t4[:1500])
except Exception as e:
    print("ERR", type(e).__name__, str(e)[:150])

print("\n########## UCSD grad 链接 ##########")
r5 = requests.get("https://grad.ucsd.edu/", headers=UA, timeout=25, verify=False)
raw = re.findall(r'href="([^"]+)"', r5.text)
seen=[]
for h in raw:
    if re.search(r'tuition|fee|cost|fund', h, re.I):
        if h.startswith('/'): h = "https://grad.ucsd.edu" + h
        if h not in seen: seen.append(h)
print("\n".join(seen[:15]))
