from pathlib import Path
import json,hashlib,subprocess,shutil,datetime,platform,struct,io
from PIL import Image
root=Path(__file__).resolve().parent; out=root/'local-conversion-benchmark';out.mkdir(exist_ok=True)
manifest=json.loads((root/'fixed-three-inputs.json').read_text(encoding='utf-8-sig'))
sha=lambda b:hashlib.sha256(b).hexdigest()
rows=[];runs=[]
for row in manifest['inputs']:
 f=root/Path(row['file']).name;assert len(f.read_bytes())==row['bytes'] and sha(f.read_bytes())==row['sha256']
 raw=f.read_bytes(); refs={}
 for i in range(struct.unpack_from('<H',raw,4)[0]):
  w,h,_,_,_,_,n,off=struct.unpack_from('<BBBBHHII',raw,6+16*i)
  with Image.open(io.BytesIO(raw[off:off+n])) as im:refs[im.size]=im.convert('RGBA').tobytes()
 for route in ['pillow-default','ffmpeg-default','pillow-explicit-32']:
  dest=out/(f.stem+'-'+route+'.png');start=datetime.datetime.now(datetime.timezone.utc).isoformat()
  if route.startswith('pillow'):
   with Image.open(f) as im:
    image=im.ico.getimage((32,32)) if route.endswith('32') else im
    image.save(dest,'PNG')
   cmd=['Pillow Image.open',str(f),'ico.getimage((32,32))' if route.endswith('32') else 'default','save PNG']; rc=0;stderr=''
  else:
   cmd=[shutil.which('ffmpeg'),'-hide_banner','-loglevel','info','-y','-i',str(f),'-frames:v','1',str(dest)]
   proc=subprocess.run(cmd,capture_output=True,text=True,encoding='utf-8',errors='replace',timeout=30);rc=proc.returncode;stderr=proc.stderr
  runs.append(dict(input=f.name,route=route,started_at=start,command=cmd,exit_code=rc,stderr=stderr))
  if rc:continue
  b=dest.read_bytes()
  with Image.open(dest) as im:
   rgba=im.convert('RGBA');p=rgba.tobytes();alphas=rgba.getchannel('A');hist=alphas.histogram();ref=refs.get(im.size);differ=sum(p[i:i+4]!=ref[i:i+4] for i in range(0,len(p),4)) if ref is not None else None
   rows.append(dict(input=f.name,route=route,output=dest.name,bytes=len(b),width=im.width,height=im.height,mode=im.mode,has_alpha_channel='A' in im.getbands(),alpha_min=alphas.getextrema()[0],alpha_max=alphas.getextrema()[1],transparent_pixels=hist[0],semitransparent_pixels=sum(hist[1:255]),opaque_pixels=hist[255],center_rgba=list(rgba.getpixel((im.width//2,im.height//2))),sha256=sha(b),rgba_sha256=sha(p),different_pixels_from_matching_input=differ,edge_blur_measure='Zero pixel differences proves no pixel/edge change at matching size; visual browser test not performed' if differ==0 else 'Not established'))
report=dict(measured_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),python=platform.python_version(),pillow=Image.__version__,ffmpeg_version=subprocess.run(['ffmpeg','-version'],capture_output=True,text=True).stdout.splitlines()[0],inputs=manifest['inputs'],runs=runs,outputs=rows)
(out/'results.json').write_text(json.dumps(report,indent=2),encoding='utf-8');print(json.dumps(rows))
