kitedb 0.2.3

High-performance embedded graph database
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
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
//! Ray - High-level API for KiteDB
//!
//! The Ray struct provides a clean, ergonomic API for graph operations.
//! It wraps the lower-level GraphDB with schema definitions and type-safe operations.
//!
//! Provides:
//! - Node and edge CRUD operations
//! - Graph traversal with fluent API
//! - Shortest path finding (Dijkstra, BFS, Yen's k-shortest)
//! - Schema-based type safety
//!
//! Ported from src/api/ray.ts

use crate::error::{RayError, Result};
use crate::graph::db::{close_graph_db, open_graph_db, GraphDB, OpenOptions};
use crate::graph::edges::{
  add_edge,
  del_edge_prop,
  delete_edge,
  edge_exists,
  // Direct read functions (no transaction)
  edge_exists_db,
  get_edge_prop_db,
  get_edge_props_db,
  get_neighbors_in_db,
  get_neighbors_out_db,
  set_edge_prop,
};
use crate::graph::iterators::{
  count_edges, count_nodes, list_edges, list_nodes, FullEdge, ListEdgesOptions,
};
use crate::graph::key_index::get_node_key;
use crate::graph::nodes::{
  create_node, del_node_prop, delete_node, get_node_by_key, get_node_by_key_db, get_node_prop,
  get_node_prop_db, node_exists, node_exists_db, set_node_prop, NodeOpts,
};
use crate::graph::tx::{begin_tx, commit, rollback, TxHandle};
use crate::types::*;

use std::collections::{HashMap, HashSet};
use std::path::Path;

// ============================================================================
// Schema Definitions
// ============================================================================

/// Property definition for nodes or edges
#[derive(Debug, Clone)]
pub struct PropDef {
  /// Property name
  pub name: String,
  /// Property type hint (for documentation/validation)
  pub prop_type: PropType,
  /// Whether this property is required
  pub required: bool,
  /// Default value (if any)
  pub default: Option<PropValue>,
}

/// Property type hints
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropType {
  String,
  Int,
  Float,
  Bool,
  Any,
}

impl PropDef {
  pub fn string(name: &str) -> Self {
    Self {
      name: name.to_string(),
      prop_type: PropType::String,
      required: false,
      default: None,
    }
  }

  pub fn int(name: &str) -> Self {
    Self {
      name: name.to_string(),
      prop_type: PropType::Int,
      required: false,
      default: None,
    }
  }

  pub fn float(name: &str) -> Self {
    Self {
      name: name.to_string(),
      prop_type: PropType::Float,
      required: false,
      default: None,
    }
  }

  pub fn bool(name: &str) -> Self {
    Self {
      name: name.to_string(),
      prop_type: PropType::Bool,
      required: false,
      default: None,
    }
  }

  pub fn required(mut self) -> Self {
    self.required = true;
    self
  }

  pub fn default(mut self, value: PropValue) -> Self {
    self.default = Some(value);
    self
  }
}

/// Node type definition
#[derive(Debug, Clone)]
pub struct NodeDef {
  /// Node type name
  pub name: String,
  /// Property definitions
  pub props: HashMap<String, PropDef>,
  /// Key prefix for this node type (e.g., "user:")
  pub key_prefix: String,
  /// Internal label ID (set after registration)
  pub label_id: Option<LabelId>,
  /// Property key IDs (set after registration)
  pub prop_key_ids: HashMap<String, PropKeyId>,
}

impl NodeDef {
  pub fn new(name: &str, key_prefix: &str) -> Self {
    Self {
      name: name.to_string(),
      props: HashMap::new(),
      key_prefix: key_prefix.to_string(),
      label_id: None,
      prop_key_ids: HashMap::new(),
    }
  }

  pub fn prop(mut self, prop: PropDef) -> Self {
    self.props.insert(prop.name.clone(), prop);
    self
  }

  /// Generate a full key from a key suffix
  pub fn key(&self, suffix: &str) -> String {
    format!("{}{}", self.key_prefix, suffix)
  }
}

/// Edge type definition
#[derive(Debug, Clone)]
pub struct EdgeDef {
  /// Edge type name
  pub name: String,
  /// Property definitions
  pub props: HashMap<String, PropDef>,
  /// Internal edge type ID (set after registration)
  pub etype_id: Option<ETypeId>,
  /// Property key IDs (set after registration)
  pub prop_key_ids: HashMap<String, PropKeyId>,
}

impl EdgeDef {
  pub fn new(name: &str) -> Self {
    Self {
      name: name.to_string(),
      props: HashMap::new(),
      etype_id: None,
      prop_key_ids: HashMap::new(),
    }
  }

  pub fn prop(mut self, prop: PropDef) -> Self {
    self.props.insert(prop.name.clone(), prop);
    self
  }
}

// ============================================================================
// Node Reference
// ============================================================================

/// Reference to a node in the database
#[derive(Debug, Clone)]
pub struct NodeRef {
  /// Node ID
  pub id: NodeId,
  /// Full key (if available)
  pub key: Option<String>,
  /// Node type name
  pub node_type: String,
}

impl NodeRef {
  pub fn new(id: NodeId, key: Option<String>, node_type: &str) -> Self {
    Self {
      id,
      key,
      node_type: node_type.to_string(),
    }
  }
}

// ============================================================================
// Ray Options
// ============================================================================

/// Options for opening a Ray database
#[derive(Debug, Clone, Default)]
pub struct RayOptions {
  /// Node type definitions
  pub nodes: Vec<NodeDef>,
  /// Edge type definitions
  pub edges: Vec<EdgeDef>,
  /// Open in read-only mode
  pub read_only: bool,
  /// Create database if it doesn't exist
  pub create_if_missing: bool,
  /// Acquire file lock
  pub lock_file: bool,
}

impl RayOptions {
  pub fn new() -> Self {
    Self {
      nodes: Vec::new(),
      edges: Vec::new(),
      read_only: false,
      create_if_missing: true,
      lock_file: true,
    }
  }

  pub fn node(mut self, node: NodeDef) -> Self {
    self.nodes.push(node);
    self
  }

  pub fn edge(mut self, edge: EdgeDef) -> Self {
    self.edges.push(edge);
    self
  }

  pub fn read_only(mut self, value: bool) -> Self {
    self.read_only = value;
    self
  }
}

// ============================================================================
// Ray Database
// ============================================================================

/// High-level graph database API
pub struct Ray {
  /// Underlying database
  db: GraphDB,
  /// Node type definitions by name
  nodes: HashMap<String, NodeDef>,
  /// Edge type definitions by name
  edges: HashMap<String, EdgeDef>,
  /// Key prefix to node def mapping for fast lookups
  key_prefix_to_node: HashMap<String, String>,
}

impl Ray {
  /// Open or create a Ray database
  pub fn open<P: AsRef<Path>>(path: P, options: RayOptions) -> Result<Self> {
    let db_options = OpenOptions {
      read_only: options.read_only,
      create_if_missing: options.create_if_missing,
      lock_file: options.lock_file,
      ..Default::default()
    };

    let db = open_graph_db(path, db_options)?;

    // Initialize schema in a transaction
    let mut nodes: HashMap<String, NodeDef> = HashMap::new();
    let mut edges: HashMap<String, EdgeDef> = HashMap::new();
    let mut key_prefix_to_node: HashMap<String, String> = HashMap::new();

    // Process node definitions
    for mut node_def in options.nodes {
      // Define label
      let label_id = db.get_or_create_label(&node_def.name);
      node_def.label_id = Some(label_id);

      // Define property keys
      for prop_name in node_def.props.keys() {
        let prop_key_id = db.get_or_create_propkey(prop_name);
        node_def.prop_key_ids.insert(prop_name.clone(), prop_key_id);
      }

      key_prefix_to_node.insert(node_def.key_prefix.clone(), node_def.name.clone());
      nodes.insert(node_def.name.clone(), node_def);
    }

    // Process edge definitions
    for mut edge_def in options.edges {
      // Define edge type
      let etype_id = db.get_or_create_etype(&edge_def.name);
      edge_def.etype_id = Some(etype_id);

      // Define property keys
      for prop_name in edge_def.props.keys() {
        let prop_key_id = db.get_or_create_propkey(prop_name);
        edge_def.prop_key_ids.insert(prop_name.clone(), prop_key_id);
      }

      edges.insert(edge_def.name.clone(), edge_def);
    }

    Ok(Self {
      db,
      nodes,
      edges,
      key_prefix_to_node,
    })
  }

  // ========================================================================
  // Node Operations
  // ========================================================================

  /// Create a new node
  pub fn create_node(
    &mut self,
    node_type: &str,
    key_suffix: &str,
    props: HashMap<String, PropValue>,
  ) -> Result<NodeRef> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?
      .clone();

    let full_key = node_def.key(key_suffix);

    // Begin transaction
    let mut handle = begin_tx(&self.db)?;

    // Create the node with key
    let node_opts = NodeOpts {
      key: Some(full_key.clone()),
      labels: node_def.label_id.map(|id| vec![id]),
      props: None,
    };
    let node_id = create_node(&mut handle, node_opts)?;

    // Set properties
    for (prop_name, value) in props {
      if let Some(&prop_key_id) = node_def.prop_key_ids.get(&prop_name) {
        set_node_prop(&mut handle, node_id, prop_key_id, value)?;
      }
    }

    // Commit
    commit(&mut handle)?;

