helix-db 2.0.0

Library for working with HelixDB
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
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
//! # HelixDB Query Guide
//!
//! This module is the query-builder DSL of the `helix-db` crate (imported as `helix_db`),
//! centered on two entry points:
//! - [`read_batch()`] for read-only transactions
//! - [`write_batch()`] for write-capable transactions
//!
//! Everything in this crate is designed to be composed inside those batch chains.
//! You write one or more named traversals with `.var_as(...)` / `.var_as_if(...)`, then
//! choose the final payload with `.returning(...)`.
//!
//! For shorter query code, import the curated builder API:
//! ```
//! use helix_db::dsl::prelude::*;
//! ```
//!
//! ## Core Shape
//!
//! Read chain:
//! `read_batch() -> var_as / var_as_if -> returning`
//!
//! Write chain:
//! `write_batch() -> var_as / var_as_if -> returning`
//!
//! Each `var_as` call accepts a traversal expression, usually starting with `g()`.
//! Traversals can read, traverse, filter, aggregate, or mutate depending on whether
//! they are used in a read or write batch.
//!
//! ## Read Batches
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "user",
//!         g().n_where(SourcePredicate::eq("username", "alice")),
//!     )
//!     .var_as(
//!         "friends",
//!         g()
//!             .n(NodeRef::var("user"))
//!             .out(Some("FOLLOWS"))
//!             .dedup()
//!             .limit(100),
//!     )
//!     .returning(["user", "friends"]);
//! ```
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "active_users",
//!         g()
//!             .n_with_label_where("User", SourcePredicate::eq("status", "active"))
//!             .where_(Predicate::gt("score", 100i64))
//!             .order_by("score", Order::Desc)
//!             .limit(25)
//!             .value_map(Some(vec!["$id", "name", "score"])),
//!     )
//!     .returning(["active_users"]);
//! ```
//!
//! ## Conditional Queries
//!
//! Use [`BatchCondition`] with `var_as_if` to run later queries only when earlier
//! variables satisfy runtime conditions.
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "user",
//!         g().n_where(SourcePredicate::eq("username", "alice")),
//!     )
//!     .var_as_if(
//!         "posts",
//!         BatchCondition::VarNotEmpty("user".to_string()),
//!         g().n(NodeRef::var("user")).out(Some("POSTED")),
//!     )
//!     .returning(["user", "posts"]);
//! ```
//!
//! ## Write Batches
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! write_batch()
//!     .var_as(
//!         "alice",
//!         g().add_n("User", vec![("name", "Alice"), ("tier", "pro")]),
//!     )
//!     .var_as("bob", g().add_n("User", vec![("name", "Bob")]))
//!     .var_as(
//!         "linked",
//!         g()
//!             .n(NodeRef::var("alice"))
//!             .add_e(
//!                 "FOLLOWS",
//!                 NodeRef::var("bob"),
//!                 vec![("since", "2026-01-01")],
//!             )
//!             .count(),
//!     )
//!     .returning(["alice", "bob", "linked"]);
//! ```
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! write_batch()
//!     .var_as(
//!         "inactive_users",
//!         g().n_with_label_where(
//!             "User",
//!             SourcePredicate::eq("status", "inactive"),
//!         ),
//!     )
//!     .var_as_if(
//!         "deactivated_count",
//!         BatchCondition::VarNotEmpty("inactive_users".to_string()),
//!         g()
//!             .n(NodeRef::var("inactive_users"))
//!             .set_property("deactivated", true)
//!             .count(),
//!     )
//!     .returning(["deactivated_count"]);
//! ```
//!
//! ## Vector Search Operations (End-to-End)
//!
//! The current Helix interpreter executes vector search as top-k nearest-neighbor
//! lookup with these runtime semantics:
//! - returns up to `k` hits (top-k behavior)
//! - hit order is ascending by `$distance` (smaller is closer)
//! - hit metadata can be read through virtual fields in projections:
//!   - node hits: `$id`, `$distance`
//!   - edge hits: `$id`, `$from`, `$to`, `$distance`
//!
//! ### Result field contract
//!
//! | Field | Type | Node hits | Edge hits | Meaning |
//! |---|---|---:|---:|---|
//! | `$id` | integer | yes | yes* | Node ID (for node hits) or edge ID (for edge hits) |
//! | `$distance` | floating-point | yes | yes | Vector distance from query (`lower` = closer) |
//! | `$from` | integer | no | yes | Edge source node ID |
//! | `$to` | integer | no | yes | Edge target node ID |
//!
//! `*` For edge hits, `$id` is present when an edge ID is available in storage.
//!
//! Contract scope in the current Helix interpreter:
//! - available on direct vector-hit streams and projection terminals
//! - available in `value_map`, `values`, `project`, and (for edges) `edge_properties`
//! - once a traversal step leaves the hit stream (`out`, `in_`, `both`, etc.),
//!   downstream traversers no longer carry distance metadata
//!
//! ### 1) Create indexes and insert vectors
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! write_batch()
//!     .var_as(
//!         "create_doc_index",
//!         g().create_vector_index_nodes(
//!             "Doc",
//!             "embedding",
//!             None::<&str>,
//!         ),
//!     )
//!     .var_as(
//!         "create_similar_index",
//!         g().create_vector_index_edges(
//!             "SIMILAR",
//!             "embedding",
//!             None::<&str>,
//!         ),
//!     )
//!     .var_as(
//!         "doc_a",
//!         g().add_n(
//!             "Doc",
//!             vec![
//!                 ("title", PropertyValue::from("A")),
//!                 ("embedding", PropertyValue::from(vec![1.0f32, 0.0, 0.0])),
//!             ],
//!         ),
//!     )
//!     .var_as(
//!         "doc_b",
//!         g().add_n(
//!             "Doc",
//!             vec![
//!                 ("title", PropertyValue::from("B")),
//!                 ("embedding", PropertyValue::from(vec![0.9f32, 0.1, 0.0])),
//!             ],
//!         ),
//!     )
//!     .returning(["create_doc_index", "doc_a", "doc_b"]);
//! ```
//!
//! ### 2) Node vector search: get ranked hits and fetch node properties
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "doc_hits",
//!         g().vector_search_nodes("Doc", "embedding", vec![1.0f32, 0.0, 0.0], 5, None)
//!             .value_map(Some(vec!["$id", "$distance", "title"])),
//!     )
//!     .returning(["doc_hits"]);
//! ```
//!
//! ```text
//! doc_hits rows (example shape):
//! [
//!   { "$id": 42, "$distance": 0.0031, "title": "A" },
//!   { "$id": 77, "$distance": 0.0198, "title": "B" }
//! ]
//! ```
//!
//! ### 3) Use `project(...)` on vector hits (including distance)
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "ranked_docs",
//!         g().vector_search_nodes("Doc", "embedding", vec![1.0f32, 0.0, 0.0], 10, None)
//!             .project(vec![
//!                 PropertyProjection::renamed("$id", "doc_id"),
//!                 PropertyProjection::renamed("$distance", "score"),
//!                 PropertyProjection::new("title"),
//!             ]),
//!     )
//!     .returning(["ranked_docs"]);
//! ```
//!
//! ### 4) Traverse from hit IDs to related entities
//!
//! Store hit rows (with `$id` + `$distance`) and then use `NodeRef::var(...)` to
//! continue graph traversal from those hit IDs.
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "doc_hit_rows",
//!         g().vector_search_nodes("Doc", "embedding", vec![1.0f32, 0.0, 0.0], 5, None)
//!             .value_map(Some(vec!["$id", "$distance", "title"])),
//!     )
//!     .var_as(
//!         "authors",
//!         g().n(NodeRef::var("doc_hit_rows"))
//!             .out(Some("AUTHORED_BY"))
//!             .value_map(Some(vec!["$id", "name"])),
//!     )
//!     .returning(["doc_hit_rows", "authors"]);
//! ```
//!
//! ### 5) Edge vector search and endpoint/property extraction
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "edge_hits",
//!         g().vector_search_edges("SIMILAR", "embedding", vec![1.0f32, 0.0, 0.0], 10, None)
//!             .edge_properties(),
//!     )
//!     .var_as(
//!         "targets",
//!         g().e(EdgeRef::var("edge_hits"))
//!             .out_n()
//!             .value_map(Some(vec!["$id", "title"])),
//!     )
//!     .returning(["edge_hits", "targets"]);
//! ```
//!
//! `edge_hits` rows include `$from`, `$to`, and `$distance` (and `$id` when available),
//! so you can inspect ranking metadata and still traverse from those edges.
//!
//! ### 6) Optional multitenancy
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! write_batch()
//!     .var_as(
//!         "create_mt_index",
//!         g().create_vector_index_nodes(
//!             "Doc",
//!             "embedding",
//!             Some("tenant_id"),
//!         ),
//!     )
//!     .var_as(
//!         "insert_acme",
//!         g().add_n(
//!             "Doc",
//!             vec![
//!                 ("tenant_id", PropertyValue::from("acme")),
//!                 ("title", PropertyValue::from("Acme doc")),
//!                 ("embedding", PropertyValue::from(vec![1.0f32, 0.0, 0.0])),
//!             ],
//!         ),
//!     )
//!     .returning(["create_mt_index", "insert_acme"]);
//! ```
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "acme_hits",
//!         g().vector_search_nodes(
//!             "Doc",
//!             "embedding",
//!             vec![1.0f32, 0.0, 0.0],
//!             5,
//!             Some(PropertyValue::from("acme")),
//!         )
//!         .value_map(Some(vec!["$id", "$distance", "title"])),
//!     )
//!     .returning(["acme_hits"]);
//! ```
//!
//! Multitenant behavior in the current Helix interpreter:
//! - multitenant index + missing `tenant_value` on search => query error
//! - multitenant index + unknown tenant => empty result set
//! - write with vector present but missing tenant property => write error
//!
//! ## Edge-First Reads
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "heavy_edges",
//!         g()
//!             .e_where(SourcePredicate::gt("weight", 0.8f64))
//!             .edge_has_label("FOLLOWS")
//!             .order_by("weight", Order::Desc)
//!             .limit(50),
//!     )
//!     .var_as(
//!         "targets",
//!         g()
//!             .e(EdgeRef::var("heavy_edges"))
//!             .out_n()
//!             .dedup(),
//!     )
//!     .returning(["heavy_edges", "targets"]);
//! ```
//!
//! ## Branching and Repetition
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "recommendations",
//!         g()
//!             .n(1u64)
//!             .store("seed")
//!             .repeat(RepeatConfig::new(sub().out(Some("FOLLOWS"))).times(2))
//!             .without("seed")
//!             .union(vec![sub().out(Some("LIKES"))])
//!             .dedup()
//!             .limit(30),
//!     )
//!     .returning(["recommendations"]);
//! ```
//!
//! ## Complete Function Coverage
//!
//! The examples below are a catalog-style reference showing every public query-builder
//! function in a `read_batch()` / `write_batch()` flow.
//!
//! ### Sources, NodeRef, EdgeRef, and Vector Search
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as("n_id", g().n(NodeRef::id(1)))
//!     .var_as("n_ids", g().n(NodeRef::ids([1u64, 2, 3])))
//!     .var_as("n_var", g().n(NodeRef::var("n_ids")))
//!     .var_as(
//!         "n_where_all",
//!         g().n_where(SourcePredicate::and(vec![
//!             SourcePredicate::eq("kind", "user"),
//!             SourcePredicate::neq("status", "deleted"),
//!             SourcePredicate::gt("score", 10i64),
//!             SourcePredicate::gte("score", 10i64),
//!             SourcePredicate::lt("score", 100i64),
//!             SourcePredicate::lte("score", 100i64),
//!             SourcePredicate::between("age", 18i64, 65i64),
//!             SourcePredicate::has_key("email"),
//!             SourcePredicate::starts_with("name", "a"),
//!             SourcePredicate::or(vec![
//!                 SourcePredicate::eq("tier", "pro"),
//!                 SourcePredicate::eq("tier", "team"),
//!             ]),
//!         ])),
//!     )
//!     .var_as("n_label", g().n_with_label("User"))
//!     .var_as(
//!         "n_label_where",
//!         g().n_with_label_where("User", SourcePredicate::eq("active", true)),
//!     )
//!     .var_as("e_id", g().e(EdgeRef::id(10)))
//!     .var_as("e_ids", g().e(EdgeRef::ids([10u64, 11, 12])))
//!     .var_as("e_var", g().e(EdgeRef::var("e_ids")))
//!     .var_as("e_where", g().e_where(SourcePredicate::gte("weight", 0.5f64)))
//!     .var_as("e_label", g().e_with_label("FOLLOWS"))
//!     .var_as(
//!         "e_label_where",
//!         g().e_with_label_where("FOLLOWS", SourcePredicate::lt("weight", 2.0f64)),
//!     )
//!     .var_as(
//!         "vector_nodes",
//!         g().vector_search_nodes("Doc", "embedding", vec![0.1f32; 4], 5, None),
//!     )
//!     .var_as(
//!         "vector_edges",
//!         g().vector_search_edges("SIMILAR", "embedding", vec![0.2f32; 4], 4, None),
//!     )
//!     .var_as(
//!         "vector_nodes_tenant",
//!         g().vector_search_nodes(
//!             "Doc",
//!             "embedding",
//!             vec![0.1f32; 4],
//!             5,
//!             Some(PropertyValue::from("acme")),
//!         ),
//!     )
//!     .var_as(
//!         "vector_edges_tenant",
//!         g().vector_search_edges(
//!             "SIMILAR",
//!             "embedding",
//!             vec![0.2f32; 4],
//!             4,
//!             Some(PropertyValue::from("acme")),
//!         ),
//!     )
//!     .returning(["n_id", "e_id", "vector_nodes"]);
//! ```
//!
//! ### Node Traversal, Filters, Predicates, Expressions, and Projections
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "filtered",
//!         g()
//!             .n(1u64)
//!             .out(Some("FOLLOWS"))
//!             .in_(Some("MENTIONS"))
//!             .both(None::<&str>)
//!             .has(
//!                 "name",
//!                 PropertyValue::from("alice").as_str().unwrap_or("alice"),
//!             )
//!             .has("visits", PropertyValue::from(42i64).as_i64().unwrap_or(0i64))
//!             .has("ratio", PropertyValue::from(1.5f64).as_f64().unwrap_or(0.0f64))
//!             .has("active", PropertyValue::from(true).as_bool().unwrap_or(false))
//!             .has_label("User")
//!             .has_key("email")
//!             .where_(Predicate::and(vec![
//!                 Predicate::eq("status", "active"),
//!                 Predicate::neq("tier", "banned"),
//!                 Predicate::gt("score", 10i64),
//!                 Predicate::gte("score", 10i64),
//!                 Predicate::lt("score", 100i64),
//!                 Predicate::lte("score", 100i64),
//!                 Predicate::between("age", 18i64, 65i64),
//!                 Predicate::has_key("email"),
//!                 Predicate::starts_with("name", "a"),
//!                 Predicate::ends_with("email", ".com"),
//!                 Predicate::contains("bio", "graph"),
//!                 Predicate::not(Predicate::or(vec![
//!                     Predicate::eq("role", "bot"),
//!                     Predicate::eq("role", "system"),
//!                 ])),
//!                 Predicate::compare(
//!                     Expr::prop("price")
//!                         .mul(Expr::prop("qty"))
//!                         .add(Expr::val(10i64))
//!                         .sub(Expr::param("discount"))
//!                         .div(Expr::val(2i64))
//!                         .modulo(Expr::val(3i64))
//!                         .add(Expr::id().neg()),
//!                     CompareOp::Gt,
//!                     Expr::val(100i64),
//!                 ),
//!                 Predicate::is_in(
//!                     "status",
//!                     vec!["active".to_string(), "pending".to_string()],
//!                 ),
//!                 Predicate::eq_param("region", "target_region"),
//!                 Predicate::is_in_param("country", "allowed_countries"),
//!                 Predicate::neq_param("status", "blocked_status"),
//!                 Predicate::gt_param("score", "min_score"),
//!                 Predicate::gte_param("score", "min_score_inclusive"),
//!                 Predicate::lt_param("score", "max_score"),
//!                 Predicate::lte_param("score", "max_score_inclusive"),
//!             ]))
//!             .as_("seed")
//!             .store("seed_store")
//!             .select("seed")
//!             .inject("seed_store")
//!             .within("seed_store")
//!             .without("seed")
//!             .dedup()
//!             .order_by("score", Order::Desc)
//!             .order_by_multiple(vec![("age", Order::Asc), ("score", Order::Desc)])
//!             .limit(100)
//!             .skip(5)
//!             .range(0, 20),
//!     )
//!     .var_as("counted", g().n(NodeRef::var("filtered")).count())
//!     .var_as("exists", g().n(NodeRef::var("filtered")).exists())
//!     .var_as("ids", g().n(NodeRef::var("filtered")).id())
//!     .var_as("labels", g().n(NodeRef::var("filtered")).label())
//!     .var_as("values", g().n(NodeRef::var("filtered")).values(vec!["name", "email"]))
//!     .var_as(
//!         "value_map_some",
//!         g().n(NodeRef::var("filtered"))
//!             .value_map(Some(vec!["$id", "name", "email"])),
//!     )
//!     .var_as(
//!         "value_map_all",
//!         g().n(NodeRef::var("filtered")).value_map(None::<Vec<&str>>),
//!     )
//!     .var_as(
//!         "projected",
//!         g().n(NodeRef::var("filtered")).project(vec![
//!             PropertyProjection::new("name"),
//!             PropertyProjection::renamed("email", "contact"),
//!         ]),
//!     )
//!     .returning(["filtered", "projected"]);
//! ```
//!
//! ### Edge Traversal and Edge Terminals
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "edge_ops",
//!         g()
//!             .e_where(SourcePredicate::gt("weight", 0.1f64))
//!             .edge_has("weight", 1i64)
//!             .edge_has_label("FOLLOWS")
//!             .as_("edges_a")
//!             .store("edges_b")
//!             .dedup()
//!             .order_by("weight", Order::Desc)
//!             .limit(50)
//!             .skip(2)
//!             .range(0, 20),
//!     )
//!     .var_as("to_out_n", g().e(EdgeRef::var("edge_ops")).out_n())
//!     .var_as("to_in_n", g().e(EdgeRef::var("edge_ops")).in_n())
//!     .var_as("to_other_n", g().e(EdgeRef::var("edge_ops")).other_n())
//!     .var_as("edge_count", g().e(EdgeRef::var("edge_ops")).count())
//!     .var_as("edge_exists", g().e(EdgeRef::var("edge_ops")).exists())
//!     .var_as("edge_ids", g().e(EdgeRef::var("edge_ops")).id())
//!     .var_as("edge_labels", g().e(EdgeRef::var("edge_ops")).label())
//!     .var_as("edge_props", g().e(EdgeRef::var("edge_ops")).edge_properties())
//!     .returning(["edge_ops", "edge_props"]);
//! ```
//!
//! ### Branching, Sub-Traversals, Repeat, Grouping, Paths, and Sack
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as(
//!         "advanced",
//!         g()
//!             .n(1u64)
//!             .out_e(Some("FOLLOWS"))
//!             .in_n()
//!             .in_e(Some("MENTIONS"))
//!             .out_n()
//!             .both_e(None::<&str>)
//!             .other_n()
//!             .repeat(
//!                 RepeatConfig::new(sub().out(Some("FOLLOWS")))
//!                     .times(2)
//!                     .until(Predicate::has_key("stop"))
//!                     .emit_all()
//!                     .emit_before()
//!                     .emit_after()
//!                     .emit_if(Predicate::gt("score", 0i64))
//!                     .max_depth(8),
//!             )
//!             .union(vec![
//!                 sub().out(Some("LIKES")),
//!                 SubTraversal::new()
//!                     .out(Some("FOLLOWS"))
//!                     .in_(Some("MENTIONS"))
//!                     .both(None::<&str>)
//!                     .out_e(Some("REL"))
//!                     .in_e(Some("REL"))
//!                     .both_e(None::<&str>)
//!                     .out_n()
//!                     .in_n()
//!                     .other_n()
//!                     .has("active", true)
//!                     .has_label("User")
//!                     .has_key("email")
//!                     .where_(Predicate::eq("state", "ok"))
//!                     .dedup()
//!                     .within("allow")
//!                     .without("deny")
//!                     .edge_has("weight", 1i64)
//!                     .edge_has_label("REL")
//!                     .limit(10)
//!                     .skip(1)
//!                     .range(0, 5)
//!                     .as_("s1")
//!                     .store("s2")
//!                     .select("s1")
//!                     .order_by("score", Order::Desc)
//!                     .order_by_multiple(vec![("age", Order::Asc)])
//!                     .path()
//!                     .simple_path(),
//!             ])
//!             .choose(
//!                 Predicate::eq("vip", true),
//!                 sub().out(Some("PREMIUM")),
//!                 Some(sub().out(Some("STANDARD"))),
//!             )
//!             .coalesce(vec![sub().out(Some("POSTED")), sub().out(Some("COMMENTED"))])
//!             .optional(sub().out(Some("MENTIONED")))
//!             .fold()
//!             .unfold()
//!             .path()
//!             .simple_path()
//!             .with_sack(PropertyValue::I64(0))
//!             .sack_set("weight")
//!             .sack_add("weight")
//!             .sack_get()
//!             .dedup(),
//!     )
//!     .var_as("grouped", g().n_with_label("User").group("team"))
//!     .var_as("grouped_count", g().n_with_label("User").group_count("team"))
//!     .var_as(
//!         "aggregate_count",
//!         g().n_with_label("User")
//!             .aggregate_by(AggregateFunction::Count, "score"),
//!     )
//!     .var_as(
//!         "aggregate_sum",
//!         g().n_with_label("User").aggregate_by(AggregateFunction::Sum, "score"),
//!     )
//!     .var_as(
//!         "aggregate_min",
//!         g().n_with_label("User").aggregate_by(AggregateFunction::Min, "score"),
//!     )
//!     .var_as(
//!         "aggregate_max",
//!         g().n_with_label("User").aggregate_by(AggregateFunction::Max, "score"),
//!     )
//!     .var_as(
//!         "aggregate_mean",
//!         g().n_with_label("User")
//!             .aggregate_by(AggregateFunction::Mean, "score"),
//!     )
//!     .returning(["advanced", "grouped", "grouped_count", "aggregate_count"]);
//! ```
//!
//! ### Read-Batch Conditions
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! read_batch()
//!     .var_as("base", g().n_with_label("User"))
//!     .var_as_if(
//!         "if_not_empty",
//!         BatchCondition::VarNotEmpty("base".to_string()),
//!         g().n(NodeRef::var("base")).limit(10),
//!     )
//!     .var_as_if(
//!         "if_empty",
//!         BatchCondition::VarEmpty("base".to_string()),
//!         g().n_with_label("FallbackUser"),
//!     )
//!     .var_as_if(
//!         "if_min_size",
//!         BatchCondition::VarMinSize("base".to_string(), 5),
//!         g().n(NodeRef::var("base")).order_by("score", Order::Desc),
//!     )
//!     .var_as_if(
//!         "if_prev_not_empty",
//!         BatchCondition::PrevNotEmpty,
//!         g().n(NodeRef::var("base")).count(),
//!     )
//!     .returning(["base", "if_not_empty", "if_empty", "if_min_size", "if_prev_not_empty"]);
//! ```
//!
//! ### Write Sources, Mutations, and Vector Index Configuration
//!
//! ```
//! # use helix_db::dsl::prelude::*;
//! write_batch()
//!     .var_as("created_user", g().add_n("User", vec![("name", "Alice")]))
//!     .var_as(
//!         "created_team",
//!         g().n(NodeRef::var("created_user"))
//!             .add_n("Team", vec![("name", "Graph")]),
//!     )
//!     .var_as(
//!         "connected",
//!         g().n(NodeRef::var("created_user")).add_e(
//!             "MEMBER_OF",
//!             NodeRef::var("created_team"),
//!             vec![("since", "2026-01-01")],
//!         ),
//!     )
//!     .var_as(
//!         "updated",
//!         g().n(NodeRef::var("created_user"))
//!             .set_property("active", true)
//!             .remove_property("old_field"),
//!     )
//!     .var_as(
//!         "drop_some_edges",
//!         g().n(NodeRef::var("created_user"))
//!             .drop_edge(NodeRef::ids([2u64, 3]))
//!             .drop_edge_by_id(EdgeRef::ids([40u64, 41])),
//!     )
//!     .var_as("drop_nodes", g().n(NodeRef::var("created_team")).drop())
//!     .var_as("inject_from_empty", g().inject("created_user").has_label("User"))
//!     .var_as("drop_edge_by_id_from_empty", g().drop_edge_by_id([90u64, 91]))
//!     .var_as(
//!         "create_vector_index_nodes",
//!         g().create_vector_index_nodes(
//!             "Doc",
//!             "embedding",
//!             Some("tenant_id"),
//!         ),
//!     )
//!     .var_as(
//!         "create_vector_index_edges",
//!         g().create_vector_index_edges(
//!             "SIMILAR",
//!             "embedding",
//!             None::<&str>,
//!         ),
//!     )
//!     .var_as(
//!         "create_vector_index_edges_alt",
//!         g().create_vector_index_edges(
//!             "RELATED",
//!             "embedding",
//!             None::<&str>,
//!         ),
//!     )
//!     .var_as_if(
//!         "write_if_not_empty",
//!         BatchCondition::VarNotEmpty("created_user".to_string()),
//!         g().n(NodeRef::var("created_user")).set_property("verified", true),
//!     )
//!     .returning([
//!         "created_user",
//!         "created_team",
//!         "connected",
//!         "updated",
//!         "drop_some_edges",
//!         "drop_nodes",
//!         "inject_from_empty",
//!         "drop_edge_by_id_from_empty",
//!         "create_vector_index_nodes",
//!         "create_vector_index_edges",
//!         "create_vector_index_edges_alt",
//!         "write_if_not_empty",
//!     ]);
//! ```
//!
//! ## Traversal Building Inside `var_as(...)`
//!
//! Common source steps:
//! - `n(...)`, `n_where(...)`, `n_with_label(...)`
//! - `e(...)`, `e_where(...)`, `e_with_label(...)`
//! - `vector_search_nodes(...)`, `vector_search_edges(...)`
//!   - current Helix runtime exposes vector hit metadata via virtual fields
//!     (`$id`, `$distance`, `$from`, `$to`) in terminal projections
//!
//! Common navigation and filtering:
//! - `out/in_/both`, `out_e/in_e/both_e`, `out_n/in_n/other_n`
//! - `has`, `has_label`, `has_key`, `where_`, `within`, `without`, `dedup`
//! - `limit`, `skip`, `range`, `order_by`, `order_by_multiple`
//!
//! Common terminal projections:
//! - `count`, `exists`, `id`, `label`
//! - `values`, `value_map`, `project`, `edge_properties`
//!
//! Write-only operations (usable in [`write_batch()`] traversals):
//! - `add_n`, `add_e`, `set_property`, `remove_property`, `drop`, `drop_edge`, `drop_edge_by_id`
//! - `create_vector_index_nodes`, `create_vector_index_edges`

#![warn(missing_docs)]
#![warn(clippy::all)]
#![deny(unsafe_code)]

use std::collections::{BTreeMap, HashMap};
use std::marker::PhantomData;

use chrono::{SecondsFormat, Utc};
use serde::{Deserialize, Serialize};

pub use crate::query_generator::*;
pub use helix_dsl_macros::register;

#[doc(hidden)]
pub mod __private {
    use std::collections::BTreeMap;

    pub use inventory;

    pub fn dynamic_query_value_from_property_value(
        value: crate::PropertyValue,
        path: impl Into<String>,
    ) -> Result<crate::DynamicQueryValue, crate::DynamicQueryError> {
        fn convert(
            value: crate::PropertyValue,
            path: String,
        ) -> Result<crate::DynamicQueryValue, crate::DynamicQueryError> {
            Ok(match value {
                crate::PropertyValue::Null => crate::DynamicQueryValue::Null,
                crate::PropertyValue::Bool(value) => crate::DynamicQueryValue::Bool(value),
                crate::PropertyValue::I64(value) => crate::DynamicQueryValue::I64(value),
                crate::PropertyValue::DateTime(value) => crate::DynamicQueryValue::String(
                    crate::DateTime::from_millis(value)
                        .to_rfc3339()
                        .ok_or_else(|| crate::DynamicQueryError::invalid_datetime(path, value))?,
                ),
                crate::PropertyValue::F64(value) => crate::DynamicQueryValue::F64(value),
                crate::PropertyValue::F32(value) => crate::DynamicQueryValue::F32(value),
                crate::PropertyValue::String(value) => crate::DynamicQueryValue::String(value),
                crate::PropertyValue::Bytes(_) => {
                    return Err(crate::DynamicQueryError::unsupported_bytes(path));
                }
                crate::PropertyValue::I64Array(values) => crate::DynamicQueryValue::Array(
                    values
                        .into_iter()
                        .map(crate::DynamicQueryValue::I64)
                        .collect(),
                ),
                crate::PropertyValue::F64Array(values) => crate::DynamicQueryValue::Array(
                    values
                        .into_iter()
                        .map(crate::DynamicQueryValue::F64)
                        .collect(),
                ),
                crate::PropertyValue::F32Array(values) => crate::DynamicQueryValue::Array(
                    values
                        .into_iter()
                        .map(crate::DynamicQueryValue::F32)
                        .collect(),
                ),
                crate::PropertyValue::StringArray(values) => crate::DynamicQueryValue::Array(
                    values
                        .into_iter()
                        .map(crate::DynamicQueryValue::String)
                        .collect(),
                ),
                crate::PropertyValue::Array(values) => crate::DynamicQueryValue::Array(
                    values
                        .into_iter()
                        .enumerate()
                        .map(|(index, value)| convert(value, format!("{}[{}]", path, index)))
                        .collect::<Result<Vec<_>, _>>()?,
                ),
                crate::PropertyValue::Object(values) => crate::DynamicQueryValue::Object(
                    values
                        .into_iter()
                        .map(|(key, value)| {
                            let entry_path = format!("{}.{}", path, key);
                            Ok((key, convert(value, entry_path)?))
                        })
                        .collect::<Result<BTreeMap<_, _>, crate::DynamicQueryError>>()?,
                ),
            })
        }

        convert(value, path.into())
    }
}

/// Type alias for node IDs
pub type NodeId = u64;

/// Type alias for edge IDs (separate namespace from node IDs)
pub type EdgeId = u64;

/// Arbitrary nested parameter value.
pub type ParamValue = PropertyValue;

/// Object-shaped parameter payload.
pub type ParamObject = BTreeMap<String, PropertyValue>;

// Typestate Markers

/// Marker trait for all traversal states
#[doc(hidden)]
pub trait TraversalState: private::Sealed {}

mod private {
    /// Seal the TraversalState trait to prevent external implementation
    pub trait Sealed {}
    impl Sealed for super::Empty {}
    impl Sealed for super::OnNodes {}
    impl Sealed for super::OnEdges {}
    impl Sealed for super::Terminal {}
    impl Sealed for super::ReadOnly {}
    impl Sealed for super::WriteEnabled {}
}

/// Initial state - no source step yet
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Empty;

/// Traversal is currently operating on a node stream
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OnNodes;

/// Traversal is currently operating on an edge stream
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OnEdges;

/// Traversal has terminated - no more chaining allowed
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Terminal;

impl TraversalState for Empty {}
impl TraversalState for OnNodes {}
impl TraversalState for OnEdges {}
impl TraversalState for Terminal {}

// MutationMode Markers

/// Marker trait for mutation capability - tracks whether a traversal contains mutations
#[doc(hidden)]
pub trait MutationMode: private::Sealed {}

/// Read-only traversal - no mutation steps
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadOnly;

/// Write-enabled traversal - contains mutation steps
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriteEnabled;

impl MutationMode for ReadOnly {}
impl MutationMode for WriteEnabled {}

// Property Value Types

/// A property value that can be stored on nodes or edges
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PropertyValue {
    /// Null value
    Null,
    /// Boolean value
    Bool(bool),
    /// 64-bit signed integer
    I64(i64),
    /// UTC datetime stored as epoch milliseconds
    DateTime(i64),
    /// 64-bit floating point
    F64(f64),
    /// 32-bit floating point
    F32(f32),
    /// UTF-8 string
    String(String),
    /// Raw bytes
    Bytes(Vec<u8>),
    /// Array of i64 values
    I64Array(Vec<i64>),
    /// Array of f64 values
    F64Array(Vec<f64>),
    /// Array of f32 values
    F32Array(Vec<f32>),
    /// Array of strings
    StringArray(Vec<String>),
    /// Heterogeneous array value for parameter payloads
    Array(Vec<PropertyValue>),
    /// Object/map value for parameter payloads
    Object(BTreeMap<String, PropertyValue>),
}

impl PropertyValue {
    /// Get value as string reference if it is a String
    pub fn as_str(&self) -> Option<&str> {
        match self {
            PropertyValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Get value as i64 if it is an I64
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            PropertyValue::I64(n) => Some(*n),
            _ => None,
        }
    }

    /// Create a typed datetime value from UTC epoch milliseconds
    pub fn datetime_millis(millis: i64) -> Self {
        Self::DateTime(millis)
    }

    /// Get the datetime as UTC epoch milliseconds if it is a DateTime
    pub fn as_datetime_millis(&self) -> Option<i64> {
        match self {
            PropertyValue::DateTime(millis) => Some(*millis),
            _ => None,
        }
    }

    /// Get value as f64 if it is an F64
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            PropertyValue::F64(n) => Some(*n),
            PropertyValue::F32(n) => Some(*n as f64),
            _ => None,
        }
    }

    /// Get value as bool if it is a Bool
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            PropertyValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Get value as array reference if it is an Array
    pub fn as_array(&self) -> Option<&[PropertyValue]> {
        match self {
            PropertyValue::Array(values) => Some(values),
            _ => None,
        }
    }

    /// Get value as object reference if it is an Object
    pub fn as_object(&self) -> Option<&BTreeMap<String, PropertyValue>> {
        match self {
            PropertyValue::Object(values) => Some(values),
            _ => None,
        }
    }
}

