import json,sys,subprocess
from pathlib import Path
root=Path(sys.argv[1])
for side in ['base','head']:
    folder=root/f'{side}-record';frames=json.loads((folder/'frames.json').read_text());lines=[]
    for i,f in enumerate(frames):
        lines.append(f"file 'frames/{f['file']}'")
        duration=max(.001,frames[i+1]['time']-f['time']) if i+1<len(frames) else 1
        lines.append(f'duration {duration:.6f}')
    lines.append(f"file 'frames/{frames[-1]['file']}'")
    (folder/'frames.txt').write_text('\n'.join(lines))
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','concat','-safe','0','-i',str(folder/'frames.txt'),'-vf','fps=15','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p','-movflags','+faststart',str(root/f'{side}-interaction.mp4')],check=True)
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-i',str(root/f'{side}-interaction.mp4'),'-vf','fps=1/3,scale=360:250,tile=4x3','-frames:v','1',str(root/f'{side}-contact.png')],check=True)
    print(side,len(frames),'frames',frames[-1]['time']-frames[0]['time'],'seconds')
