prolly-map 0.4.0

Content-addressed versioned map storage primitives.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! Cursor-based tree navigation for Prolly Trees
//!
//! Cursors provide efficient, non-recursive traversal through the tree structure.
//! They maintain a reference to the current node and an index within that node,
//! with parent linkage for upward navigation.
//!
//! # Example
//!
//! ```rust
//! use prolly::{Prolly, MemStore, Config, Cursor};
//!
//! let store = std::sync::Arc::new(MemStore::new());
//! let prolly = Prolly::new(store.clone(), Config::default());
//! let mut tree = prolly.create();
//!
//! // Insert some data
//! tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
//! tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
//!
//! // Create a cursor at key "a"
//! let cursor = Cursor::at_item(&store, &tree, b"a").unwrap();
//! assert!(cursor.is_valid());
//! assert_eq!(cursor.get_key(), Some(b"a".as_slice()));
//! ```

use std::cmp::Ordering;
use std::sync::Arc;

use super::cid::Cid;
use super::error::Diff;
use super::error::Error;
use super::node::Node;
use super::store::Store;
use super::tree::Tree;

/// Iterator wrapper for cursor-based traversal.
///
/// Provides a Rust iterator interface over tree entries using cursors.
/// Yields (key, value) pairs in lexicographic key order.
///
/// # Example
///
/// ```rust
/// use prolly::{Prolly, MemStore, Config, Cursor, CursorIterator};
/// use std::sync::Arc;
///
/// let store = Arc::new(MemStore::new());
/// let prolly = Prolly::new(store.clone(), Config::default());
/// let mut tree = prolly.create();
///
/// tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
/// tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
/// tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();
///
/// // Iterate over all entries
/// let cursor = Cursor::at_item(store.as_ref(), &tree, b"").unwrap();
/// let iter = CursorIterator::new(cursor, store.as_ref(), None);
/// for (key, value) in iter {
///     println!("{:?} -> {:?}", key, value);
/// }
///
/// // Iterate with an end bound (exclusive)
/// let cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
/// let iter = CursorIterator::new(cursor, store.as_ref(), Some(b"c".to_vec()));
/// // Only yields "a" -> "1" and "b" -> "2"
/// ```
pub struct CursorIterator<'a, S: Store> {
    /// The cursor for navigation
    cursor: Cursor,
    /// Reference to the store for loading nodes during advance
    store: &'a S,
    /// Optional start key (inclusive) - only yield entries >= this key
    start_key: Option<Vec<u8>>,
    /// Optional end key (exclusive) - iteration stops before this key
    end_key: Option<Vec<u8>>,
    /// Flag to track if we've already yielded the first item
    started: bool,
}

impl<'a, S: Store> CursorIterator<'a, S> {
    /// Create a new cursor iterator.
    ///
    /// # Arguments
    /// * `cursor` - The cursor to iterate from
    /// * `store` - Reference to the store for loading nodes
    /// * `end_key` - Optional end bound (exclusive) - iteration stops before this key
    ///
    /// # Returns
    /// A new CursorIterator that yields (key, value) pairs.
    pub fn new(cursor: Cursor, store: &'a S, end_key: Option<Vec<u8>>) -> Self {
        Self {
            cursor,
            store,
            start_key: None,
            end_key,
            started: false,
        }
    }

    /// Create a new cursor iterator with start and end bounds.
    ///
    /// # Arguments
    /// * `cursor` - The cursor to iterate from
    /// * `store` - Reference to the store for loading nodes
    /// * `start_key` - Optional start bound (inclusive) - only yield entries >= this key
    /// * `end_key` - Optional end bound (exclusive) - iteration stops before this key
    ///
    /// # Returns
    /// A new CursorIterator that yields (key, value) pairs within the specified range.
    pub fn with_bounds(
        cursor: Cursor,
        store: &'a S,
        start_key: Option<Vec<u8>>,
        end_key: Option<Vec<u8>>,
    ) -> Self {
        Self {
            cursor,
            store,
            start_key,
            end_key,
            started: false,
        }
    }

    /// Check if the current cursor position is at or after the start bound.
    ///
    /// Returns true if:
    /// - There is no start bound, or
    /// - The current key is >= the start bound
    fn is_at_or_after_start(&self) -> bool {
        match (&self.start_key, self.cursor.get_key()) {
            (Some(start), Some(current)) => current >= start.as_slice(),
            (None, Some(_)) => true,
            _ => false,
        }
    }

    /// Check if the current cursor position is before the end bound.
    ///
    /// Returns true if:
    /// - There is no end bound, or
    /// - The current key is strictly less than the end bound
    fn is_before_end(&self) -> bool {
        match (&self.end_key, self.cursor.get_key()) {
            (Some(end), Some(current)) => current < end.as_slice(),
            (None, Some(_)) => true,
            _ => false,
        }
    }
}

impl<'a, S: Store> Iterator for CursorIterator<'a, S> {
    type Item = (Vec<u8>, Vec<u8>);

