# -*- coding: utf-8 -*-
import re, os, sys, io, urllib.request, ssl
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
base=os.path.dirname(os.path.abspath(__file__))
html=open(os.path.join(base,'index_main.html'),encoding='utf-8').read()
p0=html.index("const PROGRAMS=["); p1=html.index("const CATD=["); seg=html[p0:p1]
starts=[m.start() for m in re.finditer(r'\{id:"',seg)]
blocks={}
for i,a in enumerate(starts):
    b=starts[i+1] if i+1<len(starts) else len(seg)
    blk=seg[a:b]; pid=re.search(r'\{id:"([^"]+)"',blk).group(1); blocks[pid]=blk
def g(r,k):
    mm=re.search(k+r':"([^"]*)"',r); return mm.group(1) if mm else ''
EXCL=["fonts.googleapis","fonts.gstatic","cdn","jsdelivr","unpkg","cdnjs","google.com","schema.org","w3.org","file:"]
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
hdr={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
def official(det):
    fp=os.path.join(base,det.replace("/",os.sep))
    if not os.path.exists(fp): return []
    t=open(fp,encoding="utf-8",errors="ignore").read()
    urls=re.findall(r'https?://[^"\'<>\s\\]+',t)
    c=[u for u in urls if not any(x in u.lower() for x in EXCL)]
    return [u for u in c if ".ca" in u] or c
def fetch(u):
    try:
        req=urllib.request.Request(u,headers=hdr)
        with urllib.request.urlopen(req,timeout=15,context=ctx) as r: return r.status,r.read(300000).decode("utf-8","ignore")
    except Exception as e: return None,str(e)[:90]
def strip(t):
    t=re.sub(r'<script[\s\S]*?</script>',' ',t,flags=re.I); t=re.sub(r'<style[\s\S]*?</style>',' ',t,flags=re.I)
    t=re.sub(r'<[^>]+>',' ',t); return re.sub(r'\s+',' ',t)

for tid in ["ut-mmi","ut-mmpa","ut-c7a2833","ut-c839284","ut-c900110","ut-c9f57d5","ut-cc2276a","ut-cdentmsc","ut-cfce3b0","ut-meng-ece"]:
    if tid not in blocks: print("MISSING",tid); continue
    offs=official(g(blocks[tid],'url')); off=offs[0] if offs else ""
    st,body=fetch(off) if off else (None,"no off")
    kw=""
    if st==200:
        txt=strip(body); m=re.search(r'.{0,40}(tuition|fee|C\$[0-9,]|\$[0-9,]{4,}).{0,40}',txt,re.I)
        kw=m.group(0)[:110] if m else "(no tuition kw)"
    print(f"[{tid}] http={st} | {off[:70]} | {kw}")

# direct bursar / SGS tuition probes
for label,u in [("GaTech bursar","https://bursar.gatech.edu/tuition-and-fees"),
                ("UT SGS tuition","https://www.sgs.utoronto.ca/financial-support/tuition-fees"),
                ("UT engineering fees","https://gradstudies.engineering.utoronto.ca/tuition-fees")]:
    st,body=fetch(u)
    kw=""
    if st==200:
        txt=strip(body); m=re.search(r'.{0,40}(C\$[0-9,]|\$[0-9,]{4,}|per credit|per semester).{0,40}',txt,re.I)
        kw=m.group(0)[:110] if m else "(no kw)"
    print(f"[{label}] http={st} | {kw}")
