from pathlib import Path
import sys,json,hashlib,io,concurrent.futures,urllib.request,gzip
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-20261022');O.mkdir(parents=True,exist_ok=True)
if '--fixture' in sys.argv:
 parts=[]
 for n,delay in zip([0,0,1,1],[100,200,300,400]):
  im=Image.new('P',(64,40),0);im.putpalette([248,245,231,28,99,77,193,77,48]+[0]*759)
  ImageDraw.Draw(im).rectangle((8 if n==0 else 36,10,24 if n==0 else 52,29),fill=n+1)
  b=io.BytesIO();im.save(b,format='GIF',optimize=False,duration=delay,disposal=1)
  raw=b.getvalue();offset=13+3*(2**((raw[10]&7)+1));parts.append(raw[offset:-1])
  if n==0: header=raw[:offset]
 raw=b'GIF89a'+header[6:]+b'\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00'+b''.join(parts)+b'\x3b'
 (O/'input.gif').write_bytes(raw)
 print('Raw four-frame own CC0 fixture generated',len(raw));sys.exit()
def decode(path):
 im=Image.open(path);frames=[]
 for i in range(im.n_frames):
  im.seek(i);rgba=im.convert('RGBA')
  frames.append({'index':i,'delay_ms':im.info.get('duration'), 'rgba_sha256':hashlib.sha256(rgba.tobytes()).hexdigest()})
 return {'bytes':path.stat().st_size,'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'dimensions':list(im.size),'loop':im.info.get('loop'),'frame_count':im.n_frames,'duration_ms':sum(f['delay_ms'] for f in frames),'frames':frames}
if '--decode' in sys.argv:
 rows={n:decode(O/(n+'.gif')) for n in ['input','lossless','o2','o3']}
 a,b=rows['input'],rows['lossless'];assert [f['delay_ms'] for f in a['frames']]==[100,200,300,400]
 assert a['duration_ms']==b['duration_ms']==1000
 def runs(r):
  out=[]
  for f in r['frames']:
   if out and out[-1]['rgba_sha256']==f['rgba_sha256']:out[-1]['delay_ms']+=f['delay_ms']
   else:out.append({'rgba_sha256':f['rgba_sha256'],'delay_ms':f['delay_ms']})
  return out
 assert runs(a)==runs(b)
 for n in ['o2','o3']:
  assert rows[n]['frame_count']==2 and [f['delay_ms'] for f in rows[n]['frames']]==[300,700]
  assert runs(rows[n])==runs(a)
 data={'date':'2026-10-22','license':'CC0 own synthetic fixture and figures','scope':'local current-site engine; browser save tracked separately','files':rows,'visible_runs':runs(a),'quality':'no subjective visual-quality assessment'}
 (O/'evidence.json').write_text(json.dumps(data,indent=2),encoding='utf8')
 font=lambda n:ImageFont.truetype('C:/Windows/Fonts/segoeui.ttf',n)
 for k in [1,2]:
  img=Image.new('RGB',(1280,720),'#f6f8f2');d=ImageDraw.Draw(img)
  d.text((50,40),'SlimGIF | Fewer frames, same stored timeline?',font=font(40),fill='#163e32')
  for y,n in [(125,'input'),(295,'lossless'),(465,'o2')]:
   r=rows[n];d.text((50,y),f'{n}: {r["bytes"]:,} bytes | {r["frame_count"]} frames | {r["duration_ms"]} ms',font=font(29),fill='#245d47')
   x=50
   for f in r['frames']:
    duration=f['delay_ms'];w=int(duration*1.12);label='A' if f['rgba_sha256']==a['frames'][0]['rgba_sha256'] else 'B'
    d.rectangle((x,y+50,x+w-3,y+115),fill='#b2d6bc' if label=='A' else '#f1c8b3')
    d.text((x+7,y+74),f'{label}: {duration}',font=font(24),fill='#17382e');x+=w
  d.text((50,655),'Local decoded timeline. A and B are full-frame RGBA states, not frame numbers.',font=font(24),fill='#425d51')
  if k==2:
   d.rectangle((40,120,1240,620),fill='#f6f8f2')
   for x,n in [(70,'input'),(700,'lossless')]:
    im=Image.open(O/(n+'.gif'));im.seek(0);img.paste(im.convert('RGB').resize((448,280),Image.Resampling.NEAREST),(x,240))
    d.text((x,150),f'{n}: first decoded state A',font=font(29),fill='#245d47')
   d.text((70,570),'All visible runs checked; first-frame matching alone is insufficient.',font=font(28),fill='#17382e')
  img.save(O/f'check-{k}.png')
 print(json.dumps(data,indent=2));sys.exit()
if '--research' in sys.argv:
 urls=json.loads((O/'search-results.json').read_text())['urls']
 def fetch(u):
  try:
   r=urllib.request.urlopen(urllib.request.Request(u,headers={'User-Agent':'Mozilla/5.0'}),timeout=30);b=r.read()
   if b[:2]==b'\x1f\x8b':b=gzip.decompress(b)
   s=BeautifulSoup(b,'html.parser')
   for el in s(['script','style','header','footer','nav']):el.decompose()
   return {'url':u,'status':r.status,'text':s.get_text(' ',strip=True)}
  except Exception as e:return {'url':u,'error':str(e)}
 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))
