# -*- 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 ''
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)]
    edu=[u for u in c if ".edu" in u]
    return edu 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); t=re.sub(r'&nbsp;',' ',t); t=re.sub(r'&#039;',"'",t); return re.sub(r'\s+',' ',t)
targets=["jhu-c13629c","jhu-c5ed8dc","jhu-c785e3d","jhu-c97be4c","jhu-bioinfo-ms","jhu-finecon","jhu-gis-ms",
         "ut-mmi","ut-mmpa","ut-meng-ece","uw-meng-cheme-coop","uw-meng-mme-coop","uw-mmsc-coop",
         "gatech-msbcfm","unc-stands-ms","unc-stats-ds-ms"]
for tid in targets:
    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")
    print(f"===== [{tid}] http={st} | {off[:72]}")
    if st!=200: print("  ",body[:80]); continue
    txt=strip(body); hits=re.findall(r'[^.]{0,90}(?:GRE|GMAT)[^.]{0,90}\.',txt)
    if not hits: print("   无 GRE/GMAT 句子")
    for h in hits[:4]: print("   -",h.strip()[:170])
