"""Publish immutable lossless legacy inputs only after every capture is complete."""
from pathlib import Path
from collections import defaultdict
import datetime, hashlib, json, shutil, zipfile
from PIL import Image, ImageDraw, ImageFont

root = Path(__file__).resolve().parents[1]
inputs = root / 'evidence/luna-post-a-inputs'
destination = inputs / 'legacy-supplement.json'
if destination.exists():
    raise SystemExit('Immutable supplement already exists. Do not replace active review inputs.')
master = json.loads((root / 'evidence/inspection-post/inspection-manifest.json').read_text())
records = [row for row in master['records'] if row['partition'] == 'legacy']
assert len(records) == 3141
assert len({row['asset_id'] for row in records}) == 267
marker_root = root / 'evidence/legacy-outer-marker-post'
marker = json.loads((marker_root / 'capture-manifest.json').read_text())
assert len(marker['captures']) == 6 and all(c['pass'] for c in marker['checks'])
public = root / 'site/review/screenshots/post/legacy-outer-marker'
public.mkdir(parents=True, exist_ok=True)
for capture in marker['captures']:
    source = marker_root / capture['file']
    assert hashlib.sha256(source.read_bytes()).hexdigest() == capture['sha256']
    shutil.copy2(source, public / capture['name'])
    records.append({
        'asset_id': 'legacy-outer-' + capture['state'], 'partition': 'legacy',
        'source_kind': 'outer-marker-and-selected-customer',
        'url': capture['basis']['href'], 'viewport': capture['basis']['viewport'],
        'captured_at': capture['captured_at'], 'file': str(source.resolve()),
        'name': capture['name'], 'group': 'legacy-outer-marker', 'type': 'state',
        'state': capture['state'], 'sha256': capture['sha256'],
        'actual_scroll': capture['basis'], 'measured_section': capture['section'],
        'direct_path': str((public / capture['name']).relative_to(root / 'site')),
    })
shutil.copy2(marker_root / 'capture-manifest.json', public / 'capture-manifest.json')
archive = public / 'all-six-originals.zip'
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as z:
    for capture in marker['captures']:
        z.write(marker_root / capture['file'], capture['name'])
    z.write(marker_root / 'capture-manifest.json', 'capture-manifest.json')
for row in records:
    if row.get('group') == 'legacy-outer-marker':
        row['archive_path'] = str(archive.relative_to(root / 'site'))
        row['archive_entry'] = row['name']

unique = defaultdict(list)
for row in records:
    assert hashlib.sha256(Path(row['file']).read_bytes()).hexdigest() == row['sha256']
    unique[row['sha256']].append(row)
font = ImageFont.load_default(size=15)
entries = list(unique.items())
sheets = []
for offset in range(0, len(entries), 4):
    batch = entries[offset:offset + 4]
    originals = [Image.open(rows[0]['file']).convert('RGB') for _, rows in batch]
    sheet = Image.new('RGB', (sum(im.width for im in originals), max(im.height for im in originals) + 72), 'white')
    draw = ImageDraw.Draw(sheet)
    x, tiles = 0, []
    for (sha, aliases), original in zip(batch, originals):
        row = aliases[0]
        label = f"{row['asset_id']} | {row['viewport']['width']}px | {row['state']}\n{row['name'][:44]}\n{sha[:16]} | {len(aliases)} exact-pixel context(s)"
        draw.multiline_text((x + 4, 4), label, font=font, fill='#111111', spacing=3)
        sheet.paste(original, (x, 72))
        tiles.append({'sha256': sha, 'bbox': [x, 72, x + original.width, 72 + original.height],
                      'source_file': row['file'], 'aliases': aliases})
        x += original.width
    path = inputs / f'legacy-sheet-{offset // 4 + 1:04d}.png'
    sheet.save(path)
    sheets.append({'file': str(path.resolve()), 'pixels': list(sheet.size),
                   'lossless_no_resize': True, 'tiles': tiles})

result = {
    'partition': 'a-legacy-supplement', 'build': '384162de',
    'generated_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
    'base': 'https://review.clientsflow.hu/komplex-rita-funnel-2026-09-26-v1/',
    'records': records, 'unique_pixels': len(unique), 'sheets': sheets,
    'legacy_asset_count': 267, 'expanded_card_context_count': 3141, 'outer_marker_context_count': 6,
    'immutable_primary_inputs': True, 'actual_images_inspected': False,
    'inspection_instruction': 'Inspect every unique image and preserve every alias context. Native images above 390px and any unreadable tile must also be opened individually. Captures and automated checks are inputs, not visual acceptance.',
}
temporary = destination.with_suffix('.json.tmp')
temporary.write_text(json.dumps(result, ensure_ascii=False, indent=2))
temporary.replace(destination)
public_manifest = {k: v for k, v in result.items() if k not in ['records', 'sheets']}
public_manifest['records'] = [{k: v for k, v in row.items() if k != 'file'} for row in records]
(root / 'site/review/screenshots/post/legacy-supplement-index.json').write_text(json.dumps(public_manifest, ensure_ascii=False, indent=2))
print(json.dumps({'records': len(records), 'unique_pixels': len(unique), 'sheets': len(sheets), 'ready': str(destination)}, indent=2))
