"""Add static focal-plane images to an existing field-review bundle."""
import argparse
import hashlib
import json
import sys
from pathlib import Path

from PIL import Image, ImageChops

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT/'experiments'))
from scan_fields import Stack


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def add_focus_planes(bundle_dir, slide):
    bundle_dir, slide = Path(bundle_dir), Path(slide)
    bundle = json.loads((bundle_dir/'bundle.json').read_text())
    if slide.stat().st_size < 1_000_000_000:
        raise ValueError('Scan is below the 1 GB completed-file cutoff')
    if slide.name != bundle['slide'] or slide.stat().st_size != bundle['slide_size_bytes']:
        raise ValueError('Scan name or size does not match bundle provenance')
    manifest = bundle_dir/'focus-planes.json'
    if manifest.exists():
        raise FileExistsError('Focus-plane manifest already exists')
    x, y = bundle['origin_xy']; size = bundle['size']; original_z = bundle['z']
    with Stack(slide) as stack:
        if x < 0 or y < 0 or x+size > stack.width or y+size > stack.height or not 0 <= original_z < stack.depth:
            raise ValueError('Bundle field is outside the scan')
        original = stack.field(original_z, x, y, size).convert('RGB')
        with Image.open(bundle_dir/bundle['field_image']) as existing:
            if existing.size != original.size or ImageChops.difference(existing.convert('RGB'), original).getbbox():
                raise ValueError('Scan field does not match bundle source image')
        destination = bundle_dir/'focus'
        destination.mkdir(exist_ok=False)
        planes = []
        for z in range(stack.depth):
            file = f'focus/plane-{z:03d}.png'
            stack.field(z, x, y, size).save(bundle_dir/file)
            planes.append({'z': z, 'image': file, 'sha256': digest(bundle_dir/file)})
    manifest.write_text(json.dumps({'format':'diatom-focus-planes-v1', 'bundle_id':bundle['bundle_id'],
                                    'planes':planes}, indent=2)+'\n')
    print(f'Added {len(planes)} focal planes to {bundle_dir}', flush=True)


if __name__ == '__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--bundle', type=Path, required=True)
    p.add_argument('--slide', type=Path, required=True)
    args=p.parse_args()
    add_focus_planes(args.bundle,args.slide)
