from pathlib import Path
import hashlib
import json
import shutil
import numpy as np
from PIL import Image

root = Path('/tmp/issue-lead-26950-r1/evidence-capture-2')
out = root / 'deliverables'
first = root / 'run-20261029-1452-final'
repeat = root / 'run-20261029-1455-rebuild'

def compare(before, after, stem):
    b = np.asarray(Image.open(before).convert('RGB'))
    a = np.asarray(Image.open(after).convert('RGB'))
    delta = np.abs(a.astype(np.int16) - b.astype(np.int16)).max(axis=2)
    stats = {'pixels': int((delta > 0).sum()), 'maxChannelDelta': int(delta.max())}
    for threshold, suffix in [(0, 'Diff0'), (16, 'DiffT')]:
        context = b // 4
        context[delta > threshold] = [255, 0, 255]
        Image.fromarray(context).save(out / (stem + '-' + suffix + '.png'))
    return stats

stats = compare(first / 'F2-after-mixed.png', repeat / 'F2-after-mixed.png', 'F2-independent-rebuild')
stats['originalPixelSha256'] = hashlib.sha256(Image.open(first / 'F2-after-mixed.png').convert('RGB').tobytes()).hexdigest()
stats['rebuiltPixelSha256'] = hashlib.sha256(Image.open(repeat / 'F2-after-mixed.png').convert('RGB').tobytes()).hexdigest()
stats['originalRun'] = str(first)
stats['rebuiltRun'] = str(repeat)
stats['method'] = 'Stopped the first after server; started the exact same detached fix checkout with a new empty T3 home and T3CODE_DEV_SEED=0; paired a new tab; bootstrap-page.js added a new synthetic project; setup-page.js and driver.js rebuilt F2.'
stats['returnedVersusMixed'] = compare(first / 'F2-after-mixed.png', first / 'F2-after-returned.png', 'F2-returned-versus-mixed')
for p in repeat.iterdir():
    if p.is_file():
        shutil.copy2(p, out / ('rebuild-' + p.name))
for fixture, label in [('F2', 'mixed'), ('F4', 'qualified')]:
    b = np.asarray(Image.open(first / f'{fixture}-before-{label}.png').convert('RGB'))
    a = np.asarray(Image.open(first / f'{fixture}-after-{label}.png').convert('RGB'))
    mask = np.any(a != b, axis=2)
    allowed = np.zeros(mask.shape, dtype=bool)
    rectangles = [(210, 108, 232, 130), (149, 235, 1132, 340)] if fixture == 'F2' else [(149, 114, 1132, 166), (480, 330, 801, 560)]
    for x, y, xx, yy in rectangles:
        allowed[y:yy, x:xx] = True
    stats[fixture] = {'toolbarChangedPixels': int(mask[:100].sum()), 'outsideExpectedAreasChangedPixels': int((mask & ~allowed).sum()), 'allowedRectanglesPngPixels': rectangles}
    if stats[fixture]['outsideExpectedAreasChangedPixels']:
        yy, xx = np.where(mask & ~allowed)
        stats[fixture]['outsideBounds'] = [int(xx.min()), int(yy.min()), int(xx.max()), int(yy.max())]
(out / 'reproducibility-manifest.json').write_text(json.dumps(stats, indent=2))
print(json.dumps(stats, indent=2))
if stats['pixels'] or stats['returnedVersusMixed']['pixels'] or any(stats[f]['outsideExpectedAreasChangedPixels'] for f in ['F2', 'F4']):
    raise SystemExit('Unexpected pixel difference')
