"""Read R112 *development-only* synthetic scenes without inventing background labels.

The projected supports are weak hypotheses, not verified ground truth. All pixels
are marked unknown because Academy background structures and visibility have not
been annotated, including beneath insertions. This reader makes no loss-policy
choices; a caller must explicitly choose an uncertainty-aware learning method.
"""
from __future__ import annotations
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
ROOT=Path(__file__).resolve().parent.parent
DEFAULT_MANIFESTS=(ROOT/'results/r112/weak-development-v1/manifest.json',ROOT/'results/r112/weak-diverse-v1/manifest.json',ROOT/'results/r112/weak-breadth-depth-v1/manifest.json',ROOT/'results/r112/weak-new-taxa-v1/manifest.json',ROOT/'results/r112/broad-background-scenes/manifest.json')
def digest(path:Path)->str:
 h=hashlib.sha256()
 with path.open('rb') as f:
  for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
 return h.hexdigest()
class WeakSceneDataset:
 """Framework-independent access to grayscale pixels, overlapping supports and provenance."""
 def __init__(self,manifests=DEFAULT_MANIFESTS,verify_hashes=True,include_mask_variants=False,mask_roots=None,synthetic_partition=None):
  if synthetic_partition not in (None,'train','validation'):raise ValueError('Expected train or validation synthetic partition')
  self.verify_hashes=verify_hashes;self.include_mask_variants=include_mask_variants;self.mask_roots=MASK_ROOTS if mask_roots is None else mask_roots;self.entries=[]
  for path in map(Path,manifests):
   data=json.loads(path.read_text());assert data['format'] in ('r112-weak-development-v1','r112-weak-diverse-v1','r112-weak-breadth-depth-v1','r112-weak-new-taxa-v1','r112-broad-background-scenes-v1','r112-grouped-synthetic-scenes-v1')
   grouped=data['format']=='r112-grouped-synthetic-scenes-v1'
   if grouped and synthetic_partition is None:raise ValueError('Explicit train or validation partition required for grouped scenes')
   if not grouped and synthetic_partition is not None:raise ValueError('Requested partition on a manifest without group separation')
   mh=digest(path)
   for scene in data['records']:
    if scene['split']!='development_only':raise ValueError('Only development scenes may be loaded')
    if grouped:
     if scene.get('synthetic_partition') not in ('train','validation'):raise ValueError('Invalid grouped scene partition')
     if scene['synthetic_partition']!=synthetic_partition:continue
    self.entries.append((path, mh, scene, data['format']))
 def __len__(self):return len(self.entries)
 def __getitem__(self,index):
  manifest,mh,scene,format_name=self.entries[index];directory=manifest.parent;image_path=directory/scene['image'];archive_path=directory/scene['mask_archive']
  if self.verify_hashes and (digest(image_path)!=scene['image_sha256'] or digest(archive_path)!=scene['mask_archive_sha256']):raise ValueError('Scene or support archive checksum mismatch')
  image=np.asarray(Image.open(image_path).convert('L')).copy()
  with np.load(archive_path,allow_pickle=False) as z:
   shape=tuple(int(v) for v in z['support_shape']);assert len(shape)==3 and shape[0]==len(scene['instances']) and shape[1:]==image.shape
   if str(z['background_label_status'])!='unknown' or str(z['transparent_visibility_status'])!='undefined':raise ValueError('Unexpected label semantics')
   bits=np.unpackbits(z['support_bits']);assert len(bits)>=np.prod(shape);support=bits[:np.prod(shape)].reshape(shape).astype(bool)
  result={'image':image,'weak_projected_supports':support,'unknown_region':np.ones(image.shape,dtype=bool),'instances':scene['instances'],'scene_id':scene['id'],'manifest':str(manifest),'manifest_sha256':mh,'background':scene['background'],'background_um_per_pixel_xy':scene['background_um_per_pixel_xy'],'label_status':'unverified weak projected support, not ground truth; visibility undefined; entire original scene background unknown','split':'development_only'}
  if format_name=='r112-grouped-synthetic-scenes-v1':result['synthetic_partition']=scene['synthetic_partition']
  if self.include_mask_variants:
   if format_name not in self.mask_roots:raise ValueError('No source mask root for this scene format')
   fixed_root=self.mask_roots[format_name];variants=[]
   for i,instance in enumerate(scene['instances']):
    if fixed_root is None:
     root=ROOT/instance['source_mask_root'];allowed={Path(x).resolve() for x in self.mask_roots.values() if x is not None}
     if root.resolve() not in allowed:raise ValueError('Source mask root is not an approved dataset directory')
    else:root=Path(fixed_root)
    specs=[{'file':instance['source_mask_center'],'sha256':instance['source_mask_center_sha256']},instance['alternate_masks']['minus'],instance['alternate_masks']['plus']];proposals=[]
    for spec in specs:
     path=root/spec['file']
     if self.verify_hashes and digest(path)!=spec['sha256']:raise ValueError('Source mask checksum mismatch')
     source=np.asarray(Image.open(path).convert('L'))>0;proposals.append(project_source_mask(source,instance,image.shape))
    if not np.array_equal(proposals[0],support[i]):raise ValueError('Center mask reprojection differs from scene support')
    variants.append(np.stack(proposals))
   result['weak_mask_proposals']=np.stack(variants)
   result['weak_mask_vote_count']=result['weak_mask_proposals'].sum(axis=1,dtype=np.uint8)
   result['mask_proposal_order']=('center','minus','plus')
   result['mask_vote_status']='Shared-model proposal agreement only; not calibrated uncertainty or ground truth.'
  return result

# Each manifest is tied to its source-mask directory; source proposals were
# generated independently of the scene renderer. The masks are correlated
# predictions from a single model, not calibrated confidence intervals.
MASK_ROOTS={
 'r112-weak-development-v1':ROOT/'results/r112/species-depth/mask-hypotheses',
 'r112-weak-diverse-v1':ROOT/'results/r112/diversity-fetch/mask-hypotheses',
 'r112-weak-breadth-depth-v1':ROOT/'results/r112/breadth-depth/mask-hypotheses',
 'r112-weak-new-taxa-v1':ROOT/'results/r112/new-taxa/mask-hypotheses',
 'r112-broad-background-scenes-v1':None,
 'r112-grouped-synthetic-scenes-v1':None,
}

def project_source_mask(source_mask, instance, canvas_shape):
 """Reproject one source mask using the renderer's nearest-neighbor geometry."""
 import cv2
 source=np.asarray(source_mask,dtype=np.uint8)
 if source.ndim!=2:raise ValueError('Source proposal must be a 2D mask')
 dims=tuple(int(x) for x in instance['resampled_dimensions_px'])
 if len(dims)!=2 or min(dims)<1:raise ValueError('Invalid resampled dimensions')
 resized=cv2.resize(source,dims,interpolation=cv2.INTER_NEAREST)
 rotated=np.asarray(Image.fromarray(resized).rotate(instance['rotation_ccw_degrees'],resample=Image.Resampling.NEAREST,expand=True))>0
 height,width=canvas_shape;h,w=rotated.shape;x=instance['center_xy'][0]-w//2;y=instance['center_xy'][1]-h//2
 x0,y0=max(0,x),max(0,y);x1,y1=min(width,x+w),min(height,y+h);out=np.zeros((height,width),dtype=bool)
 if x1>x0 and y1>y0:out[y0:y1,x0:x1]=rotated[y0-y:y1-y,x0-x:x1-x]
 return out
