aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
use super::*;
use crate::core::temporal::{BiTemporalInterval, TIMESTAMP_MAX};

#[test]
fn test_insert_and_find_node_versions() {
    let indexes = TemporalIndexes::new();

    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();
    let v3 = VersionId::new(102).unwrap();

    // v1: [0, 1000)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v2: [1000, 2000)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v3: [2000, 3000)
    indexes
        .insert_node_version(
            node_id,
            v3,
            BiTemporalInterval::new(
                TimeRange::new(2000.into(), 3000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Test overlap logic: Query [500, 1500)
    // v1 overlaps (500 to 1000)
    // v2 overlaps (1000 to 1500)
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(500.into(), 1500.into()).unwrap(),
    );

    assert_eq!(results.len(), 2);
    assert!(results.contains(&v1));
    assert!(results.contains(&v2));
    assert!(!results.contains(&v3));
}

#[test]
fn test_edge_cases_overlap() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    // Overlapping intervals (should be possible in valid time)
    let v1 = VersionId::new(1).unwrap();
    let v2 = VersionId::new(2).unwrap();
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 3000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // Query point at 1500 (both should match)
    let results =
        indexes.find_node_versions_in_valid_time_range(node_id, TimeRange::at(1500.into()));
    assert_eq!(results.len(), 2);
    assert!(results.contains(&v1));
    assert!(results.contains(&v2));

    // Query point at 500 (only v1)
    let results =
        indexes.find_node_versions_in_valid_time_range(node_id, TimeRange::at(500.into()));
    assert_eq!(results.len(), 1);
    assert!(results.contains(&v1));

    // Query point at 2500 (only v2)
    let results =
        indexes.find_node_versions_in_valid_time_range(node_id, TimeRange::at(2500.into()));
    assert_eq!(results.len(), 1);
    assert!(results.contains(&v2));
}

#[test]
fn test_adjacent_intervals() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    let v1 = VersionId::new(1).unwrap();
    let v2 = VersionId::new(2).unwrap();
    // v1: [0, 1000), v2: [1000, 2000)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // Query point at 1000 (only v2 because [start, end) is inclusive-exclusive)
    // Use [1000, 1001) to represent the point 1000
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(1000.into(), 1001.into()).unwrap(),
    );
    assert_eq!(results.len(), 1);
    assert!(results.contains(&v2));

    // Query range [500, 1000) (only v1 because 1000 is exclusive)
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(500.into(), 1000.into()).unwrap(),
    );
    assert_eq!(results.len(), 1);
    assert!(results.contains(&v1));
}

