from pathlib import Path
import sys,struct,json,hashlib,subprocess,importlib.util
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-20261103');O.mkdir(exist_ok=True,parents=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)}


O.mkdir(exist_ok=True,parents=True)
source=(O/'source.gif').read_bytes()
for name,value in [('unknown',0),('square',49),('wide',113)]:
 raw=bytearray(source);raw[12]=value;(O/f'{name}-input.gif').write_bytes(raw)
if '--verify' in sys.argv:
 evidence={'date':'2026-11-03','license':'CC0 original synthetic files and figures','control':'Three inputs differ only byte offset 12: 0 no information,49 square pixel,113 width/height 2:1. Same raster data is not same intended display geometry.','files':{}}
 for name in ['unknown','square','wide']:
  for mode in ['input','lossless','default']:
   p=O/f'{name}-{mode}.gif';d=decode(p);raw=p.read_bytes();d['pixel_aspect_field']=raw[12];d['pixel_aspect_ratio']=None if raw[12]==0 else (raw[12]+15)/64
   pixels=subprocess.check_output(['ffmpeg','-v','error','-ignore_loop','1','-i',str(p),'-fps_mode','passthrough','-pix_fmt','rgba','-f','rawvideo','-'])
   assert len(pixels)==96*56*4*4
   assert [sha(pixels[i*21504:(i+1)*21504]) for i in range(4)]==[f['rgba_sha256'] for f in d['frames']]
   assert d['frames']==decode(O/'unknown-input.gif')['frames'] and d['dimensions']==[96,56] and d['loop']==0
   cmd=['ffprobe','-v','error','-ignore_loop','1','-show_streams','-show_frames','-of','json',str(p)];probe=json.loads(subprocess.check_output(cmd));d['ffprobe_sample_aspect_ratio']=probe['streams'][0].get('sample_aspect_ratio');d['ffprobe_display_aspect_ratio']=probe['streams'][0].get('display_aspect_ratio');d['ffprobe_delay_ms']=[round(float(f['duration_time'])*1000) for f in probe['frames']];assert d['ffprobe_delay_ms']==[100,150,200,250]
   evidence['files'][f'{name}-{mode}']=d
 a=(O/'unknown-input.gif').read_bytes()
 for name in ['square','wide']:assert [i for i,(x,y) in enumerate(zip(a,(O/f'{name}-input.gif').read_bytes())) if x!=y]==[12]
 assert all(evidence['files'][f'{n}-{m}']['pixel_aspect_field']==0 for n in ['unknown','square','wide'] for m in ['lossless','default'])
 assert len({(O/f'{n}-{m}.gif').read_bytes() for n in ['unknown','square','wide'] for m in ['lossless','default']})==1
 evidence['browser_verified']=False;evidence['subjective_quality_measured']=False;evidence['realtime_playback_measured']=False
 (O/'evidence.json').write_text(json.dumps(evidence,indent=2),encoding='utf8')
 print(json.dumps({n:{'bytes':d['bytes'],'aspect_field':d['pixel_aspect_field'],'ffprobe_sar':d['ffprobe_sample_aspect_ratio']} for n,d in evidence['files'].items()}))
 font=lambda n:ImageFont.truetype('C:/Windows/Fonts/segoeui.ttf',n)
 for number in [1,2]:
  im=Image.new('RGB',(1280,720),'#f6f8f2');draw=ImageDraw.Draw(im)
  lines=['SlimGIF | Does compression preserve pixel aspect ratio?','Same 96 x 56 raster is not proof of the same display shape.']
  if number==1:lines+=['Input field 0: no aspect information','Input field 49: square pixels, ratio 1:1','Input field 113: wide pixels, ratio 2:1','Each input: 1,913 bytes. Only byte offset 12 changes.']
  else:lines+=['Six local outputs: 580 bytes each, byte-identical.','All output aspect fields: 0 (information absent).','Full raster pixels, delays, dimensions and loop matched.','Display geometry and browser playback were not measured.']
  for i,line in enumerate(lines):draw.text((45,50+i*90),line,font=font(32 if i else 35),fill='#173e32')
  im.save(O/f'check-{number}.png')
