import json, pathlib, hashlib, subprocess, sys
root=pathlib.Path(sys.argv[1]); side=sys.argv[2]; sha=sys.argv[3]
frames=sorted(root.glob('frame-*.png'))
final=root/'final-a.png'
concat=root/'video-input.txt'
with concat.open('w') as f:
    for p in frames:
        f.write(f"file '{p}'\nduration 0.5\n")
    f.write(f"file '{final}'\nduration 3\nfile '{final}'\n")
parent=root.parent
for name in ['a','b']:
    subprocess.run(['convert',str(root/f'final-{name}.png'),'-crop','1230x740+10+0','+repage','-strip',str(parent/f'{side}-{name}.png')],check=True)
image_a=(parent/f'{side}-a.png').read_bytes();image_b=(parent/f'{side}-b.png').read_bytes()
assert image_a==image_b, 'The final stills are not stable'
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','concat','-safe','0','-i',str(concat),'-vf','crop=1230:740:10:0,fps=10','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(parent/f'{side}-proof.mp4')],check=True)
timeline=[json.loads(x) for x in (root/'observations.ndjson').read_text().splitlines()]
report={'commit':sha,'environment':{'os':'Windows Server 2025 Datacenter 10.0.26100','powershell':'7.7.0 official zip','app':'Electron via vp run dev:desktop','seed':'T3CODE_DEV_SEED=0, fresh isolated home','desktopResolution':'1920x1080','captureCrop':'1230x740+10+0 observer window','recording':'Time lapse at 2 captured frames per playback second; on-screen elapsed timer is real elapsed time'},'stableFinalStill':{'identical':True,'sha256':hashlib.sha256(image_a).hexdigest()},'timeline':timeline,'cachedPathInspection':(root/'cache-inspection.txt').read_text().splitlines(),'warmProfileMeasurement':(root/'pwsh-recovered.txt').read_text().splitlines()}
(parent/f'{side}-observations.json').write_text(json.dumps(report,indent=2))
print(json.dumps({'frames':len(frames),'lastObservation':timeline[-1],'stableFinalStill':True}))
