# -*- coding: utf-8 -*-
import json, re, os, io, sys, ssl, urllib.request, socket
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
BASE=os.path.dirname(os.path.abspath(__file__))
cands=json.load(open(os.path.join(BASE,'_cands28.json'),encoding='utf-8'))

# 历史聚合页坑 / 已排除 / 403 不可达校，本轮不直取
skip_school={'berkeley','ucla','ucsd','unc','gatech','emory','usc','duke','princeton','uchicago','uva'}
# 已定性排除/待终检 det 前缀（历史结论）
skip_det={'geo-cybersecurity-risk-management-ms.html','jhu-c785e3d.html','jhu-c13629c.html',
 'cmu-c46c856.html','wustl-stats-data-science-polsci-conc-ma.html','duke-c76be69.html',
 'notre-applied-and-computational-mathematics-and-statistics-ms---masters-professional.html',
 'notre-computer-science-and-engineering-mscse---masters-professional.html',
 'notre-data-science-ms---masters-professional.html','usc-c531fe9.html','usc-cac5b60.html',
 'usc-ccfb8b7.html','usc-c8eee33.html'}

ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
socket.setdefaulttimeout(8)

targets=[x for x in cands if x['s'] not in skip_school and os.path.basename(x['det']) not in skip_det]
print('targets after skip:',len(targets))
from collections import Counter
print(Counter(x['s'] for x in targets).most_common(30))

results=[]
for x in targets:
    url=x['url']; code='ERR'; n=0; err=''
    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=8)
        b=r.read(); code=r.status; n=len(b)
    except urllib.error.HTTPError as e:
        code=str(e.code)
    except Exception as e:
        err=type(e).__name__
    results.append((x['s'],x['deg'],x['disc'],x['en'][:42],os.path.basename(x['det']),code,n,err,url))

for r in results:
    print('|'.join(str(v) for v in r[:7]))
json.dump([{'s':r[0],'deg':r[1],'disc':r[2],'en':r[3],'det':r[4],'code':r[5],'bytes':r[6],'err':r[7],'url':r[8]} for r in results],
 open(os.path.join(BASE,'_probe28b.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1)
