"""Access uncalibrated diagnostic scenes and separately stored supports."""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
from PIL import Image

from diatom_pilot.ude_scaleup_dataset import sha256

ROOT = Path(__file__).resolve().parent.parent
DEFAULT = ROOT / 'results/r112/gunduz-uncalibrated-scenes'


class GunduzUncalibratedScenes:
    def __init__(self, scope: str, root=DEFAULT):
        if scope != 'development_diagnostic':
            raise ValueError('Only development_diagnostic is available; sizes are not calibrated')
        self.root = Path(root)
        manifest, protocol, verification = (self.root / p for p in ('manifest.json', 'protocol.json', 'verify.json'))
        data, check = json.loads(manifest.read_text()), json.loads(verification.read_text())
        if ((data.get('format'), check.get('format')) != ('r112-gunduz-uncalibrated-scenes-v1', 'r112-gunduz-uncalibrated-scenes-verify-v1')
                or check['manifest_sha256'] != sha256(manifest)
                or check['protocol_sha256'] != sha256(protocol)
                or data['protocol_sha256'] != sha256(protocol)):
            raise ValueError('Scene provenance mismatch')
        self.records = data['records']
        if len(self.records) != check['counts']['scenes']:
            raise ValueError('Scene count mismatch')

    def __len__(self):
        return len(self.records)

    def __getitem__(self, index):
        row = self.records[index]
        image_path, mask_path = self.root / row['image'], self.root / row['mask_archive']
        if (image_path.resolve().parent != self.root.resolve() or mask_path.resolve().parent != self.root.resolve()
                or sha256(image_path) != row['image_sha256'] or sha256(mask_path) != row['mask_archive_sha256']):
            raise ValueError('Scene checksum mismatch')
        image = Image.open(image_path).convert('L')
        image.load()
        with np.load(mask_path, allow_pickle=False) as z:
            shape = tuple(int(x) for x in z['support_shape'])
            if (shape != (len(row['instances']), image.height, image.width)
                    or str(z['background_label_status']) != 'unknown'
                    or str(z['visible_support_status']) != 'undefined'):
                raise ValueError('Invalid support metadata')
            masks = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        return {'image': image, 'projected_source_supports': masks, 'instances': row['instances'],
                'background': row['background'], 'scene_id': row['id'], 'scope': 'development_diagnostic',
                'background_label_status': 'unknown including under insertions',
                'visible_support_status': 'undefined', 'source_physical_scale_status': 'unknown',
                'license': 'CC BY-NC-SA 4.0'}
