"""Explicit location-partition access to UDE development crops and optional weak masks.

Partitions are local development controls, not independent biological tests.
Source taxon strings and model-generated masks are not Academy-verified.
"""
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_ROOT=ROOT/'results/r112/species-scaleup'
def sha256(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 UDEScaleupDataset:
 """Reader that requires training, tuning, or check; no implicit background labels."""
 def __init__(self,partition:str,root=DEFAULT_ROOT,*,include_unverified_masks=False):
  if partition not in ('training','tuning','check'):raise ValueError('Explicit training, tuning, or check partition required')
  self.root=Path(root);self.partition=partition;self.include_unverified_masks=include_unverified_masks;sel=self.root/'selection.json';asset_file=self.root/'assets.json';verify=self.root/'verify.json';split=self.root/'location-partitions.json';partition_verify=self.root/'partition-verify.json';s=json.loads(split.read_text());a=json.loads(asset_file.read_text());v=json.loads(verify.read_text());pv=json.loads(partition_verify.read_text())
  if s.get('format')!='r112-scaleup-location-partitions-v1' or a.get('format')!='r112-scaleup-assets-v1' or v.get('format')!='r112-scaleup-verify-v1' or pv.get('format')!='r112-scaleup-partition-verify-v1':raise ValueError('Unsupported scale-up artifact format')
  if pv['partition_sha256']!=sha256(split) or pv['selection_sha256']!=sha256(sel) or pv['assets_sha256']!=sha256(asset_file):raise ValueError('Partition verification mismatch')
  if s['selection_sha256']!=sha256(sel) or s['assets_sha256']!=sha256(asset_file) or v['selection_sha256']!=sha256(sel) or v['assets_sha256']!=sha256(asset_file):raise ValueError('Scale-up provenance mismatch')
  if len(s['records'])!=len(a['records']) or len(a['records'])!=v['crops']:raise ValueError('Partition/source size mismatch')
  assets={x['annotation_id']:x for x in a['records']};seen=set();entries=[]
  for r in s['records']:
   ident=r['annotation_id'];component=r['site_component'];p=r['partition']
   if ident in seen or ident not in assets or p not in ('training','tuning','check') or s['group_partition'].get(component)!=p:raise ValueError('Invalid or duplicate partition entry')
   x=assets[ident]
   if x['source_site_component']!=component or x['source_species']!=r['source_species']:raise ValueError('Source metadata does not match partition')
   seen.add(ident)
   if p==partition:entries.append(x)
  if set(assets)!=seen or len(entries)!=s['counts'][partition]:raise ValueError('Partition membership 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('Mask proposals are not fully verified yet')
   q=json.loads(report.read_text());p=json.loads(protocol.read_text())
   if q.get('format')!='r112-scaleup-mask-verification-v1' or q['protocol_sha256']!=sha256(protocol) or p['source_assets_sha256']!=sha256(asset_file) or q['requested_sources']!=len(assets) or q['verified_records']!=len(assets) or q['missing_ids']:raise ValueError('Incomplete or mismatched mask proposal verification')
 def __len__(self):return len(self.entries)
 def __getitem__(self,index):
  x=self.entries[index];ident=x['annotation_id'];path=self.root/x['source_crop']
  if not ident.isdecimal() or path.resolve()!=(self.root/'images'/f'{ident}.png').resolve() or sha256(path)!=x['source_sha256']:raise ValueError('Source crop path or 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'],'source_slide':x['source_slide_group'],'source_um_per_pixel_xy':x['source_scale_um_px'],'partition':self.partition,'taxonomic_status':x['taxonomic_status'],'background_status':'unknown; crop may contain other organisms','mask_status':'no verified instance mask','comparison_status':'development only; not independent biological evaluation'}
  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'):
    q=record['masks'][k];p=h/q['file']
    if p.resolve()!=(h/'masks'/f'{ident}-{k}.png').resolve() or sha256(p)!=q['sha256']:raise ValueError('Mask proposal path or checksum mismatch')
    mask=np.asarray(Image.open(p).convert('L'))>0
    if mask.shape!=(image.height,image.width):raise ValueError('Mask dimensions 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 shared-model proposals; not biological ground truth'})
  return result
