"""Explicit prior-split aware access to rarer UDE development crops.

No partition is an independent benchmark. Masks, names and background are not
scientifically adjudicated. The full pool exposes prior tuning/check locations.
"""
from __future__ import annotations
import collections,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'
PRIOR_SPLIT=ROOT/'results/r112/species-scaleup/location-partitions.json'
class UDEBreadthDataset:
 def __init__(self,scope:str,root=DEFAULT,*,prior_split=PRIOR_SPLIT,include_unverified_masks=False):
  if scope not in ('prior_training_components','all_exposed_development'):raise ValueError('Explicit prior_training_components or all_exposed_development scope required')
  self.root=Path(root);self.scope=scope;self.include_unverified_masks=include_unverified_masks;assets_path=self.root/'assets.json';verify_path=self.root/'verify.json';audit_path=self.root/'prior-split-exposure.json';split_path=Path(prior_split);a=json.loads(assets_path.read_text());v=json.loads(verify_path.read_text());audit=json.loads(audit_path.read_text());split=json.loads(split_path.read_text())
  if (a.get('format'),v.get('format'),audit.get('format'))!=('r112-species-breadth-assets-v1','r112-species-breadth-verify-v1','r112-breadth-prior-split-exposure-v1'):raise ValueError('Unsupported provenance')
  if v['assets_sha256']!=sha256(assets_path) or audit['source_assets_sha256']!=sha256(assets_path) or audit['source_verify_sha256']!=sha256(verify_path) or audit['prior_80_partition_sha256']!=sha256(split_path) or v['selection_sha256']!=sha256(self.root/'selection.json'):raise ValueError('Source or location provenance mismatch')
  rows=a['records'];reports=audit['records'];parts=split['group_partition']
  if len(rows)!=len(reports) or len(rows)!=v['crops']:raise ValueError('Source count mismatch')
  seen=set();counts=collections.Counter();entries=[]
  for x,y in zip(rows,reports):
   ident=x['annotation_id'];part=parts.get(x['source_site_component'],'unassigned')
   if ident in seen or not ident.isdecimal() or (ident,x['source_species'],x['source_site_component'],part)!=(y['annotation_id'],y['source_name'],y['source_site_component'],y['old_80_name_location_partition']):raise ValueError('Invalid or duplicate source location entry')
   seen.add(ident);counts[part]+=1
   if scope=='all_exposed_development' or part=='training':entries.append((x,part))
  if dict(counts)!=audit['counts'] or len(seen)!=v['crops']:raise ValueError('Location exposure counts mismatch')
  self.entries=entries
  if include_unverified_masks:
   h=self.root/'mask-hypotheses';protocol=h/'protocol.json';report=h/'verify.json'
   if not report.exists():raise ValueError('Complete proposal verification is required')
   q=json.loads(report.read_text());p=json.loads(protocol.read_text())
   if q.get('format')!='r112-breadth-mask-verification-v1' or q['protocol_sha256']!=sha256(protocol) or p['source_assets_sha256']!=sha256(assets_path) or q['requested_sources']!=v['crops'] or q['verified_records']!=v['crops'] or q['missing_ids']:raise ValueError('Incomplete or mismatched proposal verification')
 def __len__(self):return len(self.entries)
 def __getitem__(self,index):
  x,part=self.entries[index];ident=x['annotation_id'];path=self.root/x['source_crop']
  if path.resolve()!=(self.root/'images'/f'{ident}.png').resolve() or sha256(path)!=x['source_sha256']:raise ValueError('Source crop checksum mismatch')
  image=Image.open(path).convert('L');image.load();result={'image':image,'annotation_id':ident,'source_name':x['source_species'],'source_genus':x['source_genus'],'source_site_component':x['source_site_component'],'prior_80_location_partition':part,'scope':self.scope,'source_um_per_pixel_xy':x['source_scale_um_px'],'taxonomic_status':x['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:
   h=self.root/'mask-hypotheses';record=json.loads((h/'records'/f'{ident}.json').read_text())
   if record['source_sha256']!=x['source_sha256'] or record['protocol_sha256']!=sha256(h/'protocol.json'):raise ValueError('Mask proposal provenance mismatch')
   masks=[]
   for k in ('center','minus','plus'):
    item=record['masks'][k];path=h/item['file']
    if path.resolve()!=(h/'masks'/f'{ident}-{k}.png').resolve() or sha256(path)!=item['sha256']:raise ValueError('Mask proposal checksum mismatch')
    m=np.asarray(Image.open(path).convert('L'))>0
    if m.shape!=(image.height,image.width):raise ValueError('Mask shape mismatch')
    masks.append(m)
   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
