"""Read alpha bounds for frame viewports. Does not alter image pixels."""
from pathlib import Path
from PIL import Image
import json
root=Path(__file__).resolve().parent
result={}
for p in sorted((root/'atlases').glob('*.png')):
 im=Image.open(p);assert im.mode=='RGBA'
 alpha=im.getchannel('A');mask=alpha.point(lambda v:255 if v>180 else 0)
 sums=[sum(mask.crop((0,y,im.width,y+1)).get_flattened_data())/255 for y in range(im.height)]
 bands=[];start=None
 for y,n in enumerate(sums+[0]):
  if n>16 and start is None:start=y
  if n<=16 and start is not None:
   if y-start>40:bands.append([start,y])
   start=None
 assert len(bands)==6,(p.name,bands)
 boundaries=[0]+[(bands[i-1][1]+bands[i][0])//2 for i in range(1,6)]+[im.height]
 cw=im.width//4;cells=[]
 for row in range(6):
  y0,y1=boundaries[row:row+2]
  for col in range(4):
   x0=col*cw;b=mask.crop((x0,y0,x0+cw,y1)).getbbox();assert b is not None
   cells.append({'index':row*4+col,'sourceRect':[x0,y0,cw,y1-y0],'solidBounds':list(b),'placement':[150-cw/2,282-b[3]],'frameViewport':[300,300]})
 result[p.stem]={'imageSize':list(im.size),'rowBands':bands,'rowBoundaries':boundaries,'cells':cells,'alphaExtrema':list(alpha.getextrema()),'transparentCorners':all(alpha.getpixel(pt)<8 for pt in [(0,0),(im.width-1,0),(0,im.height-1),(im.width-1,im.height-1)])}
(root/'atlas-geometry.json').write_text(json.dumps(result,indent=2)+'\n')
print('Analyzed six alpha atlases, 24 frames each. Source pixels unchanged.')
