from PIL import Image,ImageDraw,ImageFont,ImageChops
from pathlib import Path
import re,textwrap
p=Path(__file__).parent
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
f=ImageFont.truetype(font,26); bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',30)
for side,source,sha in [('before','base','2a99314a4708d1c84d7a361445558eb7262c570f'),('after','head','eb67e04552ea896565b4c836a3e7509f68b326a4')]:
 a=Image.open(p/f'{source}-fresh-a.png').convert('RGB').crop((0,748,1080,1296))
 b=Image.open(p/f'{source}-fresh-b.png').convert('RGB').crop((0,748,1080,1296))
 assert ImageChops.difference(a,b).getbbox() is None
 labels=[]
 for line in (p/f'{side}-raw.txt').read_text().splitlines():
  m=re.search(r'\[button\] "(Issue #[123], (?:Zero comments|One comment|Two comments),.*?)"$',line)
  if m: labels.append(m.group(1))
 assert len(labels)==3,labels
 (p/f'{side}-accessibility.txt').write_text('Android Pixel 9, API 36; English; light theme\nCommit: '+sha+'\nDevice accessibility snapshot excerpt (fixture rows only):\n'+'\n'.join(labels)+'\n')
 out=Image.new('RGB',(1080,1130),'white');d=ImageDraw.Draw(out)
 d.text((25,18),f'{side.capitalize()} | Pixel 9, Android API 36 | English, light',font=bold,fill='black')
 d.text((25,65),'Commit '+sha[:10]+' | Native issue-row crop',font=f,fill='#444444')
 out.paste(a,(0,112));d.text((25,689),'Device accessibility labels (verbatim snapshot excerpt)',font=bold,fill='black')
 y=750
 for label in labels:
  color='#a42020' if side=='before' and 'One comment,' in label else '#116b39' if side=='after' and 'One comment,' in label else '#222222'
  for line in textwrap.wrap(label,width=69):d.text((25,y),line,font=f,fill=color);y+=37
  y+=23
 out.save(p/f'{side}-evidence.png')
 print(side,labels,'stable fixture crop confirmed')