#[test]
fn test_batch_insertion() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    let versions = vec![
        (
            VersionId::new(1).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 10.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            VersionId::new(3).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(20.into(), 30.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            VersionId::new(2).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(10.into(), 20.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
    ];

    indexes
        .insert_node_versions_batch(node_id, versions)
        .unwrap();

    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(5.into(), 25.into()).unwrap(),
    );
    assert_eq!(results.len(), 3);

    // Verify sort order internally (though opaque to API)
    let timelines = indexes.index.get(&EntityId::Node(node_id)).unwrap();
    assert_eq!(timelines.valid.versions[0].start, 0.into());
    assert_eq!(timelines.valid.versions[1].start, 10.into());
    assert_eq!(timelines.valid.versions[2].start, 20.into());
}

#[test]
fn test_transaction_time_range_query() {
    let indexes = TemporalIndexes::new();

    let edge_id = EdgeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    // v1: tx [1000, MAX)
    indexes
        .insert_edge_version(
            edge_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                TimeRange::new(1000.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v2: tx [2000, MAX)
    indexes
        .insert_edge_version(
            edge_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                TimeRange::new(2000.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Query: [1500, 2500)
    let results = indexes.find_edge_versions_in_transaction_time_range(
        edge_id,
        TimeRange::new(1500.into(), 2500.into()).unwrap(),
    );

    assert_eq!(results.len(), 2);
    assert!(results.contains(&v1));
    assert!(results.contains(&v2));
}

#[test]
fn test_multiple_entities() {
    let indexes = TemporalIndexes::new();

    let node1 = NodeId::new(1).unwrap();
    let node2 = NodeId::new(2).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    indexes
        .insert_node_version(node1, v1, BiTemporalInterval::current(1000.into()))
        .unwrap();
    indexes
        .insert_node_version(node2, v2, BiTemporalInterval::current(1000.into()))
        .unwrap();

    let results = indexes.find_node_versions_in_valid_time_range(
        node1,
        TimeRange::new(0.into(), 2000.into()).unwrap(),
    );

    assert_eq!(results.len(), 1);
    assert!(results.contains(&v1));
    assert!(!results.contains(&v2));
}

#[test]
fn test_clear() {
    let indexes = TemporalIndexes::new();

    indexes
        .insert_node_version(
            NodeId::new(1).unwrap(),
            VersionId::new(100).unwrap(),
            BiTemporalInterval::current(1000.into()),
        )
        .unwrap();

    assert!(indexes.version_count() > 0);

    indexes.clear();

    assert_eq!(indexes.version_count(), 0);
}

#[test]
fn test_empty_timeline_query() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    // Query an entity with no versions
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(0.into(), 1000.into()).unwrap(),
    );

    assert_eq!(results.len(), 0, "Empty timeline should return no results");
}

#[test]
fn test_retroactive_single_inserts() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();
    let v3 = VersionId::new(102).unwrap();

    // Insert in non-chronological order to test retroactive insertion
    // v1 at t=0
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v3 at t=20000 (far future)
    indexes
        .insert_node_version(
            node_id,
            v3,
            BiTemporalInterval::new(
                TimeRange::new(20000.into(), 21000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v2 at t=10000 (retroactive - inserted between v1 and v3)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(10000.into(), 11000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Verify correct sort order is maintained
    let entity_id = EntityId::Node(node_id);
    let timelines = indexes.index.get(&entity_id).unwrap();

    assert_eq!(timelines.valid.versions.len(), 3, "Should have 3 versions");
    assert_eq!(
        timelines.valid.versions[0].start,
        0.into(),
        "First version should start at 0"
    );
    // Verify version via metadata resolution
    let idx0 = timelines.valid.versions[0].metadata_index();
    assert_eq!(
        timelines.get_version_metadata(idx0).unwrap().version_id(),
        v1,
        "First version should be v1"
    );
    assert_eq!(
        timelines.valid.versions[1].start,
        10000.into(),
        "Second version should start at 10000"
    );
    let idx1 = timelines.valid.versions[1].metadata_index();
    assert_eq!(
        timelines.get_version_metadata(idx1).unwrap().version_id(),
        v2,
        "Second version should be v2"
    );
    assert_eq!(
        timelines.valid.versions[2].start,
        20000.into(),
        "Third version should start at 20000"
    );
    let idx2 = timelines.valid.versions[2].metadata_index();
    assert_eq!(
        timelines.get_version_metadata(idx2).unwrap().version_id(),
        v3,
        "Third version should be v3"
    );

    // Verify queries work correctly with retroactively inserted versions
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(9000.into(), 11000.into()).unwrap(),
    );
    assert_eq!(results.len(), 1, "Should find 1 version in range");
    assert_eq!(results[0], v2, "Should find v2 in the middle");
}

#[test]
fn test_batch_insert_deduplication() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    // Insert v1 normally (gets metadata_idx = 0)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Insert v2 normally (gets metadata_idx = 1)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Simulate recovery scenario: batch insert including duplicate metadata_idx=0 (with different timing)
    // This would cause memory leak without deduplication
    let mut timelines = indexes.index.get_mut(&EntityId::Node(node_id)).unwrap();

    // Add a new metadata entry for the new version (idx=2)
    let v3 = VersionId::new(102).unwrap();
    let new_metadata_idx = timelines
        .add_version_metadata(TimelineVersionMetadata::new(v3))
        .unwrap();

    let duplicate_entries = vec![
        TimelineEntry {
            start: 0.into(),
            end: 1500.into(), // Different end time (recovery scenario)
            metadata_idx: 0,  // Duplicate of the first entry
        },
        TimelineEntry {
            start: 2000.into(),
            end: 3000.into(),
            metadata_idx: new_metadata_idx,
        },
    ];
    timelines
        .valid
        .insert_batch(duplicate_entries, DeduplicationPolicy::default())
        .unwrap();

    // Verify deduplication worked - should have 3 unique entries, not 4
    assert_eq!(
        timelines.valid.versions.len(),
        3,
        "Deduplication should remove duplicate entry with metadata_idx=0"
    );

    // Verify metadata_idx=0 appears only once
    let idx0_count = timelines
        .valid
        .versions
        .iter()
        .filter(|e| e.metadata_idx == 0)
        .count();
    assert_eq!(
        idx0_count, 1,
        "metadata_idx=0 should appear exactly once after dedup"
    );

    // Verify the kept entry with metadata_idx=0 has the first data (end=1000, not end=1500)
    // dedup_by_key keeps the first occurrence
    let idx0_entry = timelines
        .valid
        .versions
        .iter()
        .find(|e| e.metadata_idx == 0)
        .unwrap();
    assert_eq!(
        idx0_entry.end,
        1000.into(),
        "Should keep first occurrence (end=1000)"
    );
}

#[test]
fn test_batch_insert_deduplication_non_consecutive_first_occurrence() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(200).unwrap();
    let v2 = VersionId::new(201).unwrap();

    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    let mut timelines = indexes.index.get_mut(&EntityId::Node(node_id)).unwrap();
    let v3 = VersionId::new(202).unwrap();
    let new_metadata_idx = timelines
        .add_version_metadata(TimelineVersionMetadata::new(v3))
        .unwrap();

    timelines
        .valid
        .insert_batch(
            vec![
                TimelineEntry {
                    // Duplicate of metadata_idx=0 but with later start, so duplicate entries
                    // are non-consecutive after sorting by start.
                    start: 1500.into(),
                    end: 2500.into(),
                    metadata_idx: 0,
                },
                TimelineEntry {
                    start: 2000.into(),
                    end: 3000.into(),
                    metadata_idx: new_metadata_idx,
                },
            ],
            DeduplicationPolicy::FirstOccurrence,
        )
        .unwrap();

    assert_eq!(
        timelines.valid.versions.len(),
        3,
        "FirstOccurrence must deduplicate non-consecutive duplicate metadata indices"
    );
    let idx0_entries: Vec<_> = timelines
        .valid
        .versions
        .iter()
        .filter(|e| e.metadata_idx == 0)
        .collect();
    assert_eq!(idx0_entries.len(), 1);
    assert_eq!(idx0_entries[0].start, 0.into());
    assert_eq!(idx0_entries[0].end, 1000.into());
}

#[test]
fn test_batch_insert_deduplication_non_consecutive_last_occurrence() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(2).unwrap();
    let v1 = VersionId::new(300).unwrap();
    let v2 = VersionId::new(301).unwrap();

    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    let mut timelines = indexes.index.get_mut(&EntityId::Node(node_id)).unwrap();
    timelines
        .valid
        .insert_batch(
            vec![TimelineEntry {
                // Duplicate of metadata_idx=0 appears after metadata_idx=1 in sorted order.
                start: 1500.into(),
                end: 2500.into(),
                metadata_idx: 0,
            }],
            DeduplicationPolicy::LastOccurrence,
        )
        .unwrap();

    assert_eq!(
        timelines.valid.versions.len(),
        2,
        "LastOccurrence must deduplicate non-consecutive duplicate metadata indices"
    );
    let idx0_entries: Vec<_> = timelines
        .valid
        .versions
        .iter()
        .filter(|e| e.metadata_idx == 0)
        .collect();
    assert_eq!(idx0_entries.len(), 1);
    assert_eq!(idx0_entries[0].start, 1500.into());
    assert_eq!(idx0_entries[0].end, 2500.into());
}

#[test]
fn test_concurrent_entity_writes() {
    use std::sync::Arc;
    use std::thread;

    let indexes = Arc::new(TemporalIndexes::new());
    let num_threads = 10;
    let versions_per_thread = 1000;

    // Spawn multiple threads writing to different entities
    let handles: Vec<_> = (0..num_threads)
        .map(|thread_id| {
            let idx = Arc::clone(&indexes);
            thread::spawn(move || {
                let node_id = NodeId::new(thread_id + 1).unwrap();
                for v in 0..versions_per_thread {
                    let version_id = VersionId::new(thread_id * versions_per_thread + v).unwrap();
                    idx.insert_node_version(
                        node_id,
                        version_id,
                        BiTemporalInterval::new(
                            TimeRange::new(
                                ((v * 1000) as i64).into(),
                                (((v + 1) * 1000) as i64).into(),
                            )
                            .unwrap(),
                            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                        ),
                    )
                    .unwrap();
                }
            })
        })
        .collect();

    // Wait for all threads to complete
    for h in handles {
        h.join().unwrap();
    }

    // Verify all versions were indexed correctly
    for thread_id in 0..num_threads {
        let node_id = NodeId::new(thread_id + 1).unwrap();
        let results = indexes.find_node_versions_in_valid_time_range(
            node_id,
            TimeRange::new(0.into(), ((versions_per_thread * 1000) as i64).into()).unwrap(),
        );
        assert_eq!(
            results.len(),
            versions_per_thread as usize,
            "Thread {} should have {} versions",
            thread_id,
            versions_per_thread
        );
    }

    // Verify total version count (only counts valid timeline)
    assert_eq!(
        indexes.version_count(),
        (num_threads * versions_per_thread) as usize,
        "Total version count should match number of inserts"
    );
}

#[test]
fn test_concurrent_same_entity_contention() {
    use std::sync::Arc;
    use std::thread;
    use std::time::Instant;

    let indexes = Arc::new(TemporalIndexes::new());
    let node_id = NodeId::new(1).unwrap(); // Same entity for all threads
    let num_threads = 8;
    let versions_per_thread = 500;

    let start = Instant::now();

    // Multiple threads writing to THE SAME entity - tests DashMap lock contention
    let handles: Vec<_> = (0..num_threads)
        .map(|thread_id| {
            let idx = Arc::clone(&indexes);
            thread::spawn(move || {
                for v in 0..versions_per_thread {
                    let version_id = VersionId::new(thread_id * versions_per_thread + v).unwrap();
                    idx.insert_node_version(
                        node_id, // Same entity!
                        version_id,
                        BiTemporalInterval::new(
                            TimeRange::new(
                                (((thread_id * versions_per_thread + v) * 100) as i64).into(),
                                ((((thread_id * versions_per_thread + v) + 1) * 100) as i64).into(),
                            )
                            .unwrap(),
                            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                        ),
                    )
                    .unwrap();
                }
            })
        })
        .collect();

    // Wait for all threads to complete
    for h in handles {
        h.join().unwrap();
    }

    let elapsed = start.elapsed();

    // Verify all versions were indexed correctly
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(
            0.into(),
            (((num_threads * versions_per_thread) * 100) as i64).into(),
        )
        .unwrap(),
    );

    assert_eq!(
        results.len(),
        (num_threads * versions_per_thread) as usize,
        "All versions should be indexed despite contention"
    );

    // Verify no deadlocks occurred and performance is reasonable
    // With 8 threads × 500 ops = 4000 total inserts, should complete in < 1 second
    assert!(
        elapsed.as_secs() < 2,
        "Should complete in reasonable time despite contention, took {:?}",
        elapsed
    );

    // Verify timeline is correctly sorted despite concurrent inserts
    let entity_id = EntityId::Node(node_id);
    let timelines = indexes.index.get(&entity_id).unwrap();
    let versions = &timelines.valid.versions;

    for i in 1..versions.len() {
        assert!(
            versions[i - 1].start <= versions[i].start,
            "Timeline must remain sorted despite concurrent writes"
        );
    }
}

#[test]
fn test_very_large_history() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let version_count = 100_000;

    // Insert 100K versions
    for i in 0..version_count {
        let version_id = VersionId::new(i).unwrap();
        indexes
            .insert_node_version(
                node_id,
                version_id,
                BiTemporalInterval::new(
                    TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into())
                        .unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();
    }

    // Query a small range in the middle - should be fast
    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(5_000_000.into(), 5_001_000.into()).unwrap(),
    );

    // Should find ~10 versions in this range
    assert!(
        results.len() >= 10 && results.len() <= 11,
        "Should find ~10 versions in 1000-tick range, found {}",
        results.len()
    );

    // Query the entire timeline - should return all versions
    let all_results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(0.into(), ((version_count * 100) as i64).into()).unwrap(),
    );

    assert_eq!(
        all_results.len(),
        version_count as usize,
        "Should find all versions in full range query"
    );
}

#[test]
fn test_same_start_time_different_versions() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(1).unwrap();
    let v2 = VersionId::new(2).unwrap();

    // Both versions start at time 1000 (e.g., two corrections recorded simultaneously)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 3000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // Query at time 1500 should return both versions
    let results =
        indexes.find_node_versions_in_valid_time_range(node_id, TimeRange::at(1500.into()));
    assert_eq!(
        results.len(),
        2,
        "Both versions should be found when they have the same start time"
    );
    assert!(results.contains(&v1), "Version 1 should be in results");
    assert!(results.contains(&v2), "Version 2 should be in results");

    // Verify timeline is sorted and both entries exist
    let entity_id = EntityId::Node(node_id);
    let timelines = indexes.index.get(&entity_id).unwrap();
    assert_eq!(
        timelines.valid.versions.len(),
        2,
        "Timeline should contain both versions"
    );
    // Both should have start time 1000
    assert_eq!(timelines.valid.versions[0].start, 1000.into());
    assert_eq!(timelines.valid.versions[1].start, 1000.into());
}

