from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFont
import json, subprocess, sys
P = Path(sys.argv[1]) if len(sys.argv)>1 else Path('/tmp/issue-lead-26280-r1/evidence-capture')
FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
font=ImageFont.truetype(FONT,18)
files=[('C1-before-49a9e80e0b','Before: 49a9e80e0b | C1 | real web app | 1280 x 900 | dark','C1-before-49a9e80e0b-final-raw.mp4'),('C2-after-9740f8522e','After: 9740f8522e | C2 | real web app | 1280 x 900 | dark','C2-after-9740f8522e-raw.mp4')]
checks={}
for base,label,video in files:
    a=Image.open(P/(base+'-check1.png')).convert('RGB'); b=Image.open(P/(base+'.png')).convert('RGB')
    delta=ImageChops.difference(a,b)
    checks[base]={'settled_identical':delta.getbbox() is None,'size':b.size}
    assert checks[base]['settled_identical']
    sheet=Image.new('RGB',(1280,940),'#151515');sheet.paste(b,(0,40));ImageDraw.Draw(sheet).text((16,10),label,font=font,fill='white');sheet.save(P/(base+'-sheet.png'))
    out=P/(base+'-recording.mp4')
    subprocess.run(['ffmpeg','-y','-v','error','-i',str(P/video),'-vf',f"pad=iw:ih+40:0:40:color=0x151515,drawtext=fontfile={FONT}:text='{label.replace(':', chr(92)+':')}':x=16:y=10:fontsize=18:fontcolor=white",'-c:v','libx264','-crf','18','-preset','fast','-pix_fmt','yuv420p',str(out)],check=True)
    probe=json.loads(subprocess.check_output(['ffprobe','-v','quiet','-show_streams','-show_format','-of','json',str(P/video)]))
    checks[base]['video_duration']=float(probe['format']['duration'])
    contact=Image.new('RGB',(1280,940),'#151515');draw=ImageDraw.Draw(contact)
    for i,t in enumerate([0,3,checks[base]['video_duration']/2,checks[base]['video_duration']-1]):
        frame=P/(base+f'-video-{t}s.png')
        subprocess.run(['ffmpeg','-y','-v','error','-ss',str(t),'-i',str(out),'-frames:v','1',str(frame)],check=True)
        im=Image.open(frame).convert('RGB').resize((640,470));contact.paste(im,((i%2)*640,(i//2)*470))
    contact.save(P/(base+'-recording-contact.png'))
a=Image.open(P/'C1-before-49a9e80e0b.png').convert('RGB');b=Image.open(P/'C2-after-9740f8522e.png').convert('RGB')
d=ImageChops.difference(a,b)
px=list(d.getdata());changed=[(i%1280,i//1280) for i,p in enumerate(px) if max(p)>0]
threshold=8
checks['pair']={'diff_bbox':d.getbbox(),'changed_pixels_zero':len(changed),'changed_pixels_threshold_8':sum(max(p)>threshold for p in px),'total_pixels':1280*900,'amplification':32,'threshold':threshold}
d.point(lambda v:min(255,v*32)).save(P/'C1-C2-diff0-x32.png')
t=Image.new('RGB',d.size);t.putdata([tuple(min(255,v*32) for v in p) if max(p)>threshold else (0,0,0) for p in px]);t.save(P/'C1-C2-diffT8-x32.png')
(P/'capture-checks.json').write_text(json.dumps(checks,indent=2)+'\n')
print(json.dumps(checks,indent=2))