    Ok(NodeRef::new(node_id, Some(full_key), node_type))
  }

  /// Insert a node using fluent builder API
  ///
  /// This method provides a more ergonomic way to create nodes with properties
  /// using the builder pattern. Use `.values()` to specify the node data,
  /// then either `.execute()` to insert without returning, or `.returning()`
  /// to get the created node reference.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::PropValue;
  /// # use std::collections::HashMap;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// # let props: HashMap<String, PropValue> = HashMap::new();
  /// // Insert and get the node reference
  /// let user = ray.insert("User")?
  ///     .values("alice", props)?
  ///     .returning()?;
  ///
  /// // Insert without returning (slightly faster)
  /// ray.insert("User")?
  ///     .values("bob", HashMap::new())?
  ///     .execute()?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn insert(&mut self, node_type: &str) -> Result<RayInsertBuilder<'_>> {
    let key_prefix = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?
      .key_prefix
      .clone();

    Ok(RayInsertBuilder {
      ray: self,
      node_type: node_type.to_string(),
      key_prefix,
    })
  }

  /// Get a node by key (direct read, no transaction overhead)
  pub fn get(&self, node_type: &str, key_suffix: &str) -> Result<Option<NodeRef>> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?;

    let full_key = node_def.key(key_suffix);

    // Direct read without transaction
    let node_id = get_node_by_key_db(&self.db, &full_key);

    match node_id {
      Some(id) => Ok(Some(NodeRef::new(id, Some(full_key), node_type))),
      None => Ok(None),
    }
  }

  /// Get a node by ID (direct read, no transaction overhead)
  pub fn get_by_id(&self, node_id: NodeId) -> Result<Option<NodeRef>> {
    // Direct read without transaction
    let exists = node_exists_db(&self.db, node_id);

    if exists {
      // Look up the node's key from snapshot/delta
      let delta = self.db.delta.read();
      let key = get_node_key(self.db.snapshot.as_ref(), &delta, node_id);

      // Try to determine node type from key prefix
      let node_type = if let Some(ref k) = key {
        // Find matching node def by key prefix
        self
          .nodes
          .values()
          .find(|def| k.starts_with(&def.key_prefix))
          .map(|def| def.name.as_str())
          .unwrap_or("unknown")
      } else {
        "unknown"
      };

      Ok(Some(NodeRef::new(node_id, key, node_type)))
    } else {
      Ok(None)
    }
  }

  /// Check if a node exists (direct read, no transaction overhead)
  pub fn exists(&self, node_id: NodeId) -> bool {
    // Direct read without transaction
    node_exists_db(&self.db, node_id)
  }

  /// Delete a node
  pub fn delete_node(&mut self, node_id: NodeId) -> Result<bool> {
    let mut handle = begin_tx(&self.db)?;
    let deleted = delete_node(&mut handle, node_id)?;
    commit(&mut handle)?;
    Ok(deleted)
  }

  /// Get a node property (direct read, no transaction overhead)
  pub fn get_prop(&self, node_id: NodeId, prop_name: &str) -> Option<PropValue> {
    let prop_key_id = self.db.get_propkey_id(prop_name)?;
    // Direct read without transaction
    get_node_prop_db(&self.db, node_id, prop_key_id)
  }

  /// Set a node property
  pub fn set_prop(&mut self, node_id: NodeId, prop_name: &str, value: PropValue) -> Result<()> {
    let prop_key_id = self.db.get_or_create_propkey(prop_name);

    let mut handle = begin_tx(&self.db)?;
    set_node_prop(&mut handle, node_id, prop_key_id, value)?;
    commit(&mut handle)?;
    Ok(())
  }

  /// Update a node by reference using fluent builder API
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::PropValue;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// let alice = ray.get("User", "alice")?.unwrap();
  /// ray.update(&alice)?
  ///     .set("name", PropValue::String("Alice Updated".into()))
  ///     .set("age", PropValue::I64(31))
  ///     .execute()?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn update(&mut self, node_ref: &NodeRef) -> Result<RayUpdateNodeBuilder<'_>> {
    // Verify node exists
    let mut handle = begin_tx(&self.db)?;
    let exists = node_exists(&handle, node_ref.id);
    commit(&mut handle)?;

    if !exists {
      return Err(RayError::NodeNotFound(node_ref.id));
    }

    Ok(RayUpdateNodeBuilder {
      ray: self,
      node_id: node_ref.id,
      updates: HashMap::new(),
    })
  }

  /// Update a node by ID using fluent builder API
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::{NodeId, PropValue};
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// # let node_id: NodeId = 1;
  /// ray.update_by_id(node_id)?
  ///     .set("name", PropValue::String("Updated".into()))
  ///     .execute()?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn update_by_id(&mut self, node_id: NodeId) -> Result<RayUpdateNodeBuilder<'_>> {
    // Verify node exists
    let mut handle = begin_tx(&self.db)?;
    let exists = node_exists(&handle, node_id);
    commit(&mut handle)?;

    if !exists {
      return Err(RayError::NodeNotFound(node_id));
    }

    Ok(RayUpdateNodeBuilder {
      ray: self,
      node_id,
      updates: HashMap::new(),
    })
  }

  /// Update a node by key using fluent builder API
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::PropValue;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// ray.update_by_key("User", "alice")?
  ///     .set("name", PropValue::String("Alice Updated".into()))
  ///     .execute()?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn update_by_key(
    &mut self,
    node_type: &str,
    key_suffix: &str,
  ) -> Result<RayUpdateNodeBuilder<'_>> {
    let full_key = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?
      .key(key_suffix);

    let mut handle = begin_tx(&self.db)?;
    let node_id =
      get_node_by_key(&handle, &full_key).ok_or_else(|| RayError::KeyNotFound(full_key.clone()))?;
    commit(&mut handle)?;

    Ok(RayUpdateNodeBuilder {
      ray: self,
      node_id,
      updates: HashMap::new(),
    })
  }

  // ========================================================================
  // Edge Operations
  // ========================================================================

  /// Create an edge between two nodes
  pub fn link(&mut self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<()> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let mut handle = begin_tx(&self.db)?;
    add_edge(&mut handle, src, etype_id, dst)?;
    commit(&mut handle)?;
    Ok(())
  }

  /// Create an edge between two nodes with properties
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::{NodeRef, Ray};
  /// # use kitedb::types::PropValue;
  /// # use std::collections::HashMap;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// # let alice: NodeRef = unimplemented!();
  /// # let bob: NodeRef = unimplemented!();
  /// let mut props = HashMap::new();
  /// props.insert("weight".to_string(), PropValue::F64(0.5));
  /// props.insert("since".to_string(), PropValue::String("2024".into()));
  /// ray.link_with_props(alice.id, "FOLLOWS", bob.id, props)?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn link_with_props(
    &mut self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
    props: HashMap<String, PropValue>,
  ) -> Result<()> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?
      .clone();

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let mut handle = begin_tx(&self.db)?;
    add_edge(&mut handle, src, etype_id, dst)?;

    // Set edge properties
    for (prop_name, value) in props {
      let prop_key_id = if let Some(&id) = edge_def.prop_key_ids.get(&prop_name) {
        id
      } else {
        // Create prop key if not in schema
        handle.db.get_or_create_propkey(&prop_name)
      };
      set_edge_prop(&mut handle, src, etype_id, dst, prop_key_id, value)?;
    }

    commit(&mut handle)?;
    Ok(())
  }

  /// Remove an edge between two nodes
  pub fn unlink(&mut self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<bool> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let mut handle = begin_tx(&self.db)?;
    let deleted = delete_edge(&mut handle, src, etype_id, dst)?;
    commit(&mut handle)?;
    Ok(deleted)
  }

  /// Check if an edge exists (direct read, no transaction overhead)
  pub fn has_edge(&self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<bool> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    // Direct read without transaction
    Ok(edge_exists_db(&self.db, src, etype_id, dst))
  }

  /// Get outgoing neighbors of a node (direct read, no transaction overhead)
  pub fn neighbors_out(&self, node_id: NodeId, edge_type: Option<&str>) -> Result<Vec<NodeId>> {
    let etype_id = match edge_type {
      Some(name) => {
        let edge_def = self
          .edges
          .get(name)
          .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {name}")))?;
        edge_def.etype_id
      }
      None => None,
    };

    // Direct read without transaction
    Ok(get_neighbors_out_db(&self.db, node_id, etype_id))
  }

  /// Get incoming neighbors of a node (direct read, no transaction overhead)
  pub fn neighbors_in(&self, node_id: NodeId, edge_type: Option<&str>) -> Result<Vec<NodeId>> {
    let etype_id = match edge_type {
      Some(name) => {
        let edge_def = self
          .edges
          .get(name)
          .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {name}")))?;
        edge_def.etype_id
      }
      None => None,
    };

    // Direct read without transaction
    let neighbors = get_neighbors_in_db(&self.db, node_id, etype_id);
    Ok(neighbors)
  }

  // ========================================================================
  // Edge Property Operations
  // ========================================================================

  /// Get an edge property (direct read, no transaction overhead)
  ///
  /// Returns None if the edge doesn't exist or the property is not set.
  pub fn get_edge_prop(
    &self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
    prop_name: &str,
  ) -> Result<Option<PropValue>> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let prop_key_id = match self.db.get_propkey_id(prop_name) {
      Some(id) => id,
      None => return Ok(None), // Unknown property = not set
    };

    // Direct read without transaction
    Ok(get_edge_prop_db(&self.db, src, etype_id, dst, prop_key_id))
  }

  /// Get all properties for an edge (direct read, no transaction overhead)
  ///
  /// Returns None if the edge doesn't exist.
  pub fn get_edge_props(
    &self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
  ) -> Result<Option<HashMap<String, PropValue>>> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    // Direct read without transaction
    let props = get_edge_props_db(&self.db, src, etype_id, dst);

    // Convert PropKeyId -> String in the result
    match props {
      Some(props_by_id) => {
        let mut result = HashMap::new();
        for (key_id, value) in props_by_id {
          if let Some(name) = self.db.get_propkey_name(key_id) {
            result.insert(name, value);
          }
        }
        Ok(Some(result))
      }
      None => Ok(None),
    }
  }

  /// Set an edge property
  pub fn set_edge_prop(
    &mut self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
    prop_name: &str,
    value: PropValue,
  ) -> Result<()> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let prop_key_id = self.db.get_or_create_propkey(prop_name);

    let mut handle = begin_tx(&self.db)?;
    set_edge_prop(&mut handle, src, etype_id, dst, prop_key_id, value)?;
    commit(&mut handle)?;
    Ok(())
  }

  /// Delete an edge property
  pub fn del_edge_prop(
    &mut self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
    prop_name: &str,
  ) -> Result<()> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    let prop_key_id = self
      .db
      .get_propkey_id(prop_name)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown property: {prop_name}")))?;

    let mut handle = begin_tx(&self.db)?;
    del_edge_prop(&mut handle, src, etype_id, dst, prop_key_id)?;
    commit(&mut handle)?;
    Ok(())
  }

  /// Update edge properties using fluent builder API
  ///
  /// Returns an `UpdateEdgeBuilder` that allows setting multiple properties
  /// in a single transaction.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::{NodeId, PropValue};
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// # let alice_id: NodeId = 1;
  /// # let bob_id: NodeId = 2;
  /// ray.update_edge(alice_id, "FOLLOWS", bob_id)?
  ///    .set("weight", PropValue::F64(0.9))
  ///    .set("since", PropValue::String("2024".to_string()))
  ///    .execute()?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn update_edge(
    &mut self,
    src: NodeId,
    edge_type: &str,
    dst: NodeId,
  ) -> Result<RayUpdateEdgeBuilder<'_>> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    Ok(RayUpdateEdgeBuilder {
      ray: self,
      src,
      etype_id,
      dst,
      updates: HashMap::new(),
    })
  }

  // ========================================================================
  // Listing and Counting
  // ========================================================================

  /// Count all nodes in the database
  ///
  /// This is an O(1) operation when possible, using cached counts.
  pub fn count_nodes(&self) -> u64 {
    count_nodes(&self.db)
  }

  /// Count nodes of a specific type
  ///
  /// This requires iteration to filter by key prefix.
  pub fn count_nodes_by_type(&self, node_type: &str) -> Result<u64> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?;

    let prefix = &node_def.key_prefix;
    let mut count = 0u64;

    for node_id in list_nodes(&self.db) {
      if let Some(key) = self.get_node_key_internal(node_id) {
        if key.starts_with(prefix) {
          count += 1;
        }
      }
    }

    Ok(count)
  }

  /// Count all edges
  pub fn count_edges(&self) -> u64 {
    count_edges(&self.db, None)
  }

  /// Count edges of a specific type
  pub fn count_edges_by_type(&self, edge_type: &str) -> Result<u64> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    Ok(count_edges(&self.db, Some(etype_id)))
  }

  /// List all node IDs
  pub fn list_nodes(&self) -> Vec<NodeId> {
    list_nodes(&self.db)
  }

  /// Iterate over all nodes of a specific type
  ///
  /// Returns an iterator that yields `NodeRef` for each matching node.
  /// Filters nodes by matching their key prefix.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// for node_ref in ray.all("User")? {
  ///     println!("User: {:?}", node_ref.id);
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn all(&self, node_type: &str) -> Result<impl Iterator<Item = NodeRef> + '_> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?
      .clone();

    let prefix = node_def.key_prefix.clone();
    let node_type_str = node_type.to_string();

    Ok(list_nodes(&self.db).into_iter().filter_map(move |node_id| {
      let key = self.get_node_key_internal(node_id)?;
      if key.starts_with(&prefix) {
        Some(NodeRef::new(node_id, Some(key), &node_type_str))
      } else {
        None
      }
    }))
  }

  /// List all edges in the database
  pub fn list_all_edges(&self) -> Vec<FullEdge> {
    list_edges(&self.db, ListEdgesOptions::default())
  }

  /// Iterate over all edges, optionally filtered by type
  ///
  /// Returns an iterator that yields edge information.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// for edge in ray.all_edges(Some("FOLLOWS"))? {
  ///     println!("{} -> {}", edge.src, edge.dst);
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn all_edges(&self, edge_type: Option<&str>) -> Result<impl Iterator<Item = FullEdge> + '_> {
    let etype_id = match edge_type {
      Some(name) => {
        let edge_def = self
          .edges
          .get(name)
          .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {name}")))?;
        edge_def.etype_id
      }
      None => None,
    };

    let options = ListEdgesOptions { etype: etype_id };
    Ok(list_edges(&self.db, options).into_iter())
  }

  /// Get a lightweight node reference without loading properties
  ///
  /// This is faster than `get()` when you only need the node reference
  /// for traversals or edge operations.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// let user_ref = ray.get_ref("User", "alice")?;
  /// if let Some(node) = user_ref {
  ///     // Can now use node.id for edges, traversals, etc.
  /// }
  /// # Ok(())
  /// # }
  /// ```
  /// Get a lightweight node reference by key (direct read, no transaction overhead)
  ///
  /// This is faster than `get()` as it only returns a reference without loading properties.
  /// Use this when you only need the node ID for traversals or edge operations.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// // Fast: only gets reference (~85ns)
  /// if let Some(node) = ray.get_ref("User", "alice")? {
  ///     // Can now use node.id for edges, traversals, etc.
  ///     let friends = ray.from(node.id).out(Some("FOLLOWS"))?.to_vec();
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn get_ref(&self, node_type: &str, key_suffix: &str) -> Result<Option<NodeRef>> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?;

    let full_key = node_def.key(key_suffix);

    // Direct read without transaction
    let node_id = get_node_by_key_db(&self.db, &full_key);

    match node_id {
      Some(id) => Ok(Some(NodeRef::new(id, Some(full_key), node_type))),
      None => Ok(None),
    }
  }

  /// Helper to get node key from database
  fn get_node_key_internal(&self, node_id: NodeId) -> Option<String> {
    let delta = self.db.delta.read();
    get_node_key(self.db.snapshot.as_ref(), &delta, node_id)
  }

  // ========================================================================
  // Schema Access
  // ========================================================================

  /// Get a node definition by name
  pub fn node_def(&self, name: &str) -> Option<&NodeDef> {
    self.nodes.get(name)
  }

  /// Get an edge definition by name
  pub fn edge_def(&self, name: &str) -> Option<&EdgeDef> {
    self.edges.get(name)
  }

  /// Get all node type names
  pub fn node_types(&self) -> Vec<&str> {
    self.nodes.keys().map(|s| s.as_str()).collect()
  }

  /// Get all edge type names
  pub fn edge_types(&self) -> Vec<&str> {
    self.edges.keys().map(|s| s.as_str()).collect()
  }

  // ========================================================================
  // Traversal
  // ========================================================================

  /// Start a traversal from a node
  ///
  /// Returns a traversal builder that can be used to chain traversal steps.
  ///
  /// # Example
  ///
  /// ```rust,no_run
  /// # use kitedb::api::ray::{NodeRef, Ray};
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// # let alice: NodeRef = unimplemented!();
  /// let friends = ray
  ///     .from(alice.id)
  ///     .out(Some("FOLLOWS"))?
  ///     .out(Some("FOLLOWS"))?
  ///     .to_vec();
  /// # Ok(())
  /// # }
  /// ```
  pub fn from(&self, node_id: NodeId) -> RayTraversalBuilder<'_> {
    RayTraversalBuilder::new(self, vec![node_id])
  }

  /// Start a traversal from multiple nodes
  pub fn from_nodes(&self, node_ids: Vec<NodeId>) -> RayTraversalBuilder<'_> {
    RayTraversalBuilder::new(self, node_ids)
  }

  // ========================================================================
  // Pathfinding
  // ========================================================================

  /// Find the shortest path between two nodes
  ///
  /// Returns a path finding builder that can be configured with edge types,
  /// direction, and maximum depth.
  ///
  /// # Example
  ///
  /// ```rust,no_run
  /// # use kitedb::api::ray::{NodeRef, Ray};
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// # let alice: NodeRef = unimplemented!();
  /// # let bob: NodeRef = unimplemented!();
  /// let path = ray
  ///     .shortest_path(alice.id, bob.id)
  ///     .via("FOLLOWS")?
  ///     .max_depth(5)
  ///     .find();
  ///
  /// if path.found {
  ///     println!("Path: {:?}", path.path);
  ///     println!("Total weight: {}", path.total_weight);
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn shortest_path(&self, source: NodeId, target: NodeId) -> RayPathBuilder<'_> {
    RayPathBuilder::new(self, source, target)
  }

  /// Find shortest paths to any of the target nodes
  pub fn shortest_path_to_any(&self, source: NodeId, targets: Vec<NodeId>) -> RayPathBuilder<'_> {
    RayPathBuilder::new_multi(self, source, targets)
  }

  /// Check if a path exists between two nodes
  ///
  /// This is more efficient than `shortest_path()` when you only need to
  /// know if a path exists, not the path itself.
  pub fn has_path(
    &mut self,
    source: NodeId,
    target: NodeId,
    edge_type: Option<&str>,
  ) -> Result<bool> {
    let path = self.shortest_path(source, target);
    let path = if let Some(etype) = edge_type {
      path.via(etype)?
    } else {
      path
    };
    Ok(path.find().found)
  }

  /// Get all nodes reachable from a source within a certain depth
  ///
  /// # Example
  ///
  /// ```rust,no_run
  /// # use kitedb::api::ray::{NodeRef, Ray};
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// # let alice: NodeRef = unimplemented!();
  /// let reachable = ray.reachable_from(alice.id, 3, Some("FOLLOWS"))?;
  /// println!("Alice can reach {} nodes in 3 hops", reachable.len());
  /// # Ok(())
  /// # }
  /// ```
  pub fn reachable_from(
    &self,
    source: NodeId,
    max_depth: usize,
    edge_type: Option<&str>,
  ) -> Result<Vec<NodeId>> {
    let etype = match edge_type {
      Some(name) => {
        let edge_def = self
          .edges
          .get(name)
          .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {name}")))?;
        edge_def.etype_id
      }
      None => None,
    };

    use super::traversal::{TraversalBuilder, TraversalDirection, TraverseOptions};

    let options = TraverseOptions::new(TraversalDirection::Out, max_depth);

    let results = TraversalBuilder::from_node(source)
      .traverse(etype, options)
      .collect_node_ids(|node_id, dir, etype_filter| {
        self.get_neighbors(node_id, dir, etype_filter)
      });

    Ok(results)
  }

  // Internal helper to get neighbors for traversal/pathfinding (read-only, no transaction)
  fn get_neighbors(
    &self,
    node_id: NodeId,
    direction: super::traversal::TraversalDirection,
    etype: Option<ETypeId>,
  ) -> Vec<Edge> {
    use super::traversal::TraversalDirection;

    let mut edges = Vec::new();
    let delta = self.db.delta.read();

    match direction {
      TraversalDirection::Out => {
        // Build set of deleted edges for filtering
        let deleted_set = delta.out_del.get(&node_id);

        // Get from snapshot first
        if let Some(ref snapshot) = self.db.snapshot {
          if let Some(src_phys) = snapshot.get_phys_node(node_id) {
            for (dst_phys, edge_etype) in snapshot.iter_out_edges(src_phys) {
              // Filter by edge type if specified
              if etype.is_some() && etype != Some(edge_etype) {
                continue;
              }

              // Get the logical node ID for the destination
              if let Some(dst_id) = snapshot.get_node_id(dst_phys) {
                // Check if this edge was deleted in delta
                let is_deleted = deleted_set
                  .map(|set| {
                    set.contains(&EdgePatch {
                      etype: edge_etype,
                      other: dst_id,
                    })
                  })
                  .unwrap_or(false);

                if !is_deleted {
                  edges.push(Edge {
                    src: node_id,
                    etype: edge_etype,
                    dst: dst_id,
                  });
                }
              }
            }
          }
        }

        // Get from delta additions
        if let Some(add_set) = delta.out_add.get(&node_id) {
          for patch in add_set {
            if etype.is_none() || etype == Some(patch.etype) {
              // Only add if not already in edges (from snapshot)
              if !edges
                .iter()
                .any(|e| e.dst == patch.other && e.etype == patch.etype)
              {
                edges.push(Edge {
                  src: node_id,
                  etype: patch.etype,
                  dst: patch.other,
                });
              }
            }
          }
        }
      }
      TraversalDirection::In => {
        // Build set of deleted edges for filtering
        let deleted_set = delta.in_del.get(&node_id);

        // Get from snapshot first
        if let Some(ref snapshot) = self.db.snapshot {
          if let Some(dst_phys) = snapshot.get_phys_node(node_id) {
            for (src_phys, edge_etype, _out_index) in snapshot.iter_in_edges(dst_phys) {
              // Filter by edge type if specified
              if etype.is_some() && etype != Some(edge_etype) {
                continue;
              }

              // Get the logical node ID for the source
              if let Some(src_id) = snapshot.get_node_id(src_phys) {
                // Check if this edge was deleted in delta
                let is_deleted = deleted_set
                  .map(|set| {
                    set.contains(&EdgePatch {
                      etype: edge_etype,
                      other: src_id,
                    })
                  })
                  .unwrap_or(false);

                if !is_deleted {
                  edges.push(Edge {
                    src: src_id,
                    etype: edge_etype,
                    dst: node_id,
                  });
                }
              }
            }
          }
        }

        // Get from delta additions
        if let Some(add_set) = delta.in_add.get(&node_id) {
          for patch in add_set {
            if etype.is_none() || etype == Some(patch.etype) {
              // Only add if not already in edges (from snapshot)
              if !edges
                .iter()
                .any(|e| e.src == patch.other && e.etype == patch.etype)
              {
                edges.push(Edge {
                  src: patch.other,
                  etype: patch.etype,
                  dst: node_id,
                });
              }
            }
          }
        }
      }
      TraversalDirection::Both => {
        drop(delta); // Release lock before recursive calls
        edges.extend(self.get_neighbors(node_id, TraversalDirection::Out, etype));
        edges.extend(self.get_neighbors(node_id, TraversalDirection::In, etype));
      }
    }

    edges
  }

  // ========================================================================
  // Database Maintenance
  // ========================================================================

  /// Optimize (compact) the database
  ///
  /// This merges the write-ahead log (WAL) into the snapshot, reducing
  /// file size and improving read performance. This is equivalent to
  /// "VACUUM" in SQLite.
  ///
  /// Optimize the database by compacting snapshot + delta into a new snapshot
  ///
  /// This operation:
  /// 1. Collects all live nodes and edges from snapshot + delta
  /// 2. Builds a new snapshot with the merged data  
  /// 3. Updates manifest to point to new snapshot
  /// 4. Clears WAL and delta
  /// 5. Garbage collects old snapshots (keeps last 2)
  ///
  /// Call this periodically to reclaim space from deleted nodes/edges
  /// and improve read performance.
  pub fn optimize(&mut self) -> Result<()> {
    self.db.optimize()
  }

  /// Get database statistics
  pub fn stats(&self) -> DbStats {
    use crate::graph::iterators::{count_edges, count_nodes};

    let node_count = count_nodes(&self.db);
    let edge_count = count_edges(&self.db, None);

    // Get delta statistics
    let delta = self.db.delta.read();
    let delta_nodes_created = delta.created_nodes.len();
    let delta_nodes_deleted = delta.deleted_nodes.len();
    let delta_edges_added = delta.total_edges_added();
    let delta_edges_deleted = delta.total_edges_deleted();
    drop(delta);

    // Get snapshot statistics
    let (snapshot_gen, snapshot_nodes, snapshot_edges, snapshot_max_node_id) =
      if let Some(ref snapshot) = self.db.snapshot {
        (
          snapshot.header.generation,
          snapshot.header.num_nodes,
          snapshot.header.num_edges,
          snapshot.header.max_node_id,
        )
      } else {
        (0, 0, 0, 0)
      };

    // Get WAL segment from manifest
    let wal_segment = self
      .db
      .manifest
      .as_ref()
      .map(|m| m.active_wal_seg)
      .unwrap_or(0);

    let mvcc_stats = self.db.mvcc.as_ref().map(|mvcc| {
      let tx_mgr = mvcc.tx_manager.lock();
      let gc = mvcc.gc.lock();
      let gc_stats = gc.get_stats();
      let committed_stats = tx_mgr.get_committed_writes_stats();
      MvccStats {
        active_transactions: tx_mgr.get_active_count(),
        min_active_ts: tx_mgr.min_active_ts(),
        versions_pruned: gc_stats.versions_pruned,
        gc_runs: gc_stats.gc_runs,
        last_gc_time: gc_stats.last_gc_time,
        committed_writes_size: committed_stats.size,
        committed_writes_pruned: committed_stats.pruned,
      }
    });

    // Recommend compaction if delta has significant changes
    let total_changes =
      delta_nodes_created + delta_nodes_deleted + delta_edges_added + delta_edges_deleted;
    let recommend_compact = total_changes > 10_000;

    DbStats {
      snapshot_gen,
      snapshot_nodes: snapshot_nodes.max(node_count), // Use higher of snapshot or total
      snapshot_edges: snapshot_edges.max(edge_count),
      snapshot_max_node_id,
      delta_nodes_created,
      delta_nodes_deleted,
      delta_edges_added,
      delta_edges_deleted,
      wal_segment,
      wal_bytes: self.db.wal_bytes(),
      recommend_compact,
      mvcc_stats,
    }
  }

  /// Get a human-readable description of the database
  ///
  /// Useful for debugging and monitoring. Returns information about:
  /// - Database path and format
  /// - Schema (node types and edge types)
  /// - Current statistics
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() {
  /// # let ray: Ray = unimplemented!();
  /// println!("{}", ray.describe());
  /// // Output:
  /// // KiteDB at /path/to/db (multi-file format)
  /// // Schema:
  /// //   Node types: User, Post, Comment
  /// //   Edge types: FOLLOWS, LIKES, WROTE
  /// // Statistics:
  /// //   Nodes: 1,234 (snapshot: 1,200, delta: +34)
  /// //   Edges: 5,678 (snapshot: 5,600, delta: +78)
  /// # }
  /// ```
  pub fn describe(&self) -> String {
    let stats = self.stats();
    let path = self.db.path.display();
    let format = if self.db.is_single_file {
      "single-file"
    } else {
      "multi-file"
    };

    let node_types: Vec<&str> = self.nodes.keys().map(|s| s.as_str()).collect();
    let edge_types: Vec<&str> = self.edges.keys().map(|s| s.as_str()).collect();

    let delta_nodes = stats.delta_nodes_created as i64 - stats.delta_nodes_deleted as i64;
    let delta_edges = stats.delta_edges_added as i64 - stats.delta_edges_deleted as i64;

    format!(
      "KiteDB at {} ({} format)\n\
       Schema:\n  \
         Node types: {}\n  \
         Edge types: {}\n\
       Statistics:\n  \
         Nodes: {} (snapshot: {}, delta: {:+})\n  \
         Edges: {} (snapshot: {}, delta: {:+})\n  \
         Recommend compact: {}",
      path,
      format,
      if node_types.is_empty() {
        "(none)".to_string()
      } else {
        node_types.join(", ")
      },
      if edge_types.is_empty() {
        "(none)".to_string()
      } else {
        edge_types.join(", ")
      },
      stats.snapshot_nodes,
      stats
        .snapshot_nodes
        .saturating_sub(stats.delta_nodes_created as u64),
      delta_nodes,
      stats.snapshot_edges,
      stats
        .snapshot_edges
        .saturating_sub(stats.delta_edges_added as u64),
      delta_edges,
      if stats.recommend_compact { "yes" } else { "no" }
    )
  }

  /// Check database integrity
  ///
  /// Performs validation checks on the database structure:
  /// - Verifies edge reciprocity (for each outgoing edge, a matching incoming edge exists)
  /// - Checks that all edges reference existing nodes
  /// - Validates node key mappings
  ///
  /// Returns a `CheckResult` with `valid=true` if no errors found, or detailed
  /// error/warning messages otherwise.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// let result = ray.check()?;
  /// if !result.valid {
  ///     for error in &result.errors {
  ///         eprintln!("Error: {}", error);
  ///     }
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn check(&self) -> Result<CheckResult> {
    let mut result = if let Some(ref snapshot) = self.db.snapshot {
      crate::check::check_snapshot(snapshot)
    } else {
      CheckResult {
        valid: true,
        errors: Vec::new(),
        warnings: vec!["No snapshot to check".to_string()],
      }
    };

    // Schema consistency - verify all registered edge types have valid IDs
    for (edge_name, edge_def) in &self.edges {
      if edge_def.etype_id.is_none() {
        result
          .warnings
          .push(format!("Edge type '{edge_name}' has no assigned etype_id"));
      }
    }

    Ok(result)
  }

  // ========================================================================
  // Database Access
  // ========================================================================

  /// Get a reference to the underlying GraphDB
  pub fn raw(&self) -> &GraphDB {
    &self.db
  }

  /// Get a mutable reference to the underlying GraphDB
  pub fn raw_mut(&mut self) -> &mut GraphDB {
    &mut self.db
  }

  /// Close the database
  pub fn close(self) -> Result<()> {
    close_graph_db(self.db)
  }
}

