import json,unittest
import numpy as np
from diatom_pilot.proposal_graph import build_graph,mask_digest,pack_candidates,unpack_candidates
class TestProposalGraph(unittest.TestCase):
 def test_lossless_identical_masks_and_multistage_edges(self):
  a=np.zeros((9,13),bool);a[2:6,3:8]=True;b=a.copy();c=a.copy();c[0,0]=True
  candidates=[{'id':'a','z':0,'source':'det','mask':a},{'id':'b','z':1,'source':'point','mask':b},{'id':'c','z':0,'source':'box','mask':c}];edges=[{'candidate':'b','kept':'a','stage':'first'},{'candidate':'a','kept':'b','stage':'second'},{'candidate':'c','kept':'a','stage':'second'}];g=build_graph(candidates,edges,2,{'source':'test'});self.assertEqual(len(g['candidates']),3);self.assertEqual(len(g['relations']),3);self.assertEqual(g['candidates'][0]['mask_sha256'],g['candidates'][1]['mask_sha256']);self.assertTrue(all(x['semantics']=='suppressed_by_algorithm_not_identity' for x in g['relations']));restored=unpack_candidates(pack_candidates(candidates));self.assertEqual(set(restored),{'a','b','c'});self.assertTrue(all(np.array_equal(restored[x['id']],x['mask']) for x in candidates));self.assertEqual(json.loads(json.dumps(g))['relations'],g['relations'])
 def test_invalid_links_and_duplicate_ids(self):
  a=np.ones((3,3),bool);v={'id':'x','z':0,'source':'det','mask':a}
  with self.assertRaises(ValueError):build_graph([v,v],[],1,{})
  with self.assertRaises(ValueError):build_graph([v],[{'candidate':'missing','kept':'x','stage':'nms'}],1,{})
  with self.assertRaises(ValueError):build_graph([v],[{'candidate':'x','kept':'x','stage':'nms'}],1,{})
  with self.assertRaises(ValueError):build_graph([v],[],1,{'bad':float('nan')})
 def test_packed_integrity(self):
  a=np.ones((3,3),bool);p=pack_candidates([{'id':'x','mask':a}]);self.assertEqual(mask_digest(unpack_candidates(p)['x']),mask_digest(a));p['bits'][-1]|=1
  with self.assertRaises(ValueError):unpack_candidates(p)
 def test_empty_graph(self):
  self.assertEqual(unpack_candidates(pack_candidates([])),{});self.assertEqual(build_graph([],[],1,{})['candidates'],[])
if __name__=='__main__':unittest.main()