#[test]
fn test_batch_insert_equivalence_with_same_start_retroactive_pattern() {
    let node_id = NodeId::new(1).unwrap();
    let versions = vec![
        (
            VersionId::new(1).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(10.into(), 15.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            VersionId::new(2).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(20.into(), 25.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            VersionId::new(3).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(10.into(), 12.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
    ];

    let indexes_individual = TemporalIndexes::new();
    for (version_id, temporal) in &versions {
        indexes_individual
            .insert_node_version(node_id, *version_id, *temporal)
            .unwrap();
    }

    let indexes_batch = TemporalIndexes::new();
    indexes_batch
        .insert_node_versions_batch(node_id, versions)
        .unwrap();

    let entity_id = EntityId::Node(node_id);
    let timelines_individual = indexes_individual.index.get(&entity_id).unwrap();
    let timelines_batch = indexes_batch.index.get(&entity_id).unwrap();

    let individual_entries: Vec<_> = timelines_individual
        .valid
        .versions
        .iter()
        .map(|entry| {
            (
                entry.start,
                entry.end,
                timelines_individual.resolve_version_id(entry.metadata_idx),
            )
        })
        .collect();
    let batch_entries: Vec<_> = timelines_batch
        .valid
        .versions
        .iter()
        .map(|entry| {
            (
                entry.start,
                entry.end,
                timelines_batch.resolve_version_id(entry.metadata_idx),
            )
        })
        .collect();

    assert_eq!(individual_entries, batch_entries);
}

#[test]
fn test_dos_protection_version_limit_node() {
    // Create index with very low limit for testing
    let config = TemporalIndexConfig {
        max_versions_per_entity: 10,
    };
    let indexes = TemporalIndexes::with_config(config);
    let node_id = NodeId::new(1).unwrap();

    // Insert up to the limit - should succeed
    for i in 0..10 {
        let version_id = VersionId::new(i).unwrap();
        let result = indexes.insert_node_version(
            node_id,
            version_id,
            BiTemporalInterval::new(
                TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        );
        assert!(result.is_ok(), "Insert {} should succeed", i);
    }

    // Insert one more - should fail with CapacityExceeded
    let version_id = VersionId::new(10).unwrap();
    let result = indexes.insert_node_version(
        node_id,
        version_id,
        BiTemporalInterval::new(
            TimeRange::new(1000.into(), 1100.into()).unwrap(),
            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
        ),
    );

    assert!(result.is_err(), "Insert beyond limit should fail");
    let err = result.unwrap_err();
    let err_str = err.to_string();
    assert!(
        err_str.contains("Capacity") || err_str.contains("exceeded"),
        "Error should mention capacity: {}",
        err_str
    );
    assert!(
        err_str.contains("versions for entity"),
        "Error should identify the entity: {}",
        err_str
    );

    // Verify the entity still has exactly 10 versions
    let entity_id = EntityId::Node(node_id);
    let timelines = indexes.index.get(&entity_id).unwrap();
    assert_eq!(
        timelines.valid.versions.len(),
        10,
        "Should have exactly 10 versions after rejection"
    );
}

#[test]
fn test_dos_protection_version_limit_edge() {
    // Create index with very low limit for testing
    let config = TemporalIndexConfig {
        max_versions_per_entity: 5,
    };
    let indexes = TemporalIndexes::with_config(config);
    let edge_id = EdgeId::new(1).unwrap();

    // Insert up to the limit - should succeed
    for i in 0..5 {
        let version_id = VersionId::new(i).unwrap();
        let result = indexes.insert_edge_version(
            edge_id,
            version_id,
            BiTemporalInterval::new(
                TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        );
        assert!(result.is_ok(), "Insert {} should succeed", i);
    }

    // Insert one more - should fail
    let version_id = VersionId::new(5).unwrap();
    let result = indexes.insert_edge_version(
        edge_id,
        version_id,
        BiTemporalInterval::new(
            TimeRange::new(500.into(), 600.into()).unwrap(),
            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
        ),
    );

    assert!(result.is_err(), "Insert beyond limit should fail");
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("Capacity") || err_str.contains("exceeded"),
        "Error should mention capacity: {}",
        err_str
    );
}

#[test]
fn test_dos_protection_different_entities_independent() {
    // Verify that limits are per-entity, not global
    let config = TemporalIndexConfig {
        max_versions_per_entity: 5,
    };
    let indexes = TemporalIndexes::with_config(config);

    let node1 = NodeId::new(1).unwrap();
    let node2 = NodeId::new(2).unwrap();

    // Fill node1 to its limit
    for i in 0..5 {
        indexes
            .insert_node_version(
                node1,
                VersionId::new(i).unwrap(),
                BiTemporalInterval::new(
                    TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into())
                        .unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();
    }

    // node2 should still be able to insert (independent limit)
    for i in 0..5 {
        let result = indexes.insert_node_version(
            node2,
            VersionId::new(100 + i).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        );
        assert!(
            result.is_ok(),
            "node2 insert {} should succeed (independent limit)",
            i
        );
    }

    // But node1 should still be at its limit
    let result = indexes.insert_node_version(
        node1,
        VersionId::new(10).unwrap(),
        BiTemporalInterval::new(
            TimeRange::new(500.into(), 600.into()).unwrap(),
            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
        ),
    );
    assert!(result.is_err(), "node1 should still be at limit");
}

#[test]
fn test_dos_protection_batch_insert_respects_limit() {
    let config = TemporalIndexConfig {
        max_versions_per_entity: 10,
    };
    let indexes = TemporalIndexes::with_config(config);
    let node_id = NodeId::new(1).unwrap();

    // Insert 8 versions normally
    for i in 0..8 {
        indexes
            .insert_node_version(
                node_id,
                VersionId::new(i).unwrap(),
                BiTemporalInterval::new(
                    TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into())
                        .unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();
    }

    // Try to batch insert 5 more (would exceed limit of 10)
    let batch = vec![
        (
            VersionId::new(8).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(800.into(), 900.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        ),
        (
            VersionId::new(9).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(900.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        ),
        (
            VersionId::new(10).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 1100.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        ),
    ];

    let result = indexes.insert_node_versions_batch(node_id, batch);

    // Batch should fail because it would exceed limit
    assert!(result.is_err(), "Batch insert exceeding limit should fail");
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("Capacity") || err_str.contains("exceeded"),
        "Error should mention capacity: {}",
        err_str
    );

    // Verify we still have only 8 versions (batch was rejected atomically)
    let entity_id = EntityId::Node(node_id);
    let timelines = indexes.index.get(&entity_id).unwrap();
    assert_eq!(
        timelines.valid.versions.len(),
        8,
        "Should still have 8 versions after batch rejection"
    );
}

#[test]
fn test_dos_protection_default_limit_reasonable() {
    // Verify the default limit is 1,000,000 (reasonable for production)
    let config = TemporalIndexConfig::default();
    assert_eq!(
        config.max_versions_per_entity, 1_000_000,
        "Default limit should be 1 million"
    );

    // Verify we can create indexes with default config
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    // Should be able to insert many versions
    for i in 0..1000 {
        let result = indexes.insert_node_version(
            node_id,
            VersionId::new(i).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        );
        assert!(
            result.is_ok(),
            "Insert {} should succeed with default limit",
            i
        );
    }
}

// ========================================================================
// Bi-temporal Point Query Tests (Issue #194 fix)
// ========================================================================

#[test]
fn test_find_node_version_at_point_basic() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    // v1: valid [0, 1000), tx [0, MAX)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v2: valid [1000, 2000), tx [500, MAX)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(500.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Query at valid_time=500, tx_time=600 should return v1
    let results = indexes.find_node_version_at_point(node_id, 500.into(), 600.into());
    assert_eq!(results.len(), 1, "Should find exactly one version");
    assert_eq!(results[0], v1, "Should find v1");

    // Query at valid_time=1500, tx_time=600 should return v2
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 600.into());
    assert_eq!(results.len(), 1, "Should find exactly one version");
    assert_eq!(results[0], v2, "Should find v2");

    // Query at valid_time=1500, tx_time=400 should return nothing (v2 not recorded yet)
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 400.into());
    assert!(
        results.is_empty(),
        "Should find no versions before v2 was recorded"
    );
}

#[test]
fn test_find_node_version_at_point_empty_index() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    let results = indexes.find_node_version_at_point(node_id, 500.into(), 600.into());
    assert!(results.is_empty(), "Empty index should return no results");
}

#[test]
fn test_find_edge_version_at_point_basic() {
    let indexes = TemporalIndexes::new();
    let edge_id = EdgeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    indexes
        .insert_edge_version(
            edge_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    let results = indexes.find_edge_version_at_point(edge_id, 500.into(), 600.into());
    assert_eq!(results.len(), 1, "Should find exactly one version");
    assert_eq!(results[0], v1, "Should find v1");
}

#[test]
fn test_find_node_version_at_point_overlapping_intervals() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    // v1: valid [0, 2000), tx [0, MAX) - spans the full range
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 2000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // v2: valid [1000, 3000), tx [0, MAX) - overlaps with v1
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 3000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        )
        .unwrap();

    // Query at valid_time=1500, tx_time=100 should return both v1 and v2
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 100.into());
    assert_eq!(results.len(), 2, "Should find both overlapping versions");
    assert!(results.contains(&v1), "Should include v1");
    assert!(results.contains(&v2), "Should include v2");

    // Query at valid_time=500, tx_time=100 should return only v1
    let results = indexes.find_node_version_at_point(node_id, 500.into(), 100.into());
    assert_eq!(results.len(), 1, "Should find only v1");
    assert_eq!(results[0], v1, "Should be v1");

    // Query at valid_time=2500, tx_time=100 should return only v2
    let results = indexes.find_node_version_at_point(node_id, 2500.into(), 100.into());
    assert_eq!(results.len(), 1, "Should find only v2");
    assert_eq!(results[0], v2, "Should be v2");
}

#[test]
fn test_find_node_version_at_point_boundary_conditions() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // v1: valid [1000, 2000), tx [500, 1500)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::new(500.into(), 1500.into()).unwrap(),
            ),
        )
        .unwrap();

    // Just before valid_time start - should not find
    let results = indexes.find_node_version_at_point(node_id, 999.into(), 1000.into());
    assert!(
        results.is_empty(),
        "Should not find version before valid_time start"
    );

    // At valid_time start - should find (inclusive start)
    let results = indexes.find_node_version_at_point(node_id, 1000.into(), 1000.into());
    assert_eq!(results.len(), 1, "Should find at valid_time start");

    // Just before valid_time end - should find
    let results = indexes.find_node_version_at_point(node_id, 1999.into(), 1000.into());
    assert_eq!(results.len(), 1, "Should find just before valid_time end");

    // At valid_time end - should not find (exclusive end)
    let results = indexes.find_node_version_at_point(node_id, 2000.into(), 1000.into());
    assert!(
        results.is_empty(),
        "Should not find at valid_time end (exclusive)"
    );

    // Just before tx_time start - should not find
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 499.into());
    assert!(results.is_empty(), "Should not find before tx_time start");

    // At tx_time end - should not find (exclusive end)
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 1500.into());
    assert!(
        results.is_empty(),
        "Should not find at tx_time end (exclusive)"
    );
}

