import unittest
import numpy as np
from diatom_pilot.crossplane_links import build_possible_links

class CrossPlaneLinksTest(unittest.TestCase):
    def test_high_overlap_does_not_merge_distinct_candidates(self):
        a = np.zeros((10, 10), dtype=bool); a[1:8, 1:8] = True
        b = np.zeros((10, 10), dtype=bool); b[1:8, 2:9] = True
        candidates = [{'id': 'first', 'z': 0, 'mask': a}, {'id': 'second', 'z': 1, 'mask': b}]
        graph = build_possible_links(candidates)
        self.assertEqual([n['id'] for n in graph['candidates']], ['first', 'second'])
        self.assertEqual(len(graph['possible_links']), 1)
        self.assertEqual(graph['possible_links'][0]['semantics'], 'possible_overlap_not_specimen_identity')
        self.assertTrue(np.array_equal(candidates[0]['mask'], a))

    def test_same_plane_and_nonadjacent_candidates_and_empty_mask(self):
        full = np.ones((4, 4), dtype=bool); empty = np.zeros((4, 4), dtype=bool)
        graph = build_possible_links([{'id': 'a', 'z': 0, 'mask': full}, {'id': 'b', 'z': 0, 'mask': full},
                                     {'id': 'c', 'z': 2, 'mask': full}, {'id': 'd', 'z': 1, 'mask': empty}])
        self.assertEqual(len(graph['candidates']), 4)
        self.assertEqual(graph['possible_links'], [])

    def test_threshold_and_bad_inputs(self):
        a = np.array([[True, True], [True, False]]); b = np.array([[True, True], [False, False]])
        c = [{'id': 'a', 'z': 0, 'mask': a}, {'id': 'b', 'z': 1, 'mask': b}]
        self.assertEqual(len(build_possible_links(c, iou_threshold=0.6)['possible_links']), 1)
        self.assertEqual(len(build_possible_links(c, iou_threshold=0.7)['possible_links']), 0)
        for threshold in (0, -1, float('nan'), True):
            with self.assertRaises(ValueError): build_possible_links(c, iou_threshold=threshold)
        with self.assertRaises(ValueError): build_possible_links(c + [c[0]])
        with self.assertRaises(ValueError): build_possible_links([{'id': 'bad', 'z': 0, 'mask': np.ones((2, 2))}])

if __name__ == '__main__': unittest.main()
