from pathlib import Path
import subprocess,json
import numpy as np
from PIL import Image,ImageDraw
r=Path('/tmp/lead-29548-r1/evidence-capture-2');report={}
for side in ['before','after']:
 p=r/f'W2-{side}-raw.mp4'
 meta=json.loads(subprocess.check_output(['ffprobe','-v','quiet','-show_streams','-show_format','-of','json',str(p)]));v=next(x for x in meta['streams'] if x['codec_type']=='video');w,h=v['width'],v['height'];duration=float(meta['format']['duration'])
 # Read full-frame ffmpeg output at 20fps; the banner top border is at CSS y64.
 raw=subprocess.check_output(['ffmpeg','-v','error','-i',str(p),'-vf','fps=20,scale=720:450','-f','rawvideo','-pix_fmt','rgb24','-'])
 frames=np.frombuffer(raw,np.uint8).reshape(-1,450,720,3)
 marks=[]
 for i,im in enumerate(frames):
  region=im[31:35,260:580].astype(int)
  red=((region[:,:,0]-region[:,:,1]>12)&(region[:,:,0]-region[:,:,2]>12)).sum()
  marks.append(int(red))
 first=next(i for i,n in enumerate(marks) if i>10 and n<10)
 report[side]={'duration':duration,'videoPixels':[w,h],'lastBannerFrameAt20fps':round((first-1)/20,2),'firstAbsentFrameAt20fps':round(first/20,2),'bannerRedSamples':marks}
 out=Image.new('RGB',(720*3,490*2),'#202124');d=ImageDraw.Draw(out)
 times=[0.25,2.5,max(0,first/20-.1),first/20,first/20+.5,min(duration-.2,first/20+3)]
 for i,t in enumerate(times):
  frame=Image.fromarray(frames[min(len(frames)-1,round(t*20))]);x=(i%3)*720;y=(i//3)*490
  d.text((x+8,y+8),f'{side} {t:.2f}s',fill='white');out.paste(frame,(x,y+30))
 out.save(r/f'W2-{side}-review-sheet.png')
(r/'recording-timestamps.json').write_text(json.dumps(report,indent=2))
print(json.dumps({s:{k:v for k,v in o.items() if k!='bannerRedSamples'} for s,o in report.items()},indent=2))