    fn next(&mut self) -> Option<Self::Item> {
        // If cursor is invalid, we're done
        if !self.cursor.is_valid() {
            return None;
        }

        // If we've already started, advance to the next entry
        if self.started {
            if !self
                .cursor
                .advance_before(self.store, self.end_key.as_deref())
            {
                return None;
            }
        } else {
            self.started = true;
            // On first call, skip entries that are before the start bound
            // (cursor may be positioned at greatest key <= start, but we need >= start)
            while self.cursor.is_valid() && !self.is_at_or_after_start() {
                if !self
                    .cursor
                    .advance_before(self.store, self.end_key.as_deref())
                {
                    return None;
                }
            }
        }

        // Check if cursor is still valid after potential advance
        if !self.cursor.is_valid() {
            return None;
        }

        // Check end bound before yielding
        if !self.is_before_end() {
            return None;
        }

        // Get key and value from cursor
        let key = self.cursor.get_key()?.to_vec();
        let value = self.cursor.get_value()?.to_vec();

        Some((key, value))
    }
}

/// Streaming diff iterator using dual cursor traversal.
///
/// Provides memory-efficient diff by yielding results as they're found
/// rather than allocating a Vec. Supports early termination.
///
/// # Example
///
/// ```rust
/// use prolly::{Prolly, MemStore, Config, DiffCursor};
/// use std::sync::Arc;
///
/// let store = Arc::new(MemStore::new());
/// let prolly = Prolly::new(store.clone(), Config::default());
/// let mut base = prolly.create();
/// let mut other = prolly.create();
///
/// base = prolly.put(&base, b"a".to_vec(), b"1".to_vec()).unwrap();
/// other = prolly.put(&other, b"a".to_vec(), b"1".to_vec()).unwrap();
/// other = prolly.put(&other, b"b".to_vec(), b"2".to_vec()).unwrap();
///
/// // Stream differences
/// let diff_cursor = DiffCursor::new(store.as_ref(), &base, &other).unwrap();
/// for diff in diff_cursor {
///     println!("{:?}", diff);
/// }
/// ```
pub struct DiffCursor<'a, S: Store> {
    /// Cursor for the base tree
    cursor_base: Cursor,
    /// Cursor for the other tree
    cursor_other: Cursor,
    /// Reference to the store (shared between both trees)
    store: &'a S,
    /// Whether iteration is complete
    done: bool,
}

impl<'a, S: Store> DiffCursor<'a, S> {
    /// Create a new streaming diff iterator.
    ///
    /// # Arguments
    /// * `store` - The storage backend (shared by both trees)
    /// * `base` - The base tree to compare from
    /// * `other` - The other tree to compare to
    ///
    /// # Returns
    /// * `Ok(DiffCursor)` - A new diff iterator
    /// * `Err(Error)` - If cursor initialization fails
    ///
    /// # Behavior
    /// - If both trees are empty, the iterator yields no differences
    /// - If base is empty, all entries from other are yielded as Added
    /// - If other is empty, all entries from base are yielded as Removed
    pub fn new(store: &'a S, base: &Tree, other: &Tree) -> Result<Self, Error> {
        if base.root == other.root {
            let invalid = Cursor::invalid();
            return Ok(DiffCursor {
                cursor_base: invalid.clone(),
                cursor_other: invalid,
                store,
                done: true,
            });
        }

        // Initialize cursors at leftmost positions (empty key = start)
        let cursor_base = Cursor::at_item(store, base, &[])?;
        let cursor_other = Cursor::at_item(store, other, &[])?;

        Ok(DiffCursor {
            cursor_base,
            cursor_other,
            store,
            done: false,
        })
    }
}

impl<'a, S: Store> Iterator for DiffCursor<'a, S> {
    type Item = Diff;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        loop {
            let base_valid = self.cursor_base.is_valid();
            let other_valid = self.cursor_other.is_valid();

            match (base_valid, other_valid) {
                // Both exhausted - done
                (false, false) => {
                    self.done = true;
                    return None;
                }

                // Only other has entries - all additions
                (false, true) => {
                    let key = self.cursor_other.get_key()?.to_vec();
                    let val = self.cursor_other.get_value()?.to_vec();
                    self.cursor_other.advance(self.store);
                    return Some(Diff::Added { key, val });
                }

                // Only base has entries - all removals
                (true, false) => {
                    let key = self.cursor_base.get_key()?.to_vec();
                    let val = self.cursor_base.get_value()?.to_vec();
                    self.cursor_base.advance(self.store);
                    return Some(Diff::Removed { key, val });
                }

                // Both have entries - compare keys
                (true, true) => {
                    let base_key = self.cursor_base.get_key()?.to_vec();
                    let other_key = self.cursor_other.get_key()?.to_vec();

                    match base_key.cmp(&other_key) {
                        Ordering::Less => {
                            // Key only in base - removed
                            let val = self.cursor_base.get_value()?.to_vec();
                            self.cursor_base.advance(self.store);
                            return Some(Diff::Removed { key: base_key, val });
                        }
                        Ordering::Greater => {
                            // Key only in other - added
                            let val = self.cursor_other.get_value()?.to_vec();
                            self.cursor_other.advance(self.store);
                            return Some(Diff::Added {
                                key: other_key,
                                val,
                            });
                        }
                        Ordering::Equal => {
                            // Same key - compare values
                            let base_val = self.cursor_base.get_value()?.to_vec();
                            let other_val = self.cursor_other.get_value()?.to_vec();

                            self.cursor_base.advance(self.store);
                            self.cursor_other.advance(self.store);

                            if base_val != other_val {
                                return Some(Diff::Changed {
                                    key: base_key,
                                    old: base_val,
                                    new: other_val,
                                });
                            }
                            // Values equal - continue to next
                            continue;
                        }
                    }
                }
            }
        }
    }
}

