import pathlib,json,subprocess,re,concurrent.futures
R=pathlib.Path('/tmp/lead-27909-r1/capture')
P=json.loads((R/'pairs.json').read_text())
O=pathlib.Path((R/'diff-path.txt').read_text())
files=[]
for pair in P.values():
    files.extend(pathlib.Path(pair[k]) for k in ['before','after','diff0','diffT16'])
for key in ['A1-1440x1000-light','A2-1440x1000-dark','A3-390x844-light','A4-390x844-dark','A-rec-start-1440x1000-light','B-1440x1000-dark','E-default-1440x1000-light','P-1440x1000-light']:
    files.append(pathlib.Path(P[key]['sheet']))
files.extend(O/name for name in ['D-combined-sheet.png','Q-combined-sheet.png','D-prose-readable-crops.png','D-code-readable-crops.png','diff-stats.json','quality.json'])
for side in ['before','after']:
    d=pathlib.Path((R/f'{side}-record-path.txt').read_text())
    files.extend([d/f'A-rec-{side}.mp4',d/f'timing-{side}.json'])
files.extend(sorted(R.glob('*.cjs')))
files.extend(sorted(R.glob('*.py')))
files.extend([R/'REBUILD.md',R/'environment-metadata.json',R/'pairs.json'])
files=list(dict.fromkeys(files))
assert all(f.is_file() for f in files)
assert len({f.name for f in files})==len(files)
def upload(batch):
    result=subprocess.run(['ghdrop','upload','-m',*map(str,batch)],text=True,capture_output=True)
    return batch,result
completed=[];errors=[]
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
    pending=[pool.submit(upload,files[i:i+4]) for i in range(0,len(files),4)]
    for task in concurrent.futures.as_completed(pending):
        batch,result=task.result()
        if result.returncode:
            errors.append({'files':list(map(str,batch)),'stderr':result.stderr,'stdout':result.stdout})
            print('FAILED',batch[0].name,result.stderr,flush=True)
        else:
            completed.extend(result.stdout.strip().splitlines())
            print(result.stdout,end='',flush=True)
        (R/'uploads.md').write_text('\n'.join(completed)+'\n')
        (R/'upload-errors.json').write_text(json.dumps(errors,indent=2))
out='\n'.join(completed)+'\n'
rows=re.findall(r'!?\[([^\]]+)\]\((https://[^)]+)\)',out)
byname={f.name:f for f in files}
mapping={name:{'path':str(byname[name]),'url':url,'markdown':line} for (name,url),line in zip(rows,completed)}
(R/'upload-map.json').write_text(json.dumps(mapping,indent=2))
assert not errors and len(rows)==len(files),(len(rows),len(files),errors)
