# -*- coding: utf-8 -*-
import json, re, os, io, sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
BASE=os.path.dirname(os.path.abspath(__file__))
todo=json.load(open(os.path.join(BASE,'todo_upgrade.json'),encoding='utf-8'))
main=open(os.path.join(BASE,'index_main.html'),encoding='utf-8').read()
prog_seg=main[main.find('const PROGRAMS='):main.find('const CATD=')]
existing_det=set(re.findall(r'url:"(details/[^"]+)"',prog_seg))
print('existing PROGRAMS det:',len(existing_det))

PHD=re.compile(r'phd|drph|scd|dsc|dphil|doctor',re.I)
disc_order={'cs':0,'biz':1,'soc':2,'eng':3,'sci':4,'med':5,'art':6,'edu':7}

cands=[]; seen=set()
for x in todo:
    deg=(x.get('deg') or '')
    if PHD.search(deg): continue
    det=x['det']
    if det in existing_det: continue
    key=(x['s'],x['en'].strip().lower())
    if key in seen: continue
    seen.add(key); cands.append(x)

cands.sort(key=lambda x:(disc_order.get(x.get('disc'),9),x['s']))
from collections import Counter
print('master candidates after dedup:',len(cands))
print(Counter(x['disc'] for x in cands))
print('--- by school ---')
print(Counter(x['s'] for x in cands).most_common(30))
for i,x in enumerate(cands[:70]):
    print(i,x['s'],'|',x['deg'],'|',x['disc'],'|',x['en'][:48],'|',os.path.basename(x['det']))
json.dump(cands,open(os.path.join(BASE,'_cands29.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1)
