import os,json,time,urllib.request,urllib.error,posixpath,urllib.parse,threading,concurrent.futures
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
ROOT='tree'; CAP=200
refs=json.load(open('refs.json'))
# 1) build pc variants for code 35
pc=[]
for u in refs['35']:
    if '/assets/images/device/' in u: pc.append(u.replace('/assets/images/device/','/assets/images/pc/'))
print('pc refs',len(pc))
lock=threading.Lock(); res=[]
def dl(u):
    code=u.split('/h5/',1)[1].split('/',1)[0]
    rel=posixpath.normpath(u.split('/h5/',1)[1])
    dst=os.path.join(ROOT,rel)
    ref='https://h5cq.cqgame.games/h5/%s/index.html'%code
    if os.path.exists(dst) and os.path.getsize(dst)>0: return ('skip',code,u)
    for a in (0,1):
        try:
            r=urllib.request.Request(urllib.parse.quote(u,safe=":/?&=%~+"),headers={'User-Agent':UA,'Referer':ref})
            with urllib.request.urlopen(r,timeout=25) as f: st=f.status; body=f.read()
            if st==200 and len(body)>0:
                os.makedirs(os.path.dirname(dst),exist_ok=True); open(dst,'wb').write(body)
                return ('200',code,u)
            if a==0: time.sleep(0.6); continue
            return (str(st),code,u)
        except urllib.error.HTTPError as e:
            if a==0: time.sleep(0.6); continue
            return (str(e.code),code,u)
        except Exception as e:
            if a==0: time.sleep(0.6); continue
            return ('ERR:'+type(e).__name__,code,u)
with concurrent.futures.ThreadPoolExecutor(8) as ex:
    for r in ex.map(dl,pc): res.append(r)
json.dump(pc,open('pc35.json','w'),indent=0)
ok=[r for r in res if r[0] in('200','skip')]
print('PC DONE ok=%d/%d'%(len(ok),len(pc)))
for r in res:
    if r[0] not in('200','skip'): print('BAD',r)
