from remedapy.util import LeaftistHeap, LeaftistHeapNode, heap_maybe_insert, heap_to_list, heapify, is_persisted


class TestUtil:
    def test_is_persisted(self):
        assert is_persisted([])
        assert is_persisted(())
        assert is_persisted(range(5))
        assert not is_persisted(x for x in range(5))


class TestHeap:
    def test_heap_2_elems(self):
        li: list[float] = [1, 10]
        heap = heapify(li, lambda x: x)
        assert heap is not None
        assert heap_to_list(heap) == [1, 10]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=11, key=11, index=2))
        assert heap_to_list(heap) == [1, 10]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=8, key=8, index=3))
        assert heap_to_list(heap) == [1, 8]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=0, key=0, index=4))
        assert heap_to_list(heap) == [1, 0]

    def test_heap(self):
        heap: LeaftistHeap[float, float] | None = heapify([1, 10, 5, 4, 2, 3], lambda x: x)
        assert heap is not None
        assert heap.node.value == 10
        assert heap.node.index == 1
        assert heap.node.key == 10
        assert heap_to_list(heap) == [1, 10, 5, 4, 2, 3]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=11, key=11, index=6))
        assert heap_to_list(heap) == [1, 10, 5, 4, 2, 3]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=8, key=8, index=7))
        assert heap_to_list(heap) == [1, 5, 4, 2, 3, 8]
        assert heap.node.value == 8
        assert heap.node.index == 7
        assert heap.node.key == 8
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=2.5, key=2.5, index=8))
        assert heap_to_list(heap) == [1, 5, 4, 2, 3, 2.5]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=3.5, key=3.5, index=9))
        assert heap_to_list(heap) == [1, 4, 2, 3, 2.5, 3.5]
        heap = heap_maybe_insert(heap, LeaftistHeapNode(value=1.5, key=1.5, index=10))
        assert heap_to_list(heap) == [1, 2, 3, 2.5, 3.5, 1.5]
