"""Partition, provenance and weak-mask guards for expanded development data."""
import hashlib,json,tempfile,unittest
from pathlib import Path
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
class UDEScaleupDatasetTests(unittest.TestCase):
 def setUp(self):
  self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);(self.root/'images').mkdir();self.sel=self.root/'selection.json';self.assets=self.root/'assets.json';self.verify=self.root/'verify.json';self.part=self.root/'location-partitions.json';self.pverify=self.root/'partition-verify.json';self.sel.write_text('{}');records=[];split=[];group={}
  for i,label in enumerate(('training','tuning','check'),1):
   ident=str(i);path=self.root/'images'/f'{ident}.png';Image.new('L',(8,8),i).save(path);records.append({'annotation_id':ident,'source_crop':f'images/{ident}.png','source_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'source_site_component':f'loc-{i}','source_species':'Navicula gregaria','source_genus':'Navicula','source_slide_group':f'slide-{i}','source_scale_um_px':[.09,.09],'taxonomic_status':'source name unverified'});split.append({'annotation_id':ident,'source_species':'Navicula gregaria','site_component':f'loc-{i}','partition':label});group[f'loc-{i}']=label
  self.assets.write_text(json.dumps({'format':'r112-scaleup-assets-v1','records':records}));ss=hashlib.sha256(self.sel.read_bytes()).hexdigest();aa=hashlib.sha256(self.assets.read_bytes()).hexdigest();self.verify.write_text(json.dumps({'format':'r112-scaleup-verify-v1','selection_sha256':ss,'assets_sha256':aa,'crops':3}));self.part.write_text(json.dumps({'format':'r112-scaleup-location-partitions-v1','selection_sha256':ss,'assets_sha256':aa,'records':split,'group_partition':group,'counts':{'training':1,'tuning':1,'check':1}}));self.pverify.write_text(json.dumps({'format':'r112-scaleup-partition-verify-v1','selection_sha256':ss,'assets_sha256':aa,'partition_sha256':hashlib.sha256(self.part.read_bytes()).hexdigest()}))
 def tearDown(self):self.temp.cleanup()
 def test_explicit_partition_returns_only_its_record(self):
  d=UDEScaleupDataset('training',self.root);self.assertEqual(len(d),1);self.assertEqual(d[0]['annotation_id'],'1');self.assertIn('unknown',d[0]['background_status']);self.assertEqual(UDEScaleupDataset('check',self.root)[0]['annotation_id'],'3')
 def test_unknown_partition_rejected(self):
  with self.assertRaises(ValueError):UDEScaleupDataset('validation',self.root)
 def test_unverified_masks_not_ready_rejected(self):
  with self.assertRaises(ValueError):UDEScaleupDataset('training',self.root,include_unverified_masks=True)
 def test_verified_proposals_are_separate_and_tampering_rejected(self):
  h=self.root/'mask-hypotheses';(h/'records').mkdir(parents=True);(h/'masks').mkdir();protocol=h/'protocol.json';protocol.write_text(json.dumps({'source_assets_sha256':hashlib.sha256(self.assets.read_bytes()).hexdigest()}));ph=hashlib.sha256(protocol.read_bytes()).hexdigest();(h/'verify.json').write_text(json.dumps({'format':'r112-scaleup-mask-verification-v1','protocol_sha256':ph,'requested_sources':3,'verified_records':3,'missing_ids':[]}));masks={}
  for k in ('center','minus','plus'):
   path=h/'masks'/f'1-{k}.png';Image.new('L',(8,8),255 if k=='center' else 0).save(path);masks[k]={'file':f'masks/1-{k}.png','sha256':hashlib.sha256(path.read_bytes()).hexdigest()}
  assets=json.loads(self.assets.read_text());record={'source_sha256':assets['records'][0]['source_sha256'],'protocol_sha256':ph,'masks':masks,'triage':'needs-inspection'};(h/'records/1.json').write_text(json.dumps(record));d=UDEScaleupDataset('training',self.root,include_unverified_masks=True);x=d[0];self.assertEqual(x['weak_mask_proposals'].shape,(3,8,8));self.assertTrue(x['weak_mask_proposals'][0].all());self.assertFalse(x['weak_mask_proposals'][1].any());(h/'masks/1-minus.png').write_bytes(b'tampered')
  with self.assertRaises(ValueError):d[0]
 def test_modified_partition_rejected(self):
  self.part.write_text(self.part.read_text()+' ')
  with self.assertRaises(ValueError):UDEScaleupDataset('training',self.root)
 def test_modified_source_rejected_on_read(self):
  d=UDEScaleupDataset('training',self.root);(self.root/'images/1.png').write_bytes(b'changed')
  with self.assertRaises(ValueError):d[0]
if __name__=='__main__':unittest.main()