impl From<&str> for PropertyValue {
    fn from(s: &str) -> Self {
        PropertyValue::String(s.to_string())
    }
}

impl From<String> for PropertyValue {
    fn from(s: String) -> Self {
        PropertyValue::String(s)
    }
}

impl From<i64> for PropertyValue {
    fn from(n: i64) -> Self {
        PropertyValue::I64(n)
    }
}

/// UTC datetime represented internally as epoch milliseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateTime(i64);

impl DateTime {
    /// Create a datetime from UTC epoch milliseconds.
    pub fn from_millis(millis: i64) -> Self {
        Self(millis)
    }

    /// Parse an RFC3339 datetime string and normalize it to UTC.
    pub fn parse_rfc3339(input: &str) -> Result<Self, chrono::ParseError> {
        Ok(Self(
            chrono::DateTime::parse_from_rfc3339(input)?
                .with_timezone(&Utc)
                .timestamp_millis(),
        ))
    }

    /// Return the UTC epoch milliseconds.
    pub fn millis(self) -> i64 {
        self.0
    }

    /// Format this datetime as a canonical RFC3339 UTC string.
    pub fn to_rfc3339(self) -> Option<String> {
        chrono::DateTime::<Utc>::from_timestamp_millis(self.0)
            .map(|dt| dt.to_rfc3339_opts(SecondsFormat::Millis, true))
    }
}

impl From<DateTime> for PropertyValue {
    fn from(value: DateTime) -> Self {
        PropertyValue::DateTime(value.millis())
    }
}

impl From<i32> for PropertyValue {
    fn from(n: i32) -> Self {
        PropertyValue::I64(n as i64)
    }
}

impl From<f64> for PropertyValue {
    fn from(n: f64) -> Self {
        PropertyValue::F64(n)
    }
}

impl From<f32> for PropertyValue {
    fn from(n: f32) -> Self {
        PropertyValue::F32(n)
    }
}

impl From<bool> for PropertyValue {
    fn from(b: bool) -> Self {
        PropertyValue::Bool(b)
    }
}

impl From<Vec<u8>> for PropertyValue {
    fn from(bytes: Vec<u8>) -> Self {
        PropertyValue::Bytes(bytes)
    }
}

impl From<Vec<i64>> for PropertyValue {
    fn from(values: Vec<i64>) -> Self {
        PropertyValue::I64Array(values)
    }
}

impl From<Vec<f64>> for PropertyValue {
    fn from(values: Vec<f64>) -> Self {
        PropertyValue::F64Array(values)
    }
}

impl From<Vec<f32>> for PropertyValue {
    fn from(values: Vec<f32>) -> Self {
        PropertyValue::F32Array(values)
    }
}

impl From<Vec<String>> for PropertyValue {
    fn from(values: Vec<String>) -> Self {
        PropertyValue::StringArray(values)
    }
}

impl From<Vec<PropertyValue>> for PropertyValue {
    fn from(values: Vec<PropertyValue>) -> Self {
        PropertyValue::Array(values)
    }
}

impl From<BTreeMap<String, PropertyValue>> for PropertyValue {
    fn from(values: BTreeMap<String, PropertyValue>) -> Self {
        PropertyValue::Object(values)
    }
}

impl From<HashMap<String, PropertyValue>> for PropertyValue {
    fn from(values: HashMap<String, PropertyValue>) -> Self {
        PropertyValue::Object(values.into_iter().collect())
    }
}

/// Mutation input value for add/set property operations.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PropertyInput {
    /// Store a literal property value.
    Value(PropertyValue),
    /// Resolve the value from an expression at execution time.
    Expr(Expr),
}

impl PropertyInput {
    /// Create an input from a query parameter.
    pub fn param(name: impl Into<String>) -> Self {
        Self::Expr(Expr::param(name))
    }

    /// Convert into an `Expr`, promoting a literal value to `Expr::Constant`.
    #[doc(hidden)]
    pub fn into_expr(self) -> Expr {
        match self {
            PropertyInput::Value(v) => Expr::Constant(v),
            PropertyInput::Expr(e) => e,
        }
    }
}

impl<T> From<T> for PropertyInput
where
    PropertyValue: From<T>,
{
    fn from(value: T) -> Self {
        Self::Value(value.into())
    }
}

