"""Read extra UDE development crops and optional unverified mask proposals."""
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/species-breadth-extension'
SPLIT = ROOT / 'results/r112/species-scaleup/location-partitions.json'


class UDEBreadthExtensionDataset:
    def __init__(self, scope: str, root=DEFAULT, *, prior_split=SPLIT,
                 include_unverified_masks=False):
        if scope != 'prior_training_components':
            raise ValueError('Only prior_training_components development scope is available')
        self.root = Path(root)
        self.include_unverified_masks = include_unverified_masks
        assets_path = self.root / 'assets.json'
        verify_path = self.root / 'verify.json'
        selection_path = self.root / 'selection.json'
        split_path = Path(prior_split)
        assets = json.loads(assets_path.read_text())
        verify = json.loads(verify_path.read_text())
        selection = json.loads(selection_path.read_text())
        split = json.loads(split_path.read_text())
        if (assets.get('format'), verify.get('format'), selection.get('format')) != (
                'r112-breadth-depth-extension-assets-v1', 'r112-breadth-depth-extension-verify-v1',
                'r112-breadth-depth-extension-selection-v1'):
            raise ValueError('Unsupported extension provenance')
        if (verify['assets_sha256'] != sha256(assets_path)
                or verify['selection_sha256'] != sha256(selection_path)
                or assets['selection_sha256'] != sha256(selection_path)
                or selection['inputs_sha256']['results/r112/species-scaleup/location-partitions.json'] != sha256(split_path)):
            raise ValueError('Source or location provenance mismatch')
        self.records = assets['records']
        if len(self.records) != verify['assets_checked_pixel_for_pixel']:
            raise ValueError('Source count mismatch')
        ids = set()
        for row in self.records:
            ident = row['annotation_id']
            if (not ident.isdecimal() or ident in ids
                    or split['group_partition'].get(row['source_site_component']) != 'training'):
                raise ValueError('Invalid source or nontraining location component')
            ids.add(ident)
        if include_unverified_masks:
            masks = self.root / 'mask-hypotheses'
            protocol = masks / 'protocol.json'
            q = json.loads((masks / 'verify.json').read_text())
            p = json.loads(protocol.read_text())
            if (q.get('format') != 'r112-breadth-extension-mask-verification-v1'
                    or q['protocol_sha256'] != sha256(protocol)
                    or p['source_assets_sha256'] != sha256(assets_path)
                    or p['source_verify_sha256'] != sha256(verify_path)
                    or q['requested_sources'] != len(self.records)
                    or q['verified_records'] != len(self.records) or q['missing_ids']):
                raise ValueError('Incomplete or mismatched proposal verification')

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

    def __getitem__(self, index):
        row = self.records[index]
        ident = row['annotation_id']
        path = self.root / row['source_crop']
        if path.resolve() != (self.root / 'images' / f'{ident}.png').resolve() or sha256(path) != row['source_sha256']:
            raise ValueError('Source crop checksum mismatch')
        image = Image.open(path).convert('L')
        image.load()
        result = {'image': image, 'annotation_id': ident, 'source_name': row['source_species'],
                  'source_genus': row['source_genus'], 'source_site_component': row['source_site_component'],
                  'prior_80_location_partition': 'training', 'scope': 'prior_training_components',
                  'source_um_per_pixel_xy': row['source_scale_um_px'],
                  'taxonomic_status': row['taxonomic_status'], 'mask_status': 'no verified instance mask',
                  'background_status': 'unknown; crop may contain other organisms',
                  'comparison_status': 'development only, not an independent biological benchmark'}
        if self.include_unverified_masks:
            directory = self.root / 'mask-hypotheses'
            record = json.loads((directory / 'records' / f'{ident}.json').read_text())
            if record['source_sha256'] != row['source_sha256'] or record['protocol_sha256'] != sha256(directory / 'protocol.json'):
                raise ValueError('Mask proposal provenance mismatch')
            masks = []
            for k in ('center', 'minus', 'plus'):
                item = record['masks'][k]
                path = directory / item['file']
                if path.resolve() != (directory / 'masks' / f'{ident}-{k}.png').resolve() or sha256(path) != item['sha256']:
                    raise ValueError('Mask proposal checksum mismatch')
                mask = np.asarray(Image.open(path).convert('L')) > 0
                if mask.shape != (image.height, image.width):
                    raise ValueError('Mask shape mismatch')
                masks.append(mask)
            result.update({'weak_mask_proposals': np.stack(masks),
                           'weak_mask_order': ('center', 'minus', 'plus'),
                           'mask_triage': record['triage'],
                           'mask_status': 'three unverified model proposals; not biological ground truth'})
        return result
