import os,subprocess,concurrent.futures as cf,threading,urllib.parse
BASE='/app/data/tasks/29/i29bng28'
HOST='https://static-sg.nemarketingstudiols.click/aux/games/aux_b'
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
REF=HOST+'/aux_b/runner/index.html'
rows=[l.rstrip('\n').split('\t') for l in open(BASE+'/batch6.tsv') if l.strip()]
lock=threading.Lock(); man=[]
SOFT={'json','skel','xml'}
def one(r):
    slug,src,size=r; size=int(size)
    ext=src.rsplit('.',1)[-1].lower()
    out=os.path.join(BASE,slug,src)
    os.makedirs(os.path.dirname(out),exist_ok=True)
    url=f'{HOST}/{slug}/{urllib.parse.quote(src)}'
    code='000'; nb=0
    for attempt in range(2):
        p=subprocess.run(['curl','-s','--http1.1','-m','40','-A',UA,'-e',REF,'-o',out,'-w','%{http_code}',url],capture_output=True,text=True)
        code=p.stdout.strip(); nb=os.path.getsize(out) if os.path.exists(out) else 0
        if code=='200': break
    good = code=='200' and nb>0 and (nb==size or ext in SOFT)
    if not good:
        if os.path.exists(out): os.remove(out)
        nb=0
    return (slug,src,code,nb,size,1 if (code=='200' and nb==size) else 0)
with cf.ThreadPoolExecutor(max_workers=6) as ex:
    for res in ex.map(one,rows):
        with lock:
            man.append(res); print(*res,flush=True)
with open(BASE+'/manifest6.tsv','w') as f:
    for r in man: f.write('\t'.join(map(str,r))+'\n')
print('TOTAL',len(man),'OK',sum(1 for r in man if r[5]),'C200',sum(1 for r in man if r[2]=='200'),'KEPT',sum(1 for r in man if r[3]>0))
