# -*- coding: utf-8 -*-
import sys, io, re, json, concurrent.futures as cf
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'<[^>]+>', ' ', h)
    h = re.sub(r'&nbsp;', ' ', h); h = re.sub(r'&amp;', '&', h)
    h = re.sub(r'&#\d+;', ' ', h)
    h = re.sub(r'[ \t\r\f\v]+', ' ', h)
    h = re.sub(r'\n\s*\n+', '\n', h)
    return h

def get(u):
    r = requests.get(u, headers=UA, timeout=25, verify=False, allow_redirects=True)
    return r.status_code, r.text

def dump(u, kw=r'tuition|per credit|per unit|academic year|semester|quarter|\$'):
    st, h = get(u)
    if st != 200:
        print(f"--- {u} status={st}")
        return
    t = to_text(h)
    lines = [l.strip() for l in t.split('\n') if re.search(kw, l, re.I) and len(l.strip()) < 400]
    print(f"--- {u} status=200 textlen={len(t)} hitlines={len(lines)}")
    for l in lines[:35]:
        print("   ", l)

print("========== BROWN bursar tuition-fees ==========")
dump("https://www.brown.edu/about/administration/bursar/tuition-fees")

print("\n========== 链接发现 ==========")
pages = {
 "ucla-reg": "https://registrar.ucla.edu/",
 "berkeley-reg": "https://registrar.berkeley.edu/",
 "ucsd-grad": "https://grad.ucsd.edu/",
 "ucsd-stud": "https://students.ucsd.edu/",
 "nw-sfs": "https://www.northwestern.edu/sfs/",
 "jhu-sfs": "https://sfs.jhu.edu/",
 "rice-grad": "https://graduate.rice.edu/",
 "cornell-dfa": "https://www.dfa.cornell.edu/",
 "gatech-grad": "https://grad.gatech.edu/",
 "upenn-provost": "https://provost.upenn.edu/",
 "ucla-grad": "https://grad.ucla.edu/",
}
def links(item):
    name, base = item
    try:
        st, h = get(base)
        if st != 200: return [f"{name} status={st}"]
        raw = re.findall(r'href="([^"]+)"', h)
        hit = []
        for hr in raw:
            if re.search(r'tuition|fee|cost|fund', hr, re.I):
                if hr.startswith('/'):
                    m = re.match(r'(https?://[^/]+)', base)
                    hr = m.group(1) + hr
                elif not hr.startswith('http'):
                    continue
                if hr not in hit: hit.append(hr)
        return [f"{name}:"] + [f"   {x}" for x in hit[:14]]
    except Exception as e:
        return [f"{name} ERR {type(e).__name__}"]

with cf.ThreadPoolExecutor(max_workers=6) as ex:
    for group in ex.map(links, pages.items()):
        for line in group: print(line)
