import subprocess,os,urllib.request,json,sys
D=os.path.join(os.environ['TEMP'],'egj');K=open(os.path.join(D,'k.txt')).read().strip()
log=open(os.path.join(D,'dl.txt'),'a')
for spec in sys.argv[1].split(','):
    v,f,tag=spec.split(':')
    out=os.path.join(D,f'egj-{v}-{tag}.mp4')
    r=subprocess.run([sys.executable,'-m','yt_dlp','--no-update','--remote-components','ejs:github','-f',f,'-o',out,f'https://www.youtube.com/watch?v={v}'],capture_output=True,text=True)
    log.write(f'{v} dl rc={r.returncode} {r.stderr[-300:]}\n');log.flush()
    if not os.path.exists(out): continue
    data=open(out,'rb').read()
    req=urllib.request.Request('https://nyxpost.heynyx.dev/api/v1/media',data=data,headers={'Authorization':'Bearer '+K,'Content-Type':'video/mp4','X-Filename':f'egj-{v}-{tag}.mp4'})
    try:
        j=json.load(urllib.request.urlopen(req,timeout=600));log.write(f'{v} up {j.get("id")} {j.get("bytes")} local {len(data)}\n')
        if j.get('bytes')==len(data): os.remove(out)
    except Exception as e: log.write(f'{v} up FAIL {e}\n')
    log.flush()
log.write('DONE\n');log.close()
