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

picks=[
 'details/up-c6cb873.html',
 'details/mit-data-economics-design-policy.html',
 'details/up-c05f5d0.html',
 'details/nyu-c03e53a.html',
 'details/uw-c046e13.html',
 'details/geo-economics-ms.html',
 'details/uw-c596728.html',
 'details/up-c568b0a.html',
 'details/cmu-c13f7d2.html',
]
for det in picks:
    x=pr.get(os.path.basename(det))
    if not x: print('MISS',det); continue
    url=x['url']
    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(); txt=b.decode('utf-8','ignore')
        txt=html.unescape(re.sub(r'<script[\s\S]*?</script>',' ',txt))
        txt=html.unescape(re.sub(r'<style[\s\S]*?</style>',' ',txt))
        txt=re.sub(r'<[^>]+>',' ',txt); txt=re.sub(r'\s+',' ',txt).strip()
        fn='_28_'+os.path.basename(det)
        open(os.path.join(BASE,fn),'w',encoding='utf-8').write(txt)
        print(det,'OK',r.status,len(b),'->',fn)
    except Exception as e:
        print(det,'ERR',type(e).__name__,str(e)[:80])