// ============================================================================
// Traversal Builder for Ray
// ============================================================================

use super::traversal::{TraversalBuilder, TraversalDirection, TraversalResult, TraverseOptions};

/// Traversal builder bound to a Ray database
///
/// Provides ergonomic traversal operations using edge type names.
pub struct RayTraversalBuilder<'a> {
  ray: &'a Ray,
  builder: TraversalBuilder,
}

impl<'a> RayTraversalBuilder<'a> {
  fn new(ray: &'a Ray, start_nodes: Vec<NodeId>) -> Self {
    Self {
      ray,
      builder: TraversalBuilder::new(start_nodes),
    }
  }

  /// Traverse outgoing edges
  ///
  /// @param edge_type - Edge type name (or None for all types)
  pub fn out(mut self, edge_type: Option<&str>) -> Result<Self> {
    let etype = self.resolve_etype(edge_type)?;
    self.builder = self.builder.out(etype);
    Ok(self)
  }

  /// Traverse incoming edges
  pub fn r#in(mut self, edge_type: Option<&str>) -> Result<Self> {
    let etype = self.resolve_etype(edge_type)?;
    self.builder = self.builder.r#in(etype);
    Ok(self)
  }

  /// Traverse edges in both directions
  pub fn both(mut self, edge_type: Option<&str>) -> Result<Self> {
    let etype = self.resolve_etype(edge_type)?;
    self.builder = self.builder.both(etype);
    Ok(self)
  }

  /// Variable-depth traversal
  pub fn traverse(mut self, edge_type: Option<&str>, options: TraverseOptions) -> Result<Self> {
    let etype = self.resolve_etype(edge_type)?;
    self.builder = self.builder.traverse(etype, options);
    Ok(self)
  }

  /// Limit the number of results
  pub fn take(mut self, limit: usize) -> Self {
    self.builder = self.builder.take(limit);
    self
  }

  /// Select specific properties to load (optimization)
  ///
  /// Only the specified properties will be loaded when collecting results,
  /// reducing overhead. This is useful when you only need a few properties
  /// from nodes that have many properties.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::NodeId;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// # let user_id: NodeId = 1;
  /// let friends = ray.from(user_id)
  ///     .out(Some("FOLLOWS"))?
  ///     .select(&["name", "avatar"]) // Only load name and avatar
  ///     .to_vec();
  /// # Ok(())
  /// # }
  /// ```
  pub fn select(mut self, props: &[&str]) -> Self {
    self.builder = self.builder.select_props(props);
    self
  }

  /// Execute and collect node IDs
  pub fn to_vec(self) -> Vec<NodeId> {
    self
      .builder
      .collect_node_ids(|node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype))
  }

  /// Execute and get first result
  pub fn first(self) -> Option<TraversalResult> {
    self
      .builder
      .first(|node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype))
  }

  /// Execute and get first node ID
  pub fn first_node(self) -> Option<NodeId> {
    self
      .builder
      .first_node(|node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype))
  }

  /// Execute and count results
  pub fn count(self) -> usize {
    self
      .builder
      .count(|node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype))
  }

  /// Execute and return iterator over traversal results
  pub fn execute(self) -> impl Iterator<Item = TraversalResult> + 'a {
    let ray = self.ray;
    self
      .builder
      .execute(move |node_id, dir, etype| ray.get_neighbors(node_id, dir, etype))
  }

  /// Execute and return iterator over edges only
  ///
  /// This is useful when you want to collect the edges traversed rather than nodes.
  /// Each result contains the source, destination, and edge type of edges encountered.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::NodeId;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let ray: Ray = unimplemented!();
  /// # let user_id: NodeId = 1;
  /// let edges: Vec<_> = ray.from(user_id)
  ///     .out(Some("FOLLOWS"))?
  ///     .edges()
  ///     .collect();
  ///
  /// for edge in edges {
  ///     println!("{} -[{}]-> {}", edge.src, edge.etype, edge.dst);
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn edges(self) -> impl Iterator<Item = Edge> + 'a {
    let ray = self.ray;
    self
      .builder
      .execute(move |node_id, dir, etype| ray.get_neighbors(node_id, dir, etype))
      .filter_map(|result| {
        result.edge.map(|e| Edge {
          src: e.src,
          etype: e.etype,
          dst: e.dst,
        })
      })
  }

  /// Execute and return iterator over full edge details
  ///
  /// Similar to `edges()` but returns FullEdge structs.
  pub fn full_edges(self) -> impl Iterator<Item = FullEdge> + 'a {
    let ray = self.ray;
    self
      .builder
      .execute(move |node_id, dir, etype| ray.get_neighbors(node_id, dir, etype))
      .filter_map(move |result| {
        result.edge.map(|e| FullEdge {
          src: e.src,
          etype: e.etype,
          dst: e.dst,
        })
      })
  }

  fn resolve_etype(&self, edge_type: Option<&str>) -> Result<Option<ETypeId>> {
    match edge_type {
      Some(name) => {
        let edge_def = self
          .ray
          .edges
          .get(name)
          .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {name}")))?;
        Ok(edge_def.etype_id)
      }
      None => Ok(None),
    }
  }
}