impl From<Expr> for PropertyInput {
    fn from(value: Expr) -> Self {
        Self::Expr(value)
    }
}

// Reference Types

/// A reference to nodes - can be concrete IDs or a variable name
///
/// This allows the AST to express operations without knowing actual IDs at build time.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum NodeRef {
    /// All nodes in storage
    All,
    /// One or more concrete node IDs
    Ids(Vec<NodeId>),
    /// Reference nodes stored in a named variable
    Var(String),
    /// Reference node IDs from a runtime parameter
    Param(String),
}

impl NodeRef {
    /// Create a reference to all nodes
    pub fn all() -> Self {
        NodeRef::All
    }

    /// Create a reference to a single node ID
    pub fn id(id: NodeId) -> Self {
        NodeRef::Ids(vec![id])
    }

    /// Create a reference to multiple node IDs
    pub fn ids(ids: impl IntoIterator<Item = NodeId>) -> Self {
        NodeRef::Ids(ids.into_iter().collect())
    }

    /// Create a reference to a variable
    pub fn var(name: impl Into<String>) -> Self {
        NodeRef::Var(name.into())
    }

    /// Create a reference to node IDs stored in a runtime parameter
    pub fn param(name: impl Into<String>) -> Self {
        NodeRef::Param(name.into())
    }
}

impl From<NodeId> for NodeRef {
    fn from(id: NodeId) -> Self {
        NodeRef::Ids(vec![id])
    }
}

impl From<Vec<NodeId>> for NodeRef {
    fn from(ids: Vec<NodeId>) -> Self {
        NodeRef::Ids(ids)
    }
}

impl<const N: usize> From<[NodeId; N]> for NodeRef {
    fn from(ids: [NodeId; N]) -> Self {
        NodeRef::Ids(ids.to_vec())
    }
}

impl From<&str> for NodeRef {
    fn from(var_name: &str) -> Self {
        NodeRef::Var(var_name.to_string())
    }
}

/// A reference to edges - can be concrete IDs or a variable name
///
/// This allows the AST to express operations without knowing actual IDs at build time.
/// Edge IDs are separate from node IDs in the graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EdgeRef {
    /// One or more concrete edge IDs
    Ids(Vec<EdgeId>),
    /// Reference edges stored in a named variable
    Var(String),
    /// Reference edge IDs from a runtime parameter
    Param(String),
}

impl EdgeRef {
    /// Create a reference to a single edge ID
    pub fn id(id: EdgeId) -> Self {
        EdgeRef::Ids(vec![id])
    }

    /// Create a reference to multiple edge IDs
    pub fn ids(ids: impl IntoIterator<Item = EdgeId>) -> Self {
        EdgeRef::Ids(ids.into_iter().collect())
    }

    /// Create a reference to a variable containing edges
    pub fn var(name: impl Into<String>) -> Self {
        EdgeRef::Var(name.into())
    }

    /// Create a reference to edge IDs stored in a runtime parameter
    pub fn param(name: impl Into<String>) -> Self {
        EdgeRef::Param(name.into())
    }
}

impl From<EdgeId> for EdgeRef {
    fn from(id: EdgeId) -> Self {
        EdgeRef::Ids(vec![id])
    }
}

impl From<Vec<EdgeId>> for EdgeRef {
    fn from(ids: Vec<EdgeId>) -> Self {
        EdgeRef::Ids(ids)
    }
}

impl<const N: usize> From<[EdgeId; N]> for EdgeRef {
    fn from(ids: [EdgeId; N]) -> Self {
        EdgeRef::Ids(ids.to_vec())
    }
}

// Expression Types

/// An expression for computed values, math operations, and property references
///
/// Expressions can be used in predicates for property-to-property comparisons,
/// computed values, and math operations.
///
/// Note: support for some expression variants is engine-dependent. In particular,
/// `Expr::Id` may be reserved or unsupported by some runtimes.
///
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expr {
    /// Reference a property by name
    Property(String),
    /// The current element ID (engine-defined).
    Id,
    /// Server-side current timestamp in UTC epoch milliseconds.
    Timestamp,
    /// Server-side current datetime as a typed `DateTime` value.
    DateTimeNow,
    /// A constant value
    Constant(PropertyValue),
    /// Reference a query parameter by name
    Param(String),
    /// Addition: left + right
    Add(Box<Expr>, Box<Expr>),
    /// Subtraction: left - right
    Sub(Box<Expr>, Box<Expr>),
    /// Multiplication: left * right
    Mul(Box<Expr>, Box<Expr>),
    /// Division: left / right
    Div(Box<Expr>, Box<Expr>),
    /// Modulo: left % right
    Mod(Box<Expr>, Box<Expr>),
    /// Negation: -expr
    Neg(Box<Expr>),
    /// Conditional expression that evaluates the first matching branch.
    Case {
        /// Ordered predicate/expression branches.
        when_then: Vec<(Predicate, Expr)>,
        /// Fallback expression. When omitted, the result is explicit `Null`.
        else_expr: Option<Box<Expr>>,
    },
}

impl Expr {
    /// Create a property reference expression
    pub fn prop(name: impl Into<String>) -> Self {
        Expr::Property(name.into())
    }

    /// Create a constant value expression
    pub fn val(value: impl Into<PropertyValue>) -> Self {
        Expr::Constant(value.into())
    }

    /// Create an ID reference expression
    pub fn id() -> Self {
        Expr::Id
    }

    /// Create a server-side timestamp expression (UTC epoch milliseconds).
    pub fn timestamp() -> Self {
        Expr::Timestamp
    }

    /// Create a server-side datetime expression.
    pub fn datetime() -> Self {
        Expr::DateTimeNow
    }

    /// Create a parameter reference expression
    pub fn param(name: impl Into<String>) -> Self {
        Expr::Param(name.into())
    }

    /// Addition: self + other
    pub fn add(self, other: Expr) -> Self {
        Expr::Add(Box::new(self), Box::new(other))
    }

    /// Subtraction: self - other
    pub fn sub(self, other: Expr) -> Self {
        Expr::Sub(Box::new(self), Box::new(other))
    }

    /// Multiplication: self * other
    pub fn mul(self, other: Expr) -> Self {
        Expr::Mul(Box::new(self), Box::new(other))
    }

    /// Division: self / other
    pub fn div(self, other: Expr) -> Self {
        Expr::Div(Box::new(self), Box::new(other))
    }

    /// Modulo: self % other
    pub fn modulo(self, other: Expr) -> Self {
        Expr::Mod(Box::new(self), Box::new(other))
    }

    /// Negation: -self
    pub fn neg(self) -> Self {
        Expr::Neg(Box::new(self))
    }

    /// Create a conditional expression.
    pub fn case(when_then: Vec<(Predicate, Expr)>, else_expr: Option<Expr>) -> Self {
        Expr::Case {
            when_then,
            else_expr: else_expr.map(Box::new),
        }
    }
}

/// A non-negative integer input used by stream-shaping steps like `limit`, `skip`, and `range`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StreamBound {
    /// A literal bound known at query-build time.
    Literal(usize),
    /// A computed or parameterized bound resolved by the runtime.
    Expr(Expr),
}

impl StreamBound {
    /// Create a literal bound.
    pub fn literal(value: usize) -> Self {
        Self::Literal(value)
    }

    /// Create an expression-backed bound.
    pub fn expr(expr: Expr) -> Self {
        Self::Expr(expr)
    }
}

impl From<usize> for StreamBound {
    fn from(value: usize) -> Self {
        Self::Literal(value)
    }
}

impl From<u32> for StreamBound {
    fn from(value: u32) -> Self {
        Self::Literal(value as usize)
    }
}

impl From<u16> for StreamBound {
    fn from(value: u16) -> Self {
        Self::Literal(value as usize)
    }
}

impl From<u8> for StreamBound {
    fn from(value: u8) -> Self {
        Self::Literal(value as usize)
    }
}

impl From<i64> for StreamBound {
    fn from(value: i64) -> Self {
        if value >= 0 {
            Self::Literal(value as usize)
        } else {
            Self::Expr(Expr::val(value))
        }
    }
}

impl From<i32> for StreamBound {
    fn from(value: i32) -> Self {
        if value >= 0 {
            Self::Literal(value as usize)
        } else {
            Self::Expr(Expr::val(value))
        }
    }
}

impl From<Expr> for StreamBound {
    fn from(value: Expr) -> Self {
        Self::Expr(value)
    }
}

/// Comparison operators for expression-based predicates
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompareOp {
    /// Equal
    Eq,
    /// Not equal
    Neq,
    /// Greater than
    Gt,
    /// Greater than or equal
    Gte,
    /// Less than
    Lt,
    /// Less than or equal
    Lte,
}

// Predicate Types

/// A predicate for filtering nodes by properties
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Predicate {
    /// Equals: property == value
    Eq(String, PropertyValue),
    /// Not equals: property != value
    Neq(String, PropertyValue),
    /// Greater than: property > value (for numeric/string)
    Gt(String, PropertyValue),
    /// Greater than or equal: property >= value
    Gte(String, PropertyValue),
    /// Less than: property < value
    Lt(String, PropertyValue),
    /// Less than or equal: property <= value
    Lte(String, PropertyValue),
    /// Between (inclusive): min <= property <= max
    Between(String, PropertyValue, PropertyValue),
    /// Property exists
    HasKey(String),
    /// Property is missing or explicitly null.
    IsNull(String),
    /// Property exists and is not null.
    IsNotNull(String),
    /// String starts with prefix
    StartsWith(String, String),
    /// String ends with suffix
    EndsWith(String, String),
    /// String contains substring
    Contains(String, String),
    /// String contains a runtime expression result
    ContainsExpr(String, Expr),
    /// Property value is equal to one of the provided values
    IsIn(String, PropertyValue),
    /// Property value is equal to one of the values produced by a runtime expression
    IsInExpr(String, Expr),
    /// Logical AND of predicates
    And(Vec<Predicate>),
    /// Logical OR of predicates
    Or(Vec<Predicate>),
    /// Logical NOT of predicate
    Not(Box<Predicate>),
    /// Expression-based comparison (supports property-to-property, math, etc.)
    Compare {
        /// Left side of comparison
        left: Expr,
        /// Comparison operator
        op: CompareOp,
        /// Right side of comparison
        right: Expr,
    },
}

/// A predicate that can be used in source steps (`n_where` / `e_where`).
///
/// This is a restricted subset of [`Predicate`] intended to be index- and
/// planner-friendly for "source" selection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SourcePredicate {
    /// Equals: property == value
    Eq(String, PropertyValue),
    /// Not equals: property != value
    Neq(String, PropertyValue),
    /// Greater than: property > value (for numeric/string)
    Gt(String, PropertyValue),
    /// Greater than or equal: property >= value
    Gte(String, PropertyValue),
    /// Less than: property < value
    Lt(String, PropertyValue),
    /// Less than or equal: property <= value
    Lte(String, PropertyValue),
    /// Between (inclusive): min <= property <= max
    Between(String, PropertyValue, PropertyValue),
    /// Property exists
    HasKey(String),
    /// String starts with prefix
    StartsWith(String, String),
    /// Logical AND of predicates
    And(Vec<SourcePredicate>),
    /// Logical OR of predicates
    Or(Vec<SourcePredicate>),
    /// Equals against an expression/parameter: property == <expr>
    EqExpr(String, Expr),
    /// Not equals against an expression/parameter
    NeqExpr(String, Expr),
    /// Greater than an expression/parameter
    GtExpr(String, Expr),
    /// Greater than or equal to an expression/parameter
    GteExpr(String, Expr),
    /// Less than an expression/parameter
    LtExpr(String, Expr),
    /// Less than or equal to an expression/parameter
    LteExpr(String, Expr),
    /// Between two expressions/parameters (inclusive)
    BetweenExpr(String, Expr, Expr),
}

impl SourcePredicate {
    /// Create an equality predicate.
    ///
    /// Accepts a literal value or an `Expr`/query parameter. Literals keep the `Eq` variant;
    /// expressions route to `EqExpr`.
    pub fn eq(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Eq(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::EqExpr(property.into(), e),
        }
    }

    /// Create a not-equals predicate (literal or `Expr`/parameter).
    pub fn neq(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Neq(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::NeqExpr(property.into(), e),
        }
    }

    /// Create a greater-than predicate (literal or `Expr`/parameter).
    pub fn gt(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Gt(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::GtExpr(property.into(), e),
        }
    }

    /// Create a greater-than-or-equal predicate (literal or `Expr`/parameter).
    pub fn gte(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Gte(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::GteExpr(property.into(), e),
        }
    }

    /// Create a less-than predicate (literal or `Expr`/parameter).
    pub fn lt(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Lt(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::LtExpr(property.into(), e),
        }
    }

    /// Create a less-than-or-equal predicate (literal or `Expr`/parameter).
    pub fn lte(property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        match value.into() {
            PropertyInput::Value(v) => SourcePredicate::Lte(property.into(), v),
            PropertyInput::Expr(e) => SourcePredicate::LteExpr(property.into(), e),
        }
    }

    /// Create a between predicate (inclusive). Accepts literals or `Expr`/parameters; if either
    /// bound is an expression, both are promoted to `BetweenExpr`.
    pub fn between(
        property: impl Into<String>,
        min: impl Into<PropertyInput>,
        max: impl Into<PropertyInput>,
    ) -> Self {
        let prop = property.into();
        match (min.into(), max.into()) {
            (PropertyInput::Value(a), PropertyInput::Value(b)) => {
                SourcePredicate::Between(prop, a, b)
            }
            (min, max) => SourcePredicate::BetweenExpr(prop, min.into_expr(), max.into_expr()),
        }
    }

    /// Create a has-key predicate
    pub fn has_key(property: impl Into<String>) -> Self {
        SourcePredicate::HasKey(property.into())
    }

    /// Create a starts-with predicate
    pub fn starts_with(property: impl Into<String>, prefix: impl Into<String>) -> Self {
        SourcePredicate::StartsWith(property.into(), prefix.into())
    }

    /// Combine predicates with AND
    pub fn and(predicates: Vec<SourcePredicate>) -> Self {
        SourcePredicate::And(predicates)
    }

    /// Combine predicates with OR
    pub fn or(predicates: Vec<SourcePredicate>) -> Self {
        SourcePredicate::Or(predicates)
    }
}

impl From<SourcePredicate> for Predicate {
    fn from(predicate: SourcePredicate) -> Self {
        match predicate {
            SourcePredicate::Eq(prop, val) => Predicate::Eq(prop, val),
            SourcePredicate::Neq(prop, val) => Predicate::Neq(prop, val),
            SourcePredicate::Gt(prop, val) => Predicate::Gt(prop, val),
            SourcePredicate::Gte(prop, val) => Predicate::Gte(prop, val),
            SourcePredicate::Lt(prop, val) => Predicate::Lt(prop, val),
            SourcePredicate::Lte(prop, val) => Predicate::Lte(prop, val),
            SourcePredicate::Between(prop, min, max) => Predicate::Between(prop, min, max),
            SourcePredicate::HasKey(prop) => Predicate::HasKey(prop),
            SourcePredicate::StartsWith(prop, prefix) => Predicate::StartsWith(prop, prefix),
            SourcePredicate::And(predicates) => {
                Predicate::And(predicates.into_iter().map(Predicate::from).collect())
            }
            SourcePredicate::Or(predicates) => {
                Predicate::Or(predicates.into_iter().map(Predicate::from).collect())
            }
            SourcePredicate::EqExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Eq,
                right: e,
            },
            SourcePredicate::NeqExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Neq,
                right: e,
            },
            SourcePredicate::GtExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Gt,
                right: e,
            },
            SourcePredicate::GteExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Gte,
                right: e,
            },
            SourcePredicate::LtExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Lt,
                right: e,
            },
            SourcePredicate::LteExpr(prop, e) => Predicate::Compare {
                left: Expr::Property(prop),
                op: CompareOp::Lte,
                right: e,
            },
            SourcePredicate::BetweenExpr(prop, min, max) => Predicate::And(vec![
                Predicate::Compare {
                    left: Expr::Property(prop.clone()),
                    op: CompareOp::Gte,
                    right: min,
                },
                Predicate::Compare {
                    left: Expr::Property(prop),
                    op: CompareOp::Lte,
                    right: max,
                },
            ]),
        }
    }
}

impl Predicate {
    /// Create an equality predicate
    pub fn eq(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Eq(property.into(), value.into())
    }

    /// Create a not-equals predicate
    pub fn neq(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Neq(property.into(), value.into())
    }

    /// Create a greater-than predicate
    pub fn gt(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Gt(property.into(), value.into())
    }

    /// Create a greater-than-or-equal predicate
    pub fn gte(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Gte(property.into(), value.into())
    }

    /// Create a less-than predicate
    pub fn lt(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Lt(property.into(), value.into())
    }

    /// Create a less-than-or-equal predicate
    pub fn lte(property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        Predicate::Lte(property.into(), value.into())
    }

    /// Create a between predicate (inclusive)
    pub fn between(
        property: impl Into<String>,
        min: impl Into<PropertyValue>,
        max: impl Into<PropertyValue>,
    ) -> Self {
        Predicate::Between(property.into(), min.into(), max.into())
    }

    /// Create a has-key predicate
    pub fn has_key(property: impl Into<String>) -> Self {
        Predicate::HasKey(property.into())
    }

    /// Create an `IS NULL` predicate.
    pub fn is_null(property: impl Into<String>) -> Self {
        Predicate::IsNull(property.into())
    }

    /// Create an `IS NOT NULL` predicate.
    pub fn is_not_null(property: impl Into<String>) -> Self {
        Predicate::IsNotNull(property.into())
    }

    /// Create a starts-with predicate
    pub fn starts_with(property: impl Into<String>, prefix: impl Into<String>) -> Self {
        Predicate::StartsWith(property.into(), prefix.into())
    }

    /// Create an ends-with predicate
    pub fn ends_with(property: impl Into<String>, suffix: impl Into<String>) -> Self {
        Predicate::EndsWith(property.into(), suffix.into())
    }

    /// Create a contains predicate
    pub fn contains(property: impl Into<String>, substring: impl Into<String>) -> Self {
        Predicate::Contains(property.into(), substring.into())
    }

