# -*- 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_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)
    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)[:100]

def strip_tags(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); t=re.sub(r'&amp;','&',t)
    t=re.sub(r'\s+',' ',t)
    return t

targets=["nu-mlds","rice-mai-ms","dartmouth-mem-ms","dartmouth-meng-ms","vandy-biostat-ms","ubc-mj",
         "unc-cs-ms","unc-ds-ms","unc-biostat-ms","nyu-mspp","usc-macc-ms","usc-gscm-ms"]
for tid in targets:
    if tid not in blocks: print("MISSING",tid); continue
    blk=blocks[tid]; offs=official(g(blk,'url')); off=offs[0] if offs else ""
    st,body=fetch(off) if off else (None,"no off")
    print(f"===== [{tid}] http={st} | {off[:70]}")
    if st!=200: print("  ",body[:90]); continue
    txt=strip_tags(body)
    hits=re.findall(r'[^.]{0,100}(?:GRE|GMAT)[^.]{0,100}\.', txt)
    if not hits: print("   正文无 GRE/GMAT 句子")
    for h in hits[:5]: print("   -", h.strip()[:180])