// ============================================================================
// Path Finding Builder for Ray
// ============================================================================

use super::pathfinding::{bfs, dijkstra, yen_k_shortest, PathConfig, PathResult};

/// Path finding builder bound to a Ray database
///
/// Provides ergonomic pathfinding operations using edge type names.
pub struct RayPathBuilder<'a> {
  ray: &'a Ray,
  source: NodeId,
  targets: HashSet<NodeId>,
  allowed_etypes: HashSet<ETypeId>,
  direction: TraversalDirection,
  max_depth: usize,
  weights: HashMap<(NodeId, ETypeId, NodeId), f64>,
}

impl<'a> RayPathBuilder<'a> {
  fn new(ray: &'a Ray, source: NodeId, target: NodeId) -> Self {
    let mut targets = HashSet::new();
    targets.insert(target);

    Self {
      ray,
      source,
      targets,
      allowed_etypes: HashSet::new(),
      direction: TraversalDirection::Out,
      max_depth: 100,
      weights: HashMap::new(),
    }
  }

  fn new_multi(ray: &'a Ray, source: NodeId, targets: Vec<NodeId>) -> Self {
    Self {
      ray,
      source,
      targets: targets.into_iter().collect(),
      allowed_etypes: HashSet::new(),
      direction: TraversalDirection::Out,
      max_depth: 100,
      weights: HashMap::new(),
    }
  }

  /// Restrict traversal to specific edge type
  ///
  /// Can be called multiple times to allow multiple edge types.
  pub fn via(mut self, edge_type: &str) -> Result<Self> {
    let edge_def = self
      .ray
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    if let Some(etype_id) = edge_def.etype_id {
      self.allowed_etypes.insert(etype_id);
    }

    Ok(self)
  }

  /// Set maximum search depth
  pub fn max_depth(mut self, depth: usize) -> Self {
    self.max_depth = depth;
    self
  }

  /// Set traversal direction
  pub fn direction(mut self, direction: TraversalDirection) -> Self {
    self.direction = direction;
    self
  }

  /// Use bidirectional traversal
  pub fn bidirectional(mut self) -> Self {
    self.direction = TraversalDirection::Both;
    self
  }

  /// Find the shortest path using Dijkstra's algorithm
  pub fn find(self) -> PathResult {
    let config = PathConfig {
      source: self.source,
      targets: self.targets,
      allowed_etypes: self.allowed_etypes,
      direction: self.direction,
      max_depth: self.max_depth,
    };

    let weights = self.weights;
    dijkstra(
      config,
      |node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype),
      move |src, etype, dst| weights.get(&(src, etype, dst)).copied().unwrap_or(1.0),
    )
  }

  /// Find the shortest path using BFS (unweighted)
  ///
  /// Faster than Dijkstra for unweighted graphs.
  pub fn find_bfs(self) -> PathResult {
    let config = PathConfig {
      source: self.source,
      targets: self.targets,
      allowed_etypes: self.allowed_etypes,
      direction: self.direction,
      max_depth: self.max_depth,
    };

    bfs(config, |node_id, dir, etype| {
      self.ray.get_neighbors(node_id, dir, etype)
    })
  }

  /// Find the k shortest paths using Yen's algorithm
  pub fn find_k_shortest(self, k: usize) -> Vec<PathResult> {
    let config = PathConfig {
      source: self.source,
      targets: self.targets,
      allowed_etypes: self.allowed_etypes,
      direction: self.direction,
      max_depth: self.max_depth,
    };

    let weights = self.weights;
    yen_k_shortest(
      config,
      k,
      |node_id, dir, etype| self.ray.get_neighbors(node_id, dir, etype),
      move |src, etype, dst| weights.get(&(src, etype, dst)).copied().unwrap_or(1.0),
    )
  }
}

// ============================================================================
// Batch Operations
// ============================================================================

/// A batch operation that can be executed atomically with other operations
#[derive(Debug, Clone)]
pub enum BatchOp {
  /// Create a new node
  CreateNode {
    node_type: String,
    key_suffix: String,
    props: HashMap<String, PropValue>,
  },
  /// Delete a node
  DeleteNode { node_id: NodeId },
  /// Create an edge
  Link {
    src: NodeId,
    edge_type: String,
    dst: NodeId,
  },
  /// Remove an edge
  Unlink {
    src: NodeId,
    edge_type: String,
    dst: NodeId,
  },
  /// Set a node property
  SetProp {
    node_id: NodeId,
    prop_name: String,
    value: PropValue,
  },
  /// Delete a node property
  DelProp { node_id: NodeId, prop_name: String },
}

/// Result of a batch operation
#[derive(Debug, Clone)]
pub enum BatchResult {
  /// Node was created, contains the NodeRef
  NodeCreated(NodeRef),
  /// Node was deleted
  NodeDeleted(bool),
  /// Edge was created
  EdgeCreated,
  /// Edge was removed
  EdgeRemoved(bool),
  /// Property was set
  PropSet,
  /// Property was deleted
  PropDeleted,
}

impl Ray {
  /// Execute multiple operations atomically in a single transaction
  ///
  /// All operations succeed or fail together. If any operation fails,
  /// the entire batch is rolled back.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::{BatchOp, Ray, RayOptions};
  /// # use std::collections::HashMap;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let options = RayOptions::default();
  /// let mut ray = Ray::open("db", options)?;
  ///
  /// let results = ray.batch(vec![
  ///   BatchOp::CreateNode {
  ///     node_type: "User".into(),
  ///     key_suffix: "alice".into(),
  ///     props: HashMap::new(),
  ///   },
  ///   BatchOp::CreateNode {
  ///     node_type: "User".into(),
  ///     key_suffix: "bob".into(),
  ///     props: HashMap::new(),
  ///   },
  /// ])?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn batch(&mut self, ops: Vec<BatchOp>) -> Result<Vec<BatchResult>> {
    let mut handle = begin_tx(&self.db)?;
    let mut results = Vec::with_capacity(ops.len());

    for op in ops {
      let result = match op {
        BatchOp::CreateNode {
          node_type,
          key_suffix,
          props,
        } => {
          let node_def = self
            .nodes
            .get(&node_type)
            .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?;

          let full_key = node_def.key(&key_suffix);

          let node_opts = NodeOpts {
            key: Some(full_key.clone()),
            labels: node_def.label_id.map(|id| vec![id]),
            props: None,
          };
          let node_id = create_node(&mut handle, node_opts)?;

          // Set properties
          for (prop_name, value) in props {
            if let Some(&prop_key_id) = node_def.prop_key_ids.get(&prop_name) {
              set_node_prop(&mut handle, node_id, prop_key_id, value)?;
            }
          }

          BatchResult::NodeCreated(NodeRef::new(node_id, Some(full_key), &node_type))
        }

        BatchOp::DeleteNode { node_id } => {
          let deleted = delete_node(&mut handle, node_id)?;
          BatchResult::NodeDeleted(deleted)
        }

        BatchOp::Link {
          src,
          edge_type,
          dst,
        } => {
          let edge_def = self
            .edges
            .get(&edge_type)
            .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

          let etype_id = edge_def
            .etype_id
            .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

          add_edge(&mut handle, src, etype_id, dst)?;
          BatchResult::EdgeCreated
        }

        BatchOp::Unlink {
          src,
          edge_type,
          dst,
        } => {
          let edge_def = self
            .edges
            .get(&edge_type)
            .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

          let etype_id = edge_def
            .etype_id
            .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

          let deleted = delete_edge(&mut handle, src, etype_id, dst)?;
          BatchResult::EdgeRemoved(deleted)
        }

        BatchOp::SetProp {
          node_id,
          prop_name,
          value,
        } => {
          // Use handle.db to access schema methods while handle is active
          let prop_key_id = handle.db.get_or_create_propkey(&prop_name);
          set_node_prop(&mut handle, node_id, prop_key_id, value)?;
          BatchResult::PropSet
        }

        BatchOp::DelProp { node_id, prop_name } => {
          let prop_key_id = handle
            .db
            .get_propkey_id(&prop_name)
            .ok_or_else(|| RayError::InvalidSchema(format!("Unknown property: {prop_name}")))?;
          del_node_prop(&mut handle, node_id, prop_key_id)?;
          BatchResult::PropDeleted
        }
      };

      results.push(result);
    }

