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

def seg(t, a, b, title):
    print(f"\n============ {title} ============")
    s = t[a:b]
    lines = [l.strip() for l in s.split('\n') if l.strip()]
    print("\n".join(lines))

r = requests.get("https://registrar.berkeley.edu/tuition-fees/fee-schedule/", headers=UA, timeout=30, verify=False)
t = to_text(r.text)
seg(t, 7128, 7838, "Graduate: Academic (2026-27)")
seg(t, 9361, 11456, "College of Engineering M.Eng")
seg(t, 16665, 17408, "School of Information MIMS")
seg(t, 18871, 19598, "Graduate Division Statistics MA")
seg(t, 15769, 16665, "CED M.Arch/MAAD/MCP")

print("\n============ UCSD 2026-27 Graduate Registration Fees ============")
r2 = requests.get("https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html", headers=UA, timeout=30, verify=False)
t2 = to_text(r2.text)
i = t2.find("Registration fees by quarter")
j = t2.find("Health Fee Waiver", i + 100)
print(re.sub(r'\n+', '\n', t2[i:i+4000] if i > 0 else t2[:4000]))
