"""Pack original screenshot pixels losslessly, retaining every context and native crop.

Original PNG byte streams remain in their independently verified archives. These PNG
containers are analytical evidence, never newly generated customer visuals. Packing
does not establish visual acceptance or change active reviewers' immutable inputs.
"""
from pathlib import Path
from collections import defaultdict
import datetime, hashlib, json
from PIL import Image, ImageDraw, ImageFont

root = Path(__file__).resolve().parents[1]
master = json.loads((root/'evidence/inspection-post/inspection-manifest.json').read_text())
supplement = json.loads((root/'evidence/luna-post-a-inputs/legacy-supplement.json').read_text())
records = master['records'] + [r for r in supplement['records'] if r['source_kind']=='outer-marker-and-selected-customer']
assert len(records)==12001
unique=defaultdict(list)
for index,row in enumerate(records):
    unique[row['sha256']].append(index)
target=root/'site/review/criterion-captures'
sheet_root=target/'native-sheets';sheet_root.mkdir(parents=True,exist_ok=True)
font=ImageFont.load_default(size=14)
entries=list(unique.items());sheet_records=[];bindings={}
for offset in range(0,len(entries),16):
    batch=entries[offset:offset+16]
    originals=[]
    for sha,indices in batch:
        row=records[indices[0]];source=Path(row['file'])
        assert hashlib.sha256(source.read_bytes()).hexdigest()==sha
        with Image.open(source) as original:
            original.load();originals.append(original.convert('RGB'))
    header=72
    canvas=Image.new('RGB',(sum(im.width for im in originals),max(im.height for im in originals)+header),'white')
    draw=ImageDraw.Draw(canvas);x=0;tiles=[]
    for (sha,indices),original in zip(batch,originals):
        row=records[indices[0]]
        draw.multiline_text((x+4,4),f"{row['asset_id']} | {row['viewport']['width']}px\n{row.get('state',row['type'])[:38]}\n{sha[:16]}",font=font,fill='#111',spacing=3)
        canvas.paste(original,(x,header))
        box=[x,header,x+original.width,header+original.height]
        assert canvas.crop(box).tobytes()==original.tobytes(), 'Native screenshot pixels changed'
        tile={'source_sha256':sha,'bbox':box,'pixels':list(original.size),
              'pixel_sha256':hashlib.sha256(original.tobytes()).hexdigest(),'context_indices':indices}
        tiles.append(tile);x+=original.width
    name=f'native-{offset//16+1:04d}.png';path=sheet_root/name;canvas.save(path)
    assert path.stat().st_size<25*1024**2
    with Image.open(path) as decoded:
        decoded.load()
        for tile in tiles:
            assert hashlib.sha256(decoded.crop(tile['bbox']).tobytes()).hexdigest()==tile['pixel_sha256']
    sheet_path=str(path.relative_to(root/'site'))
    for tile in tiles:
        bindings[tile['source_sha256']]={'sheet_path':sheet_path,'sheet_pixels':list(canvas.size),'bbox':tile['bbox'],'source_pixels':tile['pixels'],'pixel_sha256':tile['pixel_sha256']}
    sheet_records.append({'path':sheet_path,'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
                          'bytes':path.stat().st_size,'pixels':list(canvas.size),'tiles':tiles})
    for original in originals:original.close()
    canvas.close()

public_records=[]
for index,row in enumerate(records):
    public_records.append({'capture_index':index,**{k:v for k,v in row.items() if k!='file'},
                           'native_proof':bindings[row['sha256']]})
payload={'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
         'record_count':len(records),'unique_source_hashes':len(unique),'sheet_count':len(sheet_records),
         'native_pixels_preserved':True,'all_saved_crops_redecoded_and_verified':True,
         'actual_independent_observations_attached':False,
         'scope':'Every original PNG is available in its named archive. Native-pixel sheet crops are lossless analytical presentation. Packing is not visual acceptance.',
         'records':public_records,'sheets':sheet_records}
(target/'captures.json').write_text(json.dumps(payload,ensure_ascii=False,separators=(',',':')))
assert (target/'captures.json').stat().st_size<25*1024**2
summary={k:v for k,v in payload.items() if k not in ['records','sheets']}
summary['captures_json_sha256']=hashlib.sha256((target/'captures.json').read_bytes()).hexdigest()
(root/'evidence/native-proof-packing.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2))
print(json.dumps(summary,indent=2))