// Property-based tests using proptest
mod proptests {
    use super::*;
    use proptest::prelude::*;

    // Strategy for generating valid timestamps (avoid overflow)
    fn timestamp_strategy() -> impl Strategy<Value = i64> {
        0i64..1_000_000_000i64
    }

    // Strategy for generating time ranges
    fn time_range_strategy() -> impl Strategy<Value = (i64, i64)> {
        timestamp_strategy().prop_flat_map(|start| (Just(start), (start + 1)..=(start + 10_000)))
    }

    // Strategy for generating unique version entries (to avoid duplicates)
    fn unique_version_entries_strategy(
        size: impl Into<proptest::collection::SizeRange>,
    ) -> impl Strategy<Value = Vec<(VersionId, BiTemporalInterval)>> {
        prop::collection::btree_map(
            0u64..10_000u64,       // Key generator (VersionId)
            time_range_strategy(), // Value generator (TimeRange)
            size,
        )
        .prop_flat_map(|map| {
            let vec: Vec<_> = map
                .into_iter()
                .map(|(vid, (start, end))| {
                    (
                        VersionId::new(vid).unwrap(),
                        BiTemporalInterval::new(
                            TimeRange::new(start.into(), end.into()).unwrap(),
                            TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                        ),
                    )
                })
                .collect();
            // Shuffle the vector to ensure random insertion order
            Just(vec).prop_shuffle()
        })
    }

    proptest! {
        /// Property: Inserting versions in any order should produce the same sorted timeline
        #[test]
        fn prop_insert_order_irrelevant(
            versions in unique_version_entries_strategy(1..100)
        ) {
            let indexes = TemporalIndexes::new();
            let node_id = NodeId::new(1).unwrap();

            // Insert in original order
            for (version_id, temporal) in &versions {
                indexes.insert_node_version(node_id, *version_id, *temporal).unwrap();
            }

            // Get the timeline and resolve version IDs before clearing
            let entity_id = EntityId::Node(node_id);
            let timelines1 = indexes.index.get(&entity_id).unwrap();
            let timeline1_entries: Vec<_> = timelines1.valid.versions.iter().map(|e| {
                (e.start, e.end, timelines1.resolve_version_id(e.metadata_idx))
            }).collect();
            drop(timelines1);

            // Clear and insert in shuffled order
            indexes.clear();
            let mut shuffled = versions.clone();
            shuffled.sort_by_key(|(vid, _)| *vid); // Sort by version ID (different order)
            for (version_id, temporal) in shuffled {
                indexes.insert_node_version(node_id, version_id, temporal).unwrap();
            }

            let timelines2 = indexes.index.get(&entity_id).unwrap();
            let timeline2_entries: Vec<_> = timelines2.valid.versions.iter().map(|e| {
                (e.start, e.end, timelines2.resolve_version_id(e.metadata_idx))
            }).collect();

            // Both timelines should be sorted by start time
            for i in 1..timeline1_entries.len() {
                prop_assert!(timeline1_entries[i-1].0 <= timeline1_entries[i].0);
            }
            for i in 1..timeline2_entries.len() {
                prop_assert!(timeline2_entries[i-1].0 <= timeline2_entries[i].0);
            }

            // Canonicalize order for comparison:
            // Internal order of elements with equal start time depends on insertion order (metadata_idx),
            // which changes when we shuffle the input. To compare sets, we must sort deterministically.
            let mut t1_sorted = timeline1_entries.clone();
            t1_sorted.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));

            let mut t2_sorted = timeline2_entries.clone();
            t2_sorted.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));

            // Both timelines should have the same versions
            prop_assert_eq!(t1_sorted, t2_sorted);
        }

        /// Property: Time range queries should return exactly the versions that overlap
        #[test]
        fn prop_range_query_correctness(
            versions in unique_version_entries_strategy(1..50),
            query_range in time_range_strategy()
        ) {
            let indexes = TemporalIndexes::new();
            let node_id = NodeId::new(1).unwrap();

            // Insert all versions
            for (version_id, temporal) in &versions {
                indexes.insert_node_version(node_id, *version_id, *temporal).unwrap();
            }

            // Query the range
            let query_time_range = TimeRange::new(query_range.0.into(), query_range.1.into()).unwrap();
            let results = indexes.find_node_versions_in_valid_time_range(node_id, query_time_range);

            // Manually compute expected results
            let mut expected: Vec<VersionId> = versions
                .iter()
                .filter(|(_, temporal)| {
                    let valid = temporal.valid_time();
                    // Check overlap: version.end > query.start && version.start < query.end
                    valid.end() > query_range.0.into() && valid.start() < query_range.1.into()
                })
                .map(|(vid, _)| *vid)
                .collect();

            // Sort both for comparison (query results may not be in insertion order)
            let mut results_sorted = results.clone();
            results_sorted.sort();
            expected.sort();

            prop_assert_eq!(results_sorted, expected, "Query returned incorrect versions");
        }

        /// Property: Batch insert should be equivalent to individual inserts (when no duplicates)
        #[test]
        fn prop_batch_insert_equivalence(
            versions in unique_version_entries_strategy(1..50)
        ) {
            let node_id = NodeId::new(1).unwrap();

            // Individual inserts
            let indexes1 = TemporalIndexes::new();
            for (version_id, temporal) in &versions {
                indexes1.insert_node_version(node_id, *version_id, *temporal).unwrap();
            }

            // Batch insert
            let indexes2 = TemporalIndexes::new();
            indexes2.insert_node_versions_batch(node_id, versions.clone()).unwrap();

            // Both should produce identical timelines
            let entity_id = EntityId::Node(node_id);
            let timelines1 = indexes1.index.get(&entity_id).unwrap();
            let timelines2 = indexes2.index.get(&entity_id).unwrap();

            prop_assert_eq!(timelines1.valid.versions.len(), timelines2.valid.versions.len());
            for i in 0..timelines1.valid.versions.len() {
                let e1 = &timelines1.valid.versions[i];
                let e2 = &timelines2.valid.versions[i];
                prop_assert_eq!(e1.start, e2.start);
                prop_assert_eq!(e1.end, e2.end);
                // Compare resolved version IDs
                let v1 = timelines1.resolve_version_id(e1.metadata_idx);
                let v2 = timelines2.resolve_version_id(e2.metadata_idx);
                prop_assert_eq!(v1, v2);
            }
        }

        /// Property: Timeline should remain sorted after random retroactive inserts
        #[test]
        fn prop_retroactive_inserts_maintain_order(
            versions in unique_version_entries_strategy(1..100)
        ) {
            let indexes = TemporalIndexes::new();
            let node_id = NodeId::new(1).unwrap();

            // Insert versions in random order (simulates retroactive inserts)
            for (version_id, temporal) in &versions {
                indexes.insert_node_version(node_id, *version_id, *temporal).unwrap();
            }

            // Verify timeline is sorted
            let entity_id = EntityId::Node(node_id);
            let timeline = indexes.index.get(&entity_id).unwrap().valid.versions.clone();

            for i in 1..timeline.len() {
                prop_assert!(
                    timeline[i-1].start <= timeline[i].start,
                    "Timeline not sorted: timeline[{}].start={} > timeline[{}].start={}",
                    i-1, timeline[i-1].start, i, timeline[i].start
                );
            }
        }

        /// Property: Point queries should return subset of range queries
        #[test]
        fn prop_point_query_subset_of_range(
            versions in unique_version_entries_strategy(1..50),
            point in timestamp_strategy()
        ) {
            let indexes = TemporalIndexes::new();
            let node_id = NodeId::new(1).unwrap();

            // Insert all versions
            for (version_id, temporal) in &versions {
                indexes.insert_node_version(node_id, *version_id, *temporal).unwrap();
            }

            // Point query
            let point_results = indexes.find_node_versions_in_valid_time_range(
                node_id,
                TimeRange::new(point.into(), (point + 1).into()).unwrap()
            );

            // Range query covering the point
            let range_results = indexes.find_node_versions_in_valid_time_range(
                node_id,
                TimeRange::new((point - 1000).into(), (point + 1000).into()).unwrap()
            );

            // Every version from point query should be in range query
            for version_id in point_results {
                prop_assert!(
                    range_results.contains(&version_id),
                    "Point query returned version not in range query: {:?}",
                    version_id
                );
            }
        }

        /// Property: Timeline remains sorted after batch insert
        #[test]
        fn prop_batch_maintains_sort_order(
            versions in unique_version_entries_strategy(1..50)
        ) {
            let indexes = TemporalIndexes::new();
            let node_id = NodeId::new(1).unwrap();

            // Batch insert
            indexes.insert_node_versions_batch(node_id, versions).unwrap();

            // Get timeline
            let entity_id = EntityId::Node(node_id);
            if let Some(timelines) = indexes.index.get(&entity_id) {
                let timeline = &timelines.valid.versions;

                // Verify timeline is sorted by start time
                for i in 1..timeline.len() {
                    prop_assert!(
                        timeline[i-1].start <= timeline[i].start,
                        "Timeline must be sorted by start time"
                    );
                }

                // Verify no consecutive duplicates (same metadata index + start time)
                for i in 1..timeline.len() {
                    if timeline[i-1].start == timeline[i].start {
                        prop_assert!(
                            timeline[i-1].metadata_idx != timeline[i].metadata_idx,
                            "No consecutive entries with same start time and metadata index"
                        );
                    }
                }
            }
        }
    }
}

