"""Access weak extension scenes with explicitly unknown background labels."""
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/breadth-extension-scenes'


class BreadthExtensionSceneDataset:
    def __init__(self, split: str, root=DEFAULT):
        if split != 'development_training':
            raise ValueError('Only development_training is available; this is not an evaluation set')
        self.root = Path(root)
        manifest, verification, protocol = (self.root / p for p in ('manifest.json', 'verify.json', 'protocol.json'))
        data = json.loads(manifest.read_text())
        check = json.loads(verification.read_text())
        if ((data.get('format'), check.get('format')) !=
                ('r112-breadth-extension-scenes-v1', 'r112-breadth-extension-scenes-verify-v1')
                or check['manifest_sha256'] != sha256(manifest)
                or check['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 = self.root / row['image']
        mask_path = 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 image or supports failed checksum')
        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')
            supports = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        return {'image': image, 'projected_weak_supports': supports, 'instances': row['instances'],
                'background': row['background'], 'scene_id': row['id'], 'split': 'development_training',
                'background_label_status': 'unknown, including under insertions; other diatoms may be present',
                'support_status': 'unverified projected model proposals; may overlap',
                'visible_support_status': 'undefined'}
