# -*- coding: utf-8 -*-
import sys, io, re, 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'</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

TARGETS = [
 ("UCLA-grad-tuition", "https://grad.ucla.edu/funding/tuition/"),
 ("Berkeley-fee-schedule", "https://registrar.berkeley.edu/tuition-fees/fee-schedule/"),
 ("JHU-sfs-cost", "https://sfs.jhu.edu/cost-tuition/"),
 ("Gatech-cost-fees", "https://grad.gatech.edu/cost-fees"),
 ("Rice-grad-tuition", "https://cashier.rice.edu/form/graduate-tuition-fees"),
 ("UCSD-stud-tuition", "https://student-sis.ucsd.edu/studenttuitioninformation"),
]

KW = r'\$|per credit|per unit|tuition|academic year|semester|quarter|resident|nonresident'

def run(item):
    name, u = item
    out = [f"\n========== {name} :: {u} =========="]
    try:
        r = requests.get(u, headers=UA, timeout=30, verify=False, allow_redirects=True)
        out.append(f"status={r.status_code} final={r.url} rawlen={len(r.text)}")
        if r.status_code != 200:
            return "\n".join(out)
        t = to_text(r.text)
        lines = []
        for l in t.split('\n'):
            l = l.strip()
            if not l: continue
            if re.search(KW, l, re.I) and len(l) < 500:
                lines.append(l)
        out.append(f"textlen={len(t)} hit={len(lines)}")
        out += ["  " + l for l in lines[:45]]
    except Exception as e:
        out.append(f"ERR {type(e).__name__} {str(e)[:150]}")
    return "\n".join(out)

with cf.ThreadPoolExecutor(max_workers=4) as ex:
    for res in ex.map(run, TARGETS):
        print(res)
