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

T = [
 ("UCLA-annual", "https://registrar.ucla.edu/fees-residence/annual-and-term-student-fees"),
 ("Cornell-gradschool-tuition", "https://gradschool.cornell.edu/financial-support/tuition-fees/"),
 ("JHU-AAP-tuition", "https://advanced.jhu.edu/tuition/"),
 ("NU-TGS-tuition", "https://www.tgs.northwestern.edu/financial/tuition/"),
 ("Gatech-registrar", "https://registrar.gatech.edu/"),
 ("Rice-gradprograms", "https://bursar.rice.edu/graduate-programs"),
]

def run(item):
    name, u = item
    out = [f"\n===== {name} :: {u}"]
    try:
        r = requests.get(u, headers=UA, timeout=25, verify=False, allow_redirects=True)
        out.append(f"status={r.status_code} final={r.url} len={len(r.text)}")
        if r.status_code != 200:
            return "\n".join(out)
        t = to_text(r.text)
        ls = [l.strip() for l in t.split('\n') if re.search(r'\$|per credit|per unit|tuition|academic year|semester|quarter', l, re.I) and len(l.strip())<420]
        out.append(f"textlen={len(t)} hit={len(ls)}")
        out += ["   " + l for l in ls[:28]]
        links = re.findall(r'href="([^"]+)"', r.text)
        cand = []
        for hh in links:
            if re.search(r'tuition|fee|cost|rate', hh, re.I):
                if hh.startswith('/'):
                    hh = re.match(r'(https?://[^/]+)', r.url).group(1) + hh
                if hh not in cand: cand.append(hh)
        out.append("LINKS:")
        out += ["   " + x for x in cand[:12]]
    except Exception as e:
        out.append(f"ERR {type(e).__name__} {str(e)[:120]}")
    return "\n".join(out)

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