"""Generate an original RGBA specimen and opaque source-over controls."""
from pathlib import Path
from PIL import Image,__version__ as pillow_version
import hashlib,json,platform

OUT=Path(__file__).resolve().parent
OUT.mkdir(parents=True,exist_ok=True)
colors=[(0,0,255,255),(0,0,255,128),(0,0,255,64),(255,0,0,0)]
im=Image.new('RGBA',(320,120))
for x in range(320):
 for y in range(120):im.putpixel((x,y),colors[x//80])
im.save(OUT/'alpha-source.png')
files={'source':im}
for name,bg in [('white',(255,255,255)),('black',(0,0,0))]:
 flattened=Image.alpha_composite(Image.new('RGBA',im.size,bg+(255,)),im).convert('RGB')
 flattened.save(OUT/f'alpha-{name}.png');files[name]=flattened
samples=[]
for index,(x,y) in enumerate([(40,60),(120,60),(200,60),(280,60)]):
 fg=colors[index];a=fg[3]/255
 r={'x':x,'y':y,'source_rgba':list(im.getpixel((x,y))),'alpha_fraction':f'{fg[3]}/255'}
 for name,bg in [('white',(255,255,255)),('black',(0,0,0))]:
  formula=[round(fg[c]*a+bg[c]*(1-a)) for c in range(3)]
  actual=list(files[name].getpixel((x,y)));assert actual==formula
  r[name]={'rgb':actual,'hex':'#'+''.join(f'{c:02X}' for c in actual),'formula_rgb':formula}
 samples.append(r)
report={'construction':'Original four equal-width tiles: blue with alpha 255, 128, 64; hidden red with alpha 0. No resizing, no ICC profile. Coordinates zero-based from top-left.','size':[320,120],'source_over_formula':'For each encoded RGB channel over an opaque background: round(F * (A/255) + B * (1 - A/255)); F and A are the authored source values; B is 255 for white or 0 for black. This numeric fixture is not an assertion of every application color-management path.','pillow':pillow_version,'python':platform.python_version(),'samples':samples,'files':{p.name:{'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':p.stat().st_size} for p in OUT.glob('*.png')}}
(OUT/'fixture-results.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
print(json.dumps(report,indent=2))