    /// Create a parameterized contains predicate: property contains param string
    pub fn contains_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::ContainsExpr(property.into(), Expr::Param(param_name.into()))
    }

    /// Create an `IN` predicate with a literal array value.
    pub fn is_in(property: impl Into<String>, values: impl Into<PropertyValue>) -> Self {
        Predicate::IsIn(property.into(), values.into())
    }

    /// Create an `IN` predicate whose values are resolved from an expression.
    pub fn is_in_expr(property: impl Into<String>, values: Expr) -> Self {
        Predicate::IsInExpr(property.into(), values)
    }

    /// Create a parameterized `IN` predicate: property IN param_array.
    pub fn is_in_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::IsInExpr(property.into(), Expr::Param(param_name.into()))
    }

    /// Combine predicates with AND
    pub fn and(predicates: Vec<Predicate>) -> Self {
        Predicate::And(predicates)
    }

    /// Combine predicates with OR
    pub fn or(predicates: Vec<Predicate>) -> Self {
        Predicate::Or(predicates)
    }

    /// Negate a predicate
    pub fn not(predicate: Predicate) -> Self {
        Predicate::Not(Box::new(predicate))
    }

    /// Create an expression-based comparison predicate
    ///
    /// This supports property-to-property comparisons, math expressions, and more.
    ///
    pub fn compare(left: Expr, op: CompareOp, right: Expr) -> Self {
        Predicate::Compare { left, op, right }
    }

    // Parameterized predicate constructors

    /// Create a parameterized equality predicate: property == param
    ///
    /// The parameter value is provided at query execution time.
    ///
    pub fn eq_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Eq,
            right: Expr::Param(param_name.into()),
        }
    }

    /// Create a parameterized not-equals predicate: property != param
    pub fn neq_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Neq,
            right: Expr::Param(param_name.into()),
        }
    }

    /// Create a parameterized greater-than predicate: property > param
    pub fn gt_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Gt,
            right: Expr::Param(param_name.into()),
        }
    }

    /// Create a parameterized greater-than-or-equal predicate: property >= param
    pub fn gte_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Gte,
            right: Expr::Param(param_name.into()),
        }
    }

    /// Create a parameterized less-than predicate: property < param
    pub fn lt_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Lt,
            right: Expr::Param(param_name.into()),
        }
    }

    /// Create a parameterized less-than-or-equal predicate: property <= param
    pub fn lte_param(property: impl Into<String>, param_name: impl Into<String>) -> Self {
        Predicate::Compare {
            left: Expr::Property(property.into()),
            op: CompareOp::Lte,
            right: Expr::Param(param_name.into()),
        }
    }
}

// Supporting Types

/// A property projection with optional renaming
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PropertyProjection {
    /// Original property name in the data
    pub source: String,
    /// Name to use in the output (alias)
    pub alias: String,
}

impl PropertyProjection {
    /// Create a projection without renaming
    pub fn new(name: impl Into<String>) -> Self {
        let n = name.into();
        Self {
            source: n.clone(),
            alias: n,
        }
    }

    /// Create a projection with renaming
    pub fn renamed(source: impl Into<String>, alias: impl Into<String>) -> Self {
        Self {
            source: source.into(),
            alias: alias.into(),
        }
    }
}

/// An expression-backed projection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExprProjection {
    /// Name to use in the output.
    pub alias: String,
    /// Expression to evaluate.
    pub expr: Expr,
}

impl ExprProjection {
    /// Create a projection from an expression.
    pub fn new(alias: impl Into<String>, expr: Expr) -> Self {
        Self {
            alias: alias.into(),
            expr,
        }
    }
}

/// A terminal projection entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Projection {
    /// Project a property with optional renaming.
    Property(PropertyProjection),
    /// Project a computed expression.
    Expr(ExprProjection),
}

impl Projection {
    /// Project a property with optional renaming.
    pub fn property(source: impl Into<String>, alias: impl Into<String>) -> Self {
        Self::Property(PropertyProjection::renamed(source, alias))
    }

    /// Project a computed expression.
    pub fn expr(alias: impl Into<String>, expr: Expr) -> Self {
        Self::Expr(ExprProjection::new(alias, expr))
    }
}

impl From<PropertyProjection> for Projection {
    fn from(value: PropertyProjection) -> Self {
        Self::Property(value)
    }
}

impl From<ExprProjection> for Projection {
    fn from(value: ExprProjection) -> Self {
        Self::Expr(value)
    }
}

/// Sort order for ordering steps
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Order {
    /// Ascending order (smallest first)
    Asc,
    /// Descending order (largest first)
    Desc,
}

impl Default for Order {
    fn default() -> Self {
        Order::Asc
    }
}

/// Emit behavior for repeat steps
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EmitBehavior {
    /// Don't emit intermediate results.
    None,
    /// Emit the current node stream before each repeat iteration.
    Before,
    /// Emit the node stream produced by each repeat iteration.
    After,
    /// Emit both before and after each repeat iteration.
    All,
}

impl Default for EmitBehavior {
    fn default() -> Self {
        EmitBehavior::None
    }
}

/// Aggregation function for reduce operations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AggregateFunction {
    /// Count items
    Count,
    /// Sum numeric values
    Sum,
    /// Find minimum value
    Min,
    /// Find maximum value
    Max,
    /// Calculate mean/average
    Mean,
}

// Sub-Traversal (for branching operations without typestate)

/// A sub-traversal for use in branching operations (union, choose, coalesce, optional, repeat).
///
/// Sub-traversals don't track typestate because they start from an implicit context
/// provided by the parent traversal. This allows maximum flexibility in branching
/// while the parent traversal maintains compile-time safety.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SubTraversal {
    /// The steps in this sub-traversal
    pub steps: Vec<Step>,
}

impl SubTraversal {
    /// Create a new empty sub-traversal
    pub fn new() -> Self {
        Self { steps: Vec::new() }
    }

    // Navigation Steps (node -> node)

    /// Traverse outgoing edges, optionally filtered by label
    pub fn out(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::Out(label.map(|l| l.into())));
        self
    }

    /// Traverse incoming edges, optionally filtered by label
    pub fn in_(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::In(label.map(|l| l.into())));
        self
    }

    /// Traverse edges in both directions, optionally filtered by label
    pub fn both(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::Both(label.map(|l| l.into())));
        self
    }

    // Edge Traversal Steps

    /// Traverse to outgoing edges
    pub fn out_e(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::OutE(label.map(|l| l.into())));
        self
    }

    /// Traverse to incoming edges
    pub fn in_e(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::InE(label.map(|l| l.into())));
        self
    }

    /// Traverse to edges in both directions
    pub fn both_e(mut self, label: Option<impl Into<String>>) -> Self {
        self.steps.push(Step::BothE(label.map(|l| l.into())));
        self
    }

    /// From edge, get the target node
    pub fn out_n(mut self) -> Self {
        self.steps.push(Step::OutN);
        self
    }

    /// From edge, get the source node
    pub fn in_n(mut self) -> Self {
        self.steps.push(Step::InN);
        self
    }

    /// From edge, get the "other" node (not the one we came from)
    pub fn other_n(mut self) -> Self {
        self.steps.push(Step::OtherN);
        self
    }

    // Filter Steps

    /// Filter by property value
    pub fn has(mut self, property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        self.steps.push(Step::Has(property.into(), value.into()));
        self
    }

    /// Filter by label (shorthand for has("$label", value))
    pub fn has_label(mut self, label: impl Into<String>) -> Self {
        self.steps.push(Step::HasLabel(label.into()));
        self
    }

    /// Filter by property existence
    pub fn has_key(mut self, property: impl Into<String>) -> Self {
        self.steps.push(Step::HasKey(property.into()));
        self
    }

    /// Filter by a complex predicate
    pub fn where_(mut self, predicate: Predicate) -> Self {
        self.steps.push(Step::Where(predicate));
        self
    }

    /// Remove duplicates from the stream
    pub fn dedup(mut self) -> Self {
        self.steps.push(Step::Dedup);
        self
    }

    /// Filter to nodes that exist in a variable
    pub fn within(mut self, var_name: impl Into<String>) -> Self {
        self.steps.push(Step::Within(var_name.into()));
        self
    }

    /// Filter to nodes that do NOT exist in a variable
    pub fn without(mut self, var_name: impl Into<String>) -> Self {
        self.steps.push(Step::Without(var_name.into()));
        self
    }

    // Edge Filter Steps

    /// Filter edges by property value
    pub fn edge_has(
        mut self,
        property: impl Into<String>,
        value: impl Into<PropertyInput>,
    ) -> Self {
        self.steps
            .push(Step::EdgeHas(property.into(), value.into()));
        self
    }

    /// Filter edges by label
    pub fn edge_has_label(mut self, label: impl Into<String>) -> Self {
        self.steps.push(Step::EdgeHasLabel(label.into()));
        self
    }

    // Limit Steps

    /// Take at most N items.
    pub fn limit(mut self, n: impl Into<StreamBound>) -> Self {
        self.steps.push(limit_step(n));
        self
    }

    /// Skip the first N items.
    pub fn skip(mut self, n: impl Into<StreamBound>) -> Self {
        self.steps.push(skip_step(n));
        self
    }

    /// Get items in a range [start, end).
    pub fn range(mut self, start: impl Into<StreamBound>, end: impl Into<StreamBound>) -> Self {
        self.steps.push(range_step(start, end));
        self
    }

    // Variable Steps

    /// Store current nodes with a name for later reference
    pub fn as_(mut self, name: impl Into<String>) -> Self {
        self.steps.push(Step::As(name.into()));
        self
    }

    /// Store current nodes to a variable (same as `as_`)
    pub fn store(mut self, name: impl Into<String>) -> Self {
        self.steps.push(Step::Store(name.into()));
        self
    }

    /// Replace current traversal with nodes from a variable
    pub fn select(mut self, name: impl Into<String>) -> Self {
        self.steps.push(Step::Select(name.into()));
        self
    }

    // Ordering Steps

    /// Order results by a property.
    ///
    /// Note: some interpreters represent intermediate streams as sets. In those
    /// engines, ordering may not be preserved in the returned node set.
    pub fn order_by(mut self, property: impl Into<String>, order: Order) -> Self {
        self.steps.push(Step::OrderBy(property.into(), order));
        self
    }

    /// Order results by multiple properties with priorities.
    ///
    /// Note: some interpreters represent intermediate streams as sets. In those
    /// engines, ordering may not be preserved in the returned node set.
    pub fn order_by_multiple(mut self, orderings: Vec<(impl Into<String>, Order)>) -> Self {
        let orderings: Vec<(String, Order)> =
            orderings.into_iter().map(|(p, o)| (p.into(), o)).collect();
        self.steps.push(Step::OrderByMultiple(orderings));
        self
    }

    // Path Steps

    /// Include the full traversal path in results.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn path(mut self) -> Self {
        self.steps.push(Step::Path);
        self
    }

    /// Filter to only simple paths (no repeated nodes).
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn simple_path(mut self) -> Self {
        self.steps.push(Step::SimplePath);
        self
    }
}

/// Create a new sub-traversal for use in branching operations
///
/// Use this instead of `g()` when building traversals for `union()`, `choose()`,
/// `coalesce()`, `optional()`, or `repeat()`.
///
pub fn sub() -> SubTraversal {
    SubTraversal::new()
}

// Repeat Configuration

/// Configuration for repeat steps
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RepeatConfig {
    /// The sub-traversal to repeat
    pub traversal: SubTraversal,
    /// Maximum number of iterations (None = unlimited)
    pub times: Option<usize>,
    /// Condition to stop repeating (checked each iteration)
    pub until: Option<Predicate>,
    /// Whether to emit intermediate results
    pub emit: EmitBehavior,
    /// Optional predicate for conditional emit
    pub emit_predicate: Option<Predicate>,
    /// Maximum depth to prevent infinite loops (default: 100)
    pub max_depth: usize,
}

impl RepeatConfig {
    /// Create a new repeat configuration
    pub fn new(traversal: SubTraversal) -> Self {
        Self {
            traversal,
            times: None,
            until: None,
            emit: EmitBehavior::None,
            emit_predicate: None,
            max_depth: 100,
        }
    }

    /// Set the number of times to repeat
    pub fn times(mut self, n: usize) -> Self {
        self.times = Some(n);
        self
    }

    /// Set the until condition
    pub fn until(mut self, predicate: Predicate) -> Self {
        self.until = Some(predicate);
        self
    }

    /// Emit intermediate results before and after each iteration.
    pub fn emit_all(mut self) -> Self {
        self.emit = EmitBehavior::All;
        self
    }

    /// Emit intermediate results before each iteration
    pub fn emit_before(mut self) -> Self {
        self.emit = EmitBehavior::Before;
        self
    }

    /// Emit intermediate results after each iteration
    pub fn emit_after(mut self) -> Self {
        self.emit = EmitBehavior::After;
        self
    }

