"""Explicit access to paired experimental gated-mask development scenes.

Projected masks remain unverified; all original background is unknown. This
candidate dataset is not an evaluation split or automatically approved 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/gated-alternative-scenes'
ORIGINALS={'crowded':ROOT/'results/r112/scaleup-crowded-scenes','separated':ROOT/'results/r112/scaleup-separated-scenes','breadth':ROOT/'results/r112/breadth-diverse-scenes'}
class GatedCandidateScenes:
 def __init__(self,scope:str,*,family:str='all',root=DEFAULT):
  if scope!='development_candidate':raise ValueError('Explicit development_candidate scope required')
  if family not in ('all',*ORIGINALS):raise ValueError('Unknown scene family')
  self.root=Path(root);manifest=self.root/'manifest.json';verification=self.root/'verify.json';protocol=self.root/'protocol.json'
  if not verification.exists():raise ValueError('Full candidate verification is required')
  data=json.loads(manifest.read_text());v=json.loads(verification.read_text())
  if data.get('format')!='r112-gated-alternative-scenes-v1' or v.get('format')!='r112-gated-alternative-verify-v1' or v['manifest_sha256']!=sha256(manifest) or v['protocol_sha256']!=sha256(protocol) or data['protocol_sha256']!=sha256(protocol):raise ValueError('Candidate provenance mismatch')
  self.records=[x for x in data['records'] if family=='all' or x['family']==family]
  if len(self.records)!=v['summary'][family]['scenes']:raise ValueError('Candidate scene count mismatch')
 def __len__(self):return len(self.records)
 def __getitem__(self,index):
  x=self.records[index];family=x['family'];ident=x['id'];root=ORIGINALS.get(family)
  if root is None or not ident.startswith('scene-') or not ident[6:].isdigit():raise ValueError('Invalid scene identity')
  ip=self.root/x['image'];mp=self.root/x['mask_archive'];prior=ROOT/x['original_image_path'];pm=ROOT/x['original_mask_archive_path']
  if ip.resolve()!=(self.root/family/f'{ident}.png').resolve() or mp.resolve()!=(self.root/family/f'{ident}.npz').resolve() or prior.resolve()!=(root/f'{ident}.png').resolve() or pm.resolve()!=(root/f'{ident}.npz').resolve():raise ValueError('Unexpected scene path')
  if sha256(ip)!=x['image_sha256'] or sha256(mp)!=x['mask_archive_sha256'] or sha256(prior)!=x['original_image_sha256'] or sha256(pm)!=x['original_mask_archive_sha256']:raise ValueError('Paired scene checksum mismatch')
  image=Image.open(ip).convert('L');image.load();old=Image.open(prior).convert('L');old.load();n=len(x['instances']);shape=(n,image.height,image.width)
  if image.size!=old.size:raise ValueError('Paired image dimensions differ')
  arrays=[]
  for path in (mp,pm):
   with np.load(path,allow_pickle=False) as z:
    if tuple(int(y) for y in z['support_shape'])!=shape or str(z['background_label_status'])!='unknown' or str(z['visible_support_status'])!='undefined':raise ValueError('Invalid weak support semantics')
    arrays.append(np.unpackbits(z['support_bits'],count=int(np.prod(shape))).reshape(shape).astype(bool))
  return {'image':image,'projected_weak_supports':arrays[0],'center_render_image':old,'center_projected_weak_supports':arrays[1],'instances':x['instances'],'family':family,'scene_id':ident,'background':x['background'],'changed_proposal_indices':x['changed_proposal_indices'],'background_label_status':'unknown, including beneath insertions; other organisms may be present','support_status':'experimental gated model proposals; not verified ground truth','visible_support_status':'undefined','scope':'development_candidate'}
