# -*- coding: utf-8 -*-
import re, os, sys, io, urllib.request, ssl, socket
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 ''

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 (KHTML, like Gecko) Chrome/120 Safari/537.36"}
BAD = ("fonts.google","schema.org","w3.org","cdn","googleapis","gstatic","file://")

def official_url(det_html):
    urls = re.findall(r'https?://[^"\'<>\s)]+', det_html)
    cand=[]
    for u in urls:
        if any(b in u for b in BAD): continue
        cand.append(u)
    # 优先 .edu
    edu=[u for u in cand if ".edu" in u]
    return (edu[0] if edu else (cand[0] if cand else ""))

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(200000).decode("utf-8","ignore"), ""
    except urllib.error.HTTPError as e: return None,"",f"HTTP {e.code}"
    except urllib.error.URLError as e: return None,"",f"URLError {str(e.reason)[:50]}"
    except socket.timeout: return None,"","TIMEOUT"
    except Exception as e: return None,"",f"{type(e).__name__} {str(e)[:50]}"

targets = ["unc-bcb-ms","unc-biology-ms","unc-ese-ms","unc-mcrp","unc-mha",
           "unc-global-studies-ma","unc-media-comm-ma","jhu-c726156","jhu-isai",
           "nyu-applied-stat","nyu-bme","nyu-ds","nyu-meng-me","nyu-mim",
           "usc-comds-ms","usc-bme","usc-meng-me","usc-mielr-ms","usc-mppds-ms","usc-msds"]
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')
    detp=os.path.join(base, det.replace("/",os.sep))
    det_ok=os.path.exists(detp)
    off=""
    if det_ok:
        dh=open(detp,encoding="utf-8",errors="ignore").read()
        off=official_url(dh)
    st,body,err=fetch(off) if off else (None,"","no-official-url")
    tk=""; fee=""
    if st==200:
        mt=re.search(r'.{0,45}(GRE|GMAT).{0,80}', body)
        tk=mt.group(0).replace("\n"," ")[:140] if mt else "(no GRE/GMAT)"
        mf=re.search(r'.{0,35}(\$\s?[0-9,]{3,}|tuition|per credit|per unit).{0,45}', body, re.I)
        fee=mf.group(0).replace("\n"," ")[:100] if mf else ""
    print(f"[{tid}] {n[:24]} | {deg} | det={'Y' if det_ok else 'N'} | {err}")
    if off: print(f"    off: {off[:80]}")
    if st==200:
        print(f"    test: {tk}")
        if fee: print(f"    fee : {fee}")