// ============================================================
// Tests for Issue #196: Consolidated Version Metadata Storage
// ============================================================
// These tests verify that version metadata is stored in a single
// authoritative storage structure, eliminating duplication between
// valid-time and transaction-time indexes.

mod consolidated_storage_tests {
    use super::*;

    /// Test that version metadata is stored only once per version,
    /// not duplicated across valid and transaction timelines.
    #[test]
    fn test_version_metadata_stored_once() {
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();
        let v1 = VersionId::new(100).unwrap();

        // Insert a version
        indexes
            .insert_node_version(
                node_id,
                v1,
                BiTemporalInterval::new(
                    TimeRange::new(0.into(), 1000.into()).unwrap(),
                    TimeRange::new(500.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();

        // Access the internal structure and verify version metadata count
        let entity_id = EntityId::Node(node_id);
        let timelines = indexes.index.get(&entity_id).unwrap();

        // The version_metadata_count should equal the number of unique versions,
        // NOT the sum of valid + tx timeline entries
        assert_eq!(
            timelines.version_metadata_count(),
            1,
            "Version metadata should be stored exactly once, not duplicated"
        );

        // Both timelines should reference the same metadata via index
        assert_eq!(timelines.valid.versions.len(), 1);
        assert_eq!(timelines.tx.versions.len(), 1);
    }

    /// Test that multiple versions are stored efficiently without duplication.
    #[test]
    fn test_multiple_versions_no_duplication() {
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();

        // Insert 100 versions
        for i in 0..100 {
            let version_id = VersionId::new(i).unwrap();
            let start = (i * 1000) as i64;
            indexes
                .insert_node_version(
                    node_id,
                    version_id,
                    BiTemporalInterval::new(
                        TimeRange::new(start.into(), (start + 1000).into()).unwrap(),
                        TimeRange::new(start.into(), TIMESTAMP_MAX).unwrap(),
                    ),
                )
                .unwrap();
        }

        let entity_id = EntityId::Node(node_id);
        let timelines = indexes.index.get(&entity_id).unwrap();

        // Should have exactly 100 version metadata entries (not 200)
        assert_eq!(
            timelines.version_metadata_count(),
            100,
            "Should store 100 unique versions, not 200 (duplicated)"
        );

        // Both timelines should have 100 entries referencing the metadata
        assert_eq!(timelines.valid.versions.len(), 100);
        assert_eq!(timelines.tx.versions.len(), 100);
    }

    /// Test that queries still return correct VersionIds after consolidation.
    #[test]
    fn test_queries_return_version_ids_correctly() {
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();
        let v1 = VersionId::new(100).unwrap();
        let v2 = VersionId::new(101).unwrap();
        let v3 = VersionId::new(102).unwrap();

        // Insert versions with different valid/tx time ranges
        indexes
            .insert_node_version(
                node_id,
                v1,
                BiTemporalInterval::new(
                    TimeRange::new(0.into(), 1000.into()).unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();

        indexes
            .insert_node_version(
                node_id,
                v2,
                BiTemporalInterval::new(
                    TimeRange::new(1000.into(), 2000.into()).unwrap(),
                    TimeRange::new(500.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();

        indexes
            .insert_node_version(
                node_id,
                v3,
                BiTemporalInterval::new(
                    TimeRange::new(2000.into(), 3000.into()).unwrap(),
                    TimeRange::new(1000.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();

        // Valid time range query should return correct VersionIds
        let results = indexes.find_node_versions_in_valid_time_range(
            node_id,
            TimeRange::new(500.into(), 1500.into()).unwrap(),
        );
        assert_eq!(results.len(), 2);
        assert!(results.contains(&v1));
        assert!(results.contains(&v2));

        // Transaction time range query should return correct VersionIds
        let results = indexes.find_node_versions_in_transaction_time_range(
            node_id,
            TimeRange::new(600.into(), 800.into()).unwrap(),
        );
        assert_eq!(results.len(), 2);
        assert!(results.contains(&v1));
        assert!(results.contains(&v2));

        // Bi-temporal point query should return correct VersionId
        let results = indexes.find_node_version_at_point(node_id, 1500.into(), 1500.into());
        assert_eq!(results.len(), 1);
        assert!(results.contains(&v2));
    }

    /// Test batch insertion maintains consolidated storage.
    #[test]
    fn test_batch_insert_consolidated_storage() {
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();

        let versions: Vec<_> = (0..50)
            .map(|i| {
                let version_id = VersionId::new(i).unwrap();
                let start = (i * 100) as i64;
                (
                    version_id,
                    BiTemporalInterval::new(
                        TimeRange::new(start.into(), (start + 100).into()).unwrap(),
                        TimeRange::new(start.into(), TIMESTAMP_MAX).unwrap(),
                    ),
                )
            })
            .collect();

        indexes
            .insert_node_versions_batch(node_id, versions)
            .unwrap();

        let entity_id = EntityId::Node(node_id);
        let timelines = indexes.index.get(&entity_id).unwrap();

        // Batch insert should also maintain consolidated storage
        assert_eq!(
            timelines.version_metadata_count(),
            50,
            "Batch insert should store 50 unique versions, not 100"
        );
    }

    /// Test that version_count reports correct total across all entities.
    #[test]
    fn test_version_count_reflects_consolidated_storage() {
        let indexes = TemporalIndexes::new();

        // Insert 10 versions for node 1
        let node1 = NodeId::new(1).unwrap();
        for i in 0..10 {
            indexes
                .insert_node_version(
                    node1,
                    VersionId::new(i).unwrap(),
                    BiTemporalInterval::new(
                        TimeRange::new((i as i64 * 100).into(), ((i as i64 + 1) * 100).into())
                            .unwrap(),
                        TimeRange::from(0.into()),
                    ),
                )
                .unwrap();
        }

        // Insert 5 versions for node 2
        let node2 = NodeId::new(2).unwrap();
        for i in 10..15 {
            indexes
                .insert_node_version(
                    node2,
                    VersionId::new(i).unwrap(),
                    BiTemporalInterval::new(
                        TimeRange::new((i as i64 * 100).into(), ((i as i64 + 1) * 100).into())
                            .unwrap(),
                        TimeRange::from(0.into()),
                    ),
                )
                .unwrap();
        }

        // Total version count should be 15, not 30
        assert_eq!(
            indexes.version_count(),
            15,
            "version_count should reflect consolidated storage (15 versions, not 30)"
        );
    }

    /// Test memory efficiency: TimelineVersionMetadata storage should be smaller
    /// than storing duplicate data in both timelines.
    #[test]
    fn test_memory_layout_efficiency() {
        // This test verifies the memory layout is correct for the
        // consolidated storage approach.

        // TimelineEntry should store an index (u32 or usize), not VersionId directly
        // TimelineVersionMetadata should be stored separately

        // Size of consolidated approach:
        // - TimelineEntry: start (16 bytes) + end (16 bytes) + index (4 bytes) = 36 bytes
        // - TimelineVersionMetadata: version_id (8 bytes) = 8 bytes per unique version
        // - Total for N versions: N * 36 * 2 (both timelines) + N * 8 = 80N bytes

        // Size of old approach:
        // - TimelineEntry: start (16) + end (16) + version_id (8) = 40 bytes
        // - Total for N versions: N * 40 * 2 = 80N bytes

        // With additional metadata, consolidated approach saves more:
        // - If we add more fields to TimelineVersionMetadata (e.g., entity_id, temporal),
        //   it's stored once vs twice

        // For now, verify the structural change is in place
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();
        let v1 = VersionId::new(42).unwrap();

        indexes
            .insert_node_version(
                node_id,
                v1,
                BiTemporalInterval::new(
                    TimeRange::new(0.into(), 1000.into()).unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();

        // Verify we can retrieve the version metadata
        let entity_id = EntityId::Node(node_id);
        let timelines = indexes.index.get(&entity_id).unwrap();

        // Get version metadata and verify it contains the correct version_id
        let metadata = timelines.get_version_metadata(0);
        assert!(
            metadata.is_some(),
            "Should be able to retrieve version metadata by index"
        );
        assert_eq!(
            metadata.unwrap().version_id(),
            v1,
            "Version metadata should contain the correct version_id"
        );
    }

    /// Test that timeline entries reference metadata via index.
    #[test]
    fn test_timeline_entries_use_metadata_index() {
        let indexes = TemporalIndexes::new();
        let node_id = NodeId::new(1).unwrap();

        // Insert multiple versions
        for i in 0..5 {
            indexes
                .insert_node_version(
                    node_id,
                    VersionId::new(i * 10).unwrap(),
                    BiTemporalInterval::new(
                        TimeRange::new((i as i64 * 100).into(), ((i as i64 + 1) * 100).into())
                            .unwrap(),
                        TimeRange::from(0.into()),
                    ),
                )
                .unwrap();
        }

        let entity_id = EntityId::Node(node_id);
        let timelines = indexes.index.get(&entity_id).unwrap();

        // Verify that valid and tx timelines reference the same metadata indices
        assert_eq!(timelines.valid.versions.len(), 5);
        assert_eq!(timelines.tx.versions.len(), 5);

        // Both timelines should have entries that, when resolved, give the same VersionIds
        for i in 0..5 {
            let valid_entry = &timelines.valid.versions[i];
            let tx_entry = &timelines.tx.versions[i];

            // Get version_id through metadata resolution
            let valid_version = timelines
                .get_version_metadata(valid_entry.metadata_index())
                .unwrap()
                .version_id();
            let tx_version = timelines
                .get_version_metadata(tx_entry.metadata_index())
                .unwrap()
                .version_id();

            // Both should resolve to the same VersionId
            assert_eq!(
                valid_version, tx_version,
                "Valid and tx entries for same version should resolve to same VersionId"
            );
        }
    }
}

/// Test for iterator-based find_indices_in_range (TDD - Issue #197)
///
/// This test demonstrates the performance benefits of iterator-based access:
/// 1. Count results without allocation
/// 2. Get first result without collecting all
/// 3. Lazy evaluation for partial result processing
#[test]
fn test_find_indices_in_range_iterator() {
    let mut timeline = EntityTimeline::default();

    // Create 10 versions with non-overlapping intervals
    for i in 0..10 {
        timeline.insert((i * 100).into(), ((i + 1) * 100).into(), i as u32);
    }

    // Test 1: Count without allocation
    // Query range [250, 550) should overlap with versions 2, 3, 4, 5
    let range = TimeRange::new(250.into(), 550.into()).unwrap();
    let count = timeline.find_indices_in_range_iter(range).count();
    assert_eq!(count, 4, "Should find 4 overlapping versions");

    // Test 2: Get first result without collecting all
    let first = timeline.find_indices_in_range_iter(range).next();
    assert_eq!(first, Some(2), "First result should be version 2");

    // Test 3: Collect to vec when needed (same behavior as old API)
    let collected: Vec<_> = timeline.find_indices_in_range_iter(range).collect();
    assert_eq!(collected.len(), 4);
    assert_eq!(collected[0], 2);
    assert_eq!(collected[1], 3);
    assert_eq!(collected[2], 4);
    assert_eq!(collected[3], 5);

    // Test 4: Iterator can be filtered/mapped without extra allocations
    let sum: u32 = timeline.find_indices_in_range_iter(range).sum();
    assert_eq!(sum, 2 + 3 + 4 + 5, "Sum of indices should be 14");

    // Test 5: Point query (small range)
    let point_range = TimeRange::at(250.into());
    let point_results: Vec<_> = timeline.find_indices_in_range_iter(point_range).collect();
    assert_eq!(point_results.len(), 1);
    assert_eq!(point_results[0], 2);
}

/// Test for iterator-based find_indices_at_point (TDD - Issue #197)
#[test]
fn test_find_indices_at_point_iterator() {
    let mut timeline = EntityTimeline::default();

    // Create overlapping versions at timestamp 1000
    timeline.insert(500.into(), 1500.into(), 0);
    timeline.insert(800.into(), 1200.into(), 1);
    timeline.insert(1100.into(), 2000.into(), 2);

    // Test 1: Count overlapping versions
    let count = timeline.find_indices_at_point_iter(1000.into()).count();
    assert_eq!(count, 2, "Should find 2 versions at timestamp 1000");

    // Test 2: Get first result
    let first = timeline.find_indices_at_point_iter(1000.into()).next();
    assert_eq!(first, Some(0), "First result should be version 0");

    // Test 3: Collect all results
    let collected: Vec<_> = timeline.find_indices_at_point_iter(1000.into()).collect();
    assert_eq!(collected.len(), 2);
    assert!(collected.contains(&0));
    assert!(collected.contains(&1));
    assert!(!collected.contains(&2));
}

/// Test for public iterator-based find_node_version_at_point_iter (Issue #197)
///
/// This tests the zero-allocation iterator API for bi-temporal point queries,
/// demonstrating the performance benefits for common use cases.
#[test]
fn test_find_node_version_at_point_iterator() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    // Create 3 overlapping versions at different times
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();
    let v3 = VersionId::new(102).unwrap();

    // v1: valid [0, 2000), tx [0, MAX)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // v2: valid [1000, 3000), tx [500, MAX)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 3000.into()).unwrap(),
                TimeRange::from(500.into()),
            ),
        )
        .unwrap();

    // v3: valid [1500, 4000), tx [1000, MAX)
    indexes
        .insert_node_version(
            node_id,
            v3,
            BiTemporalInterval::new(
                TimeRange::new(1500.into(), 4000.into()).unwrap(),
                TimeRange::from(1000.into()),
            ),
        )
        .unwrap();

    // Test 1: Get first result only
    // Query at valid_time=1600, tx_time=1200
    // v1: valid [0, 2000) ✓, tx [0, MAX) ✓ → MATCH
    // v2: valid [1000, 3000) ✓, tx [500, MAX) ✓ → MATCH
    // v3: valid [1500, 4000) ✓, tx [1000, MAX) ✓ → MATCH
    // All 3 versions are visible at this point
    let first = indexes
        .find_node_version_at_point_iter(node_id, 1600.into(), 1200.into())
        .next();
    assert!(first.is_some(), "Should find at least one version");
    // Any of the three versions could be first
    assert!(
        first == Some(v1) || first == Some(v2) || first == Some(v3),
        "First result should be one of the matching versions"
    );

    // Test 2: Count results
    let count = indexes
        .find_node_version_at_point_iter(node_id, 1600.into(), 1200.into())
        .count();
    assert_eq!(count, 3, "Should find 3 versions at this point");

    // Test 3: Collect to verify behavior matches Vec-based API
    let iter_results: Vec<_> = indexes
        .find_node_version_at_point_iter(node_id, 1600.into(), 1200.into())
        .collect();
    let vec_results = indexes.find_node_version_at_point(node_id, 1600.into(), 1200.into());

    assert_eq!(iter_results.len(), vec_results.len());
    for version_id in &iter_results {
        assert!(
            vec_results.contains(version_id),
            "Iterator results should match Vec results"
        );
    }

    // Test 4: Query at point with no results
    let empty_count = indexes
        .find_node_version_at_point_iter(node_id, 5000.into(), 5000.into())
        .count();
    assert_eq!(empty_count, 0, "Should find no versions outside time range");

    // Test 5: Query for non-existent node
    let missing_node = NodeId::new(999).unwrap();
    let missing_count = indexes
        .find_node_version_at_point_iter(missing_node, 1000.into(), 1000.into())
        .count();
    assert_eq!(missing_count, 0, "Should find no versions for missing node");
}

/// Test for public iterator-based find_edge_version_at_point_iter (Issue #197)
#[test]
fn test_find_edge_version_at_point_iterator() {
    let indexes = TemporalIndexes::new();
    let edge_id = EdgeId::new(1).unwrap();

    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    // v1: valid [0, 1500), tx [0, MAX)
    indexes
        .insert_edge_version(
            edge_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1500.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // v2: valid [1000, 2000), tx [500, MAX)
    indexes
        .insert_edge_version(
            edge_id,
            v2,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(500.into()),
            ),
        )
        .unwrap();

    // Test 1: Get first result
    let first = indexes
        .find_edge_version_at_point_iter(edge_id, 1200.into(), 600.into())
        .next();
    assert!(first.is_some());

    // Test 2: Verify consistency with Vec-based API
    let iter_results: Vec<_> = indexes
        .find_edge_version_at_point_iter(edge_id, 1200.into(), 600.into())
        .collect();
    let vec_results = indexes.find_edge_version_at_point(edge_id, 1200.into(), 600.into());

    assert_eq!(iter_results.len(), vec_results.len());
    for version_id in &iter_results {
        assert!(vec_results.contains(version_id));
    }
}

/// Test update_node_valid_time_end - Issue #209
#[test]
fn test_update_node_valid_time_end() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // Insert version with open-ended valid time
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::from(1000.into()), // open-ended
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // Should find version at time 2000
    let results = indexes.find_node_version_at_point(node_id, 2000.into(), 100.into());
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], v1);

    // Close the valid time interval
    indexes.update_node_valid_time_end(node_id, v1, 1500.into());

    // Should still find at time 1200 (within closed interval)
    let results = indexes.find_node_version_at_point(node_id, 1200.into(), 100.into());
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], v1);

    // Should NOT find at time 2000 (after closed interval)
    let results = indexes.find_node_version_at_point(node_id, 2000.into(), 100.into());
    assert_eq!(results.len(), 0);
}

/// Test update_edge_transaction_time_end - Issue #209
#[test]
fn test_update_edge_transaction_time_end() {
    let indexes = TemporalIndexes::new();
    let edge_id = EdgeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // Insert version with open-ended transaction time
    indexes
        .insert_edge_version(
            edge_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(500.into()), // open-ended
            ),
        )
        .unwrap();

    // Should find version at tx_time 1000
    let results = indexes.find_edge_version_at_point(edge_id, 1500.into(), 1000.into());
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], v1);

    // Close the transaction time interval
    indexes.update_edge_transaction_time_end(edge_id, v1, 800.into());

    // Should still find at tx_time 600 (within closed interval)
    let results = indexes.find_edge_version_at_point(edge_id, 1500.into(), 600.into());
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], v1);

