import sys, pathlib, json, subprocess
root=pathlib.Path(sys.argv[1])
for side, sha in [('before','f03db4fbef'),('after','65aab2acef')]:
    run=root/('before-1802' if side=='before' else 'after-1803')
    obs=json.loads((run/'observations.json').read_text())
    obs.pop('originalExecutable',None)
    for event in obs['events']:
        if isinstance(event.get('state'),dict):
            event['state']={k:v for k,v in event['state'].items() if k in ['mode','tailscaleServeEnabled']}
        if 'url' in event: event['url']='t3code://app/#/welcome'
    (root/(side+'-observations.json')).write_text(json.dumps(obs,indent=2)+'\n')
    title=f'{side.title()} - {sha} - Linux x86_64 AppImage, Xvfb 1920x1080'
    result='No window returned after relaunch' if side=='before' else 'New process reopened in network-accessible mode; agent picker responds'
    subprocess.run(['convert',str(run/'after-interaction.png'),'-fill',('#242424' if side=='before' else '#fcfcfc'),'-draw','rectangle 600,303 1100,335','-background','#111111','-gravity','north','-splice','0x100','-font','DejaVu-Sans','-fill','white','-pointsize','28','-annotate','+0+12',title,'-pointsize','24','-annotate','+0+54',result,str(root/(side+'.png'))],check=True)
    vf=f"delogo=x=600:y=303:w=500:h=32,scale=1280:720,pad=1280:820:0:100:color=0x111111,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='{side.title()} - {sha} - Linux AppImage / Xvfb':x=20:y=12:fontsize=23:fontcolor=white,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='At 3s - enable network access; at 22s - click agent picker':x=20:y=48:fontsize=21:fontcolor=white"
    subprocess.run(['ffmpeg','-y','-i',str(run/'raw.mp4'),'-vf',vf,'-c:v','libx264','-preset','fast','-crf','20','-movflags','+faststart',str(root/(side+'.mp4'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    # Review the full recording as a contact sheet, one frame per second.
    subprocess.run(['ffmpeg','-y','-i',str(root/(side+'.mp4')),'-vf','fps=1,scale=384:246,tile=5x6','-frames:v','1',str(root/(side+'-review.png'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
