import json,sys
from pathlib import Path
from PIL import Image,ImageDraw
root=Path(sys.argv[1]); proof=json.loads(Path(sys.argv[2]).read_text())
for side,label in [('base','before'),('head','after')]:
    source=Path(proof[side]['captures'][0]); im=Image.open(source)
    # Codex weekly account A: below the top edge, right of its pace marker, left of its reset label.
    box=(1100,632,1300,672)
    crop=im.crop(box).resize((800,160),Image.Resampling.NEAREST)
    output=Image.new('RGB',(800,200),'#171717');output.paste(crop,(0,40))
    ImageDraw.Draw(output).text((12,12),f'{label.capitalize()} {proof[side]["sha"][:10]} | Codex weekly A | native DPR 2 crop, 4x nearest neighbour',fill='white')
    output.save(root/f'{label}-stripe-detail.png')
print('Created 4x crops of native screenshot pixels; no retouching.')
from collections import Counter
import statistics
stats={}
for side in ['base','head']:
    im=Image.open(proof[side]['captures'][0]).convert('RGB'); runs=[]
    for y in range(632,656):
        values=[sum(im.getpixel((x,y)))/3 for x in range(1100,1300)]
        bg=min(values); start=None
        for i,v in enumerate(values+[bg]):
            if v>bg+8 and start is None:start=i
            if v<=bg+8 and start is not None:
                if start>0 and i<len(values):runs.append((i-start,round(sum(q-bg for q in values[start:i]),2)))
                start=None
    stats[side]={'rows':24,'devicePixelRegion':[1100,632,1300,656],'stripes':len(runs),'widthCounts':dict(Counter(w for w,s in runs)),'weightByWidth':{str(w):{'min':min(s for ww,s in runs if ww==w),'max':max(s for ww,s in runs if ww==w)} for w in set(ww for ww,s in runs)}}
(root/'interior-measurements.json').write_text(json.dumps(stats,indent=2))
print(json.dumps(stats,indent=2))
