import os,re,time,concurrent.futures as cf,urllib.request,urllib.error,ssl
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
H='https://static-sg.nemarketingstudiols.click'
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
slugs=[l.split('\t')[1] for l in open('groups.tsv').read().splitlines() if l.startswith('auxp\t')]
os.makedirs('auxp',exist_ok=True)
man=open('auxp/manifest.tsv','w'); man.write('slug\thtml\tgame\tbytes\tctype\n'); man.flush()
def get(url,ref):
    for a in range(3):
        try:
            r=urllib.request.Request(url,headers={'User-Agent':UA,'Referer':ref})
            with urllib.request.urlopen(r,timeout=60,context=ctx) as x:
                return x.status,x.read(),x.headers.get('Content-Type','')
        except urllib.error.HTTPError as e:
            if a==2: return e.code,b'',''
        except Exception:
            if a==2: return 0,b'',''
        time.sleep(1)
res=[]
def work(slug):
    d=os.path.join('auxp',slug); os.makedirs(d,exist_ok=True)
    ref=f'{H}/aux/games/aux_p/{slug}/index-pure.html'
    hs,body,ct=get(ref,ref)
    open(os.path.join(d,'index-pure.html'),'wb').write(body)
    if hs!=200: return (slug,hs,'-',0,'')
    m=re.search(rb'gamescript:\s*"([^"]+)"',body)
    if not m: return (slug,hs,'NOHASH',0,'')
    gf=m.group(1).decode()
    gs,gb,gct=get(f'{H}/aux/games/aux_p/{slug}/{gf}',ref)
    if gs==200 and gb:
        open(os.path.join(d,gf),'wb').write(gb)
    else:
        # retry via libs.js as fallback
        pass
    return (slug,hs,gf,len(gb),gct)
with cf.ThreadPoolExecutor(max_workers=4) as ex:
    for r in ex.map(work,slugs):
        res.append(r); man.write('\t'.join(map(str,r))+'\n'); man.flush()
ok=sum(1 for r in res if r[3]>0)
print('done',ok,'/',len(res))