/// A cursor pointing to a specific position in a prolly tree.
///
/// Cursors provide efficient navigation through the tree structure
/// without recursion. They maintain a reference to the current node
/// and an index within that node, with optional parent linkage for
/// upward navigation.
///
/// # Cloning
///
/// Cursors are cloneable. Cloned cursors are independent of the original -
/// advancing one does not affect the other.
#[derive(Clone)]
pub struct Cursor {
    /// Current position within the node (0-based index)
    pub index: usize,
    /// Current node (Arc for efficient cloning)
    pub node: Arc<Node>,
    /// Parent cursor for upward navigation
    pub parent: Option<Box<Cursor>>,
}

impl Cursor {
    pub(crate) fn invalid() -> Self {
        Self {
            index: 0,
            node: Arc::new(Node::new_leaf()),
            parent: None,
        }
    }

    /// Navigate to the position of a key in the tree.
    ///
    /// Follows the Arbor spec's CursorAtItem algorithm:
    /// 1. Find index in current node
    /// 2. If leaf, done
    /// 3. Otherwise, recurse to child with parent linkage
    ///
    /// # Arguments
    /// * `store` - The storage backend to load nodes from
    /// * `tree` - The tree to navigate
    /// * `key` - The key to position at
    ///
    /// # Returns
    /// * `Ok(Cursor)` - A cursor positioned at or near the key
    /// * `Err` - If a storage error occurs
    ///
    /// # Behavior
    /// - If the tree is empty, returns a cursor with an empty node (is_valid() == false)
    /// - If the key exists, positions at that exact key
    /// - If the key doesn't exist, positions at the greatest key <= target
    pub fn at_item<S: Store>(store: &S, tree: &Tree, key: &[u8]) -> Result<Self, Error> {
        // Handle empty tree
        let Some(root_cid) = &tree.root else {
            return Ok(Self::invalid());
        };

        // Load root node
        let root_node = Self::load_node(store, root_cid)?;

        // Navigate from root to leaf
        Self::navigate_to_key(store, root_node, key, None)
    }

    /// Navigate from a node to the leaf containing the key.
    ///
    /// Recursively descends through the tree, building parent linkage.
    fn navigate_to_key<S: Store>(
        store: &S,
        node: Node,
        key: &[u8],
        parent: Option<Box<Cursor>>,
    ) -> Result<Self, Error> {
        let index = Self::key_index(&node.keys, key);

        if node.leaf {
            // At leaf - we're done
            Ok(Self {
                index,
                node: Arc::new(node),
                parent,
            })
        } else {
            let child_cid = child_cid_at(&node, index)?;

            // Internal node - descend to child
            // Create cursor for this internal node (will be parent of child cursor)
            let current_cursor = Self {
                index,
                node: Arc::new(node),
                parent,
            };

            // Load child node
            let child_node = Self::load_node(store, &child_cid)?;

            // Recurse with current cursor as parent
            Self::navigate_to_key(store, child_node, key, Some(Box::new(current_cursor)))
        }
    }

    /// Load a node from the store by its CID.
    fn load_node<S: Store>(store: &S, cid: &Cid) -> Result<Node, Error> {
        let bytes = store
            .get(cid.as_bytes())
            .map_err(|e| Error::Store(Box::new(e)))?
            .ok_or_else(|| Error::NotFound(cid.clone()))?;
        Node::from_bytes(&bytes)
    }

    /// Get the current key at the cursor position.
    ///
    /// # Returns
    /// * `Some(&[u8])` - The key at the current position
    /// * `None` - If the cursor is invalid (empty node or index out of bounds)
    pub fn get_key(&self) -> Option<&[u8]> {
        if self.is_valid() {
            Some(&self.node.keys[self.index])
        } else {
            None
        }
    }

    /// Get the current value at the cursor position.
    ///
    /// Only returns a value for leaf nodes. Internal nodes store CIDs, not values.
    ///
    /// # Returns
    /// * `Some(&[u8])` - The value at the current position (leaf nodes only)
    /// * `None` - If the cursor is invalid or at an internal node
    pub fn get_value(&self) -> Option<&[u8]> {
        if self.is_valid() && self.node.leaf {
            self.node.vals.get(self.index).map(|value| value.as_slice())
        } else {
            None
        }
    }

    /// Check if the cursor is valid.
    ///
    /// A cursor is valid if:
    /// - The node is not empty
    /// - The index is within bounds
    ///
    /// # Returns
    /// `true` if the cursor points to a valid entry, `false` otherwise.
    pub fn is_valid(&self) -> bool {
        !self.node.is_empty() && self.index < self.node.len()
    }

    /// Check if the cursor is at the end of its current node.
    ///
    /// # Returns
    /// `true` if the cursor is at the last entry of the node, `false` otherwise.
    pub fn is_at_end(&self) -> bool {
        self.node.is_empty() || self.index >= self.node.len() - 1
    }

