import json, pathlib, subprocess, sys, datetime, shutil
source=json.load(open(sys.argv[1]))
out=pathlib.Path(sys.argv[2])/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir(parents=True)
raw=out/'raw';raw.mkdir()
for run in source:
 label=run['side']+'-'+run['theme']
 for c in run['captures']:
  first=raw/(label+'-'+c['kind']+'-1.png');second=raw/(label+'-'+c['kind']+'-2.png')
  shutil.copyfile(c['first'],first);shutil.copyfile(c['second'],second)
  comparison=subprocess.run(['compare','-metric','AE',str(first),str(second),'null:'],capture_output=True,text=True)
  if comparison.returncode!=0: raise RuntimeError('Unstable '+label+' '+c['kind']+': '+comparison.stderr)
  crop='500x180+0+85' if c['kind']=='sidebar' else '620x180+650+280'
  subprocess.run(['convert',str(second),'-resize','1280x800!','-crop',crop,'+repage',str(out/(label+'-'+c['kind']+'.png'))],check=True)
 raw_video=raw/(label+'.mp4');shutil.copyfile(run['video'],raw_video)
 subprocess.run(['ffmpeg','-v','error','-i',str(raw_video),'-vf','scale=1280:800,crop=1280:520:0:0','-an','-c:v','libx264','-crf','18',str(out/(label+'.mp4'))],check=True)
 subprocess.run(['ffmpeg','-v','error','-i',str(out/(label+'.mp4')),'-vf','fps=1,scale=640:-1,tile=4x4','-frames:v','1',str(out/(label+'-review.png'))],check=True)
print(out)