    // Commit the entire batch
    commit(&mut handle)?;

    Ok(results)
  }
}

// ============================================================================
// Transaction Context
// ============================================================================

/// Context for executing operations within a transaction
///
/// Provides the same operations as Ray but within an explicit transaction scope.
/// All operations are committed together when the transaction closure returns Ok,
/// or rolled back if an error is returned.
///
/// Note: TxContext holds references to the schema maps (nodes, edges) separately
/// from the TxHandle to avoid borrow checker issues.
pub struct TxContext<'a> {
  handle: TxHandle<'a>,
  nodes: &'a HashMap<String, NodeDef>,
  edges: &'a HashMap<String, EdgeDef>,
}

impl<'a> TxContext<'a> {
  /// Create a new node
  pub fn create_node(
    &mut self,
    node_type: &str,
    key_suffix: &str,
    props: HashMap<String, PropValue>,
  ) -> Result<NodeRef> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?
      .clone();

    let full_key = node_def.key(key_suffix);

    let node_opts = NodeOpts {
      key: Some(full_key.clone()),
      labels: node_def.label_id.map(|id| vec![id]),
      props: None,
    };
    let node_id = create_node(&mut self.handle, node_opts)?;

    // Set properties
    for (prop_name, value) in props {
      if let Some(&prop_key_id) = node_def.prop_key_ids.get(&prop_name) {
        set_node_prop(&mut self.handle, node_id, prop_key_id, value)?;
      }
    }

    Ok(NodeRef::new(node_id, Some(full_key), node_type))
  }

  /// Delete a node
  pub fn delete_node(&mut self, node_id: NodeId) -> Result<bool> {
    delete_node(&mut self.handle, node_id)
  }

  /// Create an edge
  pub fn link(&mut self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<()> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    add_edge(&mut self.handle, src, etype_id, dst)?;
    Ok(())
  }

  /// Remove an edge
  pub fn unlink(&mut self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<bool> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    delete_edge(&mut self.handle, src, etype_id, dst)
  }

  /// Set a node property
  pub fn set_prop(&mut self, node_id: NodeId, prop_name: &str, value: PropValue) -> Result<()> {
    let prop_key_id = self.handle.db.get_or_create_propkey(prop_name);
    set_node_prop(&mut self.handle, node_id, prop_key_id, value)?;
    Ok(())
  }

  /// Delete a node property
  pub fn del_prop(&mut self, node_id: NodeId, prop_name: &str) -> Result<()> {
    let prop_key_id = self
      .handle
      .db
      .get_propkey_id(prop_name)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown property: {prop_name}")))?;
    del_node_prop(&mut self.handle, node_id, prop_key_id)?;
    Ok(())
  }

  /// Check if a node exists
  pub fn exists(&self, node_id: NodeId) -> bool {
    node_exists(&self.handle, node_id)
  }

  /// Check if an edge exists
  pub fn has_edge(&self, src: NodeId, edge_type: &str, dst: NodeId) -> Result<bool> {
    let edge_def = self
      .edges
      .get(edge_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown edge type: {edge_type}")))?;

    let etype_id = edge_def
      .etype_id
      .ok_or_else(|| RayError::InvalidSchema("Edge type not initialized".to_string()))?;

    Ok(edge_exists(&self.handle, src, etype_id, dst))
  }

  /// Get a node property
  pub fn get_prop(&self, node_id: NodeId, prop_name: &str) -> Result<Option<PropValue>> {
    let prop_key_id = self
      .handle
      .db
      .get_propkey_id(prop_name)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown property: {prop_name}")))?;

    Ok(get_node_prop(&self.handle, node_id, prop_key_id))
  }

  /// Get a node by key
  pub fn get(&self, node_type: &str, key_suffix: &str) -> Result<Option<NodeRef>> {
    let node_def = self
      .nodes
      .get(node_type)
      .ok_or_else(|| RayError::InvalidSchema(format!("Unknown node type: {node_type}")))?;

    let full_key = node_def.key(key_suffix);
    let node_id = get_node_by_key(&self.handle, &full_key);

    match node_id {
      Some(id) => Ok(Some(NodeRef::new(id, Some(full_key), node_type))),
      None => Ok(None),
    }
  }
}

impl Ray {
  /// Execute operations in an explicit transaction
  ///
  /// The closure receives a TxContext with access to node/edge operations.
  /// All operations performed through the context are committed together when
  /// the closure returns Ok, or rolled back if an error is returned.
  ///
  /// # Example
  /// ```rust,no_run
  /// # use kitedb::api::ray::Ray;
  /// # use kitedb::types::PropValue;
  /// # use std::collections::HashMap;
  /// # fn main() -> kitedb::error::Result<()> {
  /// # let mut ray: Ray = unimplemented!();
  /// let result = ray.transaction(|ctx| {
  ///   let alice = ctx.create_node("User", "alice", HashMap::new())?;
  ///   let bob = ctx.create_node("User", "bob", HashMap::new())?;
  ///   ctx.link(alice.id, "FOLLOWS", bob.id)?;
  ///   Ok((alice, bob))
  /// })?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn transaction<T, F>(&mut self, f: F) -> Result<T>
  where
    F: FnOnce(&mut TxContext) -> Result<T>,
  {
    // Start the transaction
    let handle = begin_tx(&self.db)?;

    // Create context with references to schema maps
    let mut ctx = TxContext {
      handle,
      nodes: &self.nodes,
      edges: &self.edges,
    };

    match f(&mut ctx) {
      Ok(result) => {
        commit(&mut ctx.handle)?;
        Ok(result)
      }
      Err(e) => {
        rollback(&mut ctx.handle)?;
        Err(e)
      }
    }
  }

  /// Execute a transaction with a simpler API using a builder pattern
  ///
  /// Returns a TxBuilder that collects operations and executes them atomically.
  pub fn tx(&mut self) -> TxBuilder {
    TxBuilder { ops: Vec::new() }
  }
}

/// Builder for constructing transactions with a fluent API
#[derive(Debug, Default)]
pub struct TxBuilder {
  ops: Vec<BatchOp>,
}

impl TxBuilder {
  /// Add a create node operation
  pub fn create_node(
    mut self,
    node_type: impl Into<String>,
    key_suffix: impl Into<String>,
    props: HashMap<String, PropValue>,
  ) -> Self {
    self.ops.push(BatchOp::CreateNode {
      node_type: node_type.into(),
      key_suffix: key_suffix.into(),
      props,
    });
    self
  }

  /// Add a delete node operation
  pub fn delete_node(mut self, node_id: NodeId) -> Self {
    self.ops.push(BatchOp::DeleteNode { node_id });
    self
  }

  /// Add a link operation
  pub fn link(mut self, src: NodeId, edge_type: impl Into<String>, dst: NodeId) -> Self {
    self.ops.push(BatchOp::Link {
      src,
      edge_type: edge_type.into(),
      dst,
    });
    self
  }

  /// Add an unlink operation
  pub fn unlink(mut self, src: NodeId, edge_type: impl Into<String>, dst: NodeId) -> Self {
    self.ops.push(BatchOp::Unlink {
      src,
      edge_type: edge_type.into(),
      dst,
    });
    self
  }

  /// Add a set property operation
  pub fn set_prop(
    mut self,
    node_id: NodeId,
    prop_name: impl Into<String>,
    value: PropValue,
  ) -> Self {
    self.ops.push(BatchOp::SetProp {
      node_id,
      prop_name: prop_name.into(),
      value,
    });
    self
  }

  /// Add a delete property operation
  pub fn del_prop(mut self, node_id: NodeId, prop_name: impl Into<String>) -> Self {
    self.ops.push(BatchOp::DelProp {
      node_id,
      prop_name: prop_name.into(),
    });
    self
  }

  /// Execute the transaction on the given Ray instance
  pub fn execute(self, ray: &mut Ray) -> Result<Vec<BatchResult>> {
    ray.batch(self.ops)
  }

  /// Get the operations as a Vec<BatchOp>
  pub fn into_ops(self) -> Vec<BatchOp> {
    self.ops
  }
}

// ============================================================================
// Update Node Builder
// ============================================================================

/// Fluent builder for updating node properties
///
/// Created via `ray.update()`, `ray.update_by_id()`, or `ray.update_by_key()`
/// and allows chaining multiple property set/unset operations before executing
/// in a single transaction.
///
/// # Example
/// ```rust,no_run
/// # use kitedb::api::ray::{NodeRef, Ray};
/// # use kitedb::types::PropValue;
/// # fn main() -> kitedb::error::Result<()> {
/// # let mut ray: Ray = unimplemented!();
/// # let alice: NodeRef = unimplemented!();
/// // Update by node reference
/// ray.update(&alice)?
///     .set("name", PropValue::String("Alice Updated".into()))
///     .set("age", PropValue::I64(31))
///     .unset("old_field")
///     .execute()?;
///
/// // Update by key
/// ray.update_by_key("User", "alice")?
///     .set("name", PropValue::String("New Name".into()))
///     .execute()?;
/// # Ok(())
/// # }
/// ```
pub struct RayUpdateNodeBuilder<'a> {
  ray: &'a mut Ray,
  node_id: NodeId,
  updates: HashMap<String, Option<PropValue>>,
}

impl<'a> RayUpdateNodeBuilder<'a> {
  /// Set a node property value
  ///
  /// The property will be set when `execute()` is called.
  pub fn set(mut self, prop_name: &str, value: PropValue) -> Self {
    self.updates.insert(prop_name.to_string(), Some(value));
    self
  }

  /// Remove a node property
  ///
  /// The property will be deleted when `execute()` is called.
  pub fn unset(mut self, prop_name: &str) -> Self {
    self.updates.insert(prop_name.to_string(), None);
    self
  }

  /// Set multiple properties at once from a HashMap
  ///
  /// Convenience method for setting multiple properties.
  pub fn set_all(mut self, props: HashMap<String, PropValue>) -> Self {
    for (k, v) in props {
      self.updates.insert(k, Some(v));
    }
    self
  }

  /// Execute the update, applying all property changes in a single transaction
  pub fn execute(self) -> Result<()> {
    if self.updates.is_empty() {
      return Ok(());
    }

    let mut handle = begin_tx(&self.ray.db)?;

    for (prop_name, value_opt) in self.updates {
      let prop_key_id = self.ray.db.get_or_create_propkey(&prop_name);

      match value_opt {
        Some(value) => {
          set_node_prop(&mut handle, self.node_id, prop_key_id, value)?;
        }
        None => {
          // Only delete if prop exists
          del_node_prop(&mut handle, self.node_id, prop_key_id)?;
        }
      }
    }

    commit(&mut handle)?;
    Ok(())
  }

  /// Get the node ID being updated
  pub fn node_id(&self) -> NodeId {
    self.node_id
  }
}

// ============================================================================
// Insert Builder
// ============================================================================

/// Fluent builder for inserting nodes
///
/// Created via `ray.insert(node_type)` and provides a fluent API for creating
/// nodes with the `.values().returning()` or `.values().execute()` pattern.
///
/// # Example
/// ```rust,no_run
/// # use kitedb::api::ray::Ray;
/// # use kitedb::types::PropValue;
/// # use std::collections::HashMap;
/// # fn main() -> kitedb::error::Result<()> {
/// # let mut ray: Ray = unimplemented!();
/// # let props: HashMap<String, PropValue> = HashMap::new();
/// # let alice_props: HashMap<String, PropValue> = HashMap::new();
/// # let bob_props: HashMap<String, PropValue> = HashMap::new();
/// // Insert and get the node reference back
/// let user = ray.insert("User")?
///     .values("alice", props)?
///     .returning()?;
///
/// // Insert multiple nodes
/// let users = ray.insert("User")?
///     .values_many(vec![
///         ("alice", alice_props),
///         ("bob", bob_props),
///     ])?
///     .returning()?;
/// # Ok(())
/// # }
/// ```
pub struct RayInsertBuilder<'a> {
  ray: &'a mut Ray,
  node_type: String,
  key_prefix: String,
}

impl<'a> RayInsertBuilder<'a> {
  /// Specify the values for a single node insert
  ///
  /// Returns an executor that can either `.execute()` (no return) or
  /// `.returning()` (returns NodeRef).
  pub fn values(
    self,
    key_suffix: &str,
    props: HashMap<String, PropValue>,
  ) -> Result<InsertExecutorSingle<'a>> {
    let full_key = format!("{}{}", self.key_prefix, key_suffix);
    Ok(InsertExecutorSingle {
      ray: self.ray,
      node_type: self.node_type,
      full_key,
      props,
    })
  }

  /// Specify values for multiple nodes
  ///
  /// Returns an executor that can either `.execute()` (no return) or
  /// `.returning()` (returns Vec<NodeRef>).
  pub fn values_many(
    self,
    items: Vec<(&str, HashMap<String, PropValue>)>,
  ) -> Result<InsertExecutorMultiple<'a>> {
    let entries: Vec<(String, HashMap<String, PropValue>)> = items
      .into_iter()
      .map(|(key_suffix, props)| {
        let full_key = format!("{}{}", self.key_prefix, key_suffix);
        (full_key, props)
      })
      .collect();

    Ok(InsertExecutorMultiple {
      ray: self.ray,
      node_type: self.node_type,
      entries,
    })
  }
}