    /// Emit intermediate results that match a predicate.
    ///
    /// This enables post-iteration emission (equivalent to [`EmitBehavior::After`])
    /// and applies `predicate` to decide which vertices to emit.
    pub fn emit_if(mut self, predicate: Predicate) -> Self {
        self.emit = EmitBehavior::After;
        self.emit_predicate = Some(predicate);
        self
    }

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

/// Dynamic index declaration used by runtime index-management steps.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IndexSpec {
    /// Equality index over node properties.
    NodeEquality {
        /// Node label to scope the index.
        label: String,
        /// Indexed property name.
        property: String,
        /// Whether the index enforces uniqueness for supported non-null values.
        #[serde(default)]
        unique: bool,
    },
    /// Range index over node properties.
    NodeRange {
        /// Node label to scope the index.
        label: String,
        /// Indexed property name.
        property: String,
    },
    /// Equality index over edge properties.
    EdgeEquality {
        /// Edge label to scope the index.
        label: String,
        /// Indexed property name.
        property: String,
    },
    /// Range index over edge properties.
    EdgeRange {
        /// Edge label to scope the index.
        label: String,
        /// Indexed property name.
        property: String,
    },
    /// Vector index over node properties.
    NodeVector {
        /// Node label to scope the index.
        label: String,
        /// Property name containing vectors.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },
    /// Text index over node properties.
    NodeText {
        /// Node label to scope the index.
        label: String,
        /// Property name containing text.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },
    /// Vector index over edge properties.
    EdgeVector {
        /// Edge label to scope the index.
        label: String,
        /// Property name containing vectors.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },
    /// Text index over edge properties.
    EdgeText {
        /// Edge label to scope the index.
        label: String,
        /// Property name containing text.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },
}

impl IndexSpec {
    /// Build a node equality index declaration.
    pub fn node_equality(label: impl Into<String>, property: impl Into<String>) -> Self {
        Self::NodeEquality {
            label: label.into(),
            property: property.into(),
            unique: false,
        }
    }

    /// Build a unique node equality index declaration.
    pub fn node_unique_equality(label: impl Into<String>, property: impl Into<String>) -> Self {
        Self::NodeEquality {
            label: label.into(),
            property: property.into(),
            unique: true,
        }
    }

    /// Build a node range index declaration.
    pub fn node_range(label: impl Into<String>, property: impl Into<String>) -> Self {
        Self::NodeRange {
            label: label.into(),
            property: property.into(),
        }
    }

    /// Build an edge equality index declaration.
    pub fn edge_equality(label: impl Into<String>, property: impl Into<String>) -> Self {
        Self::EdgeEquality {
            label: label.into(),
            property: property.into(),
        }
    }

    /// Build an edge range index declaration.
    pub fn edge_range(label: impl Into<String>, property: impl Into<String>) -> Self {
        Self::EdgeRange {
            label: label.into(),
            property: property.into(),
        }
    }

    /// Build a node vector index declaration.
    pub fn node_vector(
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Self {
        Self::NodeVector {
            label: label.into(),
            property: property.into(),
            tenant_property: tenant_property.map(|value| value.into()),
        }
    }

    /// Build a node text index declaration.
    pub fn node_text(
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Self {
        Self::NodeText {
            label: label.into(),
            property: property.into(),
            tenant_property: tenant_property.map(|value| value.into()),
        }
    }

    /// Build an edge vector index declaration.
    pub fn edge_vector(
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Self {
        Self::EdgeVector {
            label: label.into(),
            property: property.into(),
            tenant_property: tenant_property.map(|value| value.into()),
        }
    }

    /// Build an edge text index declaration.
    pub fn edge_text(
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Self {
        Self::EdgeText {
            label: label.into(),
            property: property.into(),
            tenant_property: tenant_property.map(|value| value.into()),
        }
    }
}

// Step Enum (AST Nodes)

/// A single step in a traversal AST.
///
/// Most users should build traversals via [`g()`] and the [`Traversal`] builder.
/// This enum exists so the traversal can be inspected, serialized, transported,
/// and reconstructed with [`Traversal::from_steps`].
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Step {
    // Source Steps - Start a traversal or switch context
    /// Start (or switch) on nodes.
    ///
    /// Typical usage is as the first traversal source via [`Traversal::n`].
    N(NodeRef),

    /// Start from nodes matching a [`SourcePredicate`].
    NWhere(SourcePredicate),

    /// Start (or switch) on edges.
    ///
    /// Typical usage is as the first traversal source via [`Traversal::e`].
    E(EdgeRef),

    /// Start from edges matching a [`SourcePredicate`].
    EWhere(SourcePredicate),

    /// Vector similarity search on nodes
    ///
    /// Start traversal from nodes with vectors similar to the query vector.
    /// Uses the HNSW index for the given (label, property) combination.
    ///
    /// Note: this step encodes the nearest-neighbor search inputs.
    /// Implementations may expose ranking and distance metadata at runtime.
    VectorSearchNodes {
        /// The node label to search
        label: String,
        /// The property name containing vectors
        property: String,
        /// Optional multitenant partition value.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_value: Option<PropertyInput>,
        /// The query vector input.
        query_vector: PropertyInput,
        /// Number of nearest neighbors to return.
        k: StreamBound,
    },

    /// BM25 text search on nodes.
    TextSearchNodes {
        /// The node label to search.
        label: String,
        /// The property name containing indexed text.
        property: String,
        /// Optional multitenant partition value.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_value: Option<PropertyInput>,
        /// The query text input.
        query_text: PropertyInput,
        /// Number of ranked results to return.
        k: StreamBound,
    },

    /// Vector similarity search on edges
    ///
    /// Start traversal from edges with vectors similar to the query vector.
    /// Uses the HNSW index for the given (label, property) combination.
    ///
    /// Note: this step encodes the nearest-neighbor search inputs.
    /// Implementations may expose ranking and distance metadata at runtime.
    VectorSearchEdges {
        /// The edge label to search
        label: String,
        /// The property name containing vectors
        property: String,
        /// Optional multitenant partition value.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_value: Option<PropertyInput>,
        /// The query vector input.
        query_vector: PropertyInput,
        /// Number of nearest neighbors to return.
        k: StreamBound,
    },

    /// BM25 text search on edges.
    TextSearchEdges {
        /// The edge label to search.
        label: String,
        /// The property name containing indexed text.
        property: String,
        /// Optional multitenant partition value.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_value: Option<PropertyInput>,
        /// The query text input.
        query_text: PropertyInput,
        /// Number of ranked results to return.
        k: StreamBound,
    },

    // Traversal Steps - Navigate the graph
    /// Traverse outgoing edges, optionally filtered by label.
    ///
    /// Builder forms:
    /// - `.out(Some("KNOWS"))`
    /// - `.out(None::<&str>)` (no label filter)
    Out(Option<String>),

    /// Traverse incoming edges, optionally filtered by label.
    ///
    /// Builder forms:
    /// - `.in_(Some("KNOWS"))`
    /// - `.in_(None::<&str>)`
    In(Option<String>),

    /// Traverse edges in both directions, optionally filtered by label.
    ///
    /// Builder forms:
    /// - `.both(Some("KNOWS"))`
    /// - `.both(None::<&str>)`
    Both(Option<String>),

    // Edge Traversal Steps - Navigate to/from edges
    /// Traverse from nodes to outgoing edges.
    ///
    /// Builder forms:
    /// - `.out_e(Some("KNOWS"))`
    /// - `.out_e(None::<&str>)`
    OutE(Option<String>),

    /// Traverse from nodes to incoming edges.
    ///
    /// Builder forms:
    /// - `.in_e(Some("KNOWS"))`
    /// - `.in_e(None::<&str>)`
    InE(Option<String>),

    /// Traverse from nodes to edges in both directions.
    ///
    /// Builder forms:
    /// - `.both_e(Some("KNOWS"))`
    /// - `.both_e(None::<&str>)`
    BothE(Option<String>),

    /// From an edge stream, switch back to nodes by selecting the edge target.
    ///
    /// Builder form: `.out_n()`
    OutN,

    /// From an edge stream, switch back to nodes by selecting the edge source.
    ///
    /// Builder form: `.in_n()`
    InN,

    /// From an edge stream, switch back to nodes by selecting the "other" endpoint.
    ///
    /// Builder form: `.other_n()`
    OtherN,

    // Filter Steps - Reduce the stream
    /// Filter nodes by property equality: `.has("name", "Alice")`
    Has(String, PropertyValue),

    /// Filter nodes by label: `.has_label("User")`.
    ///
    /// This is shorthand for filtering on the reserved `$label` property.
    HasLabel(String),

    /// Filter nodes by property existence: `.has_key("email")`
    HasKey(String),

    /// Filter nodes by a [`Predicate`]: `.where_(Predicate::gt("age", 18i64))`
    /// or `.where_(Predicate::is_in("status", vec!["active".to_string()]))`
    Where(Predicate),

    /// Remove duplicates: `dedup()`
    Dedup,

    /// Filter to nodes that exist in a variable: `within("x")`
    Within(String),

    /// Filter to nodes that do NOT exist in a variable: `without("x")`
    Without(String),

    // Edge Filter Steps - Filter edges
    /// Filter edges by property equality: `.edge_has("weight", 1i64)`
    EdgeHas(String, PropertyInput),

    /// Filter edges by label: `.edge_has_label("KNOWS")`
    EdgeHasLabel(String),

    // Limit Steps - Control stream size
    /// Take first N items: `limit(10)`
    Limit(usize),

    /// Take first N items using a runtime-resolved expression.
    LimitBy(Expr),

    /// Skip first N items: `skip(5)`
    Skip(usize),

    /// Skip first N items using a runtime-resolved expression.
    SkipBy(Expr),

    /// Get items in range [start, end): equivalent to skip(start).limit(end - start)
    Range(usize, usize),

    /// Get items in range [start, end) using literal and/or runtime-resolved bounds.
    RangeBy(StreamBound, StreamBound),

    // Variable Steps - Store and reference results
    /// Store the current stream in the traversal context under a name.
    ///
    /// Builder form: `.as_("x")`
    As(String),

    /// Store the current stream in the traversal context under a name.
    ///
    /// Builder form: `.store("x")`
    Store(String),

    /// Replace the current node stream with nodes referenced by a stored variable.
    ///
    /// Builder form: `.select("x")`
    Select(String),

    // Terminal Steps - End the traversal
    /// Count results (returns single value)
    Count,

    /// Check if any results exist (returns bool)
    Exists,

    /// Get the ID of current nodes/edges (returns the ID as a value)
    Id,

    /// Get the label of current nodes/edges (returns the $label property)
    Label,

    // Property Projection Steps - Return property data
    /// Return specific node properties.
    ///
    /// Builder form: `.values(vec!["name", "age"])`
    Values(Vec<String>),

    /// Return node properties as maps.
    ///
    /// Builder forms:
    /// - `.value_map(None::<Vec<&str>>)` (all properties)
    /// - `.value_map(Some(vec!["name", "age"]))`
    ValueMap(Option<Vec<String>>),

    /// Project properties and expressions with optional renaming.
    Project(Vec<Projection>),

    /// Return edge properties for the current edge stream.
    ///
    /// Builder form: `.edge_properties()`
    EdgeProperties,

    /// Create a runtime index, treating existing matching definitions as a no-op
    /// when `if_not_exists` is true.
    CreateIndex {
        /// Index specification to create.
        spec: IndexSpec,
        /// Whether duplicate creates should be ignored.
        if_not_exists: bool,
    },

    /// Drop a runtime index.
    DropIndex {
        /// Index specification to drop.
        spec: IndexSpec,
    },

    // Mutation Steps - Modify the graph (write transactions only)
    /// Create a vector index for nodes with the given label and property
    CreateVectorIndexNodes {
        /// Node label to scope the index
        label: String,
        /// Property name containing vectors
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },

    /// Create a vector index for edges with the given label and property
    CreateVectorIndexEdges {
        /// Edge label to scope the index
        label: String,
        /// Property name containing vectors
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },

    /// Create a text index for nodes with the given label and property.
    CreateTextIndexNodes {
        /// Node label to scope the index.
        label: String,
        /// Property name containing text.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },

    /// Create a text index for edges with the given label and property.
    CreateTextIndexEdges {
        /// Edge label to scope the index.
        label: String,
        /// Property name containing text.
        property: String,
        /// Optional multitenant partition property.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tenant_property: Option<String>,
    },

    /// Add a node with a label and properties.
    ///
    /// Builder form: `.add_n("User", vec![("name", "Alice")])`
    /// The node ID is allocated automatically.
    /// The new node becomes the current traversal context.
    AddN {
        /// The node label (required)
        label: String,
        /// Optional properties
        properties: Vec<(String, PropertyInput)>,
    },

    /// Add edges from the current nodes to `to`.
    ///
    /// Builder form: `.add_e("FOLLOWS", to, vec![("weight", 1i64)])`
    AddE {
        /// The edge label (required)
        label: String,
        /// Target nodes (by ID or variable)
        to: NodeRef,
        /// Optional edge properties
        properties: Vec<(String, PropertyInput)>,
    },

    /// Set/update a property on the current nodes: `.set_property(name, value)`
    SetProperty(String, PropertyInput),

    /// Remove a property from the current nodes: `.remove_property(name)`
    RemoveProperty(String),

    /// Delete current nodes (and their edges): `drop()`
    Drop,

    /// Delete edges from the current nodes to a target set: `.drop_edge(target)`
    ///
    /// **Note**: In multigraph scenarios, this removes ALL edges between the current
    /// nodes and the target nodes. Use `DropEdgeById` for precise edge removal.
    DropEdge(NodeRef),

    /// Delete only edges with a specific label from the current nodes to a target set.
    DropEdgeLabeled {
        /// Target nodes to disconnect from.
        to: NodeRef,
        /// Edge label to remove.
        label: String,
    },

    /// Delete specific edges by their IDs: `.drop_edge_by_id(edge_ref)`
    ///
    /// This is the multigraph-safe way to remove edges, as it removes specific
    /// edges rather than all edges between a pair of nodes.
    DropEdgeById(EdgeRef),

    // Ordering Steps - Sort the stream
    /// Order the node stream by a property: `.order_by("age", Order::Desc)`
    OrderBy(String, Order),

    /// Order by multiple properties with priorities
    OrderByMultiple(Vec<(String, Order)>),

    // Loop/Repeat Steps - Iterative traversal
    /// Repeat a traversal body.
    ///
    /// Builder form: `.repeat(RepeatConfig::new(sub().out(None::<&str>)).times(3))`
    Repeat(RepeatConfig),

    // Branching Steps - Conditional execution
    /// Execute multiple sub-traversals and merge their results: `.union(vec![...])`
    Union(Vec<SubTraversal>),

    /// Conditional branching: `choose(predicate, then_traversal, else_traversal)`
    Choose {
        /// Condition to check
        condition: Predicate,
        /// Traversal if condition is true
        then_traversal: SubTraversal,
        /// Traversal if condition is false (optional)
        else_traversal: Option<SubTraversal>,
    },

    /// Try sub-traversals in order until one produces results: `.coalesce(vec![...])`
    Coalesce(Vec<SubTraversal>),

    /// Execute a sub-traversal if it produces results, otherwise pass through: `.optional(t)`
    Optional(SubTraversal),

    // Aggregation Steps - Group and reduce
    /// Group by a property.
    Group(String),

    /// Count occurrences grouped by a property.
    GroupCount(String),

    /// Apply an aggregation function to a property.
    ///
    /// Builder form: `.aggregate_by(AggregateFunction::Sum, "price")`
    AggregateBy(AggregateFunction, String),

    /// Barrier step.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    Fold,

    /// Expand a collected list back into individual items.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    Unfold,

    // Path Steps - Track traversal history
    /// Include the full traversal path in results.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    Path,

    /// Filter to paths without repeated nodes (cycle detection).
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    SimplePath,

    // Sack Steps - Carry state through traversal
    /// Initialize a sack with a value.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    WithSack(PropertyValue),

    /// Update the sack with a property value.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    SackSet(String),

    /// Add to the sack (numeric only).
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    SackAdd(String),

    /// Get the current sack value.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    SackGet,

    // Inject Steps - Add values to the stream
    /// Inject nodes from a variable into the stream.
    ///
    /// As a source step, this starts from the variable's stored node set.
    /// When used mid-traversal, engines may interpret this as a union/merge.
    Inject(String),
}

fn limit_step(bound: impl Into<StreamBound>) -> Step {
    match bound.into() {
        StreamBound::Literal(n) => Step::Limit(n),
        StreamBound::Expr(expr) => Step::LimitBy(expr),
    }
}

fn skip_step(bound: impl Into<StreamBound>) -> Step {
    match bound.into() {
        StreamBound::Literal(n) => Step::Skip(n),
        StreamBound::Expr(expr) => Step::SkipBy(expr),
    }
}

fn range_step(start: impl Into<StreamBound>, end: impl Into<StreamBound>) -> Step {
    let start = start.into();
    let end = end.into();
    match (&start, &end) {
        (StreamBound::Literal(start), StreamBound::Literal(end)) => Step::Range(*start, *end),
        _ => Step::RangeBy(start, end),
    }
}

// Traversal with Typestate

/// A complete traversal - a sequence of steps with compile-time state tracking.
///
/// The type parameter `S` tracks what kind of elements the traversal is currently
/// operating on, preventing invalid operation sequences at compile time.
///
/// # State Types
/// - `Empty` - No source step yet, only source operations allowed
/// - `OnNodes` - Currently on node stream, node operations allowed
/// - `OnEdges` - Currently on edge stream, edge operations allowed
/// - `Terminal` - Traversal complete, no more chaining allowed
///
/// The second type parameter `M` tracks mutation capability:
/// - `ReadOnly` - No mutation steps (can be used in read batches)
/// - `WriteEnabled` - Contains mutation steps (requires write batch)
#[derive(Debug, Clone, PartialEq)]
pub struct Traversal<S: TraversalState = OnNodes, M: MutationMode = ReadOnly> {
    /// The steps in this traversal.
    ///
    /// Mutating this vector directly bypasses typestate guarantees enforced by
    /// builder methods. Prefer builder APIs unless you intentionally need to
    /// manipulate raw AST steps.
    #[doc(hidden)]
    pub steps: Vec<Step>,
    /// Phantom data to track the typestate
    _state: PhantomData<S>,
    /// Phantom data to track mutation mode
    _mode: PhantomData<M>,
}

impl<S: TraversalState, M: MutationMode> Default for Traversal<S, M> {
    fn default() -> Self {
        Self {
            steps: Vec::new(),
            _state: PhantomData,
            _mode: PhantomData,
        }
    }
}

impl<S: TraversalState, M: MutationMode> Traversal<S, M> {
    /// Get the steps of this traversal
    #[doc(hidden)]
    pub fn into_steps(self) -> Vec<Step> {
        self.steps
    }

    /// Check if this traversal has a terminal step
    #[doc(hidden)]
    pub fn has_terminal(&self) -> bool {
        self.steps.iter().any(|s| {
            matches!(
                s,
                Step::Count
                    | Step::Exists
                    | Step::Id
                    | Step::Label
                    | Step::Values(_)
                    | Step::ValueMap(_)
                    | Step::Project(_)
                    | Step::EdgeProperties
                    | Step::CreateIndex { .. }
                    | Step::DropIndex { .. }
                    | Step::CreateVectorIndexNodes { .. }
                    | Step::CreateVectorIndexEdges { .. }
                    | Step::CreateTextIndexNodes { .. }
                    | Step::CreateTextIndexEdges { .. }
            )
        })
    }

    /// Create a traversal from steps
    ///
    /// This is useful for batch execution where queries are stored as Vec<Step>
    /// and need to be reconstructed into a Traversal.
    ///
    /// This constructor does not validate that `steps` matches `S`/`M`.
    /// Prefer builder entry points like [`g()`], [`read_batch()`], and [`write_batch()`]
    /// unless you intentionally need a raw reconstruction.
    #[doc(hidden)]
    pub fn from_steps(steps: Vec<Step>) -> Self {
        Self {
            steps,
            _state: PhantomData,
            _mode: PhantomData,
        }
    }

    /// Add a step and transition to a new state (preserving mutation mode)
    fn push_step<T: TraversalState>(mut self, step: Step) -> Traversal<T, M> {
        self.steps.push(step);
        Traversal::from_steps(self.steps)
    }

    /// Add a step and transition to WriteEnabled mode
    fn push_mutation_step<T: TraversalState>(mut self, step: Step) -> Traversal<T, WriteEnabled> {
        self.steps.push(step);
        Traversal::from_steps(self.steps)
    }
}

// Empty State Implementation - Source Steps Only

impl Traversal<Empty, ReadOnly> {
    /// Create a new empty traversal
    #[doc(hidden)]
    pub fn new() -> Self {
        Self {
            steps: Vec::new(),
            _state: PhantomData,
            _mode: PhantomData,
        }
    }

    // Node Source Steps: Empty -> OnNodes

    /// Start traversal from nodes by IDs or a variable.
    ///
    pub fn n(self, nodes: impl Into<NodeRef>) -> Traversal<OnNodes> {
        self.push_step(Step::N(nodes.into()))
    }

    /// Start traversal from nodes matching a predicate
    ///
    ///
    pub fn n_where(self, predicate: SourcePredicate) -> Traversal<OnNodes> {
        self.push_step(Step::NWhere(predicate))
    }

    /// Start traversal from nodes with a specific label
    ///
    /// This is a convenience method equivalent to `n_where(SourcePredicate::eq("$label", label))`.
    ///
    pub fn n_with_label(self, label: impl Into<String>) -> Traversal<OnNodes> {
        self.n_where(SourcePredicate::Eq(
            "$label".to_string(),
            PropertyValue::String(label.into()),
        ))
    }

    /// Start traversal from nodes with a specific label and additional predicate
    ///
    /// This is a convenience method equivalent to
    /// `n_where(SourcePredicate::and(vec![SourcePredicate::eq("$label", label), predicate]))`.
    ///
    pub fn n_with_label_where(
        self,
        label: impl Into<String>,
        predicate: SourcePredicate,
    ) -> Traversal<OnNodes> {
        self.n_where(SourcePredicate::And(vec![
            SourcePredicate::Eq("$label".to_string(), PropertyValue::String(label.into())),
            predicate,
        ]))
    }

    // Vector Search Source Steps

    /// Start traversal from nodes with vectors similar to the query vector
    ///
    /// Uses the HNSW index for the given (label, property) combination to find
    /// the k nearest neighbors to the query vector.
    ///
    /// Runtime behavior in the current Helix interpreter:
    /// - returns top-k nearest hits (up to `k`) ordered by ascending distance
    /// - `value_map`, `values`, and `project` can read virtual fields `$id` and `$distance`
    /// - after traversing away from the hit stream (for example, `out`/`in_`),
    ///   distance metadata is no longer attached to downstream traversers
    ///
    /// # Arguments
    /// * `label` - The node label to search
    /// * `property` - The property name containing vectors
    /// * `query_vector` - The query vector
    /// * `k` - Number of nearest neighbors to return
    /// * `tenant_value` - Optional multitenant partition value
    ///
    pub fn vector_search_nodes(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_vector: Vec<f32>,
        k: usize,
        tenant_value: Option<PropertyValue>,
    ) -> Traversal<OnNodes> {
        self.vector_search_nodes_with(
            label,
            property,
            query_vector,
            k,
            tenant_value.map(PropertyInput::from),
        )
    }

    /// Start traversal from nodes with vectors similar to the query vector.
    ///
    /// This variant accepts runtime-resolved inputs for the query vector, result
    /// count, and tenant partition value.
    pub fn vector_search_nodes_with(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_vector: impl Into<PropertyInput>,
        k: impl Into<StreamBound>,
        tenant_value: Option<PropertyInput>,
    ) -> Traversal<OnNodes> {
        self.push_step(Step::VectorSearchNodes {
            label: label.into(),
            property: property.into(),
            tenant_value,
            query_vector: query_vector.into(),
            k: k.into(),
        })
    }

    /// Start traversal from nodes matching a text query.
    pub fn text_search_nodes(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_text: impl Into<String>,
        k: usize,
        tenant_value: Option<PropertyValue>,
    ) -> Traversal<OnNodes> {
        self.text_search_nodes_with(
            label,
            property,
            PropertyInput::from(query_text.into()),
            k,
            tenant_value.map(PropertyInput::from),
        )
    }

    /// Start traversal from nodes matching a text query with runtime-resolved inputs.
    pub fn text_search_nodes_with(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_text: impl Into<PropertyInput>,
        k: impl Into<StreamBound>,
        tenant_value: Option<PropertyInput>,
    ) -> Traversal<OnNodes> {
        self.push_step(Step::TextSearchNodes {
            label: label.into(),
            property: property.into(),
            tenant_value,
            query_text: query_text.into(),
            k: k.into(),
        })
    }

    // Edge Source Steps: Empty -> OnEdges

    /// Start traversal from edges by IDs or a variable.
    ///
    pub fn e(self, edges: impl Into<EdgeRef>) -> Traversal<OnEdges> {
        self.push_step(Step::E(edges.into()))
    }

    /// Start traversal from edges matching a predicate
    ///
    ///
    pub fn e_where(self, predicate: SourcePredicate) -> Traversal<OnEdges> {
        self.push_step(Step::EWhere(predicate))
    }

    /// Start traversal from edges with a specific label
    ///
    /// This is a convenience method equivalent to `e_where(SourcePredicate::eq("$label", label))`.
    ///
    pub fn e_with_label(self, label: impl Into<String>) -> Traversal<OnEdges> {
        self.e_where(SourcePredicate::Eq(
            "$label".to_string(),
            PropertyValue::String(label.into()),
        ))
    }

    /// Start traversal from edges with a specific label and additional predicate
    ///
    /// This is a convenience method equivalent to
    /// `e_where(SourcePredicate::and(vec![SourcePredicate::eq("$label", label), predicate]))`.
    ///
    pub fn e_with_label_where(
        self,
        label: impl Into<String>,
        predicate: SourcePredicate,
    ) -> Traversal<OnEdges> {
        self.e_where(SourcePredicate::And(vec![
            SourcePredicate::Eq("$label".to_string(), PropertyValue::String(label.into())),
            predicate,
        ]))
    }

    /// Start traversal from edges with vectors similar to the query vector
    ///
    /// Uses the HNSW index for the given (label, property) combination to find
    /// the k nearest neighbors to the query vector.
    ///
    /// Runtime behavior in the current Helix interpreter:
    /// - returns top-k nearest hits (up to `k`) ordered by ascending distance
    /// - `edge_properties` includes virtual fields `$from`, `$to`, and `$distance`
    ///   (plus `$id` when available)
    ///
    /// # Arguments
    /// * `label` - The edge label to search
    /// * `property` - The property name containing vectors
    /// * `query_vector` - The query vector
    /// * `k` - Number of nearest neighbors to return
    /// * `tenant_value` - Optional multitenant partition value
    ///
    pub fn vector_search_edges(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_vector: Vec<f32>,
        k: usize,
        tenant_value: Option<PropertyValue>,
    ) -> Traversal<OnEdges> {
        self.vector_search_edges_with(
            label,
            property,
            query_vector,
            k,
            tenant_value.map(PropertyInput::from),
        )
    }

    /// Start traversal from edges with vectors similar to the query vector.
    ///
    /// This variant accepts runtime-resolved inputs for the query vector, result
    /// count, and tenant partition value.
    pub fn vector_search_edges_with(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_vector: impl Into<PropertyInput>,
        k: impl Into<StreamBound>,
        tenant_value: Option<PropertyInput>,
    ) -> Traversal<OnEdges> {
        self.push_step(Step::VectorSearchEdges {
            label: label.into(),
            property: property.into(),
            tenant_value,
            query_vector: query_vector.into(),
            k: k.into(),
        })
    }

    /// Start traversal from edges matching a text query.
    pub fn text_search_edges(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_text: impl Into<String>,
        k: usize,
        tenant_value: Option<PropertyValue>,
    ) -> Traversal<OnEdges> {
        self.text_search_edges_with(
            label,
            property,
            PropertyInput::from(query_text.into()),
            k,
            tenant_value.map(PropertyInput::from),
        )
    }

    /// Start traversal from edges matching a text query with runtime-resolved inputs.
    pub fn text_search_edges_with(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        query_text: impl Into<PropertyInput>,
        k: impl Into<StreamBound>,
        tenant_value: Option<PropertyInput>,
    ) -> Traversal<OnEdges> {
        self.push_step(Step::TextSearchEdges {
            label: label.into(),
            property: property.into(),
            tenant_value,
            query_text: query_text.into(),
            k: k.into(),
        })
    }

    // Mutation Source Steps: Empty -> OnNodes

    /// Create a runtime index if it does not already exist.
    pub fn create_index_if_not_exists(self, spec: IndexSpec) -> Traversal<Terminal, WriteEnabled> {
        self.push_mutation_step(Step::CreateIndex {
            spec,
            if_not_exists: true,
        })
    }

    /// Drop a runtime index.
    pub fn drop_index(self, spec: IndexSpec) -> Traversal<Terminal, WriteEnabled> {
        self.push_mutation_step(Step::DropIndex { spec })
    }

    /// Create a vector index on nodes.
    ///
    /// This is a write-only source step intended for index management. It does not
    /// produce a useful traversal stream, so the builder marks it as terminal.
    /// Runtime index parameters are selected by the database.
    ///
    pub fn create_vector_index_nodes(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Traversal<Terminal, WriteEnabled> {
        self.create_index_if_not_exists(IndexSpec::node_vector(label, property, tenant_property))
    }

    /// Create a vector index on edges.
    ///
    /// This is a write-only source step intended for index management. It does not
    /// produce a useful traversal stream, so the builder marks it as terminal.
    /// Runtime index parameters are selected by the database.
    ///
    pub fn create_vector_index_edges(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Traversal<Terminal, WriteEnabled> {
        self.create_index_if_not_exists(IndexSpec::edge_vector(label, property, tenant_property))
    }

    /// Create a text index on nodes.
    pub fn create_text_index_nodes(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Traversal<Terminal, WriteEnabled> {
        self.create_index_if_not_exists(IndexSpec::node_text(label, property, tenant_property))
    }

    /// Create a text index on edges.
    pub fn create_text_index_edges(
        self,
        label: impl Into<String>,
        property: impl Into<String>,
        tenant_property: Option<impl Into<String>>,
    ) -> Traversal<Terminal, WriteEnabled> {
        self.create_index_if_not_exists(IndexSpec::edge_text(label, property, tenant_property))
    }

    /// Add a new node with a label and optional properties.
    ///
    /// The node ID is automatically allocated.
    ///
    /// In the current Helix interpreter, this step creates exactly one node and
    /// starts the traversal from that node.
    ///
    pub fn add_n<K, V>(
        self,
        label: impl Into<String>,
        properties: Vec<(K, V)>,
    ) -> Traversal<OnNodes, WriteEnabled>
    where
        K: Into<String>,
        V: Into<PropertyInput>,
    {
        let props: Vec<(String, PropertyInput)> = properties
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        self.push_mutation_step(Step::AddN {
            label: label.into(),
            properties: props,
        })
    }

    /// Start from nodes stored in a variable (Empty -> OnNodes).
    ///
    /// This is a convenience for starting from a node set previously saved via
    /// `store()` / `as_()` in the same traversal context.
    ///
    /// If you want to start from a variable that yields node IDs via other means
    /// (for example, an `id()` terminal result), prefer `n(NodeRef::var(name))`.
    ///
    pub fn inject(self, var_name: impl Into<String>) -> Traversal<OnNodes, ReadOnly> {
        self.push_step(Step::Inject(var_name.into()))
    }

    /// Delete specific edges by their IDs without needing a source
    ///
    /// This is the multigraph-safe way to remove edges, as it removes specific
    /// edges rather than all edges between a pair of nodes.
    ///
    pub fn drop_edge_by_id(self, edges: impl Into<EdgeRef>) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::DropEdgeById(edges.into()))
    }
}

// OnNodes State Implementation

impl<M: MutationMode> Traversal<OnNodes, M> {
    // Navigation Steps: OnNodes -> OnNodes

    /// Traverse outgoing edges, optionally filtered by label
    pub fn out(self, label: Option<impl Into<String>>) -> Traversal<OnNodes, M> {
        self.push_step(Step::Out(label.map(|l| l.into())))
    }

    /// Traverse incoming edges, optionally filtered by label
    pub fn in_(self, label: Option<impl Into<String>>) -> Traversal<OnNodes, M> {
        self.push_step(Step::In(label.map(|l| l.into())))
    }

    /// Traverse edges in both directions, optionally filtered by label
    pub fn both(self, label: Option<impl Into<String>>) -> Traversal<OnNodes, M> {
        self.push_step(Step::Both(label.map(|l| l.into())))
    }

    // Edge Traversal Steps: OnNodes -> OnEdges

    /// Traverse to outgoing edges
    pub fn out_e(self, label: Option<impl Into<String>>) -> Traversal<OnEdges, M> {
        self.push_step(Step::OutE(label.map(|l| l.into())))
    }

    /// Traverse to incoming edges
    pub fn in_e(self, label: Option<impl Into<String>>) -> Traversal<OnEdges, M> {
        self.push_step(Step::InE(label.map(|l| l.into())))
    }

    /// Traverse to edges in both directions
    pub fn both_e(self, label: Option<impl Into<String>>) -> Traversal<OnEdges, M> {
        self.push_step(Step::BothE(label.map(|l| l.into())))
    }

    // Node Filter Steps: OnNodes -> OnNodes

    /// Filter by property value
    pub fn has(self, property: impl Into<String>, value: impl Into<PropertyValue>) -> Self {
        self.push_step(Step::Has(property.into(), value.into()))
    }

    /// Filter by label (shorthand for has("$label", value))
    pub fn has_label(self, label: impl Into<String>) -> Self {
        self.push_step(Step::HasLabel(label.into()))
    }

    /// Filter by property existence
    pub fn has_key(self, property: impl Into<String>) -> Self {
        self.push_step(Step::HasKey(property.into()))
    }

    /// Filter by a complex predicate
    pub fn where_(self, predicate: Predicate) -> Self {
        self.push_step(Step::Where(predicate))
    }

    /// Remove duplicates from the stream
    pub fn dedup(self) -> Self {
        self.push_step(Step::Dedup)
    }

    /// Filter to nodes that exist in a variable
    pub fn within(self, var_name: impl Into<String>) -> Self {
        self.push_step(Step::Within(var_name.into()))
    }

    /// Filter to nodes that do NOT exist in a variable
    pub fn without(self, var_name: impl Into<String>) -> Self {
        self.push_step(Step::Without(var_name.into()))
    }

    // Limit Steps: OnNodes -> OnNodes

    /// Take at most N items.
    pub fn limit(self, n: impl Into<StreamBound>) -> Self {
        self.push_step(limit_step(n))
    }

    /// Skip the first N items.
    pub fn skip(self, n: impl Into<StreamBound>) -> Self {
        self.push_step(skip_step(n))
    }

    /// Get items in a range [start, end)
    ///
    /// Equivalent to `.skip(start).limit(end - start)` but more concise.
    ///
    pub fn range(self, start: impl Into<StreamBound>, end: impl Into<StreamBound>) -> Self {
        self.push_step(range_step(start, end))
    }

    // Variable Steps: OnNodes -> OnNodes

    /// Store the current node stream in the traversal context under `name`.
    ///
    /// This is identical to `store()`; it exists for Gremlin-style naming.
    pub fn as_(self, name: impl Into<String>) -> Self {
        self.push_step(Step::As(name.into()))
    }

    /// Store the current node stream in the traversal context under `name`.
    ///
    /// This does not change the current stream; it only creates/overwrites a
    /// named binding that later steps can reference.
    pub fn store(self, name: impl Into<String>) -> Self {
        self.push_step(Step::Store(name.into()))
    }

    /// Replace the current node stream with nodes referenced by a variable.
    ///
    /// Use this when you want to *switch* streams. If you want to *merge* a stored
    /// node set into the current stream, use `inject()`.
    pub fn select(self, name: impl Into<String>) -> Self {
        self.push_step(Step::Select(name.into()))
    }

    /// Union the current node stream with nodes stored in `var_name`.
    ///
    /// This keeps the current stream and adds any nodes stored in the named
    /// variable. Use `select()` to replace the stream instead.
    ///
    pub fn inject(self, var_name: impl Into<String>) -> Self {
        self.push_step(Step::Inject(var_name.into()))
    }

    // Terminal Steps: OnNodes -> Terminal

    /// Count the number of results
    pub fn count(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Count)
    }

    /// Check if any results exist
    pub fn exists(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Exists)
    }

    /// Get the ID of current nodes
    ///
    /// Returns the node ID as a value. Useful when you need
    /// to extract just the ID without other properties.
    ///
    pub fn id(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Id)
    }

    /// Get the label of current nodes
    ///
    /// Returns the $label property value.
    ///
    pub fn label(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Label)
    }

    /// Get specific property values from current nodes
    pub fn values(self, properties: Vec<impl Into<String>>) -> Traversal<Terminal, M> {
        self.push_step(Step::Values(
            properties.into_iter().map(|p| p.into()).collect(),
        ))
    }

    /// Get properties as a map, optionally filtered to specific properties
    pub fn value_map(self, properties: Option<Vec<impl Into<String>>>) -> Traversal<Terminal, M> {
        self.push_step(Step::ValueMap(
            properties.map(|ps| ps.into_iter().map(|p| p.into()).collect()),
        ))
    }

    /// Project properties and expressions with optional renaming.
    pub fn project<P>(self, projections: Vec<P>) -> Traversal<Terminal, M>
    where
        P: Into<Projection>,
    {
        self.push_step(Step::Project(
            projections.into_iter().map(Into::into).collect(),
        ))
    }

    // Ordering Steps: OnNodes -> OnNodes

    /// Order results by a property.
    ///
    /// Note: some interpreters represent intermediate streams as sets. In those
    /// engines, ordering may not be preserved in the returned node set.
    ///
    pub fn order_by(self, property: impl Into<String>, order: Order) -> Self {
        self.push_step(Step::OrderBy(property.into(), order))
    }

    /// Order results by multiple properties with priorities.
    ///
    /// Note: some interpreters represent intermediate streams as sets. In those
    /// engines, ordering may not be preserved in the returned node set.
    ///
    pub fn order_by_multiple(self, orderings: Vec<(impl Into<String>, Order)>) -> Self {
        let orderings: Vec<(String, Order)> =
            orderings.into_iter().map(|(p, o)| (p.into(), o)).collect();
        self.push_step(Step::OrderByMultiple(orderings))
    }

    // Loop/Repeat Steps: OnNodes -> OnNodes

    /// Repeat a traversal with configuration
    ///
    pub fn repeat(self, config: RepeatConfig) -> Self {
        self.push_step(Step::Repeat(config))
    }

    // Branching Steps: OnNodes -> OnNodes

    /// Execute multiple traversals and merge their results
    ///
    pub fn union(self, traversals: Vec<SubTraversal>) -> Self {
        self.push_step(Step::Union(traversals))
    }

    /// Conditional execution based on a predicate
    ///
    pub fn choose(
        self,
        condition: Predicate,
        then_traversal: SubTraversal,
        else_traversal: Option<SubTraversal>,
    ) -> Self {
        self.push_step(Step::Choose {
            condition,
            then_traversal,
            else_traversal,
        })
    }

    /// Try traversals in order until one produces results
    ///
    pub fn coalesce(self, traversals: Vec<SubTraversal>) -> Self {
        self.push_step(Step::Coalesce(traversals))
    }

    /// Execute a traversal per input item and fall back to the original item when that
    /// input produces no results.
    ///
    /// Note: when the optional branch changes the runtime stream family (for example,
    /// nodes to edges), unmatched inputs drop out of that branch result instead of
    /// producing nullable row bindings.
    ///
    pub fn optional(self, traversal: SubTraversal) -> Self {
        self.push_step(Step::Optional(traversal))
    }

    // Aggregation Steps: OnNodes -> OnNodes (or Terminal for some)

    /// Group nodes by a property value.
    pub fn group(self, property: impl Into<String>) -> Traversal<Terminal, M> {
        self.push_step(Step::Group(property.into()))
    }

    /// Count occurrences grouped by a property.
    pub fn group_count(self, property: impl Into<String>) -> Traversal<Terminal, M> {
        self.push_step(Step::GroupCount(property.into()))
    }

    /// Apply an aggregation function to a property.
    pub fn aggregate_by(
        self,
        function: AggregateFunction,
        property: impl Into<String>,
    ) -> Traversal<Terminal, M> {
        self.push_step(Step::AggregateBy(function, property.into()))
    }

    /// Barrier step.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn fold(self) -> Self {
        self.push_step(Step::Fold)
    }

    /// Expand a collected list back into individual items.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn unfold(self) -> Self {
        self.push_step(Step::Unfold)
    }

    // Path Steps: OnNodes -> OnNodes

    /// Include the full traversal path in results.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    ///
    pub fn path(self) -> Self {
        self.push_step(Step::Path)
    }

    /// Filter to only simple paths (no repeated nodes).
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn simple_path(self) -> Self {
        self.push_step(Step::SimplePath)
    }

    // Sack Steps: OnNodes -> OnNodes

    /// Initialize a sack (traverser-local state) with a value.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    ///
    pub fn with_sack(self, initial: PropertyValue) -> Self {
        self.push_step(Step::WithSack(initial))
    }

    /// Set the sack to a property value from the current node.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn sack_set(self, property: impl Into<String>) -> Self {
        self.push_step(Step::SackSet(property.into()))
    }

    /// Add a property value to the sack (numeric types only).
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn sack_add(self, property: impl Into<String>) -> Self {
        self.push_step(Step::SackAdd(property.into()))
    }

    /// Get the current sack value.
    ///
    /// Note: this step is reserved; the current Helix interpreter treats it as a no-op.
    pub fn sack_get(self) -> Self {
        self.push_step(Step::SackGet)
    }

    // Mutation Steps: OnNodes -> OnNodes (WriteEnabled)

    /// Add a new node with a label and optional properties.
    ///
    /// The node ID is automatically allocated.
    ///
    /// In the current Helix interpreter, this step creates exactly one node and
    /// replaces the current node stream with that new node.
    pub fn add_n<K, V>(
        self,
        label: impl Into<String>,
        properties: Vec<(K, V)>,
    ) -> Traversal<OnNodes, WriteEnabled>
    where
        K: Into<String>,
        V: Into<PropertyInput>,
    {
        let props: Vec<(String, PropertyInput)> = properties
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        self.push_mutation_step(Step::AddN {
            label: label.into(),
            properties: props,
        })
    }

    /// Add edges from the current nodes to target nodes.
    ///
    /// In the current Helix interpreter, this creates edges for every pair in the
    /// cartesian product `current_nodes x target_nodes` and leaves the current
    /// node stream unchanged.
    ///
    pub fn add_e<K, V>(
        self,
        label: impl Into<String>,
        to: impl Into<NodeRef>,
        properties: Vec<(K, V)>,
    ) -> Traversal<OnNodes, WriteEnabled>
    where
        K: Into<String>,
        V: Into<PropertyInput>,
    {
        let props: Vec<(String, PropertyInput)> = properties
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        self.push_mutation_step(Step::AddE {
            label: label.into(),
            to: to.into(),
            properties: props,
        })
    }

    /// Set a property on current nodes
    pub fn set_property(
        self,
        name: impl Into<String>,
        value: impl Into<PropertyInput>,
    ) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::SetProperty(name.into(), value.into()))
    }

    /// Remove a property from current nodes
    pub fn remove_property(self, name: impl Into<String>) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::RemoveProperty(name.into()))
    }

    /// Delete current nodes and their edges
    pub fn drop(self) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::Drop)
    }

    /// Delete edges from current nodes to target nodes
    ///
    /// **Note**: In multigraph scenarios, this removes ALL edges between the current
    /// nodes and the target nodes. Use `drop_edge_by_id` for precise edge removal.
    pub fn drop_edge(self, to: impl Into<NodeRef>) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::DropEdge(to.into()))
    }

    /// Delete only edges with a specific label from current nodes to target nodes.
    pub fn drop_edge_labeled(
        self,
        to: impl Into<NodeRef>,
        label: impl Into<String>,
    ) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::DropEdgeLabeled {
            to: to.into(),
            label: label.into(),
        })
    }

    /// Delete specific edges by their IDs
    ///
    /// This is the multigraph-safe way to remove edges, as it removes specific
    /// edges rather than all edges between a pair of nodes.
    ///
    pub fn drop_edge_by_id(self, edges: impl Into<EdgeRef>) -> Traversal<OnNodes, WriteEnabled> {
        self.push_mutation_step(Step::DropEdgeById(edges.into()))
    }
}