    /// Advance the cursor to the next entry in the tree.
    ///
    /// Follows the Arbor spec's AdvanceCursor algorithm:
    /// 1. Try to advance within current node
    /// 2. If at end, navigate up to parent
    /// 3. Advance parent and load next child
    /// 4. Descend to leftmost leaf of next subtree
    ///
    /// # Arguments
    /// * `store` - The storage backend to load nodes from
    ///
    /// # Returns
    /// * `true` if successfully advanced to next entry
    /// * `false` if at end of tree (no more entries)
    ///
    /// # Behavior
    /// After returning `false`, the cursor becomes invalid (`is_valid()` returns `false`).
    pub fn advance<S: Store>(&mut self, store: &S) -> bool {
        self.advance_before(store, None)
    }

    fn advance_before<S: Store>(&mut self, store: &S, end: Option<&[u8]>) -> bool {
        // If cursor is already invalid, can't advance
        if !self.is_valid() {
            return false;
        }

        // Try to advance within current node
        if self.index + 1 < self.node.len() {
            if let Some(end) = end {
                if self.node.keys[self.index + 1].as_slice() >= end {
                    self.index = self.node.len();
                    return false;
                }
            }
            self.index += 1;
            return true;
        }

        // At end of current node - need to navigate up and find next subtree
        self.advance_via_parent_before(store, end)
    }

    fn advance_via_parent_before<S: Store>(&mut self, store: &S, end: Option<&[u8]>) -> bool {
        // Take ownership of parent to navigate up
        let Some(mut parent) = self.parent.take() else {
            // No parent - we're at root and exhausted, mark as invalid
            self.index = self.node.len(); // Mark as invalid
            return false;
        };

        // Try to advance the parent
        if parent.index + 1 < parent.node.len() {
            // Parent can advance - move to next child
            let next_index = parent.index + 1;
            if child_starts_at_or_after_end(end, &parent.node, next_index) {
                self.index = self.node.len();
                return false;
            }
            parent.index = next_index;

            // Load the next child and descend to its leftmost leaf
            match self.descend_to_leftmost_leaf(store, &parent) {
                Ok(new_cursor) => {
                    *self = new_cursor;
                    true
                }
                Err(_) => {
                    // Storage error - mark as invalid
                    self.index = self.node.len();
                    false
                }
            }
        } else {
            // Parent is also at end - recurse up
            // Temporarily set self to parent to continue navigation
            let mut temp_cursor = *parent;
            if temp_cursor.advance_via_parent_before(store, end) {
                *self = temp_cursor;
                true
            } else {
                // No more entries in tree
                self.index = self.node.len();
                false
            }
        }
    }

    /// Descend from a parent cursor to the leftmost leaf of its current child.
    fn descend_to_leftmost_leaf<S: Store>(
        &self,
        store: &S,
        parent: &Cursor,
    ) -> Result<Cursor, Error> {
        // Load the child node at parent's current index
        let child_cid = child_cid_at(&parent.node, parent.index)?;
        let child_node = Self::load_node(store, &child_cid)?;

        if child_node.leaf {
            // Child is a leaf - create cursor at index 0
            Ok(Cursor {
                index: 0,
                node: Arc::new(child_node),
                parent: Some(Box::new(parent.clone())),
            })
        } else {
            // Child is internal - continue descending
            let child_cursor = Cursor {
                index: 0,
                node: Arc::new(child_node),
                parent: Some(Box::new(parent.clone())),
            };
            child_cursor.descend_to_leftmost_leaf_from_self(store)
        }
    }

    /// Descend from the current cursor (at an internal node) to the leftmost leaf.
    fn descend_to_leftmost_leaf_from_self<S: Store>(self, store: &S) -> Result<Cursor, Error> {
        if self.node.leaf {
            return Ok(self);
        }

        // Load child at index 0
        let child_cid = child_cid_at(&self.node, self.index)?;
        let child_node = Self::load_node(store, &child_cid)?;

        let child_cursor = Cursor {
            index: 0,
            node: Arc::new(child_node),
            parent: Some(Box::new(self)),
        };

        child_cursor.descend_to_leftmost_leaf_from_self(store)
    }

    /// Find the index in keys closest to but not larger than the given key.
    ///
    /// Uses binary search to find the position. Returns:
    /// - The exact index if the key exists
    /// - The index of the greatest key less than the target if key doesn't exist
    /// - 0 if the target is smaller than all keys (or keys is empty)
    ///
    /// # Arguments
    /// * `keys` - Sorted slice of keys to search
    /// * `key` - The target key to find
    ///
    /// # Returns
    /// Index of the key closest to but not larger than the target.
    fn key_index(keys: &[Vec<u8>], key: &[u8]) -> usize {
        if keys.is_empty() {
            return 0;
        }

        match keys.binary_search_by(|k| k.as_slice().cmp(key)) {
            // Exact match found
            Ok(i) => i,
            // Key not found, Err(i) is the insertion point
            // We want the greatest key less than target, which is i - 1
            // But if i == 0, target is smaller than all keys, return 0
            Err(i) => {
                if i == 0 {
                    0
                } else {
                    i - 1
                }
            }
        }
    }
}