/// Executor for single node insert
pub struct InsertExecutorSingle<'a> {
  ray: &'a mut Ray,
  node_type: String,
  full_key: String,
  props: HashMap<String, PropValue>,
}

impl<'a> InsertExecutorSingle<'a> {
  /// Execute the insert and return the created node reference
  pub fn returning(self) -> Result<NodeRef> {
    let mut handle = begin_tx(&self.ray.db)?;

    // Create the node
    let node_opts = NodeOpts::new().with_key(self.full_key.clone());
    let node_id = create_node(&mut handle, node_opts)?;

    // Set properties
    for (prop_name, value) in self.props {
      let prop_key_id = self.ray.db.get_or_create_propkey(&prop_name);
      set_node_prop(&mut handle, node_id, prop_key_id, value)?;
    }

    commit(&mut handle)?;

    Ok(NodeRef::new(node_id, Some(self.full_key), &self.node_type))
  }

  /// Execute the insert without returning the node reference
  ///
  /// Slightly more efficient when you don't need the result.
  pub fn execute(self) -> Result<()> {
    let _ = self.returning()?;
    Ok(())
  }
}

/// Executor for multiple node insert
pub struct InsertExecutorMultiple<'a> {
  ray: &'a mut Ray,
  node_type: String,
  entries: Vec<(String, HashMap<String, PropValue>)>,
}

impl<'a> InsertExecutorMultiple<'a> {
  /// Execute the insert and return all created node references
  pub fn returning(self) -> Result<Vec<NodeRef>> {
    if self.entries.is_empty() {
      return Ok(Vec::new());
    }

    let mut handle = begin_tx(&self.ray.db)?;
    let mut results = Vec::with_capacity(self.entries.len());

    for (full_key, props) in self.entries {
      // Create the node
      let node_opts = NodeOpts::new().with_key(full_key.clone());
      let node_id = create_node(&mut handle, node_opts)?;

      // Set properties
      for (prop_name, value) in props {
        let prop_key_id = self.ray.db.get_or_create_propkey(&prop_name);
        set_node_prop(&mut handle, node_id, prop_key_id, value)?;
      }

      results.push(NodeRef::new(node_id, Some(full_key), &self.node_type));
    }

    commit(&mut handle)?;

    Ok(results)
  }

  /// Execute the insert without returning node references
  pub fn execute(self) -> Result<()> {
    let _ = self.returning()?;
    Ok(())
  }
}

// ============================================================================
// Update Edge Builder
// ============================================================================

/// Fluent builder for updating edge properties
///
/// Created via `ray.update_edge(src, edge_type, dst)` and allows chaining
/// multiple property set/unset operations before executing in a single transaction.
///
/// # Example
/// ```rust,no_run
/// # use kitedb::api::ray::Ray;
/// # use kitedb::types::{NodeId, PropValue};
/// # fn main() -> kitedb::error::Result<()> {
/// # let mut ray: Ray = unimplemented!();
/// # let alice_id: NodeId = 1;
/// # let bob_id: NodeId = 2;
/// ray.update_edge(alice_id, "FOLLOWS", bob_id)?
///    .set("weight", PropValue::F64(0.9))
///    .set("since", PropValue::String("2024".to_string()))
///    .unset("deprecated_field")
///    .execute()?;
/// # Ok(())
/// # }
/// ```
pub struct RayUpdateEdgeBuilder<'a> {
  ray: &'a mut Ray,
  src: NodeId,
  etype_id: ETypeId,
  dst: NodeId,
  updates: HashMap<String, Option<PropValue>>,
}

impl<'a> RayUpdateEdgeBuilder<'a> {
  /// Set an edge property value
  ///
  /// The property will be set when `execute()` is called.
  pub fn set(mut self, prop_name: &str, value: PropValue) -> Self {
    self.updates.insert(prop_name.to_string(), Some(value));
    self
  }

  /// Remove an edge property
  ///
  /// The property will be deleted when `execute()` is called.
  pub fn unset(mut self, prop_name: &str) -> Self {
    self.updates.insert(prop_name.to_string(), None);
    self
  }

  /// Set multiple properties at once from a HashMap
  ///
  /// Convenience method for setting multiple properties.
  pub fn set_all(mut self, props: HashMap<String, PropValue>) -> Self {
    for (k, v) in props {
      self.updates.insert(k, Some(v));
    }
    self
  }

  /// Execute the update, applying all property changes in a single transaction
  pub fn execute(self) -> Result<()> {
    if self.updates.is_empty() {
      return Ok(());
    }

    let mut handle = begin_tx(&self.ray.db)?;

    for (prop_name, value_opt) in self.updates {
      let prop_key_id = self.ray.db.get_or_create_propkey(&prop_name);

      match value_opt {
        Some(value) => {
          set_edge_prop(
            &mut handle,
            self.src,
            self.etype_id,
            self.dst,
            prop_key_id,
            value,
          )?;
        }
        None => {
          // Only delete if prop_key exists
          if let Some(existing_key_id) = self.ray.db.get_propkey_id(&prop_name) {
            del_edge_prop(
              &mut handle,
              self.src,
              self.etype_id,
              self.dst,
              existing_key_id,
            )?;
          }
        }
      }
    }

    commit(&mut handle)?;
    Ok(())
  }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
  use super::*;
  use tempfile::tempdir;

  fn create_test_schema() -> RayOptions {
    let user = NodeDef::new("User", "user:")
      .prop(PropDef::string("name").required())
      .prop(PropDef::int("age"));

    let post = NodeDef::new("Post", "post:")
      .prop(PropDef::string("title").required())
      .prop(PropDef::string("content"));

    let follows = EdgeDef::new("FOLLOWS");
    let authored = EdgeDef::new("AUTHORED");

    RayOptions::new()
      .node(user)
      .node(post)
      .edge(follows)
      .edge(authored)
  }

  #[test]
  fn test_open_database() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let ray = Ray::open(temp_dir.path(), options).unwrap();

    assert_eq!(ray.node_types().len(), 2);
    assert_eq!(ray.edge_types().len(), 2);
    assert!(ray.node_def("User").is_some());
    assert!(ray.edge_def("FOLLOWS").is_some());