// OnEdges State Implementation

impl<M: MutationMode> Traversal<OnEdges, M> {
    // Node Extraction Steps: OnEdges -> OnNodes

    /// From edge, get the target node
    pub fn out_n(self) -> Traversal<OnNodes, M> {
        self.push_step(Step::OutN)
    }

    /// From edge, get the source node
    pub fn in_n(self) -> Traversal<OnNodes, M> {
        self.push_step(Step::InN)
    }

    /// From edge, get the "other" node (not the one we came from)
    pub fn other_n(self) -> Traversal<OnNodes, M> {
        self.push_step(Step::OtherN)
    }

    // Edge Filter Steps: OnEdges -> OnEdges

    /// Filter edges by property value
    pub fn edge_has(self, property: impl Into<String>, value: impl Into<PropertyInput>) -> Self {
        self.push_step(Step::EdgeHas(property.into(), value.into()))
    }

    /// Filter edges by label
    pub fn edge_has_label(self, label: impl Into<String>) -> Self {
        self.push_step(Step::EdgeHasLabel(label.into()))
    }

    /// Remove duplicates from the stream
    pub fn dedup(self) -> Self {
        self.push_step(Step::Dedup)
    }

    // Limit Steps: OnEdges -> OnEdges

    /// Take at most N items.
    pub fn limit(self, n: impl Into<StreamBound>) -> Self {
        self.push_step(limit_step(n))
    }

