from pathlib import Path
from tempfile import TemporaryDirectory
from reportlab.pdfgen.canvas import Canvas
import hashlib,subprocess,json
p=Path(__file__).resolve().parent; blocks={'W':(245,195,'CAUTION: use the training copy.'),'A':(16,195,'STEP 1: open the sample.'),'B':(16,150,'STEP 2: record the marker.')}
rows=[]
for name,order in [('warning-first','WAB'),('warning-last','ABW')]:
 path=p/(name+'.pdf');c=Canvas(str(path),pagesize=(500,250),invariant=True)
 for code in order:c.drawString(*blocks[code])
 c.showPage();c.save()
 text=subprocess.run(['pdftotext','-raw',str(path),'-'],capture_output=True,text=True,check=True).stdout
 assert all(text.count(b[2]) == 1 for b in blocks.values())
 seq=sorted((b[2] for b in blocks.values()),key=text.index)
 assert seq==[blocks[c][2] for c in order],seq
 with TemporaryDirectory() as tmp:
  prefix=Path(tmp)/'page';subprocess.run(['pdftoppm','-r','96','-singlefile',str(path),str(prefix)],check=True);raster=hashlib.sha256(prefix.with_suffix('.ppm').read_bytes()).hexdigest()
 rows.append({'copy':name,'pdf_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'raster_sha256':raster,'raw_extractor_sequence':seq})
assert rows[0]['raster_sha256']==rows[1]['raster_sha256']
(p/'results.json').write_text(json.dumps({'scope':'Untagged synthetic PDFs; identical Poppler rasters and different pdftotext -raw sequences. This is not a tagged PDF or assistive reader performance test.','rows':rows},indent=2)+'\n')
