"""Retrieve only four candidate images from the public ZIP into /tmp.

Each member is CRC-checked by zipfile. The images are not placed on the public
server because the source record's reuse terms remain unclear.
"""
import json
import sys
import zipfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from r16_archive_inspect import Remote

root = Path(__file__).resolve().parent.parent
rows = json.loads((root / 'results/l24/overlap-audit.json').read_text())['overlap_pairs']
entries = json.loads((root / 'results/r16/archive-contents.json').read_text())['entries']
destination = Path('/tmp/diatom-l24-overlap')
destination.mkdir(exist_ok=True)
with zipfile.ZipFile(Remote()) as archive:
    for index, row in enumerate(rows, 1):
        matches = [e for e in entries if e['name'].endswith('/' + row['filename'])]
        if len(matches) != 1:
            raise ValueError(f"Ambiguous archive image for {row['filename']}: {matches}")
        member = matches[0]
        data = archive.read(member['name'])
        (destination / f'{index:02}.jpg').write_bytes(data)
        print(index, member['name'], len(data), 'bytes', flush=True)
