# -*- 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(rest, key):
    mm = re.search(key+r':"([^"]*)"', rest)
    return mm.group(1) if mm else ''

targets = ["notre-cse-mscse","notre-ee-msee","notre-ms-acms",
           "emory-econ-ma","cornell-ms-bme","jhu-bioinfo-ms","jhu-finecon","jhu-gis-ms",
           "rice-eml-meml","uva-ds-ms","uva-mit-ms","uva-ms-cs","uva-msacc","uva-se-ms",
           "ut-mmi","ut-mmpa","gatech-msbcfm","illinois-mspe"]

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_from_det(det_rel):
    fp=os.path.join(base, det_rel.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)
    cands=[u for u in urls if not any(x in u.lower() for x in EXCL)]
    edu=[u for u in cands if ".edu" in u]
    return edu or cands

def fetch(u, timeout=12):
    try:
        req=urllib.request.Request(u, headers=hdr)
        with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
            return r.status, r.read(80000).decode("utf-8","ignore")
    except Exception as e:
        return None, str(e)[:100]

for tid in targets:
    if tid not in blocks: print("MISSING", tid); continue
    blk=blocks[tid]
    n=g(blk,'n'); deg=g(blk,'deg'); det=g(blk,'url')
    offs=official_from_det(det)
    off=offs[0] if offs else ""
    st, body = fetch(off) if off else (None,"no official url in det")
    kw=""
    if st==200:
        m=re.search(r'.{0,50}(tuition|fee per|per credit|per term|per semester|C\$|US\$|USD\s?\$?[0-9]|\$[0-9,]{4,}).{0,50}', body, re.I)
        kw=m.group(0).replace("\n"," ")[:120] if m else "(no tuition kw)"
    print(f"[{tid}] {n[:28]} | {deg} | http={st}")
    print(f"    OFF: {off[:90]}")
    if kw: print("    KW:", kw)