    // Should NOT find at tx_time 1000 (after closed interval)
    let results = indexes.find_edge_version_at_point(edge_id, 1500.into(), 1000.into());
    assert_eq!(results.len(), 0);
}

/// Test update with multiple versions - Issue #209
#[test]
fn test_update_multiple_versions() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();
    let v3 = VersionId::new(102).unwrap();

    // Insert three versions with overlapping intervals
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(TimeRange::from(1000.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(TimeRange::from(2000.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    indexes
        .insert_node_version(
            node_id,
            v3,
            BiTemporalInterval::new(TimeRange::from(3000.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    // Close v1's interval
    indexes.update_node_valid_time_end(node_id, v1, 2000.into());

    // Close v2's interval
    indexes.update_node_valid_time_end(node_id, v2, 3000.into());

    // v1 should be found only before 2000
    let results = indexes.find_node_version_at_point(node_id, 1500.into(), 100.into());
    assert_eq!(results, vec![v1]);

    // v2 should be found between 2000 and 3000
    let results = indexes.find_node_version_at_point(node_id, 2500.into(), 100.into());
    assert_eq!(results, vec![v2]);

    // v3 should be found after 3000
    let results = indexes.find_node_version_at_point(node_id, 3500.into(), 100.into());
    assert_eq!(results, vec![v3]);
}

/// Test concurrent updates (Issue #209 - thread safety)
#[test]
fn test_concurrent_updates() {
    use std::sync::Arc;
    use std::thread;

    let indexes = Arc::new(TemporalIndexes::new());
    let node_id = NodeId::new(1).unwrap();

    // Insert 100 versions from main thread
    for i in 0..100 {
        let v_id = VersionId::new(i).unwrap();
        indexes
            .insert_node_version(
                node_id,
                v_id,
                BiTemporalInterval::new(
                    TimeRange::from(((i * 1000) as i64).into()),
                    TimeRange::from(0.into()),
                ),
            )
            .unwrap();
    }

    // Spawn threads to close intervals concurrently
    let mut handles = vec![];
    for i in 0..10 {
        let indexes_clone = Arc::clone(&indexes);
        let handle = thread::spawn(move || {
            for j in 0..10 {
                let idx = i * 10 + j;
                let v_id = VersionId::new(idx).unwrap();
                indexes_clone.update_node_valid_time_end(
                    node_id,
                    v_id,
                    (((idx + 1) * 1000) as i64).into(),
                );
            }
        });
        handles.push(handle);
    }

    // Wait for all threads
    for handle in handles {
        handle.join().unwrap();
    }

    // Verify all intervals were closed correctly
    for i in 0..100 {
        let v_id = VersionId::new(i).unwrap();
        let query_time = (((i * 1000) + 500) as i64).into();

        let results = indexes.find_node_version_at_point(node_id, query_time, 100.into());
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], v_id);

        // Should NOT find after closed interval
        let query_time = (((i + 1) * 1000 + 500) as i64).into();
        let results = indexes.find_node_version_at_point(node_id, query_time, 100.into());
        // Should find the next version (if it exists) or nothing
        if i < 99 {
            assert_eq!(results.len(), 1);
            assert_eq!(results[0], VersionId::new(i + 1).unwrap());
        }
    }
}

#[test]
fn test_deduplication_policy_variants() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // 1. Test FirstOccurrence (Default)
    let batch_first = vec![
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(), // Later start
                TimeRange::from(0.into()),
            ),
        ),
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(500.into(), 1500.into()).unwrap(), // Earlier start
                TimeRange::from(0.into()),
            ),
        ),
    ];
    indexes
        .insert_node_versions_batch_with_policy(
            node_id,
            batch_first,
            DeduplicationPolicy::FirstOccurrence,
        )
        .unwrap();

    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(0.into(), 5000.into()).unwrap(),
    );
    assert_eq!(results.len(), 1);
    // Verify earliest-start wins: point query at 600 should match
    assert_eq!(
        indexes
            .find_node_versions_in_valid_time_range(node_id, TimeRange::at(600.into()))
            .len(),
        1
    );
    // point query at 1800 should NOT match
    assert_eq!(
        indexes
            .find_node_versions_in_valid_time_range(node_id, TimeRange::at(1800.into()))
            .len(),
        0
    );

    // 2. Test LastOccurrence
    indexes.clear();
    let batch_last = vec![
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(), // Later start
                TimeRange::from(0.into()),
            ),
        ),
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(500.into(), 1500.into()).unwrap(), // Earlier start
                TimeRange::from(0.into()),
            ),
        ),
    ];
    indexes
        .insert_node_versions_batch_with_policy(
            node_id,
            batch_last,
            DeduplicationPolicy::LastOccurrence,
        )
        .unwrap();

    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(0.into(), 5000.into()).unwrap(),
    );
    assert_eq!(results.len(), 1);
    // Verify latest-start wins: point query at 1800 should match
    assert_eq!(
        indexes
            .find_node_versions_in_valid_time_range(node_id, TimeRange::at(1800.into()))
            .len(),
        1
    );
    // point query at 600 should NOT match
    assert_eq!(
        indexes
            .find_node_versions_in_valid_time_range(node_id, TimeRange::at(600.into()))
            .len(),
        0
    );

    // 3. Test Reject
    indexes.clear();
    let batch_reject = vec![
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(500.into(), 1500.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
    ];
    let result = indexes.insert_node_versions_batch_with_policy(
        node_id,
        batch_reject,
        DeduplicationPolicy::Reject,
    );
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Duplicate"));
}