    /// Skip the first N items.
    pub fn skip(self, n: impl Into<StreamBound>) -> Self {
        self.push_step(skip_step(n))
    }

    /// Get items in a range [start, end)
    pub fn range(self, start: impl Into<StreamBound>, end: impl Into<StreamBound>) -> Self {
        self.push_step(range_step(start, end))
    }

    // Variable Steps: OnEdges -> OnEdges

    /// Store current edges with a name for later reference
    pub fn as_(self, name: impl Into<String>) -> Self {
        self.push_step(Step::As(name.into()))
    }

    /// Store current edges to a variable (same as `as_`)
    pub fn store(self, name: impl Into<String>) -> Self {
        self.push_step(Step::Store(name.into()))
    }

    // Terminal Steps: OnEdges -> Terminal

    /// Count the number of edges
    pub fn count(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Count)
    }

    /// Check if any edges exist
    pub fn exists(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Exists)
    }

    /// Get the ID of current edges
    pub fn id(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Id)
    }

    /// Get the label of current edges
    pub fn label(self) -> Traversal<Terminal, M> {
        self.push_step(Step::Label)
    }

    /// Get edge properties
    pub fn edge_properties(self) -> Traversal<Terminal, M> {
        self.push_step(Step::EdgeProperties)
    }

    // Ordering Steps: OnEdges -> OnEdges

    /// Order results by a property.
    ///
    /// Note: some interpreters represent intermediate streams as sets. In those
    /// engines, ordering may not be preserved in the returned edge set.
    pub fn order_by(self, property: impl Into<String>, order: Order) -> Self {
        self.push_step(Step::OrderBy(property.into(), order))
    }
}

// Terminal State - No additional methods (traversal is complete)

// Terminal has no additional methods - the traversal is complete

// Entry Point

/// Create a new traversal - the entry point for building queries
///
pub fn g() -> Traversal<Empty> {
    Traversal::new()
}

// Batch Query Types

/// Condition for conditional query execution within a batch
///
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BatchCondition {
    /// Execute only if the named variable is not empty
    VarNotEmpty(String),
    /// Execute only if the named variable is empty
    VarEmpty(String),
    /// Execute only if the named variable has at least N items
    VarMinSize(String, usize),
    /// Execute only if the previous query result was not empty
    PrevNotEmpty,
}

/// A single query within a batch
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NamedQuery {
    /// Variable name to store result (required for var_as)
    pub name: Option<String>,
    /// The traversal steps to execute for this query.
    pub steps: Vec<Step>,
    /// Skip if condition fails
    pub condition: Option<BatchCondition>,
}

/// A batch entry executed in sequence.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BatchEntry {
    /// Execute a single traversal query.
    Query(NamedQuery),
    /// Execute the enclosed entries once per object in the named array param.
    ForEach {
        /// The top-level parameter containing an array of objects.
        param: String,
        /// Entries to execute for each object.
        body: Vec<BatchEntry>,
    },
}

/// A batch of read-only queries for sequential execution in one transaction
///
/// This allows multiple related read queries to be executed atomically,
/// with results stored in named variables that can be referenced
/// by subsequent queries and returned as a structured result.
///
/// **Important**: ReadBatch only accepts read-only traversals (no mutations).
/// Attempting to add a traversal containing mutation steps will fail at compile time.
///
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ReadBatch {
    /// Queries to execute in order.
    ///
    /// Most users should build this with [`ReadBatch::var_as`] / [`ReadBatch::var_as_if`]
    /// to preserve type-level read-only guarantees.
    #[doc(hidden)]
    pub queries: Vec<BatchEntry>,
    /// Variables to include in final result (empty = all named variables)
    #[doc(hidden)]
    pub returns: Vec<String>,
}

impl ReadBatch {
    /// Create a new empty read batch
    #[doc(hidden)]
    pub fn new() -> Self {
        Self {
            queries: Vec::new(),
            returns: Vec::new(),
        }
    }

    /// Add a read-only query that stores result in a named variable
    ///
    /// The traversal is executed and its result is stored in a variable
    /// that can be referenced by subsequent queries using `NodeRef::var()`.
    ///
    /// **Note**: Only accepts read-only traversals. Mutation traversals will fail at compile time.
    ///
    pub fn var_as<S: TraversalState>(
        mut self,
        name: &str,
        traversal: Traversal<S, ReadOnly>,
    ) -> Self {
        self.queries.push(BatchEntry::Query(NamedQuery {
            name: Some(name.to_string()),
            steps: traversal.into_steps(),
            condition: None,
        }));
        self
    }

    /// Add a conditional read-only query that only executes if the condition is met
    ///
    pub fn var_as_if<S: TraversalState>(
        mut self,
        name: &str,
        condition: BatchCondition,
        traversal: Traversal<S, ReadOnly>,
    ) -> Self {
        self.queries.push(BatchEntry::Query(NamedQuery {
            name: Some(name.to_string()),
            steps: traversal.into_steps(),
            condition: Some(condition),
        }));
        self
    }

    /// Execute the provided body once per object in the named array parameter.
    pub fn for_each_param(mut self, param: &str, body: ReadBatch) -> Self {
        self.queries.push(BatchEntry::ForEach {
            param: param.to_string(),
            body: body.queries,
        });
        self
    }

    /// Specify which variables to return (call at end)
    ///
    /// If not called, all named variables are returned.
    ///
    pub fn returning<I, S>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.returns = vars.into_iter().map(|s| s.into()).collect();
        self
    }
}

/// A batch of write queries for sequential execution in one transaction
///
/// This allows multiple related queries (including mutations) to be executed atomically,
/// with results stored in named variables that can be referenced
/// by subsequent queries and returned as a structured result.
///
/// **Note**: WriteBatch accepts both read-only and mutation traversals.
///
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct WriteBatch {
    /// Queries to execute in order.
    ///
    /// Most users should build this with [`WriteBatch::var_as`] / [`WriteBatch::var_as_if`]
    /// for clearer intent and safer construction.
    #[doc(hidden)]
    pub queries: Vec<BatchEntry>,
    /// Variables to include in final result (empty = all named variables)
    #[doc(hidden)]
    pub returns: Vec<String>,
}

impl WriteBatch {
    /// Create a new empty write batch
    #[doc(hidden)]
    pub fn new() -> Self {
        Self {
            queries: Vec::new(),
            returns: Vec::new(),
        }
    }

    /// Add a query that stores result in a named variable
    ///
    /// The traversal is executed and its result is stored in a variable
    /// that can be referenced by subsequent queries using `NodeRef::var()`.
    ///
    /// Accepts both read-only and mutation traversals.
    ///
    pub fn var_as<S: TraversalState, M: MutationMode>(
        mut self,
        name: &str,
        traversal: Traversal<S, M>,
    ) -> Self {
        self.queries.push(BatchEntry::Query(NamedQuery {
            name: Some(name.to_string()),
            steps: traversal.into_steps(),
            condition: None,
        }));
        self
    }

    /// Add a conditional query that only executes if the condition is met
    ///
    pub fn var_as_if<S: TraversalState, M: MutationMode>(
        mut self,
        name: &str,
        condition: BatchCondition,
        traversal: Traversal<S, M>,
    ) -> Self {
        self.queries.push(BatchEntry::Query(NamedQuery {
            name: Some(name.to_string()),
            steps: traversal.into_steps(),
            condition: Some(condition),
        }));
        self
    }

    /// Execute the provided body once per object in the named array parameter.
    pub fn for_each_param(mut self, param: &str, body: WriteBatch) -> Self {
        self.queries.push(BatchEntry::ForEach {
            param: param.to_string(),
            body: body.queries,
        });
        self
    }

    /// Specify which variables to return (call at end)
    ///
    /// If not called, all named variables are returned.
    ///
    pub fn returning<I, S>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.returns = vars.into_iter().map(|s| s.into()).collect();
        self
    }
}

/// A batch query payload for wire transport or storage
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BatchQuery {
    /// Read-only batch
    Read(ReadBatch),
    /// Write-capable batch
    Write(WriteBatch),
}

/// Errors returned while building or serializing a dynamic query request payload.
#[derive(Debug)]
pub enum DynamicQueryError {
    /// Failed to serialize the request to JSON.
    Serialize(sonic_rs::Error),
    /// Failed to decode serialized JSON bytes as UTF-8.
    Utf8(std::string::FromUtf8Error),
    /// Dynamic query JSON cannot faithfully represent a bytes parameter.
    UnsupportedBytesParameter(String),
    /// A datetime parameter could not be rendered as RFC3339.
    InvalidDateTimeParameter {
        /// Parameter path within the request payload.
        path: String,
        /// Raw UTC epoch milliseconds that failed to render.
        millis: i64,
    },
}

impl DynamicQueryError {
    /// Build an error for a bytes parameter path that cannot be represented safely.
    pub fn unsupported_bytes(path: impl Into<String>) -> Self {
        Self::UnsupportedBytesParameter(path.into())
    }

    /// Build an error for a datetime value that cannot be rendered safely.
    pub fn invalid_datetime(path: impl Into<String>, millis: i64) -> Self {
        Self::InvalidDateTimeParameter {
            path: path.into(),
            millis,
        }
    }
}

impl std::fmt::Display for DynamicQueryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Serialize(err) => write!(f, "json serialization error: {err}"),
            Self::Utf8(err) => write!(f, "utf8 conversion error: {err}"),
            Self::UnsupportedBytesParameter(path) => write!(
                f,
                "parameter '{path}' uses bytes, which the dynamic query JSON route cannot represent"
            ),
            Self::InvalidDateTimeParameter { path, millis } => write!(
                f,
                "parameter '{path}' uses datetime millis '{millis}', which cannot be rendered as RFC3339"
            ),
        }
    }
}

impl std::error::Error for DynamicQueryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Serialize(err) => Some(err),
            Self::Utf8(err) => Some(err),
            Self::UnsupportedBytesParameter(_) => None,
            Self::InvalidDateTimeParameter { .. } => None,
        }
    }
}

impl From<sonic_rs::Error> for DynamicQueryError {
    fn from(value: sonic_rs::Error) -> Self {
        Self::Serialize(value)
    }
}

impl From<std::string::FromUtf8Error> for DynamicQueryError {
    fn from(value: std::string::FromUtf8Error) -> Self {
        Self::Utf8(value)
    }
}

/// Request type accepted by the gateway dynamic query route.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DynamicQueryRequestType {
    /// Read-only dynamic query request.
    Read,
    /// Write-capable dynamic query request.
    Write,
}

/// JSON-compatible parameter value for a dynamic query request payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DynamicQueryValue {
    /// Null JSON value.
    Null,
    /// Boolean JSON value.
    Bool(bool),
    /// 64-bit signed integer JSON value.
    I64(i64),
    /// 64-bit floating-point JSON value.
    F64(f64),
    /// 32-bit floating-point JSON value.
    F32(f32),
    /// UTF-8 string JSON value.
    String(String),
    /// Array JSON value.
    Array(Vec<DynamicQueryValue>),
    /// Object JSON value.
    Object(BTreeMap<String, DynamicQueryValue>),
}

/// Full JSON payload accepted by the gateway dynamic query route.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DynamicQueryRequest {
    /// Whether the inline query should execute as a read or write.
    #[serde(rename = "request_type")]
    pub request_type: DynamicQueryRequestType,
    /// Inline query AST payload.
    pub query: BatchQuery,
    /// Runtime parameters forwarded to the query engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameters: Option<BTreeMap<String, DynamicQueryValue>>,
    /// Optional parameter schema used by runtimes to coerce typed inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameter_types: Option<BTreeMap<String, QueryParamType>>,
}

impl DynamicQueryRequest {
    fn new(request_type: DynamicQueryRequestType, query: BatchQuery) -> Self {
        Self {
            request_type,
            query,
            parameters: None,
            parameter_types: None,
        }
    }

    /// Create a dynamic request payload for a read batch.
    pub fn read(query: ReadBatch) -> Self {
        Self::new(DynamicQueryRequestType::Read, BatchQuery::Read(query))
    }

    /// Create a dynamic request payload for a write batch.
    pub fn write(query: WriteBatch) -> Self {
        Self::new(DynamicQueryRequestType::Write, BatchQuery::Write(query))
    }

    /// Insert a named parameter value into the request payload.
    pub fn insert_parameter_value(&mut self, name: impl Into<String>, value: DynamicQueryValue) {
        self.parameters
            .get_or_insert_with(BTreeMap::new)
            .insert(name.into(), value);
    }

    /// Insert a named parameter type into the request payload.
    pub fn insert_parameter_type(&mut self, name: impl Into<String>, ty: QueryParamType) {
        self.parameter_types
            .get_or_insert_with(BTreeMap::new)
            .insert(name.into(), ty);
    }

    /// Insert a named parameter value and return the updated request.
    pub fn with_parameter_value(
        mut self,
        name: impl Into<String>,
        value: DynamicQueryValue,
    ) -> Self {
        self.insert_parameter_value(name, value);
        self
    }

    /// Insert a named parameter type and return the updated request.
    pub fn with_parameter_type(mut self, name: impl Into<String>, ty: QueryParamType) -> Self {
        self.insert_parameter_type(name, ty);
        self
    }

    /// Serialize the request payload to JSON bytes.
    pub fn to_json_bytes(&self) -> Result<Vec<u8>, DynamicQueryError> {
        Ok(sonic_rs::to_vec(self)?)
    }

    /// Serialize the request payload to a JSON string.
    pub fn to_json_string(&self) -> Result<String, DynamicQueryError> {
        Ok(String::from_utf8(self.to_json_bytes()?)?)
    }
}

/// Create a new read batch - the entry point for read-only multi-query transactions
///
pub fn read_batch() -> ReadBatch {
    ReadBatch::new()
}

/// Create a new write batch - the entry point for write multi-query transactions
///
pub fn write_batch() -> WriteBatch {
    WriteBatch::new()
}

/// Common query-builder imports.
///
/// This module re-exports the APIs most users reach for when building read and
/// write batches.
///
/// Typical usage in application code: `use helix_db::dsl::prelude::*;`
#[allow(missing_docs)]
pub mod prelude {
    pub use crate::{
        g, read_batch, register, sub, write_batch, AggregateFunction, BatchCondition, BatchEntry,
        CompareOp, DateTime, DynamicQueryError, DynamicQueryRequest, DynamicQueryRequestType,
        DynamicQueryValue, EdgeId, EdgeRef, EmitBehavior, Expr, ExprProjection, IndexSpec, NodeId,
        NodeRef, Order, ParamObject, ParamValue, Predicate, Projection, PropertyInput,
        PropertyProjection, PropertyValue, ReadBatch, RepeatConfig, SourcePredicate, StreamBound,
        SubTraversal, Traversal, WriteBatch,
        // query bundle generation
        generate, generate_to_path, GenerateError, QueryBundle, QueryParameter, QueryParamType,
    };
}

