"""Measure the four inscription crops without modifying source images.
Requires Pillow and NumPy. Source pages are combined-archive 50,52,55,56.
"""
from pathlib import Path
import hashlib,json
import numpy as np
from PIL import Image
ROOT=Path(__file__).resolve().parent

def main():
    out=[];base=None
    for n in [50,52,55,56]:
        p=ROOT/f'{n}.jpg';im=np.array(Image.open(p).convert('L'));h,w=im.shape
        # Manual regions from full-page inspection, normalized to source size.
        x0,x1=int(w*500/1280),int(w*800/1280)
        ya,yb=(1600,1880) if n==50 else (50,330)
        y0,y1=int(h*ya/1920),int(h*yb/1920)
        a=im[y0:y1,x0:x1]<128;yy,xx=np.where(a)
        bbox=[int(x0+xx.min()),int(y0+yy.min()),int(x0+xx.max()+1),int(y0+yy.max()+1)]
        crop=a[yy.min():yy.max()+1,xx.min():xx.max()+1]
        if base is None:base=crop
        row=dict(lp2_page=n-17,file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest(),
                 image_dimensions=[w,h],ink_bbox=bbox,binary_shape=list(crop.shape),
                 threshold=128,exact_binary_match_to_page33=bool(np.array_equal(base,crop)))
        if base.shape==crop.shape:
            def iou(b):return float(np.count_nonzero(base & b)/np.count_nonzero(base | b))
            row['ink_iou']={'same_orientation':iou(crop),'horizontal_reflection':iou(crop[:,::-1]),'rotation_180':iou(crop[::-1,::-1])}
        out.append(row)
    (ROOT/'reversal_layout_results.json').write_text(json.dumps(out,indent=2))
    print(json.dumps(out,indent=2))

if __name__=='__main__':main()
