import os,json,time,urllib.request,urllib.error,concurrent.futures,threading,posixpath
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
BASE='https://h5cq.cqgame.games/h5/'
ROOT='assets/tree'
CAP=6000; DEADLINE=time.time()+520
lock=threading.Lock(); n_ok=n_bad=n_fail=0
refs=json.load(open('assets/refs.json'))
tasks=[]
for code,urls in refs.items():
    for u in urls: tasks.append((code,u))
print('TASKS',len(tasks))

def local(code,url):
    rel=url.split('/h5/',1)[1]  # code/... or slot-common-files/...
    if '/../' in rel:
        pre,rest=rel.split('/../',1)
        rel='../'+pre+'/'+rest
    p=posixpath.normpath(rel)
    return os.path.join(ROOT,p)

def dl(t):
    global n_ok,n_bad,n_fail
    code,url=t
    dst=local(code,url)
    if os.path.exists(dst) and os.path.getsize(dst)>0: return ('skip',code,url)
    ref=BASE+code+'/index.html'
    for attempt in (0,1):
        if time.time()>DEADLINE: return ('dead',code,url)
        try:
            r=urllib.request.Request(url,headers={'User-Agent':UA,'Referer':ref})
            with urllib.request.urlopen(r,timeout=20) as f:
                st=f.status; body=f.read()
            with lock:
                if n_ok>=CAP: return ('cap',code,url)
            if st==200 and len(body)>0:
                os.makedirs(os.path.dirname(dst),exist_ok=True)
                open(dst,'wb').write(body)
                with lock: n_ok+=1
                return ('200',code,url)
            else:
                if attempt==0: time.sleep(0.5); continue
                with lock: n_bad+=1
                return (str(st),code,url)
        except urllib.error.HTTPError as e:
            if attempt==0: time.sleep(0.5); continue
            with lock: n_bad+=1
            return (str(e.code),code,url)
        except Exception as e:
            if attempt==0: time.sleep(0.5); continue
            with lock: n_fail+=1
            return ('ERR',code,url)

log=open('assets/fetch.log','w')
with concurrent.futures.ThreadPoolExecutor(40) as ex:
    for res in ex.map(dl,tasks):
        log.write('%s\t%s\t%s\n'%res)
        if res[0] not in ('skip','200'): log.flush()
print('DONE ok=%d bad=%d err=%d'%(n_ok,n_bad,n_fail))