fn child_cid_at(node: &Node, index: usize) -> Result<Cid, Error> {
    let child_cid_bytes = node.vals.get(index).ok_or(Error::InvalidNode)?;
    Ok(Cid(child_cid_bytes
        .as_slice()
        .try_into()
        .map_err(|_| Error::InvalidNode)?))
}

fn child_starts_at_or_after_end(end: Option<&[u8]>, node: &Node, child_index: usize) -> bool {
    let Some(end) = end else {
        return false;
    };

    match node.keys.get(child_index) {
        Some(first_key) => first_key.as_slice() >= end,
        None => true,
    }
}

#[cfg(test)]
mod tests {
    use super::super::config::Config;
    use super::super::store::{BatchOp, MemStore};
    use super::super::Prolly;
    use super::*;
    use std::collections::BTreeMap;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex;

    #[derive(Debug)]
    struct CountingStoreError;

    impl std::fmt::Display for CountingStoreError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("counting store error")
        }
    }

    impl std::error::Error for CountingStoreError {}

    #[derive(Default)]
    struct CountingStore {
        data: Mutex<BTreeMap<Vec<u8>, Vec<u8>>>,
        get_calls: AtomicUsize,
    }

    impl Store for CountingStore {
        type Error = CountingStoreError;

        fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
            self.get_calls.fetch_add(1, Ordering::Relaxed);
            Ok(self.data.lock().unwrap().get(key).cloned())
        }

        fn put(&self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
            self.data
                .lock()
                .unwrap()
                .insert(key.to_vec(), value.to_vec());
            Ok(())
        }

        fn delete(&self, key: &[u8]) -> Result<(), Self::Error> {
            self.data.lock().unwrap().remove(key);
            Ok(())
        }

        fn batch(&self, ops: &[BatchOp]) -> Result<(), Self::Error> {
            let mut data = self.data.lock().unwrap();
            for op in ops {
                match op {
                    BatchOp::Upsert { key, value } => {
                        data.insert(key.to_vec(), value.to_vec());
                    }
                    BatchOp::Delete { key } => {
                        data.remove(*key);
                    }
                }
            }
            Ok(())
        }
    }

    #[test]
    fn test_key_index_empty_keys() {
        let keys: Vec<Vec<u8>> = vec![];
        assert_eq!(Cursor::key_index(&keys, b"any"), 0);
    }

    #[test]
    fn test_key_index_exact_match() {
        let keys = vec![b"a".to_vec(), b"c".to_vec(), b"e".to_vec()];
        assert_eq!(Cursor::key_index(&keys, b"a"), 0);
        assert_eq!(Cursor::key_index(&keys, b"c"), 1);
        assert_eq!(Cursor::key_index(&keys, b"e"), 2);
    }

    #[test]
    fn test_key_index_between_keys() {
        let keys = vec![b"a".to_vec(), b"c".to_vec(), b"e".to_vec()];
        // "b" is between "a" and "c", should return index of "a" (0)
        assert_eq!(Cursor::key_index(&keys, b"b"), 0);
        // "d" is between "c" and "e", should return index of "c" (1)
        assert_eq!(Cursor::key_index(&keys, b"d"), 1);
    }

    #[test]
    fn test_key_index_smaller_than_all() {
        let keys = vec![b"b".to_vec(), b"c".to_vec(), b"d".to_vec()];
        // "a" is smaller than all keys, should return 0
        assert_eq!(Cursor::key_index(&keys, b"a"), 0);
    }

    #[test]
    fn test_key_index_larger_than_all() {
        let keys = vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()];
        // "z" is larger than all keys, should return index of last key (2)
        assert_eq!(Cursor::key_index(&keys, b"z"), 2);
    }

    #[test]
    fn test_key_index_single_key() {
        let keys = vec![b"m".to_vec()];
        assert_eq!(Cursor::key_index(&keys, b"a"), 0); // smaller
        assert_eq!(Cursor::key_index(&keys, b"m"), 0); // exact
        assert_eq!(Cursor::key_index(&keys, b"z"), 0); // larger
    }

    #[test]
    fn test_at_item_empty_tree() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let tree = prolly.create();

        let cursor = Cursor::at_item(store.as_ref(), &tree, b"any").unwrap();
        assert!(!cursor.is_valid());
        assert_eq!(cursor.get_key(), None);
        assert_eq!(cursor.get_value(), None);
    }

    #[test]
    fn diff_cursor_skips_identical_roots_without_reads() {
        let store = std::sync::Arc::new(CountingStore::default());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();
        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        let gets_before = store.get_calls.load(Ordering::Relaxed);

        let mut diff = DiffCursor::new(store.as_ref(), &tree, &tree).unwrap();

        assert_eq!(diff.next(), None);
        assert_eq!(
            store.get_calls.load(Ordering::Relaxed),
            gets_before,
            "identical-root cursor diffs should avoid root and leaf reads"
        );
    }

    #[test]
    fn get_value_returns_none_for_leaf_with_missing_value() {
        let mut leaf = Node::new_leaf();
        leaf.keys.push(b"a".to_vec());
        let cursor = Cursor {
            index: 0,
            node: Arc::new(leaf),
            parent: None,
        };

        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"a".as_slice()));
        assert_eq!(cursor.get_value(), None);
    }

    #[test]
    fn internal_descent_rejects_missing_child_cid() {
        let store = std::sync::Arc::new(MemStore::new());
        let mut root = Node::new_internal(1);
        root.keys.push(b"a".to_vec());
        let cursor = Cursor {
            index: 0,
            node: Arc::new(root),
            parent: None,
        };

        let err = match cursor.descend_to_leftmost_leaf_from_self(store.as_ref()) {
            Ok(_) => panic!("malformed internal node should be rejected"),
            Err(err) => err,
        };

        assert!(matches!(err, Error::InvalidNode));
    }

    #[test]
    fn test_at_item_exact_key() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();

        let cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"b".as_slice()));
        assert_eq!(cursor.get_value(), Some(b"2".as_slice()));
    }

    #[test]
    fn test_at_item_nonexistent_key() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();
        tree = prolly.put(&tree, b"e".to_vec(), b"5".to_vec()).unwrap();

        // "b" doesn't exist, should position at "a" (greatest key <= "b")
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"a".as_slice()));

        // "d" doesn't exist, should position at "c"
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"d").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"c".as_slice()));
    }

    #[test]
    fn test_at_item_key_smaller_than_all() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();

        // "a" is smaller than all keys, should position at first key "b"
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"b".as_slice()));
    }

    #[test]
    fn test_at_item_key_larger_than_all() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();

        // "z" is larger than all keys, should position at last key "b"
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"z").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"b".as_slice()));
    }

    #[test]
    fn test_cursor_is_at_end() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();

        // Cursor at "a" is not at end (there's "b" after)
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        assert!(!cursor.is_at_end());

        // Cursor at "b" is at end (last key)
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        assert!(cursor.is_at_end());
    }

    #[test]
    fn test_cursor_clone_independence() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();

        let cursor1 = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        let cursor2 = cursor1.clone();

        // Both should point to the same key
        assert_eq!(cursor1.get_key(), cursor2.get_key());
        assert_eq!(cursor1.get_value(), cursor2.get_value());
    }

    #[test]
    fn test_advance_within_node() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();

        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        assert_eq!(cursor.get_key(), Some(b"a".as_slice()));

        // Advance to "b"
        assert!(cursor.advance(store.as_ref()));
        assert_eq!(cursor.get_key(), Some(b"b".as_slice()));
        assert_eq!(cursor.get_value(), Some(b"2".as_slice()));

        // Advance to "c"
        assert!(cursor.advance(store.as_ref()));
        assert_eq!(cursor.get_key(), Some(b"c".as_slice()));
        assert_eq!(cursor.get_value(), Some(b"3".as_slice()));
    }

    #[test]
    fn test_advance_at_end_of_tree() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();

        // Start at last key
        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        assert_eq!(cursor.get_key(), Some(b"b".as_slice()));

        // Advance should return false (no more entries)
        assert!(!cursor.advance(store.as_ref()));
        assert!(!cursor.is_valid());
    }

    #[test]
    fn test_advance_full_iteration() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        // Insert entries
        let entries = vec![
            (b"a".to_vec(), b"1".to_vec()),
            (b"b".to_vec(), b"2".to_vec()),
            (b"c".to_vec(), b"3".to_vec()),
            (b"d".to_vec(), b"4".to_vec()),
        ];

        for (k, v) in &entries {
            tree = prolly.put(&tree, k.clone(), v.clone()).unwrap();
        }

        // Start at first key
        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        let mut collected: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();

        // Collect all entries via cursor
        while cursor.is_valid() {
            let key = cursor.get_key().unwrap().to_vec();
            let val = cursor.get_value().unwrap().to_vec();
            collected.push((key, val));
            if !cursor.advance(store.as_ref()) {
                break;
            }
        }

        assert_eq!(collected, entries);
    }

    #[test]
    fn test_advance_single_entry() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly
            .put(&tree, b"only".to_vec(), b"one".to_vec())
            .unwrap();

        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"only").unwrap();
        assert!(cursor.is_valid());
        assert_eq!(cursor.get_key(), Some(b"only".as_slice()));

        // Advance should return false (only one entry)
        assert!(!cursor.advance(store.as_ref()));
        assert!(!cursor.is_valid());
    }

    #[test]
    fn test_advance_invalid_cursor() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let tree = prolly.create();

        // Empty tree cursor
        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"any").unwrap();
        assert!(!cursor.is_valid());

        // Advance on invalid cursor should return false
        assert!(!cursor.advance(store.as_ref()));
    }

    // CursorIterator tests

    #[test]
    fn test_cursor_iterator_full_iteration() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        // Insert entries
        let entries = vec![
            (b"a".to_vec(), b"1".to_vec()),
            (b"b".to_vec(), b"2".to_vec()),
            (b"c".to_vec(), b"3".to_vec()),
            (b"d".to_vec(), b"4".to_vec()),
        ];

        for (k, v) in &entries {
            tree = prolly.put(&tree, k.clone(), v.clone()).unwrap();
        }

        // Create cursor at beginning and iterate
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), None);
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        assert_eq!(collected, entries);
    }

    #[test]
    fn test_cursor_iterator_with_end_bound() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();
        tree = prolly.put(&tree, b"d".to_vec(), b"4".to_vec()).unwrap();

        // Iterate from "a" to "c" (exclusive)
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), Some(b"c".to_vec()));
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        let expected = vec![
            (b"a".to_vec(), b"1".to_vec()),
            (b"b".to_vec(), b"2".to_vec()),
        ];
        assert_eq!(collected, expected);
    }

    #[test]
    fn test_cursor_iterator_empty_tree() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let tree = prolly.create();

        let cursor = Cursor::at_item(store.as_ref(), &tree, b"any").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), None);
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        assert!(collected.is_empty());
    }

    #[test]
    fn test_cursor_iterator_single_entry() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly
            .put(&tree, b"only".to_vec(), b"one".to_vec())
            .unwrap();

        let cursor = Cursor::at_item(store.as_ref(), &tree, b"").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), None);
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        assert_eq!(collected, vec![(b"only".to_vec(), b"one".to_vec())]);
    }

    #[test]
    fn test_cursor_iterator_end_bound_at_start() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();

        // End bound "a" is before all keys, should yield nothing
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), Some(b"a".to_vec()));
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        assert!(collected.is_empty());
    }

    #[test]
    fn test_cursor_iterator_start_from_middle() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();
        tree = prolly.put(&tree, b"d".to_vec(), b"4".to_vec()).unwrap();

        // Start from "b" and iterate to end
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), None);
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        let expected = vec![
            (b"b".to_vec(), b"2".to_vec()),
            (b"c".to_vec(), b"3".to_vec()),
            (b"d".to_vec(), b"4".to_vec()),
        ];
        assert_eq!(collected, expected);
    }

    #[test]
    fn test_cursor_iterator_range_middle() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();
        tree = prolly.put(&tree, b"b".to_vec(), b"2".to_vec()).unwrap();
        tree = prolly.put(&tree, b"c".to_vec(), b"3".to_vec()).unwrap();
        tree = prolly.put(&tree, b"d".to_vec(), b"4".to_vec()).unwrap();

        // Range [b, d) - should yield b and c
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"b").unwrap();
        let iter = CursorIterator::new(cursor, store.as_ref(), Some(b"d".to_vec()));
        let collected: Vec<(Vec<u8>, Vec<u8>)> = iter.collect();

        let expected = vec![
            (b"b".to_vec(), b"2".to_vec()),
            (b"c".to_vec(), b"3".to_vec()),
        ];
        assert_eq!(collected, expected);
    }

    // ============================================================
    // Edge Case Unit Tests (Task 9.1)
    // Requirements: 1.5, 3.3, 3.4
    // ============================================================

    /// Test: Empty tree cursor creation
    #[test]
    fn test_empty_tree_cursor_is_invalid() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let tree = prolly.create();

        // Create cursor on empty tree
        let cursor = Cursor::at_item(store.as_ref(), &tree, b"any_key").unwrap();

        // Cursor should be invalid
        assert!(!cursor.is_valid(), "Cursor on empty tree should be invalid");

        // get_key should return None for invalid cursor
        assert_eq!(
            cursor.get_key(),
            None,
            "get_key should return None for empty tree cursor"
        );

        // get_value should return None for invalid cursor
        assert_eq!(
            cursor.get_value(),
            None,
            "get_value should return None for empty tree cursor"
        );

        // is_at_end should handle empty node gracefully
        assert!(
            cursor.is_at_end(),
            "is_at_end should return true for empty tree cursor"
        );
    }

    /// Test: Single-entry tree navigation
    #[test]
    fn test_single_entry_tree_navigation() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        // Insert single entry
        tree = prolly
            .put(&tree, b"only_key".to_vec(), b"only_value".to_vec())
            .unwrap();

        // Create cursor at the key
        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"only_key").unwrap();

        // Cursor should be valid and at the correct position
        assert!(
            cursor.is_valid(),
            "Cursor should be valid for single-entry tree"
        );
        assert_eq!(
            cursor.get_key(),
            Some(b"only_key".as_slice()),
            "Cursor should be at the only key"
        );
        assert_eq!(
            cursor.get_value(),
            Some(b"only_value".as_slice()),
            "Cursor should return the only value"
        );

        // Single entry means cursor is at end of node
        assert!(
            cursor.is_at_end(),
            "Cursor should be at end for single-entry tree"
        );

        // Advance should return false (no more entries)
        assert!(
            !cursor.advance(store.as_ref()),
            "advance should return false for single-entry tree"
        );

        // After advance past end, cursor should be invalid
        assert!(
            !cursor.is_valid(),
            "Cursor should be invalid after advancing past end"
        );
        assert_eq!(
            cursor.get_key(),
            None,
            "get_key should return None after advancing past end"
        );
        assert_eq!(
            cursor.get_value(),
            None,
            "get_value should return None after advancing past end"
        );
    }

    /// Test: Cursor at internal node (get_value returns None)
    #[test]
    fn test_cursor_at_internal_node_get_value_returns_none() {
        use super::super::node::Node;

        // Create an internal node directly (not a leaf)
        let internal_node = Node::builder()
            .keys(vec![b"key1".to_vec(), b"key2".to_vec()])
            .vals(vec![vec![0u8; 32], vec![1u8; 32]]) // CID-like values (32 bytes)
            .leaf(false) // Internal node
            .level(1)
            .build();

        // Create a cursor pointing to this internal node
        let cursor = Cursor {
            index: 0,
            node: Arc::new(internal_node),
            parent: None,
        };

        // Cursor should be valid (node is not empty, index is in bounds)
        assert!(cursor.is_valid(), "Cursor at internal node should be valid");

        // get_key should return the key
        assert_eq!(
            cursor.get_key(),
            Some(b"key1".as_slice()),
            "get_key should return key for internal node"
        );

        // get_value should return None for internal node (not a leaf)
        assert_eq!(
            cursor.get_value(),
            None,
            "get_value should return None for internal node"
        );

        // Test at second index
        let cursor_at_second = Cursor {
            index: 1,
            node: cursor.node.clone(),
            parent: None,
        };

        assert!(
            cursor_at_second.is_valid(),
            "Cursor at second index should be valid"
        );
        assert_eq!(
            cursor_at_second.get_key(),
            Some(b"key2".as_slice()),
            "get_key should return second key"
        );
        assert_eq!(
            cursor_at_second.get_value(),
            None,
            "get_value should still return None for internal node"
        );
    }

    /// Test: Invalid cursor accessors return None
    #[test]
    fn test_invalid_cursor_accessors_return_none() {
        use super::super::node::Node;

        // Case 1: Cursor with empty node
        let empty_node = Node::new_leaf();
        let cursor_empty = Cursor {
            index: 0,
            node: Arc::new(empty_node),
            parent: None,
        };

        assert!(
            !cursor_empty.is_valid(),
            "Cursor with empty node should be invalid"
        );
        assert_eq!(
            cursor_empty.get_key(),
            None,
            "get_key should return None for cursor with empty node"
        );
        assert_eq!(
            cursor_empty.get_value(),
            None,
            "get_value should return None for cursor with empty node"
        );

        // Case 2: Cursor with index out of bounds
        let node_with_data = Node::builder()
            .keys(vec![b"a".to_vec(), b"b".to_vec()])
            .vals(vec![b"1".to_vec(), b"2".to_vec()])
            .leaf(true)
            .build();

        let cursor_out_of_bounds = Cursor {
            index: 5, // Out of bounds (only 2 entries)
            node: Arc::new(node_with_data.clone()),
            parent: None,
        };

        assert!(
            !cursor_out_of_bounds.is_valid(),
            "Cursor with out-of-bounds index should be invalid"
        );
        assert_eq!(
            cursor_out_of_bounds.get_key(),
            None,
            "get_key should return None for out-of-bounds cursor"
        );
        assert_eq!(
            cursor_out_of_bounds.get_value(),
            None,
            "get_value should return None for out-of-bounds cursor"
        );

        // Case 3: Cursor at exactly the boundary (index == len)
        let cursor_at_boundary = Cursor {
            index: 2, // Exactly at len (2 entries, so index 2 is out of bounds)
            node: Arc::new(node_with_data),
            parent: None,
        };

        assert!(
            !cursor_at_boundary.is_valid(),
            "Cursor at boundary should be invalid"
        );
        assert_eq!(
            cursor_at_boundary.get_key(),
            None,
            "get_key should return None for cursor at boundary"
        );
        assert_eq!(
            cursor_at_boundary.get_value(),
            None,
            "get_value should return None for cursor at boundary"
        );
    }

    /// Test: Advance on invalid cursor returns false
    #[test]
    fn test_advance_on_invalid_cursor_returns_false() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let tree = prolly.create();

        // Create cursor on empty tree (invalid cursor)
        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"any").unwrap();
        assert!(
            !cursor.is_valid(),
            "Cursor should be invalid for empty tree"
        );

        // Advance on invalid cursor should return false
        assert!(
            !cursor.advance(store.as_ref()),
            "advance on invalid cursor should return false"
        );

        // Cursor should still be invalid
        assert!(
            !cursor.is_valid(),
            "Cursor should remain invalid after advance"
        );
    }

    /// Test: Multiple advances past end keep cursor invalid
    #[test]
    fn test_multiple_advances_past_end() {
        let store = std::sync::Arc::new(MemStore::new());
        let prolly = Prolly::new(store.clone(), Config::default());
        let mut tree = prolly.create();

        tree = prolly.put(&tree, b"a".to_vec(), b"1".to_vec()).unwrap();

        let mut cursor = Cursor::at_item(store.as_ref(), &tree, b"a").unwrap();
        assert!(cursor.is_valid());

        // First advance past end
        assert!(
            !cursor.advance(store.as_ref()),
            "First advance past end should return false"
        );
        assert!(
            !cursor.is_valid(),
            "Cursor should be invalid after first advance past end"
        );

        // Second advance on already invalid cursor
        assert!(
            !cursor.advance(store.as_ref()),
            "Second advance should also return false"
        );
        assert!(!cursor.is_valid(), "Cursor should remain invalid");

        // Third advance
        assert!(
            !cursor.advance(store.as_ref()),
            "Third advance should also return false"
        );
        assert!(!cursor.is_valid(), "Cursor should still be invalid");

        // Accessors should consistently return None
        assert_eq!(cursor.get_key(), None);
        assert_eq!(cursor.get_value(), None);
    }
}