/// Helper type alias for property maps
#[doc(hidden)]
pub type PropertyMap = HashMap<String, PropertyValue>;

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use crate::query_generator::{
        deserialize_query_bundle, serialize_query_bundle, GenerateError, QueryBundle,
        QueryParamType, QueryParameter, QUERY_BUNDLE_VERSION,
    };

    use super::*;

    fn query_entry(entry: &BatchEntry) -> &NamedQuery {
        match entry {
            BatchEntry::Query(query) => query,
            other => panic!("expected query entry, got {other:?}"),
        }
    }

    #[test]
    fn query_bundle_roundtrip_with_bincode_fixint() {
        let mut bundle = QueryBundle::default();
        bundle.read_routes.insert(
            "read_users".to_string(),
            read_batch().var_as(
                "count",
                g().n_with_label("User")
                    .where_(Predicate::is_in(
                        "status",
                        vec!["active".to_string(), "pending".to_string()],
                    ))
                    .count(),
            ),
        );
        bundle.read_parameters.insert(
            "read_users".to_string(),
            vec![QueryParameter {
                name: "filters".to_string(),
                ty: QueryParamType::Object,
            }],
        );
        bundle.write_routes.insert(
            "create_user".to_string(),
            write_batch().var_as("created", g().add_n("User", vec![("name", "Alice")])),
        );
        bundle.write_parameters.insert(
            "create_user".to_string(),
            vec![QueryParameter {
                name: "data".to_string(),
                ty: QueryParamType::Array(Box::new(QueryParamType::Object)),
            }],
        );

        let bytes = serialize_query_bundle(&bundle).expect("serialize query bundle");
        let decoded = deserialize_query_bundle(&bytes).expect("deserialize query bundle");

        assert_eq!(decoded.version, QUERY_BUNDLE_VERSION);
        assert_eq!(decoded.read_routes.len(), 1);
        assert_eq!(decoded.write_routes.len(), 1);
        assert!(decoded.read_routes.contains_key("read_users"));
        assert!(decoded.write_routes.contains_key("create_user"));
        assert_eq!(
            decoded.read_parameters.get("read_users"),
            Some(&vec![QueryParameter {
                name: "filters".to_string(),
                ty: QueryParamType::Object,
            }])
        );
        assert_eq!(
            decoded.write_parameters.get("create_user"),
            Some(&vec![QueryParameter {
                name: "data".to_string(),
                ty: QueryParamType::Array(Box::new(QueryParamType::Object)),
            }])
        );
    }

    #[test]
    fn query_bundle_rejects_unsupported_version() {
        let mut bundle = QueryBundle::default();
        bundle.version = QUERY_BUNDLE_VERSION + 1;

        let bytes = serialize_query_bundle(&bundle).expect("serialize query bundle");
        let err = deserialize_query_bundle(&bytes).expect_err("version should fail");

        assert!(matches!(
            err,
            GenerateError::UnsupportedVersion {
                found: _,
                expected: QUERY_BUNDLE_VERSION,
            }
        ));
    }

    #[test]
    fn test_traversal_builder() {
        let t = g()
            .n([1u64, 2, 3])
            .out(Some("FOLLOWS"))
            .has("active", "true")
            .limit(10);

        assert_eq!(t.steps.len(), 4);
        assert!(matches!(&t.steps[0], Step::N(NodeRef::Ids(ids)) if ids == &vec![1, 2, 3]));
        assert!(matches!(&t.steps[1], Step::Out(Some(label)) if label == "FOLLOWS"));
    }

    #[test]
    fn test_variable_steps() {
        let t = g()
            .n([1u64])
            .out(None::<String>)
            .as_("neighbors")
            .out(None::<String>)
            .within("neighbors");

        assert_eq!(t.steps.len(), 5);
        assert!(matches!(&t.steps[2], Step::As(name) if name == "neighbors"));
        assert!(matches!(&t.steps[4], Step::Within(name) if name == "neighbors"));
    }

    #[test]
    fn test_terminal_detection() {
        let t1 = g().n([1u64]).out(None::<String>);
        assert!(!t1.has_terminal());

        let t2 = g().n([1u64]).count();
        assert!(t2.has_terminal());

        let t3 = g().n([1u64]).exists();
        assert!(t3.has_terminal());
    }

    #[test]
    fn test_node_ref_from_impls() {
        let all = NodeRef::all();
        assert!(matches!(all, NodeRef::All));

        let r1: NodeRef = 42u64.into();
        assert!(matches!(r1, NodeRef::Ids(ids) if ids == vec![42]));

        let r2: NodeRef = vec![1u64, 2, 3].into();
        assert!(matches!(r2, NodeRef::Ids(ids) if ids == vec![1, 2, 3]));

        let r3: NodeRef = "my_var".into();
        assert!(matches!(r3, NodeRef::Var(name) if name == "my_var"));

        let r4 = NodeRef::param("node_id");
        assert!(matches!(r4, NodeRef::Param(name) if name == "node_id"));
    }

    #[test]
    fn test_edge_ref_param_constructor() {
        let r = EdgeRef::param("edge_id");
        assert!(matches!(r, EdgeRef::Param(name) if name == "edge_id"));
    }

    #[test]
    fn test_add_n_and_add_e() {
        let t = g()
            .add_n("User", vec![("name", "Alice")])
            .as_("alice")
            .add_n("User", vec![("name", "Bob")])
            .add_e("KNOWS", NodeRef::var("alice"), vec![("since", "2024")]);

        assert_eq!(t.steps.len(), 4);
        assert!(
            matches!(&t.steps[0], Step::AddN { label, properties } if label == "User" && properties.len() == 1)
        );
        assert!(
            matches!(&t.steps[3], Step::AddE { label, to: NodeRef::Var(name), .. } if label == "KNOWS" && name == "alice")
        );
    }

    #[test]
    fn test_predicate_builder() {
        let p1 = Predicate::eq("name", "Alice");
        assert!(
            matches!(p1, Predicate::Eq(prop, PropertyValue::String(val)) if prop == "name" && val == "Alice")
        );

        let p_in = Predicate::is_in("status", vec!["active".to_string(), "pending".to_string()]);
        assert!(matches!(
            p_in,
            Predicate::IsIn(prop, PropertyValue::StringArray(values))
                if prop == "status" && values == vec!["active".to_string(), "pending".to_string()]
        ));

        let p2 = Predicate::and(vec![
            Predicate::eq("status", "active"),
            Predicate::gt("age", "18"),
        ]);
        assert!(matches!(p2, Predicate::And(preds) if preds.len() == 2));
    }

    #[test]
    fn test_edge_traversal() {
        // This should compile: nodes -> edges -> nodes
        let t = g()
            .n([1u64])
            .out_e(Some("FOLLOWS"))
            .edge_has("weight", 1i64)
            .out_n()
            .has_label("User");

        assert_eq!(t.steps.len(), 5);
    }

    #[test]
    fn test_sub_traversal() {
        let t = g()
            .n([1u64])
            .union(vec![sub().out(Some("FOLLOWS")), sub().out(Some("LIKES"))]);

        assert_eq!(t.steps.len(), 2);
        if let Step::Union(subs) = &t.steps[1] {
            assert_eq!(subs.len(), 2);
        } else {
            panic!("Expected Union step");
        }
    }

    #[test]
    fn test_repeat_with_sub_traversal() {
        let t = g()
            .n([1u64])
            .repeat(RepeatConfig::new(sub().out(None::<&str>)).times(3));

        assert_eq!(t.steps.len(), 2);
    }

    #[test]
    fn test_read_batch_construction() {
        let b = read_batch()
            .var_as(
                "user",
                g().n_where(SourcePredicate::eq("username", "alice")),
            )
            .var_as("friends", g().n(NodeRef::var("user")).out(Some("FOLLOWS")))
            .returning(["user", "friends"]);

        assert_eq!(b.queries.len(), 2);
        assert_eq!(b.returns, vec!["user", "friends"]);

        let first = query_entry(&b.queries[0]);
        let second = query_entry(&b.queries[1]);

        // First query: user
        assert_eq!(first.name, Some("user".to_string()));
        assert!(first.condition.is_none());
        assert_eq!(first.steps.len(), 1); // NWhere

        // Second query: friends
        assert_eq!(second.name, Some("friends".to_string()));
        assert_eq!(second.steps.len(), 2); // N + Out
    }

    #[test]
    fn test_read_batch_conditional() {
        let b = read_batch()
            .var_as("user", g().n_where(SourcePredicate::eq("id", 1i64)))
            .var_as_if(
                "posts",
                BatchCondition::VarNotEmpty("user".to_string()),
                g().n(NodeRef::var("user")).out(Some("POSTED")),
            );

        assert_eq!(b.queries.len(), 2);

        // Second query has condition
        assert!(matches!(
            &query_entry(&b.queries[1]).condition,
            Some(BatchCondition::VarNotEmpty(name)) if name == "user"
        ));
    }

    #[test]
    fn test_read_batch_with_terminal() {
        let b = read_batch()
            .var_as("user", g().n([1u64]).value_map(None::<Vec<&str>>))
            .var_as("friend_count", g().n([1u64]).out(Some("FOLLOWS")).count())
            .returning(["user", "friend_count"]);

        assert_eq!(b.queries.len(), 2);

        // First query ends with ValueMap
        assert!(matches!(
            query_entry(&b.queries[0]).steps.last(),
            Some(Step::ValueMap(_))
        ));

        // Second query ends with Count
        assert!(matches!(
            query_entry(&b.queries[1]).steps.last(),
            Some(Step::Count)
        ));
    }

    #[test]
    fn test_write_batch_construction() {
        let b = write_batch()
            .var_as("user", g().add_n("User", vec![("name", "Alice")]))
            .var_as("post", g().add_n("Post", vec![("title", "Hello")]))
            .returning(["user", "post"]);

        assert_eq!(b.queries.len(), 2);
        assert_eq!(b.returns, vec!["user", "post"]);
    }

    #[test]
    fn test_property_input_from_expr() {
        let traversal = g().add_n(
            "User",
            vec![
                ("name", PropertyInput::param("name")),
                ("age", PropertyInput::param("age")),
            ],
        );

        assert!(matches!(
            &traversal.steps[0],
            Step::AddN { properties, .. }
                if matches!(&properties[0].1, PropertyInput::Expr(Expr::Param(name)) if name == "name")
                && matches!(&properties[1].1, PropertyInput::Expr(Expr::Param(name)) if name == "age")
        ));
    }

    #[test]
    fn test_edge_has_accepts_param_input() {
        let traversal = g()
            .e([1u64])
            .edge_has("targetExternalId", PropertyInput::param("targetExternalId"));

        assert!(matches!(
            &traversal.steps[1],
            Step::EdgeHas(property, PropertyInput::Expr(Expr::Param(name)))
                if property == "targetExternalId" && name == "targetExternalId"
        ));
    }

    #[test]
    fn test_write_batch_for_each_param() {
        let body = write_batch()
            .var_as(
                "existing",
                g().n_where(SourcePredicate::eq("$label", "User")),
            )
            .var_as(
                "created",
                g().add_n("User", vec![("name", PropertyInput::param("name"))]),
            );

        let batch = write_batch().for_each_param("data", body);

        assert_eq!(batch.queries.len(), 1);
        assert!(matches!(
            &batch.queries[0],
            BatchEntry::ForEach { param, body }
                if param == "data" && matches!(&body[1], BatchEntry::Query(NamedQuery { name: Some(name), .. }) if name == "created")
        ));
    }

    #[test]
    fn test_property_value_nested_payload_variants() {
        let mut row = BTreeMap::new();
        row.insert("externalId".to_string(), PropertyValue::from("u-1"));
        row.insert("active".to_string(), PropertyValue::from(true));

        let payload = PropertyValue::from(vec![PropertyValue::from(row.clone())]);

        assert!(matches!(payload.as_array(), Some(values) if values.len() == 1));
        assert_eq!(
            payload
                .as_array()
                .and_then(|values| values[0].as_object())
                .and_then(|map| map.get("externalId"))
                .and_then(PropertyValue::as_str),
            Some("u-1")
        );
    }

    #[test]
    fn test_vector_search_steps() {
        let embedding = vec![0.1f32; 4];
        let t = g().vector_search_nodes("Doc", "embedding", embedding.clone(), 5, None);
        assert!(matches!(
            &t.steps[0],
            Step::VectorSearchNodes {
                label,
                property,
                query_vector: PropertyInput::Value(PropertyValue::F32Array(values)),
                k: StreamBound::Literal(k),
                tenant_value,
            }
                if label == "Doc"
                    && property == "embedding"
                    && values == &embedding
                    && *k == 5
                    && tenant_value.is_none()
        ));

        let t2 = g().vector_search_edges("SIMILAR", "embedding", embedding.clone(), 3, None);
        assert!(matches!(
            &t2.steps[0],
            Step::VectorSearchEdges {
                label,
                property,
                query_vector: PropertyInput::Value(PropertyValue::F32Array(values)),
                k: StreamBound::Literal(k),
                tenant_value,
            }
                if label == "SIMILAR"
                    && property == "embedding"
                    && values == &embedding
                    && *k == 3
                    && tenant_value.is_none()
        ));

        let t3 = g().vector_search_nodes(
            "Doc",
            "embedding",
            vec![0.1f32; 4],
            5,
            Some(PropertyValue::from("tenant-a")),
        );
        assert!(matches!(
            &t3.steps[0],
            Step::VectorSearchNodes {
                label,
                property,
                k: StreamBound::Literal(k),
                tenant_value: Some(PropertyInput::Value(PropertyValue::String(value))),
                ..
            } if label == "Doc" && property == "embedding" && *k == 5 && value == "tenant-a"
        ));
    }

    #[test]
    fn test_parameterized_vector_search_steps() {
        let t = g().vector_search_nodes_with(
            "Doc",
            "embedding",
            PropertyInput::param("queryVector"),
            Expr::param("limit"),
            Some(PropertyInput::param("firmId")),
        );

        assert!(matches!(
            &t.steps[0],
            Step::VectorSearchNodes {
                label,
                property,
                query_vector: PropertyInput::Expr(Expr::Param(query_vector)),
                k: StreamBound::Expr(Expr::Param(limit)),
                tenant_value: Some(PropertyInput::Expr(Expr::Param(firm_id))),
            }
                if label == "Doc"
                    && property == "embedding"
                    && query_vector == "queryVector"
                    && limit == "limit"
                && firm_id == "firmId"
        ));
    }

    #[test]
    fn test_text_search_steps() {
        let t = g().text_search_nodes("Doc", "body", "alice search", 5, None);
        assert!(matches!(
            &t.steps[0],
            Step::TextSearchNodes {
                label,
                property,
                query_text: PropertyInput::Value(PropertyValue::String(query)),
                k: StreamBound::Literal(k),
                tenant_value,
            }
                if label == "Doc"
                    && property == "body"
                    && query == "alice search"
                    && *k == 5
                    && tenant_value.is_none()
        ));

        let t2 = g().text_search_edges(
            "REL",
            "body",
            "alice edge",
            3,
            Some(PropertyValue::from("tenant-a")),
        );
        assert!(matches!(
            &t2.steps[0],
            Step::TextSearchEdges {
                label,
                property,
                query_text: PropertyInput::Value(PropertyValue::String(query)),
                k: StreamBound::Literal(k),
                tenant_value: Some(PropertyInput::Value(PropertyValue::String(tenant))),
            }
                if label == "REL"
                    && property == "body"
                    && query == "alice edge"
                    && *k == 3
                    && tenant == "tenant-a"
        ));
    }

    #[test]
    fn test_parameterized_text_search_steps() {
        let t = g().text_search_nodes_with(
            "Doc",
            "body",
            PropertyInput::param("queryText"),
            Expr::param("limit"),
            Some(PropertyInput::param("tenantId")),
        );

        assert!(matches!(
            &t.steps[0],
            Step::TextSearchNodes {
                label,
                property,
                query_text: PropertyInput::Expr(Expr::Param(query_text)),
                k: StreamBound::Expr(Expr::Param(limit)),
                tenant_value: Some(PropertyInput::Expr(Expr::Param(tenant_id))),
            }
                if label == "Doc"
                    && property == "body"
                    && query_text == "queryText"
                    && limit == "limit"
                    && tenant_id == "tenantId"
        ));
    }

    #[test]
    fn test_parameterized_stream_bounds() {
        let range = g()
            .n_with_label("User")
            .range(Expr::param("start"), Expr::param("end"));
        assert!(matches!(
            range.steps.as_slice(),
            [
                Step::NWhere(_),
                Step::RangeBy(StreamBound::Expr(Expr::Param(start)), StreamBound::Expr(Expr::Param(end))),
            ] if start == "start" && end == "end"
        ));

        let ordered = g()
            .n_with_label("User")
            .order_by("age", Order::Desc)
            .limit(Expr::param("limit"))
            .skip(Expr::param("offset"));
        assert!(matches!(
            ordered.steps.as_slice(),
            [
                Step::NWhere(_),
                Step::OrderBy(property, Order::Desc),
                Step::LimitBy(Expr::Param(limit)),
                Step::SkipBy(Expr::Param(offset)),
            ] if property == "age" && limit == "limit" && offset == "offset"
        ));
    }

    #[test]
    fn test_contains_param_predicate() {
        assert!(matches!(
            Predicate::contains_param("location", "city"),
            Predicate::ContainsExpr(property, Expr::Param(param))
                if property == "location" && param == "city"
        ));
    }

    #[test]
    fn test_is_in_param_predicate() {
        assert!(matches!(
            Predicate::is_in_param("location", "cities"),
            Predicate::IsInExpr(property, Expr::Param(param))
                if property == "location" && param == "cities"
        ));
    }

    #[test]
    fn source_predicate_literal_stays_literal() {
        // A literal value keeps the existing PropertyValue variant (JSON unchanged).
        assert!(matches!(
            SourcePredicate::eq("username", "alice"),
            SourcePredicate::Eq(prop, PropertyValue::String(v))
                if prop == "username" && v == "alice"
        ));
        assert!(matches!(
            SourcePredicate::gt("score", 10i64),
            SourcePredicate::Gt(_, PropertyValue::I64(10))
        ));
    }

    #[test]
    fn source_predicate_param_routes_to_expr_variant() {
        // An Expr/parameter routes to the new *Expr variant.
        assert!(matches!(
            SourcePredicate::eq("username", Expr::param("name")),
            SourcePredicate::EqExpr(prop, Expr::Param(p))
                if prop == "username" && p == "name"
        ));
        assert!(matches!(
            SourcePredicate::lte("score", Expr::param("max")),
            SourcePredicate::LteExpr(_, Expr::Param(p)) if p == "max"
        ));
    }

    #[test]
    fn source_predicate_between_dispatch() {
        // Two literals -> Between; any expr bound -> BetweenExpr.
        assert!(matches!(
            SourcePredicate::between("age", 18i64, 65i64),
            SourcePredicate::Between(_, PropertyValue::I64(18), PropertyValue::I64(65))
        ));
        assert!(matches!(
            SourcePredicate::between("age", Expr::param("lo"), 65i64),
            SourcePredicate::BetweenExpr(_, Expr::Param(lo), Expr::Constant(PropertyValue::I64(65)))
                if lo == "lo"
        ));
    }

    #[test]
    fn source_predicate_expr_converts_to_compare() {
        // From<SourcePredicate> for Predicate maps the *Expr variants to Predicate::Compare.
        let pred: Predicate = SourcePredicate::eq("username", Expr::param("name")).into();
        assert!(matches!(
            pred,
            Predicate::Compare { left: Expr::Property(prop), op: CompareOp::Eq, right: Expr::Param(p) }
                if prop == "username" && p == "name"
        ));
    }

    #[test]
    fn test_create_vector_index_steps() {
        let t = g().create_vector_index_nodes("Doc", "embedding", None::<&str>);
        assert!(t.has_terminal());
        assert!(matches!(
            &t.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::NodeVector {
                    label,
                    property,
                    tenant_property,
                },
                if_not_exists,
            } if label == "Doc"
                && property == "embedding"
                && tenant_property.is_none()
                && *if_not_exists
        ));

        let t2 = g().create_vector_index_edges("REL", "embedding", None::<&str>);
        assert!(matches!(
            &t2.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::EdgeVector {
                    label,
                    property,
                    tenant_property,
                },
                if_not_exists,
            } if label == "REL"
                && property == "embedding"
                && tenant_property.is_none()
                && *if_not_exists
        ));

        let t3 = g().create_vector_index_nodes("Doc", "embedding", Some("tenant_id"));
        assert!(matches!(
            &t3.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::NodeVector {
                    tenant_property: Some(tenant_property),
                    ..
                },
                if_not_exists,
            } if tenant_property == "tenant_id" && *if_not_exists
        ));
    }

    #[test]
    fn test_create_text_index_steps() {
        let t = g().create_text_index_nodes("Doc", "body", None::<&str>);
        assert!(matches!(
            &t.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::NodeText {
                    label,
                    property,
                    tenant_property,
                },
                if_not_exists,
            } if label == "Doc"
                && property == "body"
                && tenant_property.is_none()
                && *if_not_exists
        ));

        let t2 = g().create_text_index_edges("REL", "body", Some("tenant_id"));
        assert!(matches!(
            &t2.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::EdgeText {
                    label,
                    property,
                    tenant_property: Some(tenant_property),
                },
                if_not_exists,
            } if label == "REL"
                && property == "body"
                && tenant_property == "tenant_id"
                && *if_not_exists
        ));
    }

    #[test]
    fn test_generic_index_steps() {
        let create = g().create_index_if_not_exists(IndexSpec::node_equality("User", "status"));
        assert!(create.has_terminal());
        assert!(matches!(
            &create.steps[0],
            Step::CreateIndex {
                spec: IndexSpec::NodeEquality {
                    label,
                    property,
                    unique,
                },
                if_not_exists,
            } if label == "User" && property == "status" && !unique && *if_not_exists
        ));

        let drop = g().drop_index(IndexSpec::edge_range("FOLLOWS", "weight"));
        assert!(drop.has_terminal());
        assert!(matches!(
            &drop.steps[0],
            Step::DropIndex {
                spec: IndexSpec::EdgeRange { label, property },
            } if label == "FOLLOWS" && property == "weight"
        ));
    }

    #[test]
    fn test_unique_node_equality_constructor() {
        assert_eq!(
            IndexSpec::node_unique_equality("User", "email"),
            IndexSpec::NodeEquality {
                label: "User".to_string(),
                property: "email".to_string(),
                unique: true,
            }
        );
    }

    #[test]
    fn test_node_equality_deserializes_unique_default_false() {
        let decoded: IndexSpec =
            sonic_rs::from_str(r#"{"NodeEquality":{"label":"User","property":"status"}}"#)
                .expect("deserialize old node equality payload");

        assert_eq!(
            decoded,
            IndexSpec::NodeEquality {
                label: "User".to_string(),
                property: "status".to_string(),
                unique: false,
            }
        );
    }

    #[test]
    fn test_node_unique_equality_serializes_unique_flag() {
        let encoded = sonic_rs::to_string(&IndexSpec::node_unique_equality("User", "status"))
            .expect("serialize unique node equality");

        assert!(encoded.contains(r#""NodeEquality""#));
        assert!(encoded.contains(r#""unique":true"#));
    }
}