"""Deterministic owned-text fixture. No external image assets. Pillow 12.3.0.
Run: python make-sample.py --font arial.ttf --out .
Download base-test.png for identical bytes if the specified font is unavailable.
"""
from pathlib import Path
from datetime import datetime,timezone
from PIL import Image,ImageDraw,ImageFont
import argparse,hashlib,json
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def make(font_path,out):
 out.mkdir(parents=True,exist_ok=True)
 assert not (out/'base-test.png').exists(),'Preserve existing fixture; do not regenerate in place.'
 canvas=Image.new('RGBA',(1200,800),'white');draw=ImageDraw.Draw(canvas)
 font=ImageFont.truetype(str(font_path),28)
 lines=[
  ('KEEP THE PRODUCT LABEL EXACTLY AS WRITTEN.',80,80),
  ('READ THIS SERIAL NUMBER BEFORE USING THE IMAGE.',80,145),
  ('THIS CAPTION IS REAL CONTENT, NOT A WATERMARK.',80,560),
  ('PLEASE PRESERVE EVERY LETTER IN THIS SENTENCE.',80,625)]
 normal=[]
 for text,x,y in lines:
  draw.text((x,y),text,font=font,fill=(0,0,0,255),anchor='lt')
  box=draw.textbbox((x,y),text,font=font,anchor='lt')
  normal.append({'text':text,'anchor':[x,y],'ink_bbox_xyxy_exclusive':list(box),'roi_xyxy_exclusive':[box[0]-8,box[1]-8,box[2]+8,box[3]+8]})
 clean=canvas.convert('RGB');clean.save(out/'normal-text-control.png',compress_level=9)
 wm=Image.new('RGBA',(1200,800),(0,0,0,0))
 text_layer=Image.new('RGBA',(900,120),(0,0,0,0));d=ImageDraw.Draw(text_layer)
 wf=ImageFont.truetype(str(font_path),64);message='DEMO WATERMARK'
 box=d.textbbox((0,0),message,font=wf,anchor='lt');w,h=box[2]-box[0],box[3]-box[1]
 d.text(((900-w)//2,(120-h)//2),message,font=wf,fill=(0,0,0,96),anchor='lt')
 rotated=text_layer.rotate(24,resample=Image.Resampling.BICUBIC,expand=True)
 wm.alpha_composite(rotated,(600-rotated.width//2,365-rotated.height//2))
 bbox1=wm.getchannel('A').getbbox()
 corner=Image.new('RGBA',(1200,800),(0,0,0,0));c=ImageDraw.Draw(corner)
 c.text((900,750),'REMOVE THIS MARK',font=ImageFont.truetype(str(font_path),22),fill=(0,0,0,255),anchor='lt')
 bbox2=corner.getchannel('A').getbbox();wm=Image.alpha_composite(wm,corner)
 for row in normal:assert wm.getchannel('A').crop(row['roi_xyxy_exclusive']).getbbox() is None,'Watermark overlaps normal-text measurement area.'
 result=Image.alpha_composite(canvas,wm).convert('RGB');result.save(out/'base-test.png',compress_level=9)
 normal_mask=Image.new('L',(1200,800),0);md=ImageDraw.Draw(normal_mask)
 for row in normal:
  x0,y0,x1,y1=row['roi_xyxy_exclusive'];md.rectangle((x0,y0,x1-1,y1-1),fill=255)
 normal_mask.save(out/'normal-text-mask.png',compress_level=9)
 wm.getchannel('A').save(out/'watermark-mask.png',compress_level=9)
 boxes=[[max(0,b[0]-8),max(0,b[1]-8),min(1200,b[2]+8),min(800,b[3]+8)] for b in [bbox1,bbox2]]
 data={'created_at_utc':datetime.now(timezone.utc).isoformat(),'ownership':'New synthetic fixture; generated from text and geometric layers; no third-party photos.', 'image':{'file':'base-test.png','format':'PNG','mode':'RGB','width':1200,'height':800,'bytes':(out/'base-test.png').stat().st_size,'sha256':sha(out/'base-test.png')},'font':{'filename':font_path.name,'size_normal':28,'sha256':sha(font_path),'redistributed':False},'normal_text':normal,'roi_area_pixels':sum((r['roi_xyxy_exclusive'][2]-r['roi_xyxy_exclusive'][0])*(r['roi_xyxy_exclusive'][3]-r['roi_xyxy_exclusive'][1]) for r in normal),'roi_definition':'Union of four disjoint rectangles, x0/y0 inclusive, x1/y1 exclusive; each glyph bounding box plus eight pixels. Both watermarks are outside these rectangles. Compare decoded output RGB directly to base-test.png; no JPEG/control subtraction.', 'watermarks':[{'text':'DEMO WATERMARK','angle_ccw_degrees':24,'alpha':96,'alpha_denominator':255,'ink_bbox_xyxy_exclusive':list(bbox1)},{'text':'REMOVE THIS MARK','angle_ccw_degrees':0,'alpha':255,'alpha_denominator':255,'ink_bbox_xyxy_exclusive':list(bbox2)}], 'manual_selection_boxes_xyxy_exclusive':boxes,'manual_parameters':'Select only the two listed watermark rectangles; do not select normal text. If these exact selections cannot be applied, record the mode as untested rather than silently changing selection.', 'difference_fraction_formula':'changed_RGB_pixels_in_union / roi_area_pixels; a pixel is changed if any RGB channel differs by at least 1 decoded integer value. Percentage = changed / area * 100.', 'mae_formula':'sum absolute RGB channel differences in union / (roi_area_pixels * 3). Unit: 8-bit RGB level, range 0-255. No resize, registration, or threshold adjustment.', 'reproduction':'Use the downloaded base-test.png byte-for-byte. Generator and font hash document construction; font file is not redistributed. Rendering may vary with another font or Pillow version.', 'files':{name:{'sha256':sha(out/name),'bytes':(out/name).stat().st_size} for name in ['base-test.png','normal-text-control.png','normal-text-mask.png','watermark-mask.png']}}
 (out/'sample-manifest.json').write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
 print(json.dumps(data,ensure_ascii=False))
if __name__=='__main__':
 parser=argparse.ArgumentParser();parser.add_argument('--font',type=Path,required=True);parser.add_argument('--out',type=Path,default=Path('.'));args=parser.parse_args();make(args.font,args.out)