    ray.close().unwrap();
  }

  #[test]
  fn test_create_and_get_node() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a user
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".to_string()));
    props.insert("age".to_string(), PropValue::I64(30));

    let user_ref = ray.create_node("User", "alice", props).unwrap();
    assert!(user_ref.id > 0);
    assert_eq!(user_ref.key, Some("user:alice".to_string()));

    // Get the user
    let found = ray.get("User", "alice").unwrap();
    assert!(found.is_some());
    assert_eq!(found.unwrap().id, user_ref.id);

    // Non-existent user
    let not_found = ray.get("User", "bob").unwrap();
    assert!(not_found.is_none());

    ray.close().unwrap();
  }

  #[test]
  fn test_link_and_unlink() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create two users
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Link them
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Check edge exists
    assert!(ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());
    assert!(!ray.has_edge(bob.id, "FOLLOWS", alice.id).unwrap());

    // Check neighbors
    let alice_follows = ray.neighbors_out(alice.id, Some("FOLLOWS")).unwrap();
    assert_eq!(alice_follows, vec![bob.id]);

    let bob_followers = ray.neighbors_in(bob.id, Some("FOLLOWS")).unwrap();
    assert_eq!(bob_followers, vec![alice.id]);

    // Unlink
    ray.unlink(alice.id, "FOLLOWS", bob.id).unwrap();
    assert!(!ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());

    ray.close().unwrap();
  }

  #[test]
  fn test_properties() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a user
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".to_string()));
    let user = ray.create_node("User", "alice", props).unwrap();

    // Get property
    let name = ray.get_prop(user.id, "name");
    assert_eq!(name, Some(PropValue::String("Alice".to_string())));

    // Set property
    ray.set_prop(user.id, "age", PropValue::I64(25)).unwrap();
    let age = ray.get_prop(user.id, "age");
    assert_eq!(age, Some(PropValue::I64(25)));

    ray.close().unwrap();
  }

  #[test]
  fn test_count_nodes() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    assert_eq!(ray.count_nodes(), 0);

    ray.create_node("User", "alice", HashMap::new()).unwrap();
    ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.create_node("Post", "post1", HashMap::new()).unwrap();

    assert_eq!(ray.count_nodes(), 3);

    ray.close().unwrap();
  }

  #[test]
  fn test_delete_node() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let user = ray.create_node("User", "alice", HashMap::new()).unwrap();
    assert!(ray.exists(user.id));

    ray.delete_node(user.id).unwrap();
    assert!(!ray.exists(user.id));

    ray.close().unwrap();
  }

  #[test]
  fn test_get_ref() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a user
    let user = ray.create_node("User", "alice", HashMap::new()).unwrap();

    // Get lightweight reference
    let node_ref = ray.get_ref("User", "alice").unwrap();
    assert!(node_ref.is_some());
    let node_ref = node_ref.unwrap();
    assert_eq!(node_ref.id, user.id);
    assert_eq!(node_ref.key, Some("user:alice".to_string()));

    // Non-existent user
    let not_found = ray.get_ref("User", "bob").unwrap();
    assert!(not_found.is_none());

    ray.close().unwrap();
  }

  #[test]
  fn test_all_nodes_by_type() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some users and posts
    ray.create_node("User", "alice", HashMap::new()).unwrap();
    ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.create_node("Post", "post1", HashMap::new()).unwrap();

    // Iterate all users
    let users: Vec<_> = ray.all("User").unwrap().collect();
    assert_eq!(users.len(), 2);

    // Iterate all posts
    let posts: Vec<_> = ray.all("Post").unwrap().collect();
    assert_eq!(posts.len(), 1);

    ray.close().unwrap();
  }

  #[test]
  fn test_count_nodes_by_type() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some users and posts
    ray.create_node("User", "alice", HashMap::new()).unwrap();
    ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.create_node("Post", "post1", HashMap::new()).unwrap();

    // Count by type
    assert_eq!(ray.count_nodes_by_type("User").unwrap(), 2);
    assert_eq!(ray.count_nodes_by_type("Post").unwrap(), 1);
    assert_eq!(ray.count_nodes(), 3);

    ray.close().unwrap();
  }

  #[test]
  fn test_all_edges() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create nodes and edges
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let post = ray.create_node("Post", "post1", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(alice.id, "AUTHORED", post.id).unwrap();

    // List all edges
    let all_edges: Vec<_> = ray.all_edges(None).unwrap().collect();
    assert_eq!(all_edges.len(), 2);

    // List FOLLOWS edges only
    let follows_edges: Vec<_> = ray.all_edges(Some("FOLLOWS")).unwrap().collect();
    assert_eq!(follows_edges.len(), 1);
    assert_eq!(follows_edges[0].src, alice.id);
    assert_eq!(follows_edges[0].dst, bob.id);

    ray.close().unwrap();
  }

  #[test]
  fn test_count_edges_by_type() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let post = ray.create_node("Post", "post1", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(alice.id, "AUTHORED", post.id).unwrap();

    // Count by type
    assert_eq!(ray.count_edges_by_type("FOLLOWS").unwrap(), 1);
    assert_eq!(ray.count_edges_by_type("AUTHORED").unwrap(), 1);
    assert_eq!(ray.count_edges(), 2);

    ray.close().unwrap();
  }

  // ============================================================================
  // Traversal Tests
  // ============================================================================

  #[test]
  fn test_from_traversal() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a chain: alice -> bob -> charlie
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(bob.id, "FOLLOWS", charlie.id).unwrap();

    // Single hop traversal
    let friends = ray.from(alice.id).out(Some("FOLLOWS")).unwrap().to_vec();
    assert_eq!(friends, vec![bob.id]);

    // Two hop traversal
    let friends_of_friends = ray
      .from(alice.id)
      .out(Some("FOLLOWS"))
      .unwrap()
      .out(Some("FOLLOWS"))
      .unwrap()
      .to_vec();
    assert_eq!(friends_of_friends, vec![charlie.id]);

    ray.close().unwrap();
  }

  #[test]
  fn test_traversal_first() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Get first result
    let first = ray
      .from(alice.id)
      .out(Some("FOLLOWS"))
      .unwrap()
      .first_node();
    assert_eq!(first, Some(bob.id));

    // No results
    let no_result = ray.from(bob.id).out(Some("FOLLOWS")).unwrap().first_node();
    assert_eq!(no_result, None);

    ray.close().unwrap();
  }

  #[test]
  fn test_traversal_count() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(alice.id, "FOLLOWS", charlie.id).unwrap();

    let count = ray.from(alice.id).out(Some("FOLLOWS")).unwrap().count();
    assert_eq!(count, 2);

    ray.close().unwrap();
  }

  // ============================================================================
  // Pathfinding Tests
  // ============================================================================

  #[test]
  fn test_shortest_path() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a chain: alice -> bob -> charlie
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(bob.id, "FOLLOWS", charlie.id).unwrap();

    // Find path
    let path = ray
      .shortest_path(alice.id, charlie.id)
      .via("FOLLOWS")
      .unwrap()
      .find();

    assert!(path.found);
    assert_eq!(path.path, vec![alice.id, bob.id, charlie.id]);
    assert_eq!(path.edges.len(), 2);

    ray.close().unwrap();
  }

  #[test]
  fn test_shortest_path_not_found() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // No edge between them
    let path = ray
      .shortest_path(alice.id, bob.id)
      .via("FOLLOWS")
      .unwrap()
      .find();

    assert!(!path.found);
    assert!(path.path.is_empty());

    ray.close().unwrap();
  }

  #[test]
  fn test_has_path() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    assert!(ray.has_path(alice.id, bob.id, Some("FOLLOWS")).unwrap());
    assert!(!ray.has_path(alice.id, charlie.id, Some("FOLLOWS")).unwrap());
    assert!(!ray.has_path(bob.id, alice.id, Some("FOLLOWS")).unwrap()); // No reverse

    ray.close().unwrap();
  }

  #[test]
  fn test_reachable_from() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create: alice -> bob -> charlie -> dave
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();
    let dave = ray.create_node("User", "dave", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(bob.id, "FOLLOWS", charlie.id).unwrap();
    ray.link(charlie.id, "FOLLOWS", dave.id).unwrap();

    // Reachable within 2 hops
    let reachable = ray.reachable_from(alice.id, 2, Some("FOLLOWS")).unwrap();
    assert!(reachable.contains(&bob.id));
    assert!(reachable.contains(&charlie.id));
    assert!(!reachable.contains(&dave.id)); // 3 hops away

    // Reachable within 3 hops
    let reachable_3 = ray.reachable_from(alice.id, 3, Some("FOLLOWS")).unwrap();
    assert!(reachable_3.contains(&dave.id));

    ray.close().unwrap();
  }

  #[test]
  fn test_k_shortest_paths() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a diamond: alice -> bob -> dave, alice -> charlie -> dave
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();
    let dave = ray.create_node("User", "dave", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(alice.id, "FOLLOWS", charlie.id).unwrap();
    ray.link(bob.id, "FOLLOWS", dave.id).unwrap();
    ray.link(charlie.id, "FOLLOWS", dave.id).unwrap();

    // Find 2 shortest paths
    let paths = ray
      .shortest_path(alice.id, dave.id)
      .via("FOLLOWS")
      .unwrap()
      .find_k_shortest(2);

    assert_eq!(paths.len(), 2);
    assert!(paths[0].found);
    assert!(paths[1].found);
    // Both paths have same length (2 edges)
    assert_eq!(paths[0].edges.len(), 2);
    assert_eq!(paths[1].edges.len(), 2);

    ray.close().unwrap();
  }

  // ============================================================================
  // Batch Operation Tests
  // ============================================================================

  #[test]
  fn test_batch_create_nodes() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create multiple nodes in a batch
    let results = ray
      .batch(vec![
        BatchOp::CreateNode {
          node_type: "User".into(),
          key_suffix: "alice".into(),
          props: HashMap::new(),
        },
        BatchOp::CreateNode {
          node_type: "User".into(),
          key_suffix: "bob".into(),
          props: HashMap::new(),
        },
        BatchOp::CreateNode {
          node_type: "Post".into(),
          key_suffix: "post1".into(),
          props: HashMap::new(),
        },
      ])
      .unwrap();

    assert_eq!(results.len(), 3);

    // Verify all nodes were created
    assert_eq!(ray.count_nodes(), 3);
    assert!(ray.get("User", "alice").unwrap().is_some());
    assert!(ray.get("User", "bob").unwrap().is_some());
    assert!(ray.get("Post", "post1").unwrap().is_some());

    ray.close().unwrap();
  }

  #[test]
  fn test_batch_create_and_link() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // First batch: create nodes
    let results = ray
      .batch(vec![
        BatchOp::CreateNode {
          node_type: "User".into(),
          key_suffix: "alice".into(),
          props: HashMap::new(),
        },
        BatchOp::CreateNode {
          node_type: "User".into(),
          key_suffix: "bob".into(),
          props: HashMap::new(),
        },
      ])
      .unwrap();

    // Extract node IDs from results
    let alice_id = match &results[0] {
      BatchResult::NodeCreated(node_ref) => node_ref.id,
      _ => panic!("Expected NodeCreated"),
    };
    let bob_id = match &results[1] {
      BatchResult::NodeCreated(node_ref) => node_ref.id,
      _ => panic!("Expected NodeCreated"),
    };

    // Second batch: create edge
    ray
      .batch(vec![BatchOp::Link {
        src: alice_id,
        edge_type: "FOLLOWS".into(),
        dst: bob_id,
      }])
      .unwrap();

    // Verify edge was created
    assert!(ray.has_edge(alice_id, "FOLLOWS", bob_id).unwrap());

    ray.close().unwrap();
  }

  #[test]
  fn test_batch_set_properties() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let user = ray.create_node("User", "alice", HashMap::new()).unwrap();

    // Batch set properties
    ray
      .batch(vec![
        BatchOp::SetProp {
          node_id: user.id,
          prop_name: "name".into(),
          value: PropValue::String("Alice".into()),
        },
        BatchOp::SetProp {
          node_id: user.id,
          prop_name: "age".into(),
          value: PropValue::I64(30),
        },
      ])
      .unwrap();

    // Verify properties
    assert_eq!(
      ray.get_prop(user.id, "name"),
      Some(PropValue::String("Alice".into()))
    );
    assert_eq!(ray.get_prop(user.id, "age"), Some(PropValue::I64(30)));

    ray.close().unwrap();
  }

  #[test]
  fn test_batch_mixed_operations() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create initial nodes
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Mixed batch: link, set prop, create node, unlink
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    let results = ray
      .batch(vec![
        BatchOp::SetProp {
          node_id: alice.id,
          prop_name: "name".into(),
          value: PropValue::String("Alice".into()),
        },
        BatchOp::CreateNode {
          node_type: "User".into(),
          key_suffix: "charlie".into(),
          props: HashMap::new(),
        },
        BatchOp::Unlink {
          src: alice.id,
          edge_type: "FOLLOWS".into(),
          dst: bob.id,
        },
      ])
      .unwrap();

    assert_eq!(results.len(), 3);

    // Verify results
    assert_eq!(
      ray.get_prop(alice.id, "name"),
      Some(PropValue::String("Alice".into()))
    );
    assert!(ray.get("User", "charlie").unwrap().is_some());
    assert!(!ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());

    ray.close().unwrap();
  }

  #[test]
  fn test_batch_delete_operations() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create nodes and edges
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Batch delete
    let results = ray
      .batch(vec![
        BatchOp::Unlink {
          src: alice.id,
          edge_type: "FOLLOWS".into(),
          dst: bob.id,
        },
        BatchOp::DeleteNode { node_id: bob.id },
      ])
      .unwrap();

    // Verify
    match &results[0] {
      BatchResult::EdgeRemoved(removed) => assert!(*removed),
      _ => panic!("Expected EdgeRemoved"),
    }
    match &results[1] {
      BatchResult::NodeDeleted(deleted) => assert!(*deleted),
      _ => panic!("Expected NodeDeleted"),
    }

    assert!(!ray.exists(bob.id));

    ray.close().unwrap();
  }

  // ============================================================================
  // Transaction Tests
  // ============================================================================

  #[test]
  fn test_transaction_basic() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Execute a transaction
    let (alice, bob) = ray
      .transaction(|ctx| {
        let alice = ctx.create_node("User", "alice", HashMap::new())?;
        let bob = ctx.create_node("User", "bob", HashMap::new())?;
        ctx.link(alice.id, "FOLLOWS", bob.id)?;
        Ok((alice, bob))
      })
      .unwrap();

    // Verify results
    assert!(ray.exists(alice.id));
    assert!(ray.exists(bob.id));
    assert!(ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());

    ray.close().unwrap();
  }

  #[test]
  fn test_transaction_with_properties() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create node with properties in transaction
    let alice = ray
      .transaction(|ctx| {
        let mut props = HashMap::new();
        props.insert("name".to_string(), PropValue::String("Alice".into()));
        let alice = ctx.create_node("User", "alice", props)?;
        ctx.set_prop(alice.id, "age", PropValue::I64(30))?;
        Ok(alice)
      })
      .unwrap();

    // Verify properties
    assert_eq!(
      ray.get_prop(alice.id, "name"),
      Some(PropValue::String("Alice".into()))
    );
    assert_eq!(ray.get_prop(alice.id, "age"), Some(PropValue::I64(30)));

    ray.close().unwrap();
  }

  #[test]
  fn test_transaction_rollback_on_error() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Transaction that fails partway through
    let result: Result<()> = ray.transaction(|ctx| {
      ctx.create_node("User", "alice", HashMap::new())?;
      // This should fail - unknown node type
      ctx.create_node("UnknownType", "bob", HashMap::new())?;
      Ok(())
    });

    // Transaction should have failed
    assert!(result.is_err());

    // Alice should NOT exist because the transaction was rolled back
    // Note: Due to WAL-based implementation, rollback happens at commit time
    // so we need to verify the final state

    ray.close().unwrap();
  }

  #[test]
  fn test_transaction_read_operations() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some data first
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    ray
      .set_prop(alice.id, "name", PropValue::String("Alice".into()))
      .unwrap();

    // Transaction that reads and writes
    let name = ray
      .transaction(|ctx| {
        // Read existing data
        let existing = ctx.get("User", "alice")?;
        assert!(existing.is_some());

        let name = ctx.get_prop(alice.id, "name")?;
        assert!(ctx.exists(alice.id));

        // Create new node
        ctx.create_node("User", "bob", HashMap::new())?;

        Ok(name)
      })
      .unwrap();

    assert_eq!(name, Some(PropValue::String("Alice".into())));
    assert!(ray.get("User", "bob").unwrap().is_some());

    ray.close().unwrap();
  }

  #[test]
  fn test_transaction_edge_operations() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create nodes first
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    // Link edges in transaction
    ray
      .transaction(|ctx| {
        ctx.link(alice.id, "FOLLOWS", bob.id)?;
        ctx.link(bob.id, "FOLLOWS", charlie.id)?;
        Ok(())
      })
      .unwrap();

    // Verify edges exist after commit
    assert!(ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());
    assert!(ray.has_edge(bob.id, "FOLLOWS", charlie.id).unwrap());
    assert!(!ray.has_edge(alice.id, "FOLLOWS", charlie.id).unwrap());

    // Test unlink in transaction
    ray
      .transaction(|ctx| {
        ctx.unlink(alice.id, "FOLLOWS", bob.id)?;
        Ok(())
      })
      .unwrap();

    // Verify edge was removed
    assert!(!ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());
    // Other edge still exists
    assert!(ray.has_edge(bob.id, "FOLLOWS", charlie.id).unwrap());

    ray.close().unwrap();
  }

  // ============================================================================
  // TxBuilder Tests
  // ============================================================================

  #[test]
  fn test_tx_builder() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Use the builder pattern
    let results = ray
      .tx()
      .create_node("User", "alice", HashMap::new())
      .create_node("User", "bob", HashMap::new())
      .execute(&mut ray)
      .unwrap();

    assert_eq!(results.len(), 2);

    // Extract IDs and create edges
    let alice_id = match &results[0] {
      BatchResult::NodeCreated(node_ref) => node_ref.id,
      _ => panic!("Expected NodeCreated"),
    };
    let bob_id = match &results[1] {
      BatchResult::NodeCreated(node_ref) => node_ref.id,
      _ => panic!("Expected NodeCreated"),
    };

    ray
      .tx()
      .link(alice_id, "FOLLOWS", bob_id)
      .set_prop(alice_id, "name", PropValue::String("Alice".into()))
      .execute(&mut ray)
      .unwrap();

    assert!(ray.has_edge(alice_id, "FOLLOWS", bob_id).unwrap());
    assert_eq!(
      ray.get_prop(alice_id, "name"),
      Some(PropValue::String("Alice".into()))
    );

    ray.close().unwrap();
  }

  #[test]
  fn test_tx_builder_into_ops() {
    // Test that into_ops returns the operations without executing
    let ops = TxBuilder::default()
      .create_node("User", "alice", HashMap::new())
      .link(1, "FOLLOWS", 2)
      .set_prop(1, "name", PropValue::String("Test".into()))
      .into_ops();

    assert_eq!(ops.len(), 3);
  }

  // ============================================================================
  // Edge Property Tests
  // ============================================================================

  #[test]
  fn test_link_with_props() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Link with properties
    let mut props = HashMap::new();
    props.insert("weight".to_string(), PropValue::F64(0.8));
    props.insert("since".to_string(), PropValue::String("2024".into()));

    ray
      .link_with_props(alice.id, "FOLLOWS", bob.id, props)
      .unwrap();

    // Verify edge exists
    assert!(ray.has_edge(alice.id, "FOLLOWS", bob.id).unwrap());

    // Verify edge properties
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, Some(PropValue::F64(0.8)));

    let since = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "since")
      .unwrap();
    assert_eq!(since, Some(PropValue::String("2024".into())));

    ray.close().unwrap();
  }

  #[test]
  fn test_set_edge_prop() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge without properties
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Set edge property
    ray
      .set_edge_prop(alice.id, "FOLLOWS", bob.id, "weight", PropValue::F64(0.5))
      .unwrap();

    // Get edge property
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, Some(PropValue::F64(0.5)));

    // Update edge property
    ray
      .set_edge_prop(alice.id, "FOLLOWS", bob.id, "weight", PropValue::F64(0.9))
      .unwrap();
    let new_weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(new_weight, Some(PropValue::F64(0.9)));

    ray.close().unwrap();
  }

  #[test]
  fn test_get_edge_props() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge with properties
    let mut props = HashMap::new();
    props.insert("weight".to_string(), PropValue::F64(0.7));
    props.insert("type".to_string(), PropValue::String("friend".into()));
    ray
      .link_with_props(alice.id, "FOLLOWS", bob.id, props)
      .unwrap();

    // Get all properties
    let all_props = ray.get_edge_props(alice.id, "FOLLOWS", bob.id).unwrap();
    assert!(all_props.is_some());

    let all_props = all_props.unwrap();
    assert_eq!(all_props.get("weight"), Some(&PropValue::F64(0.7)));
    assert_eq!(
      all_props.get("type"),
      Some(&PropValue::String("friend".into()))
    );

    ray.close().unwrap();
  }

  #[test]
  fn test_del_edge_prop() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge with property
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray
      .set_edge_prop(alice.id, "FOLLOWS", bob.id, "weight", PropValue::F64(0.5))
      .unwrap();

    // Verify property exists
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, Some(PropValue::F64(0.5)));

    // Delete property
    ray
      .del_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();

    // Verify property is gone
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, None);

    ray.close().unwrap();
  }

  #[test]
  fn test_edge_prop_nonexistent_edge() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Try to get prop on nonexistent edge - should fail gracefully
    // First we need to create the prop key
    ray
      .set_edge_prop(alice.id, "FOLLOWS", bob.id, "weight", PropValue::F64(0.5))
      .ok();

    // Edge doesn't exist, so getting props should return None
    let _props = ray.get_edge_props(alice.id, "FOLLOWS", bob.id).unwrap();
    // The edge was implicitly created when we set the prop, so it exists now
    // Let's test with a truly nonexistent edge
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();
    let props2 = ray.get_edge_props(alice.id, "FOLLOWS", charlie.id).unwrap();
    assert!(props2.is_none());

    ray.close().unwrap();
  }

  #[test]
  fn test_update_edge_builder() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge first
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Update edge properties using the builder
    ray
      .update_edge(alice.id, "FOLLOWS", bob.id)
      .unwrap()
      .set("weight", PropValue::F64(0.9))
      .set("since", PropValue::String("2024".into()))
      .execute()
      .unwrap();

    // Verify properties were set
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, Some(PropValue::F64(0.9)));

    let since = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "since")
      .unwrap();
    assert_eq!(since, Some(PropValue::String("2024".into())));

    // Update with unset
    ray
      .update_edge(alice.id, "FOLLOWS", bob.id)
      .unwrap()
      .set("weight", PropValue::F64(0.5))
      .unset("since")
      .execute()
      .unwrap();

    // Verify update and unset
    let weight = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "weight")
      .unwrap();
    assert_eq!(weight, Some(PropValue::F64(0.5)));

    let since = ray
      .get_edge_prop(alice.id, "FOLLOWS", bob.id, "since")
      .unwrap();
    assert_eq!(since, None);

    ray.close().unwrap();
  }

  #[test]
  fn test_update_edge_builder_set_all() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Update using set_all
    let mut props = HashMap::new();
    props.insert("weight".to_string(), PropValue::F64(0.8));
    props.insert("type".to_string(), PropValue::String("close_friend".into()));

    ray
      .update_edge(alice.id, "FOLLOWS", bob.id)
      .unwrap()
      .set_all(props)
      .execute()
      .unwrap();

    // Verify
    let all_props = ray
      .get_edge_props(alice.id, "FOLLOWS", bob.id)
      .unwrap()
      .unwrap();
    assert_eq!(all_props.get("weight"), Some(&PropValue::F64(0.8)));
    assert_eq!(
      all_props.get("type"),
      Some(&PropValue::String("close_friend".into()))
    );

    ray.close().unwrap();
  }

  #[test]
  fn test_update_edge_builder_empty() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();

    // Create edge
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Empty update should succeed (no-op)
    ray
      .update_edge(alice.id, "FOLLOWS", bob.id)
      .unwrap()
      .execute()
      .unwrap();

    ray.close().unwrap();
  }

  #[test]
  fn test_insert_builder_returning() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Insert with returning
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".into()));
    props.insert("age".to_string(), PropValue::I64(30));

    let alice = ray
      .insert("User")
      .unwrap()
      .values("alice", props)
      .unwrap()
      .returning()
      .unwrap();

    // Verify the returned node
    assert!(alice.id > 0);
    assert_eq!(alice.key, Some("user:alice".to_string()));
    assert_eq!(alice.node_type, "User");

    // Verify properties were set
    let name = ray.get_prop(alice.id, "name");
    assert_eq!(name, Some(PropValue::String("Alice".into())));

    let age = ray.get_prop(alice.id, "age");
    assert_eq!(age, Some(PropValue::I64(30)));

    ray.close().unwrap();
  }

  #[test]
  fn test_insert_builder_execute() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Insert without returning
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Bob".into()));

    ray
      .insert("User")
      .unwrap()
      .values("bob", props)
      .unwrap()
      .execute()
      .unwrap();

    // Verify node was created
    let bob = ray.get("User", "bob").unwrap();
    assert!(bob.is_some());

    let bob = bob.unwrap();
    let name = ray.get_prop(bob.id, "name");
    assert_eq!(name, Some(PropValue::String("Bob".into())));

    ray.close().unwrap();
  }

  #[test]
  fn test_insert_builder_values_many() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Insert multiple nodes
    let mut alice_props = HashMap::new();
    alice_props.insert("name".to_string(), PropValue::String("Alice".into()));

    let mut bob_props = HashMap::new();
    bob_props.insert("name".to_string(), PropValue::String("Bob".into()));

    let mut charlie_props = HashMap::new();
    charlie_props.insert("name".to_string(), PropValue::String("Charlie".into()));

    let users = ray
      .insert("User")
      .unwrap()
      .values_many(vec![
        ("alice", alice_props),
        ("bob", bob_props),
        ("charlie", charlie_props),
      ])
      .unwrap()
      .returning()
      .unwrap();

    // Verify all nodes were created
    assert_eq!(users.len(), 3);
    assert_eq!(users[0].key, Some("user:alice".to_string()));
    assert_eq!(users[1].key, Some("user:bob".to_string()));
    assert_eq!(users[2].key, Some("user:charlie".to_string()));

    // Verify count
    assert_eq!(ray.count_nodes(), 3);

    ray.close().unwrap();
  }

  #[test]
  fn test_insert_builder_empty_values_many() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Empty insert should succeed
    let users = ray
      .insert("User")
      .unwrap()
      .values_many(vec![])
      .unwrap()
      .returning()
      .unwrap();

    assert_eq!(users.len(), 0);
    assert_eq!(ray.count_nodes(), 0);

    ray.close().unwrap();
  }

  #[test]
  fn test_check_empty_database() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let ray = Ray::open(temp_dir.path(), options).unwrap();

    let result = ray.check().unwrap();
    assert!(result.valid);
    assert!(result.errors.is_empty());
    // Should have a warning about missing snapshot
    assert!(result.warnings.iter().any(|w| w.contains("No snapshot")));

    ray.close().unwrap();
  }

  #[test]
  fn test_check_valid_database() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some nodes and edges
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    let charlie = ray.create_node("User", "charlie", HashMap::new()).unwrap();

    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();
    ray.link(bob.id, "FOLLOWS", charlie.id).unwrap();
    ray.link(charlie.id, "FOLLOWS", alice.id).unwrap();

    // Check should pass
    let result = ray.check().unwrap();
    assert!(
      result.valid,
      "Expected valid database, got errors: {:?}",
      result.errors
    );
    assert!(result.errors.is_empty());

    ray.close().unwrap();
  }

  #[test]
  fn test_check_with_properties() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create nodes with properties
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".into()));
    props.insert("age".to_string(), PropValue::I64(30));
    let alice = ray.create_node("User", "alice", props).unwrap();

    let mut props2 = HashMap::new();
    props2.insert("name".to_string(), PropValue::String("Bob".into()));
    let bob = ray.create_node("User", "bob", props2).unwrap();

    // Create edge with properties
    let mut edge_props = HashMap::new();
    edge_props.insert("weight".to_string(), PropValue::F64(0.9));
    ray
      .link_with_props(alice.id, "FOLLOWS", bob.id, edge_props)
      .unwrap();

    // Check should pass
    let result = ray.check().unwrap();
    assert!(
      result.valid,
      "Expected valid database, got errors: {:?}",
      result.errors
    );
    assert!(result.errors.is_empty());

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_by_ref() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".into()));
    props.insert("age".to_string(), PropValue::I64(30));
    let alice = ray.create_node("User", "alice", props).unwrap();

    // Update by reference
    ray
      .update(&alice)
      .unwrap()
      .set("name", PropValue::String("Alice Updated".into()))
      .set("age", PropValue::I64(31))
      .execute()
      .unwrap();

    // Verify updates
    let name = ray.get_prop(alice.id, "name");
    assert_eq!(name, Some(PropValue::String("Alice Updated".into())));

    let age = ray.get_prop(alice.id, "age");
    assert_eq!(age, Some(PropValue::I64(31)));

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_by_key() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Bob".into()));
    ray.create_node("User", "bob", props).unwrap();

    // Update by key
    ray
      .update_by_key("User", "bob")
      .unwrap()
      .set("name", PropValue::String("Bob Updated".into()))
      .set("age", PropValue::I64(25))
      .execute()
      .unwrap();

    // Verify updates
    let bob = ray.get("User", "bob").unwrap().unwrap();
    let name = ray.get_prop(bob.id, "name");
    assert_eq!(name, Some(PropValue::String("Bob Updated".into())));

    let age = ray.get_prop(bob.id, "age");
    assert_eq!(age, Some(PropValue::I64(25)));

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_by_id() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Charlie".into()));
    let charlie = ray.create_node("User", "charlie", props).unwrap();

    // Update by ID
    ray
      .update_by_id(charlie.id)
      .unwrap()
      .set("name", PropValue::String("Charlie Updated".into()))
      .execute()
      .unwrap();

    // Verify updates
    let name = ray.get_prop(charlie.id, "name");
    assert_eq!(name, Some(PropValue::String("Charlie Updated".into())));

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_unset() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node with properties
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Dave".into()));
    props.insert("age".to_string(), PropValue::I64(40));
    let dave = ray.create_node("User", "dave", props).unwrap();

    // Verify properties exist
    assert!(ray.get_prop(dave.id, "age").is_some());

    // Update with unset
    ray
      .update(&dave)
      .unwrap()
      .set("name", PropValue::String("Dave Updated".into()))
      .unset("age")
      .execute()
      .unwrap();

    // Verify name updated and age removed
    let name = ray.get_prop(dave.id, "name");
    assert_eq!(name, Some(PropValue::String("Dave Updated".into())));

    let age = ray.get_prop(dave.id, "age");
    assert_eq!(age, None);

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_set_all() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let eve = ray.create_node("User", "eve", HashMap::new()).unwrap();

    // Update with set_all
    let mut updates = HashMap::new();
    updates.insert("name".to_string(), PropValue::String("Eve".into()));
    updates.insert("age".to_string(), PropValue::I64(28));

    ray
      .update(&eve)
      .unwrap()
      .set_all(updates)
      .execute()
      .unwrap();

    // Verify all properties set
    let name = ray.get_prop(eve.id, "name");
    assert_eq!(name, Some(PropValue::String("Eve".into())));

    let age = ray.get_prop(eve.id, "age");
    assert_eq!(age, Some(PropValue::I64(28)));

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_nonexistent() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Try to update non-existent node by ID
    let result = ray.update_by_id(999999);
    assert!(result.is_err());

    // Try to update non-existent node by key
    let result = ray.update_by_key("User", "nonexistent");
    assert!(result.is_err());

    ray.close().unwrap();
  }

  #[test]
  fn test_update_node_empty() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create a node
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Frank".into()));
    let frank = ray.create_node("User", "frank", props).unwrap();

    // Empty update should succeed (no-op)
    ray.update(&frank).unwrap().execute().unwrap();

    // Verify nothing changed
    let name = ray.get_prop(frank.id, "name");
    assert_eq!(name, Some(PropValue::String("Frank".into())));

    ray.close().unwrap();
  }

  #[test]
  fn test_describe() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some data
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Get description
    let desc = ray.describe();

    // Should contain path
    assert!(desc.contains("KiteDB at"));
    // Should mention format
    assert!(desc.contains("format"));
    // Should list node types
    assert!(desc.contains("User"));
    // Should list edge types
    assert!(desc.contains("FOLLOWS"));
    // Should include stats
    assert!(desc.contains("Nodes:"));
    assert!(desc.contains("Edges:"));

    ray.close().unwrap();
  }

  #[test]
  fn test_stats() {
    let temp_dir = tempdir().unwrap();
    let options = create_test_schema();

    let mut ray = Ray::open(temp_dir.path(), options).unwrap();

    // Create some data
    let alice = ray.create_node("User", "alice", HashMap::new()).unwrap();
    let bob = ray.create_node("User", "bob", HashMap::new()).unwrap();
    ray.link(alice.id, "FOLLOWS", bob.id).unwrap();

    // Get stats
    let stats = ray.stats();

    // Should report correct counts
    assert!(stats.snapshot_nodes >= 2);
    assert!(stats.snapshot_edges >= 1);
    // Delta should show created nodes
    assert!(stats.delta_nodes_created >= 2);
    assert!(stats.delta_edges_added >= 1);

    ray.close().unwrap();
  }
}