from pathlib import Path
import sys,io,json,hashlib,subprocess
P=Path('C:/Users/Administrator/Documents/Codex/2026-09-29/da-kai');sys.path.insert(0,str(P/'work/python-daily-deps'))
from PIL import Image,ImageDraw,ImageFont
O=Path('outputs/daily-20261030');O.mkdir(parents=True,exist_ok=True)
def sha(b):return hashlib.sha256(b).hexdigest()
def structure(raw):
 g=3*2**((raw[10]&7)+1) if raw[10]&128 else 0;i=13+g;frames=[]
 while i<len(raw):
  tag=raw[i];i+=1
  if tag==59:break
  if tag==33:i+=1
  elif tag==44:
   flags=raw[i+8];i+=9;local=3*2**((flags&7)+1) if flags&128 else 0;i+=local;minimum=raw[i];i+=1;payload=[];sizes=[]
   while raw[i]:
    n=raw[i];sizes.append(n);payload.append(raw[i+1:i+1+n]);i+=n+1
   i+=1;frames.append({'local_table_bytes':local,'minimum_code_size':minimum,'payload_bytes':sum(sizes),'subblock_lengths':sizes,'payload_sha256':sha(b''.join(payload))});continue
  else:raise ValueError(tag)
  while raw[i]:i+=raw[i]+1
  i+=1
 return {'global_table_bytes':g,'total_table_bytes':g+sum(f['local_table_bytes'] for f in frames),'frames':frames}
def decode(p):
 raw=p.read_bytes();im=Image.open(p);loop=im.info.get('loop');frames=[]
 for i in range(im.n_frames):
  im.seek(i);frames.append({'delay_ms':im.info.get('duration'),'rgba_sha256':sha(im.convert('RGBA').tobytes())})
 return {'bytes':len(raw),'sha256':sha(raw),'dimensions':list(im.size),'loop':loop,'frames':frames,'structure':structure(raw)}
if '--fixture' in sys.argv:
 colors=[(248,245,232),(24,103,76),(201,90,50),(58,95,161)]
 # Swap 0..3 with 252..255 in both pixel indices and table entries.
 for name,offset in [('low',0),('high',252)]:
  palette=[0]*768
  for j,c in enumerate(colors):palette[3*(j+offset):3*(j+offset)+3]=c
  parts=[]
  for k,delay in enumerate([100,150,200,250]):
   im=Image.new('P',(96,56),offset);im.putpalette(palette);d=ImageDraw.Draw(im)
   d.rectangle((6+19*k,8,18+19*k,45),fill=offset+1)
   d.rectangle((4,48,91,51),fill=offset+2);d.rectangle((75,4,89,12),fill=offset+3)
   b=io.BytesIO();im.save(b,format='GIF',optimize=False,duration=delay,disposal=1,interlace=False)
   raw=b.getvalue();assert raw[10]&7==7;parts.append(raw[781:-1]);header=bytearray(raw[:781])
  header[:6]=b'GIF89a';header[11]=offset
  result=bytes(header)+b'\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00'+b''.join(parts)+b'\x3b'
  (O/f'{name}-input.gif').write_bytes(result)
 a=decode(O/'low-input.gif');b=decode(O/'high-input.gif')
 assert a['frames']==b['frames'] and a['bytes']==b['bytes'] and a['sha256']!=b['sha256']
 assert all(f['minimum_code_size']==8 for x in [a,b] for f in x['structure']['frames'])
 print('Controlled inputs:',a['bytes'],b['bytes']);sys.exit()
