from pathlib import Path
import sys,json,hashlib,math,shutil,urllib.request,gzip,concurrent.futures
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
from bs4 import BeautifulSoup
O=Path('outputs/daily-20261020');O.mkdir(parents=True,exist_ok=True)
urls=['https://www.freeconvert.com/gif-compressor','https://ezgif.com/optimize','https://gif.pi7.org/gif-compressor-for-discord','https://www.iloveimg.com/compress-image/compress-gif','https://cloudinary.com/tools/compress-gif-to-1mb','https://www.veed.io/tools/video-compressor/gif-compressor','https://watermarkly.com/compress-gif/','https://bulkpictools.com/tools/gif/gif-compressor','https://www.gifspeed.com/gif-compressor','https://imagekit.io/tools/compress-gif/']
def fetch(u):
 try:
  b=urllib.request.urlopen(urllib.request.Request(u,headers={'User-Agent':'Mozilla/5.0'}),timeout=25).read()
  if b[:2]==b'\x1f\x8b':b=gzip.decompress(b)
  s=BeautifulSoup(b,'html.parser')
  for x in s(['script','style','nav','footer','header']):x.decompose()
  t=s.get_text(' ',strip=True);return {'url':u,'text':t}
 except Exception as e:return {'url':u,'error':str(e)}
if '--research' in sys.argv:
 rows=list(concurrent.futures.ThreadPoolExecutor(8).map(fetch,urls))
 (O/'top10.json').write_text(json.dumps(rows,indent=2),encoding='utf8')
 for i,r in enumerate(rows,1):(O/f'top10-{i:02}.txt').write_text(r.get('text',r.get('error','')),encoding='utf8')
 print(json.dumps([{'url':r['url'],'chars':len(r.get('text','')),'error':r.get('error')} for r in rows],indent=2));sys.exit()
if '--fixture' in sys.argv:
 frames=[]
 palette=[0,0,0,20,120,200,138,188,228]+[0,0,0]*253
 for shift in [0,6,12]:
  im=Image.new('P',(96,64),0);im.putpalette(palette);d=ImageDraw.Draw(im)
  d.rectangle((16,16,47,47),fill=2);d.rectangle((17,17,46,46),fill=1);d.rectangle((20+shift,25,23+shift,28),fill=2);frames.append(im)
 frames[0].save(O/'input.gif',save_all=True,append_images=frames[1:],duration=[100,200,300],loop=0,transparency=0,disposal=2,optimize=False)
 print('generated CC0 palette fixture');sys.exit()
def decode(path):
 im=Image.open(path);rows=[]
 for i in range(im.n_frames):
  im.seek(i);rgba=im.convert('RGBA');canonical=bytearray(rgba.tobytes())
  for k in range(0,len(canonical),4):
   if canonical[k+3]==0:canonical[k:k+3]=b'\0\0\0'
  rows.append({'duration_ms':im.info.get('duration'),'visible_rgba_sha256_transparent_rgb_zeroed':hashlib.sha256(canonical).hexdigest(),'transparent_pixels':sum(a==0 for a in rgba.getchannel('A').getdata())})
 im.seek(0);rgba=im.convert('RGBA')
 return {'bytes':path.stat().st_size,'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'size':list(im.size),'loop':im.info.get('loop'),'frames':rows,'edge_rgba':list(rgba.getpixel((16,16)))},rgba
if '--decode' in sys.argv:
 a,ra=decode(O/'input.gif');b,rb=decode(O/'lossless.gif');print(json.dumps([a,b],indent=2));assert a['frames']==b['frames'] and a['size']==b['size'] and a['loop']==b['loop'];assert a['edge_rgba']==[138,188,228,255]
 (O/'evidence.json').write_text(json.dumps({'date':'2026-10-20','license':'CC0 own synthetic fixture','method':'Local current-site WASM -O1; not a browser download measurement','input':a,'output':b,'edge_construction':'50% #1478c8 blended over white, rounded; stored fully opaque','perceptual_quality':'not scored'},indent=2))
 font=lambda n:ImageFont.truetype('C:/Windows/Fonts/segoeui.ttf',n)
 for n,(bg,label) in enumerate([('white','White background'),('#102030','Dark background')],1):
  panel=Image.new('RGB',(1280,720),'#f7f7ee');d=ImageDraw.Draw(panel);d.text((55,45),'SlimGIF | Same saved pixels, two backgrounds',font=font(37),fill='#173d31')
  d.text((55,115),label,font=font(30),fill='#245b45')
  for x,rgba,lab in [(55,ra,'Input'),(675,rb,'Lossless engine output')]:
   tile=Image.new('RGBA',rgba.size,bg);tile.alpha_composite(rgba);tile=tile.convert('RGB').resize((480,320),Image.Resampling.NEAREST);panel.paste(tile,(x,200));d.text((x,550),lab,font=font(28),fill='#173d31')
  d.text((55,635),'5x nearest-neighbor enlargement | Synthetic example | No visual-quality score',font=font(23),fill='#435e51');panel.save(O/f'check-{n}.png')
 print(json.dumps({'input':a,'output':b},indent=2));sys.exit()

