# -*- coding: utf-8 -*-
import json, re, os, io, sys, ssl, urllib.request, socket, html
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
BASE=os.path.dirname(os.path.abspath(__file__))
pr={x['det']:x for x in json.load(open(os.path.join(BASE,'_probe29b.json'),encoding='utf-8'))}

want=['nyu-c529fb8.html','cornell-cb05803.html','uw-cfa123b.html','yale-international-development-economics.html',
 'harvard-computational-science-and-engineering.html','nyu-c804839.html','nyu-c568b0a.html',
 'uw-c1fa362.html','up-c6b3731.html','rice-engineering-management-leadership.html']

ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
socket.setdefaulttimeout(10)
KW=re.compile(r'(full[- ]time|part[- ]time|on[- ]campus|online|hybrid|in person|residential|STEM|credit|unit|tuition|GRE|GMAT|TOEFL|IELTS|deadline|February|January|December|September|co-op|cooperative|thesis|coursework|credits|months|year)',re.I)

for w in want:
    x=pr.get(w)
    if not x: print('NOENTRY',w); continue
    url=x['url']; code='ERR'; b=b''
    try:
        req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'})
        r=urllib.request.urlopen(req,context=ctx,timeout=10); b=r.read(); code=r.status
    except Exception as e:
        print(w,'ERR',type(e).__name__); continue
    txt=html.unescape(re.sub(r'<script[\s\S]*?</script>|<style[\s\S]*?</style>',' ',b.decode('utf-8','ignore')))
    txt=html.unescape(re.sub(r'<[^>]+>',' ',txt)); txt=re.sub(r'\s+',' ',txt).strip()
    open(os.path.join(BASE,'_29_'+w),'w',encoding='utf-8').write(txt)
    print('===',w,code,len(b),'B ===')
    # 标题
    m=re.search(r'(Master[^\.]{5,90})',txt)
    print('TITLE:',m.group(1)[:90] if m else '?')
    hits=[t.strip() for t in txt.split('. ') if KW.search(t)][:10]
    for h in hits: print('  -',h[:150])
    print()