if '--verify' in sys.argv:
 data={};ff={}
 for name in ['low','high']:
  data[name]={}
  for mode in ['input','lossless','default']:
   p=O/f'{name}-{mode}.gif';r=decode(p);data[name][mode]=r
   assert r['dimensions']==[96,56] and r['loop']==0 and len(r['frames'])==4
   assert [f['delay_ms'] for f in r['frames']]==[100,150,200,250]
   command=['ffmpeg','-v','error','-ignore_loop','1','-i',str(p),'-fps_mode','passthrough','-pix_fmt','rgba','-f','rawvideo','-']
   pixels=subprocess.check_output(command);assert len(pixels)==96*56*4*4
   hashes=[sha(pixels[i*96*56*4:(i+1)*96*56*4]) for i in range(4)]
   probecommand=['ffprobe','-v','error','-ignore_loop','1','-show_frames','-show_entries','frame=duration_time,width,height','-of','json',str(p)]
   probe=json.loads(subprocess.check_output(probecommand));delays=[round(float(f['duration_time'])*1000) for f in probe['frames']]
   assert delays==[100,150,200,250] and all(f['width']==96 and f['height']==56 for f in probe['frames'])
   assert hashes==[f['rgba_sha256'] for f in r['frames']]
   ff[f'{name}-{mode}']={'command':command,'probe_command':probecommand,'rgba_frame_sha256':hashes,'delay_ms':delays,'dimensions':[96,56],'pillow_rgba_match':True}
   assert r['frames']==data[name]['input']['frames']
 for mode in ['input','lossless','default']:assert data['low'][mode]['frames']==data['high'][mode]['frames']
 equality={m:(O/f'low-{m}.gif').read_bytes()==(O/f'high-{m}.gif').read_bytes() for m in ['input','lossless','default']}
 evidence={'date':'2026-10-30','license':'CC0: original synthetic GIFs and figures','scope':'Local deployed-engine outputs, not website downloads','hypothesis':'Changing only numeric palette labels at fixed 256-slot tables and LZW minimum code size','input_indices':{'low':[0,1,2,3],'high':[252,253,254,255]},'input_control':'Same four RGB colors, same four full frames, same order/delays/loop; table entries and image indices bijectively relabeled; background index relabeled too.','files':data,'paired_bytes_equal':equality,'input_size_delta_bytes':data['high']['input']['bytes']-data['low']['input']['bytes'],'decoder_versions':{'pillow':__import__('PIL').__version__,'ffmpeg':subprocess.check_output(['ffmpeg','-version']).decode().splitlines()[0]},'browser_verified':False,'subjective_quality_measured':False,'realtime_playback_measured':False}
 evidence['input_differing_byte_count']=sum(a!=b for a,b in zip((O/'low-input.gif').read_bytes(),(O/'high-input.gif').read_bytes()))
 evidence['summary']={'input_payload_bytes_each':[258,261,257,249],'input_payload_total_bytes_each':1025,'output_payload_bytes_each':[201,82,82,86],'output_payload_total_bytes_each':451,'output_table_bytes':12,'output_minimum_code_size':2,'reduction_bytes':1333,'reduction_percent':round(1333/1913*100,4),'interpretation':'Index relabeling alone saved zero bytes in this controlled pair. Engine changed table size, code size and frame representation, so its savings cannot be assigned solely to index relabeling.'}
 (O/'evidence.json').write_text(json.dumps(evidence,indent=2));(O/'ffmpeg-verification.json').write_text(json.dumps(ff,indent=2))
 font=lambda n:ImageFont.truetype('C:/Windows/Fonts/segoeui.ttf',n)
 for number in [1,2]:
  im=Image.new('RGB',(1280,720),'#f6f8f2');d=ImageDraw.Draw(im)
  d.text((45,34),'SlimGIF | Do palette index numbers change GIF size?',font=font(35),fill='#173e32')
  if number==1:
   d.text((45,100),'Same colors and frames. Only the numeric palette labels change.',font=font(27),fill='#435c4d')
   for y,name,label in [(170,'low','Indices 0, 1, 2, 3'),(365,'high','Indices 252, 253, 254, 255')]:
    d.text((45,y),label,font=font(27),fill='#245d47');q=Image.open(O/f'{name}-input.gif')
    for k in range(4):
     q.seek(k);preview=q.convert('RGB').resize((240,140),Image.Resampling.NEAREST);im.paste(preview,(45+k*300,y+45))
   d.text((45,585),'256 palette slots / 768 table bytes / LZW minimum code size 8',font=font(27),fill='#173e32')
   d.text((45,635),'Four 96 x 56 frames; delays 100, 150, 200, 250 ms; infinite loop.',font=font(25),fill='#435c4d')
  else:
   d.text((45,105),'Measured locally with the deployed compression engine',font=font(28),fill='#435c4d')
   columns=[(45,'Index labels'),(490,'Input'),(750,'Lossless -O1'),(1020,'Default')]
   for x,label in columns:d.text((x,190),label,font=font(28),fill='#173e32')
   for y,name,label in [(260,'low','0 to 3'),(340,'high','252 to 255')]:
    d.text((45,y),label,font=font(31),fill='#245d47')
    for x,mode in [(490,'input'),(750,'lossless'),(1020,'default')]:d.text((x,y),f'{data[name][mode]["bytes"]:,} B',font=font(31),fill='#245d47')
   d.text((45,445),'Input size difference: 0 bytes. Different bytes, identical decoded pixels.',font=font(27),fill='#173e32')
   d.text((45,495),'Both outputs match all four input frames in Pillow and FFmpeg.',font=font(27),fill='#173e32')
   d.text((45,545),'Same dimensions, delays and loop count in all six files.',font=font(27),fill='#173e32')
   d.text((45,630),'Original CC0 fixture. File-level checks; browser playback not measured.',font=font(24),fill='#435c4d')
  im.save(O/f'check-{number}.png')
 print(json.dumps({'sizes':{n:{m:r['bytes'] for m,r in row.items()} for n,row in data.items()},'paired_bytes_equal':equality},indent=2))