#[test]
fn test_metadata_index_reuse_across_batches() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // First batch: insert v1
    indexes
        .insert_node_versions_batch(
            node_id,
            vec![(
                v1,
                BiTemporalInterval::new(
                    TimeRange::new(1000.into(), 2000.into()).unwrap(),
                    TimeRange::from(0.into()),
                ),
            )],
        )
        .unwrap();

    // Second batch: insert v1 again with different time
    // It should reuse the metadata index and then deduplicate
    indexes
        .insert_node_versions_batch(
            node_id,
            vec![(
                v1,
                BiTemporalInterval::new(
                    TimeRange::new(500.into(), 1500.into()).unwrap(),
                    TimeRange::from(0.into()),
                ),
            )],
        )
        .unwrap();

    let timelines = indexes.index.get(&EntityId::Node(node_id)).unwrap();
    assert_eq!(
        timelines.version_metadata_count(),
        1,
        "Metadata should be reused"
    );
    assert_eq!(
        timelines.valid.versions.len(),
        1,
        "Duplicate should be removed by insert_batch"
    );
}

#[test]
fn test_batch_insert_reject_policy_valid_batch() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();

    let batch = vec![
        (
            v1,
            BiTemporalInterval::new(
                TimeRange::new(1000.into(), 2000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
        (
            v2,
            BiTemporalInterval::new(
                TimeRange::new(2000.into(), 3000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        ),
    ];

    // This should succeed because there are no duplicates
    let result =
        indexes.insert_node_versions_batch_with_policy(node_id, batch, DeduplicationPolicy::Reject);

    assert!(
        result.is_ok(),
        "Reject policy should accept valid batch without duplicates"
    );
}

#[test]
fn test_get_all_entity_ids() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let edge_id = EdgeId::new(2).unwrap();

    indexes
        .insert_node_version(
            node_id,
            VersionId::new(1).unwrap(),
            BiTemporalInterval::current(1000.into()),
        )
        .unwrap();

    indexes
        .insert_edge_version(
            edge_id,
            VersionId::new(2).unwrap(),
            BiTemporalInterval::current(1000.into()),
        )
        .unwrap();

    let ids: Vec<_> = indexes.entity_ids().collect();
    assert_eq!(ids.len(), 2);
    assert!(ids.contains(&EntityId::Node(node_id)));
    assert!(ids.contains(&EntityId::Edge(edge_id)));
}

#[test]
fn test_update_after_retroactive_insert() {
    // This test ensures that the metadata_to_position map is correctly updated
    // when an insertion shifts existing entries (retroactive insertion).
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();
    let v2 = VersionId::new(101).unwrap();
    let v3 = VersionId::new(102).unwrap();

    // 1. Insert v1 at start 0 (index 0)
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(TimeRange::from(0.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    // 2. Insert v3 at start 20 (index 1)
    indexes
        .insert_node_version(
            node_id,
            v3,
            BiTemporalInterval::new(TimeRange::from(20.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    // 3. Insert v2 at start 10 (index 1, shifts v3 to index 2)
    indexes
        .insert_node_version(
            node_id,
            v2,
            BiTemporalInterval::new(TimeRange::from(10.into()), TimeRange::from(0.into())),
        )
        .unwrap();

    // 4. Update v3 (which moved from index 1 to index 2)
    // If the map wasn't updated, this would try to update index 1 (which is now v2)
    // or fail if it somehow kept old index but didn't find the entry.
    // We verify that the update succeeds and targets the correct version.
    indexes.update_node_valid_time_end(node_id, v3, 30.into());

    // Verify v3 was updated. At time 25, v1, v2, and v3 should be visible.
    let mut results = indexes.find_node_version_at_point(node_id, 25.into(), 0.into());
    results.sort();
    assert_eq!(
        results,
        vec![v1, v2, v3],
        "v1, v2, and v3 should be visible at 25"
    );

    // Verify v3 is NOT found after 30. At time 35, only v1 and v2 should be visible.
    let mut results = indexes.find_node_version_at_point(node_id, 35.into(), 0.into());
    results.sort();
    assert_eq!(
        results,
        vec![v1, v2],
        "Only v1 and v2 should be visible at 35"
    );

    // 5. Update v2 (newly inserted at index 1)
    // Verify v2 is intact before update. At time 15, v1 and v2 should be visible.
    let mut results = indexes.find_node_version_at_point(node_id, 15.into(), 0.into());
    results.sort();
    assert_eq!(results, vec![v1, v2], "v1 and v2 should be visible at 15");

    indexes.update_node_valid_time_end(node_id, v2, 18.into());

    // Verify v2 was updated. At time 19, only v1 should be visible.
    let results = indexes.find_node_version_at_point(node_id, 19.into(), 0.into());
    assert_eq!(results, vec![v1], "Only v1 should be visible at 19");
}

#[test]
fn test_batch_insert_unsorted_query() {
    // This test ensures that insert_batch sorts the entries, which is critical
    // for binary search (partition_point) to work correctly.
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();

    let v1 = VersionId::new(100).unwrap(); // start 0
    let v2 = VersionId::new(101).unwrap(); // start 20
    let v3 = VersionId::new(102).unwrap(); // start 10

    // Create a batch with unsorted entries: [0, 20, 10]
    let batch = vec![
        (
            v1,
            BiTemporalInterval::new(TimeRange::from(0.into()), TimeRange::from(0.into())),
        ),
        (
            v2,
            BiTemporalInterval::new(TimeRange::from(20.into()), TimeRange::from(0.into())),
        ),
        (
            v3,
            BiTemporalInterval::new(TimeRange::from(10.into()), TimeRange::from(0.into())),
        ),
    ];

    indexes.insert_node_versions_batch(node_id, batch).unwrap();

    // Query a range that covers [0, 15).
    // This should include v1 (start 0) and v3 (start 10).
    // It should EXCLUDE v2 (start 20).
    //
    // If the array was unsorted [0, 20, 10]:
    // partition_point(|e| e.start < 15):
    // - Probe middle (20). 20 < 15 is False.
    // - Go left.
    // - Probe 0. 0 < 15 is True.
    // - Returns index 1.
    // - Slice is [0].
    // - Result: only v1. MISSES v3!
    //
    // If sorted [0, 10, 20]:
    // partition_point(|e| e.start < 15):
    // - Probe middle (10). 10 < 15 is True.
    // - Go right.
    // - Probe 20. 20 < 15 is False.
    // - Returns index 2.
    // - Slice is [0, 10].
    // - Result: v1 and v3. Correct.

    let results = indexes.find_node_versions_in_valid_time_range(
        node_id,
        TimeRange::new(0.into(), 15.into()).unwrap(),
    );

    assert_eq!(results.len(), 2, "Should find 2 versions (v1 and v3)");
    assert!(results.contains(&v1));
    assert!(results.contains(&v3));
    assert!(!results.contains(&v2));
}

#[test]
fn test_reject_policy_collision_with_existing_sentinel() {
    let indexes = TemporalIndexes::new();
    let node_id = NodeId::new(1).unwrap();
    let v1 = VersionId::new(100).unwrap();

    // 1. Insert v1
    indexes
        .insert_node_version(
            node_id,
            v1,
            BiTemporalInterval::new(
                TimeRange::new(0.into(), 1000.into()).unwrap(),
                TimeRange::from(0.into()),
            ),
        )
        .unwrap();

    // 2. Batch insert v1 again with Reject policy
    let batch = vec![(
        v1,
        BiTemporalInterval::new(
            TimeRange::new(1000.into(), 2000.into()).unwrap(),
            TimeRange::from(0.into()),
        ),
    )];

    let result =
        indexes.insert_node_versions_batch_with_policy(node_id, batch, DeduplicationPolicy::Reject);

    assert!(
        result.is_err(),
        "Should reject duplicate version ID when it already exists in index"
    );
}

#[test]
fn test_batch_insert_exact_capacity_sentinel() {
    let config = TemporalIndexConfig {
        max_versions_per_entity: 10,
    };
    let indexes = TemporalIndexes::with_config(config);
    let node_id = NodeId::new(1).unwrap();

    // Insert 8 versions
    for i in 0..8 {
        indexes
            .insert_node_version(
                node_id,
                VersionId::new(i).unwrap(),
                BiTemporalInterval::new(
                    TimeRange::new(((i * 100) as i64).into(), (((i + 1) * 100) as i64).into())
                        .unwrap(),
                    TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
                ),
            )
            .unwrap();
    }

    // Insert batch of 2 (Total 10 == Limit)
    let batch = vec![
        (
            VersionId::new(8).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(800.into(), 900.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        ),
        (
            VersionId::new(9).unwrap(),
            BiTemporalInterval::new(
                TimeRange::new(900.into(), 1000.into()).unwrap(),
                TimeRange::new(0.into(), TIMESTAMP_MAX).unwrap(),
            ),
        ),
    ];

    let result = indexes.insert_node_versions_batch(node_id, batch);
    assert!(
        result.is_ok(),
        "Should accept batch that fits exactly into capacity"
    );
}