import json, shutil
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw

root = Path(__file__).parent
rows = json.loads((root / 'captures.json').read_text())
by = {r['name']: r for r in rows}
out = root / 'evidence'
out.mkdir(exist_ok=True)
summary = []
for name, r in by.items():
    if not name.startswith(('base-', 'final-')):
        continue
    a = Image.open(r.get('a', r)['screenshotPath']).convert('RGB')
    a.save(out / (name + '.png'))
    if 'b' in r:
        b = Image.open(r['b']['screenshotPath']).convert('RGB')
        b.save(out / (name + '-settled.png'))
        d = ImageChops.difference(a, b)
        summary.append({'capture': name, 'settled': d.getbbox() is None, 'settledDiffBox': d.getbbox(), 'pngSize': a.size})
    if not name.startswith('final-'):
        continue
    base = by.get(name.replace('final-', 'base-', 1))
    if base is None:
        continue
    before = Image.open(base.get('a', base)['screenshotPath']).convert('RGB')
    d = ImageChops.difference(before, a)
    pixels = list(d.getdata())
    zero = sum(max(p) > 0 for p in pixels)
    threshold16 = sum(max(p) > 16 for p in pixels)
    stem = name.removeprefix('final-')
    # A binary zero-threshold diff and an 8x channel-amplified absolute diff.
    channels = d.split()
    ImageChops.lighter(ImageChops.lighter(channels[0], channels[1]), channels[2]).point(lambda p: 255 if p else 0).save(out / (stem + '-diff-zero.png'))
    d.point(lambda p: min(255, p * 8)).save(out / (stem + '-diff-amplified8.png'))
    pair = Image.new('RGB', (a.width * 2, a.height + 32), '#dedede')
    pair.paste(before, (0,32)); pair.paste(a, (a.width,32))
    draw = ImageDraw.Draw(pair)
    draw.text((10,10),'BEFORE: exact base 200dad3b39',fill='black')
    draw.text((a.width+10,10),'AFTER: local followup d99a50058f',fill='black')
    pair.save(out / (stem + '-pair.png'))
    summary.append({'pair': stem, 'threshold0Pixels': zero, 'threshold16Pixels': threshold16, 'totalPixels': len(pixels), 'diffBox': d.getbbox()})
(out / 'metrics.json').write_text(json.dumps(summary, indent=2))
files = sorted(out.glob('*.png'))
for batch in range(0,len(files),24):
    group = files[batch:batch+24]
    sheet = Image.new('RGB', (1600, ((len(group)+3)//4)*265), '#ddd')
    draw = ImageDraw.Draw(sheet)
    for i,p in enumerate(group):
        im = Image.open(p); im.thumbnail((390,235))
        x=(i%4)*400; y=(i//4)*265
        sheet.paste(im,(x,y+25)); draw.text((x+3,y+3),p.name,fill='black')
    sheet.save(root / ('inspect-%02d.png' % (batch//24)))
print(json.dumps(summary,indent=2))
