interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Anonymous traversal factory module.
//!
//! The `__` module provides factory functions for creating anonymous traversals.
//! Anonymous traversals are unbound traversal fragments that receive their input
//! at execution time when spliced into a parent traversal.
//!
//! # Naming Convention
//!
//! The double underscore `__` is a Gremlin convention that clearly distinguishes
//! anonymous traversal fragments from bound traversals that start from `g.v()` or `g.e()`.
//!
//! # Usage
//!
//! Anonymous traversals are used with steps that accept sub-traversals:
//! - `where_()` - Filter based on sub-traversal existence
//! - `union()` - Execute multiple branches and merge results
//! - `coalesce()` - Try branches until one succeeds
//! - `choose()` - Conditional branching
//! - `repeat()` - Iterative traversal
//!
//! # Example
//!
//! ```ignore
//! use interstellar::traversal::__;
//!
//! // Create an anonymous traversal
//! let knows_bob = __.out_labels(&["knows"]).has_value("name", "Bob");
//!
//! // Use in a parent traversal
//! let people_who_know_bob = g.v()
//!     .has_label("person")
//!     .where_(knows_bob)
//!     .to_list();
//!
//! // Factory functions can also be chained
//! let complex = __.out()
//!     .has_label("person")
//!     .values("name");
//! ```
//!
//! # Return Type
//!
//! All factory functions return `Traversal<Value, Value>`, making them
//! composable with any parent traversal expecting `Value` input.

use crate::traversal::context::ExecutionContext;
use crate::traversal::filter::{
    CoinStep, DedupByKeyStep, DedupByLabelStep, DedupByTraversalStep, DedupStep, FilterStep,
    HasIdStep, HasKeyStep, HasLabelStep, HasNotStep, HasPropValueStep, HasStep, HasValueStep,
    HasWhereStep, LimitStep, RangeStep, SampleStep, SkipStep, TailStep, WherePStep,
};
use crate::traversal::navigation::{
    BothEStep, BothStep, BothVStep, InEStep, InStep, InVStep, OtherVStep, OutEStep, OutStep,
    OutVStep,
};
use crate::traversal::pipeline::Traversal;
use crate::traversal::predicate::Predicate;
use crate::traversal::step::IdentityStep;
use crate::traversal::transform::{
    AsStep, ConstantStep, ElementMapStep, FlatMapStep, IdStep, IndexStep, KeyStep, LabelStep,
    LoopsStep, MapStep, OrderBuilder, PathStep, ProjectBuilder, PropertiesStep, PropertyMapStep,
    SelectStep, UnfoldStep, ValueMapStep, ValueStep, ValuesStep,
};
use crate::value::Value;

// -------------------------------------------------------------------------
// Identity
// -------------------------------------------------------------------------

/// Create an identity traversal that passes input through unchanged.
///
/// # Example
///
/// ```ignore
/// let anon = __.identity();
/// // Equivalent to no-op, but useful as a placeholder or in union branches
/// ```
#[inline]
pub fn identity() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(IdentityStep::new())
}

// -------------------------------------------------------------------------
// Navigation - Vertex to Vertex
// -------------------------------------------------------------------------

/// Traverse to outgoing adjacent vertices.
///
/// # Example
///
/// ```ignore
/// let friends = __.out();
/// ```
#[inline]
pub fn out() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(OutStep::new())
}

/// Traverse to outgoing adjacent vertices via edges with given labels.
///
/// # Example
///
/// ```ignore
/// let friends = __.out_labels(&["knows", "likes"]);
/// ```
pub fn out_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(OutStep::with_labels(labels))
}

/// Traverse to incoming adjacent vertices.
///
/// Note: Named `in_` to avoid conflict with Rust's `in` keyword.
///
/// # Example
///
/// ```ignore
/// let known_by = __.in_();
/// ```
#[inline]
pub fn in_() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(InStep::new())
}

/// Traverse to incoming adjacent vertices via edges with given labels.
///
/// # Example
///
/// ```ignore
/// let known_by = __.in_labels(&["knows"]);
/// ```
pub fn in_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(InStep::with_labels(labels))
}

/// Traverse to adjacent vertices in both directions.
///
/// # Example
///
/// ```ignore
/// let neighbors = __.both();
/// ```
#[inline]
pub fn both() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(BothStep::new())
}

/// Traverse to adjacent vertices in both directions via edges with given labels.
///
/// # Example
///
/// ```ignore
/// let connected = __.both_labels(&["knows"]);
/// ```
pub fn both_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(BothStep::with_labels(labels))
}

// -------------------------------------------------------------------------
// Navigation - Vertex to Edge
// -------------------------------------------------------------------------

/// Traverse to outgoing edges.
///
/// # Example
///
/// ```ignore
/// let edges = __.out_e();
/// ```
#[inline]
pub fn out_e() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(OutEStep::new())
}

/// Traverse to outgoing edges with given labels.
///
/// # Example
///
/// ```ignore
/// let knows_edges = __.out_e_labels(&["knows"]);
/// ```
pub fn out_e_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(OutEStep::with_labels(labels))
}

/// Traverse to incoming edges.
///
/// # Example
///
/// ```ignore
/// let edges = __.in_e();
/// ```
#[inline]
pub fn in_e() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(InEStep::new())
}

/// Traverse to incoming edges with given labels.
///
/// # Example
///
/// ```ignore
/// let known_by_edges = __.in_e_labels(&["knows"]);
/// ```
pub fn in_e_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(InEStep::with_labels(labels))
}

/// Traverse to all incident edges (both directions).
///
/// # Example
///
/// ```ignore
/// let all_edges = __.both_e();
/// ```
#[inline]
pub fn both_e() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(BothEStep::new())
}

/// Traverse to all incident edges with given labels.
///
/// # Example
///
/// ```ignore
/// let knows_edges = __.both_e_labels(&["knows"]);
/// ```
pub fn both_e_labels(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(BothEStep::with_labels(labels))
}

// -------------------------------------------------------------------------
// Navigation - Edge to Vertex
// -------------------------------------------------------------------------

/// Get the source (outgoing) vertex of an edge.
///
/// # Example
///
/// ```ignore
/// let sources = __.out_v();
/// ```
#[inline]
pub fn out_v() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(OutVStep::new())
}

/// Get the target (incoming) vertex of an edge.
///
/// # Example
///
/// ```ignore
/// let targets = __.in_v();
/// ```
#[inline]
pub fn in_v() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(InVStep::new())
}

/// Get both vertices of an edge.
///
/// # Example
///
/// ```ignore
/// let endpoints = __.both_v();
/// ```
#[inline]
pub fn both_v() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(BothVStep::new())
}

/// Get the "other" vertex of an edge.
///
/// When traversing from a vertex to an edge, `other_v()` returns the
/// vertex at the opposite end from where the traverser came from.
/// Requires path tracking to be enabled.
///
/// # Example
///
/// ```ignore
/// let others = __.other_v();
/// ```
#[inline]
pub fn other_v() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(OtherVStep::new())
}

// -------------------------------------------------------------------------
// Filter Steps
// -------------------------------------------------------------------------

/// Filter elements by label.
///
/// # Example
///
/// ```ignore
/// let people = __.has_label("person");
/// ```
pub fn has_label(label: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasLabelStep::single(label))
}

/// Filter elements by any of the given labels.
///
/// # Example
///
/// ```ignore
/// let entities = __.has_label_any(&["person", "company"]);
/// ```
pub fn has_label_any(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(HasLabelStep::new(labels))
}

/// Filter elements by property existence.
///
/// # Example
///
/// ```ignore
/// let with_age = __.has("age");
/// ```
pub fn has(key: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasStep::new(key))
}

/// Filter elements by property absence.
///
/// Keeps only vertices/edges that do NOT have the specified property.
/// Non-element values pass through since they don't have properties.
///
/// # Example
///
/// ```ignore
/// let without_email = __.has_not("email");
/// ```
pub fn has_not(key: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasNotStep::new(key))
}

/// Filter elements by property value equality.
///
/// # Example
///
/// ```ignore
/// let alice = __.has_value("name", "Alice");
/// ```
pub fn has_value(key: impl Into<String>, value: impl Into<Value>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasValueStep::new(key, value))
}

/// Filter elements by ID.
///
/// # Example
///
/// ```ignore
/// let specific = __.has_id(VertexId(1));
/// ```
pub fn has_id(id: impl Into<Value>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasIdStep::from_value(id))
}

/// Filter elements by multiple IDs.
///
/// # Example
///
/// ```ignore
/// let specific = __.has_ids([VertexId(1), VertexId(2)]);
/// ```
pub fn has_ids<I, T>(ids: I) -> Traversal<Value, Value>
where
    I: IntoIterator<Item = T>,
    T: Into<Value>,
{
    Traversal::<Value, Value>::new().add_step(HasIdStep::from_values(
        ids.into_iter().map(Into::into).collect(),
    ))
}

/// Filter elements by property value using a predicate.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::p;
///
/// // Filter to adults
/// let adults = __.has_where("age", p::gte(18));
///
/// // Filter names starting with "A"
/// let a_names = __.has_where("name", p::starting_with("A"));
///
/// // Combine predicates
/// let working_age = __.has_where("age", p::and(p::gte(18), p::lt(65)));
/// ```
pub fn has_where(
    key: impl Into<String>,
    predicate: impl Predicate + 'static,
) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasWhereStep::new(key, predicate))
}

/// Filter by testing the current value against a predicate.
///
/// Unlike `has_where()` which tests a property of vertices/edges, `is_()` tests
/// the traverser's current value directly. This is useful after extracting
/// property values with `values()`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::{__, p};
///
/// // Filter ages greater than 25
/// let gt_25 = __.is_(p::gt(25));
/// let adults = g.v().values("age").append(gt_25).to_list();
///
/// // Filter ages in a range
/// let in_range = __.is_(p::between(20, 40));
/// ```
pub fn is_(predicate: impl Predicate + 'static) -> Traversal<Value, Value> {
    use crate::traversal::filter::IsStep;
    Traversal::<Value, Value>::new().add_step(IsStep::new(predicate))
}

/// Filter by testing the current value for equality.
///
/// This is a convenience method equivalent to `is_(p::eq(value))`.
/// Useful after extracting property values with `values()`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Filter to ages equal to 29
/// let age_29 = __.is_eq(29);
/// let results = g.v().values("age").append(age_29).to_list();
///
/// // Filter to a specific name
/// let alice = __.is_eq("Alice");
/// ```
pub fn is_eq(value: impl Into<Value>) -> Traversal<Value, Value> {
    use crate::traversal::filter::IsStep;
    Traversal::<Value, Value>::new().add_step(IsStep::eq(value))
}

/// Filter elements using a custom predicate.
///
/// # Example
///
/// ```ignore
/// let positive = __.filter(|_ctx, v| matches!(v, Value::Int(n) if *n > 0));
/// ```
pub fn filter<F>(predicate: F) -> Traversal<Value, Value>
where
    F: Fn(&ExecutionContext, &Value) -> bool + Clone + Send + Sync + 'static,
{
    Traversal::<Value, Value>::new().add_step(FilterStep::new(predicate))
}

/// Deduplicate traversers by value.
///
/// # Example
///
/// ```ignore
/// let unique = __.dedup();
/// ```
#[inline]
pub fn dedup() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(DedupStep::new())
}

/// Deduplicate traversers by property value.
///
/// Removes duplicates based on a property value extracted from elements.
/// Only the first occurrence of each unique property value passes through.
///
/// # Example
///
/// ```ignore
/// let unique_ages = __.dedup_by_key("age");
/// ```
#[inline]
pub fn dedup_by_key(key: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(DedupByKeyStep::new(key))
}

/// Deduplicate traversers by element label.
///
/// Removes duplicates based on element label. Only the first occurrence
/// of each unique label passes through.
///
/// # Example
///
/// ```ignore
/// let one_per_label = __.dedup_by_label();
/// ```
#[inline]
pub fn dedup_by_label() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(DedupByLabelStep::new())
}

/// Deduplicate traversers by sub-traversal result.
///
/// Executes the given sub-traversal for each element and uses the first
/// result as the deduplication key.
///
/// # Example
///
/// ```ignore
/// // Dedup by out-degree
/// let unique_outdegree = __.dedup_by(__.out().count());
/// ```
#[inline]
pub fn dedup_by(sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(DedupByTraversalStep::new(sub))
}

/// Limit the number of traversers.
///
/// # Example
///
/// ```ignore
/// let first_ten = __.limit(10);
/// ```
#[inline]
pub fn limit(count: usize) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(LimitStep::new(count))
}

/// Skip the first n traversers.
///
/// # Example
///
/// ```ignore
/// let after_ten = __.skip(10);
/// ```
#[inline]
pub fn skip(count: usize) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(SkipStep::new(count))
}

/// Select traversers within a range.
///
/// # Example
///
/// ```ignore
/// let page = __.range(10, 20);
/// ```
#[inline]
pub fn range(start: usize, end: usize) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(RangeStep::new(start, end))
}

/// Filter to only simple paths (no repeated elements).
///
/// A simple path visits each element at most once.
///
/// # Example
///
/// ```ignore
/// let simple = __.simple_path();
/// ```
#[inline]
pub fn simple_path() -> Traversal<Value, Value> {
    use crate::traversal::filter::SimplePathStep;
    Traversal::<Value, Value>::new().add_step(SimplePathStep::new())
}

/// Filter to only cyclic paths (at least one repeated element).
///
/// A cyclic path contains at least one element that appears more than once.
///
/// # Example
///
/// ```ignore
/// let cyclic = __.cyclic_path();
/// ```
#[inline]
pub fn cyclic_path() -> Traversal<Value, Value> {
    use crate::traversal::filter::CyclicPathStep;
    Traversal::<Value, Value>::new().add_step(CyclicPathStep::new())
}

/// Return only the last element from the traversal.
///
/// This is a **barrier step** - it must collect all elements to determine
/// which is the last. Equivalent to `tail_n(1)`.
///
/// # Example
///
/// ```ignore
/// let last = __.tail();
/// ```
#[inline]
pub fn tail() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(TailStep::last())
}

/// Return only the last n elements from the traversal.
///
/// This is a **barrier step** - it must collect all elements to determine
/// which are the last n. Elements are returned in their original order.
///
/// # Example
///
/// ```ignore
/// let last_three = __.tail_n(3);
/// ```
#[inline]
pub fn tail_n(count: usize) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(TailStep::new(count))
}

/// Probabilistic filter using random coin flip.
///
/// Each traverser has a probability `p` of passing through. Useful for
/// random sampling or probabilistic traversals.
///
/// # Example
///
/// ```ignore
/// // Random sample of approximately 50%
/// let sample = __.coin(0.5);
/// ```
#[inline]
pub fn coin(probability: f64) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(CoinStep::new(probability))
}

/// Randomly sample n elements using reservoir sampling.
///
/// This is a **barrier step** that collects all input elements and returns
/// a random sample of exactly n elements. If the input has fewer than n
/// elements, all elements are returned.
///
/// # Example
///
/// ```ignore
/// // Sample 5 random elements
/// let sampled = __.sample(5);
/// ```
#[inline]
pub fn sample(count: usize) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(SampleStep::new(count))
}

/// Filter property objects by key name.
///
/// This step filters property maps (from `properties()`) to keep only those
/// with a matching "key" field.
///
/// # Example
///
/// ```ignore
/// // Filter to only "name" properties
/// let names = __.has_key("name");
/// ```
#[inline]
pub fn has_key(key: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasKeyStep::new(key))
}

/// Filter property objects by any of the specified key names.
///
/// This step filters property maps (from `properties()`) to keep only those
/// with a "key" field matching any of the specified keys.
///
/// # Example
///
/// ```ignore
/// // Filter to "name" or "age" properties
/// let props = __.has_key_any(["name", "age"]);
/// ```
#[inline]
pub fn has_key_any<I, S>(keys: I) -> Traversal<Value, Value>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    Traversal::<Value, Value>::new().add_step(HasKeyStep::any(keys))
}

/// Filter property objects by value.
///
/// This step filters property maps (from `properties()`) to keep only those
/// with a matching "value" field.
///
/// # Example
///
/// ```ignore
/// // Filter to properties with value "Alice"
/// let alice_props = __.has_prop_value("Alice");
/// ```
#[inline]
pub fn has_prop_value(value: impl Into<Value>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(HasPropValueStep::new(value))
}

/// Filter property objects by any of the specified values.
///
/// This step filters property maps (from `properties()`) to keep only those
/// with a "value" field matching any of the specified values.
///
/// # Example
///
/// ```ignore
/// // Filter to properties with value "Alice" or "Bob"
/// let props = __.has_prop_value_any(["Alice", "Bob"]);
/// ```
#[inline]
pub fn has_prop_value_any<I, V>(values: I) -> Traversal<Value, Value>
where
    I: IntoIterator<Item = V>,
    V: Into<Value>,
{
    Traversal::<Value, Value>::new().add_step(HasPropValueStep::any(values))
}

/// Filter traversers by testing their current value against a predicate.
///
/// This step is the predicate-based variant of `where()`, complementing the
/// traversal-based `where_(traversal)` step.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::p;
///
/// // Filter values greater than 25
/// let adults = __.where_p(p::gt(25));
///
/// // Filter values within a set
/// let selected = __.where_p(p::within(["Alice", "Bob"]));
/// ```
#[inline]
pub fn where_p(
    predicate: impl crate::traversal::predicate::Predicate + 'static,
) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(WherePStep::new(predicate))
}

// -------------------------------------------------------------------------
// Transform Steps
// -------------------------------------------------------------------------

/// Extract property values.
///
/// # Example
///
/// ```ignore
/// let names = __.values("name");
/// ```
pub fn values(key: impl Into<String>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ValuesStep::new(key))
}

/// Extract multiple property values.
///
/// # Example
///
/// ```ignore
/// let data = __.values_multi(["name", "age"]);
/// ```
pub fn values_multi<I, S>(keys: I) -> Traversal<Value, Value>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    Traversal::<Value, Value>::new().add_step(ValuesStep::from_keys(keys))
}

/// Extract all property objects.
///
/// Unlike `values()` which returns just property values, `properties()` returns
/// the full property including its key as a Map with "key" and "value" entries.
///
/// # Example
///
/// ```ignore
/// let props = __.properties();
/// // Each result is Value::Map { "key": "name", "value": "Alice" } etc.
/// ```
pub fn properties() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(PropertiesStep::new())
}

/// Extract specific property objects.
///
/// Unlike `values()` which returns just property values, `properties_keys()` returns
/// the full property including its key as a Map with "key" and "value" entries.
///
/// # Example
///
/// ```ignore
/// let props = __.properties_keys(&["name", "age"]);
/// ```
pub fn properties_keys(keys: &[&str]) -> Traversal<Value, Value> {
    let keys: Vec<String> = keys.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(PropertiesStep::with_keys(keys))
}

/// Get all properties as a map with list-wrapped values.
///
/// Transforms each element into a `Value::Map` containing all properties.
/// Property values are wrapped in `Value::List` for multi-property compatibility.
///
/// # Example
///
/// ```ignore
/// let maps = __.value_map();
/// // Returns: {"name": ["Alice"], "age": [30]}
/// ```
#[inline]
pub fn value_map() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ValueMapStep::new())
}

/// Get specific properties as a map with list-wrapped values.
///
/// Transforms each element into a `Value::Map` containing only the
/// specified properties. Property values are wrapped in `Value::List`.
///
/// # Example
///
/// ```ignore
/// let maps = __.value_map_keys(&["name"]);
/// // Returns: {"name": ["Alice"]}
/// ```
pub fn value_map_keys(keys: &[&str]) -> Traversal<Value, Value> {
    let keys: Vec<String> = keys.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(ValueMapStep::with_keys(keys))
}

/// Get all properties as a map including id and label tokens.
///
/// Returns a `Value::Map` containing all properties plus "id" and "label".
/// Property values are wrapped in `Value::List`, but tokens are not.
///
/// # Example
///
/// ```ignore
/// let maps = __.value_map_with_tokens();
/// // Returns: {"id": 0, "label": "person", "name": ["Alice"], "age": [30]}
/// ```
#[inline]
pub fn value_map_with_tokens() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ValueMapStep::new().with_tokens())
}

/// Get complete element representation as a map.
///
/// Transforms each element into a `Value::Map` with id, label, and all
/// properties. Unlike `value_map()`, property values are NOT wrapped in lists.
/// For edges, also includes "IN" and "OUT" vertex references.
///
/// # Example
///
/// ```ignore
/// let maps = __.element_map();
/// // Vertex: {"id": 0, "label": "person", "name": "Alice", "age": 30}
/// // Edge: {"id": 0, "label": "knows", "IN": {...}, "OUT": {...}, "since": 2020}
/// ```
#[inline]
pub fn element_map() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ElementMapStep::new())
}

/// Get element representation with specific properties.
///
/// Like `element_map()`, but includes only the specified properties
/// along with the id, label, and (for edges) IN/OUT references.
///
/// # Example
///
/// ```ignore
/// let maps = __.element_map_keys(&["name"]);
/// // Returns: {"id": 0, "label": "person", "name": "Alice"}
/// ```
pub fn element_map_keys(keys: &[&str]) -> Traversal<Value, Value> {
    let keys: Vec<String> = keys.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(ElementMapStep::with_keys(keys))
}

/// Get all properties as a map of property objects.
///
/// Transforms each element into a `Value::Map` where keys are property names
/// and values are lists of property objects (maps with "key" and "value" entries).
///
/// # Difference from valueMap
///
/// - `value_map()`: Returns `{name: ["Alice"], age: [30]}` (just values in lists)
/// - `property_map()`: Returns `{name: [{key: "name", value: "Alice"}], age: [{key: "age", value: 30}]}` (property objects in lists)
///
/// # Example
///
/// ```ignore
/// let maps = __.property_map();
/// // Returns: {name: [{key: "name", value: "Alice"}], age: [{key: "age", value: 30}]}
/// ```
#[inline]
pub fn property_map() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(PropertyMapStep::new())
}

/// Get specific properties as a map of property objects.
///
/// Like `property_map()`, but includes only the specified properties.
///
/// # Example
///
/// ```ignore
/// let maps = __.property_map_keys(&["name"]);
/// // Returns: {name: [{key: "name", value: "Alice"}]}
/// ```
pub fn property_map_keys(keys: &[&str]) -> Traversal<Value, Value> {
    let keys: Vec<String> = keys.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(PropertyMapStep::with_keys(keys))
}

/// Unroll collections into individual elements.
///
/// - `Value::List`: Each element becomes a separate traverser
/// - `Value::Map`: Each key-value pair becomes a single-entry map traverser
/// - Non-collection values pass through unchanged
///
/// # Example
///
/// ```ignore
/// // Unfold a list
/// let unfolded = __.unfold();
///
/// // Use in pipeline
/// let entries = g.v().value_map().unfold().to_list();
/// // Each property entry becomes a separate traverser
/// ```
#[inline]
pub fn unfold() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(UnfoldStep::new())
}

/// Calculate the arithmetic mean (average) of numeric values.
///
/// This is a **barrier step** - it collects ALL input values before producing
/// a single output. Only numeric values (`Value::Int` and `Value::Float`) are
/// included in the calculation; non-numeric values are silently ignored.
///
/// # Example
///
/// ```ignore
/// // Use in branch to calculate average
/// let avg = __.mean();
///
/// // As part of a larger traversal
/// let avg_ages = g.v().has_label("person")
///     .values("age")
///     .append(__.mean())
///     .to_list();
/// ```
#[inline]
pub fn mean() -> Traversal<Value, Value> {
    use crate::traversal::transform::MeanStep;
    Traversal::<Value, Value>::new().add_step(MeanStep::new())
}

/// Collect all traversers into a single list value.
///
/// This is a **barrier step** - it collects ALL input before producing
/// a single `Value::List` containing all collected values.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().out().fold()  // Collect all outgoing vertices into a list
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Fold all values into a list
/// let folded = __.fold();
///
/// // Use with project to count and collect
/// let t = g.v().out().fold()
///     .project(&["count", "items"])
///     .by(__.count_local())
///     .by(__.identity())
///     .build();
/// ```
#[inline]
pub fn fold() -> Traversal<Value, Value> {
    use crate::traversal::transform::FoldStep;
    Traversal::<Value, Value>::new().add_step(FoldStep::new())
}

/// Sum all numeric input values.
///
/// This is a **barrier step** - it collects ALL input before producing
/// the sum as a single `Value::Int` or `Value::Float`.
///
/// # Behavior
///
/// - Sums all numeric values (`Value::Int` and `Value::Float`)
/// - Non-numeric values are silently ignored
/// - If all inputs are integers, returns `Value::Int`
/// - If any input is a float, returns `Value::Float`
/// - Empty input returns `Value::Int(0)`
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("age").sum()  // Sum all ages
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Sum numeric values
/// let total = __.sum();
/// ```
#[inline]
pub fn sum() -> Traversal<Value, Value> {
    use crate::traversal::transform::SumStep;
    Traversal::<Value, Value>::new().add_step(SumStep::new())
}

/// Count all input traversers.
///
/// This is a **barrier step** - it collects ALL input before producing
/// a single `Value::Int` containing the count.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().count()  // Count all vertices
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Count traversers
/// let count = __.count();
/// ```
#[inline]
pub fn count() -> Traversal<Value, Value> {
    use crate::traversal::aggregate::CountStep;
    Traversal::<Value, Value>::new().add_step(CountStep::new())
}

/// Find the minimum value across all traversers.
///
/// This is a **barrier step** - it collects ALL input before producing
/// the minimum value.
///
/// # Behavior
///
/// - Compares numeric values (`Value::Int` and `Value::Float`)
/// - Also compares strings lexicographically
/// - Non-comparable values are skipped
/// - Empty input returns `Value::Null`
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("age").min()  // Find minimum age
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Find minimum value
/// let min_val = __.min();
/// ```
#[inline]
pub fn min() -> Traversal<Value, Value> {
    use crate::traversal::aggregate::MinStep;
    Traversal::<Value, Value>::new().add_step(MinStep::new())
}

/// Find the maximum value across all traversers.
///
/// This is a **barrier step** - it collects ALL input before producing
/// the maximum value.
///
/// # Behavior
///
/// - Compares numeric values (`Value::Int` and `Value::Float`)
/// - Also compares strings lexicographically
/// - Non-comparable values are skipped
/// - Empty input returns `Value::Null`
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("age").max()  // Find maximum age
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Find maximum value
/// let max_val = __.max();
/// ```
#[inline]
pub fn max() -> Traversal<Value, Value> {
    use crate::traversal::aggregate::MaxStep;
    Traversal::<Value, Value>::new().add_step(MaxStep::new())
}

/// Count elements within each collection value (local scope).
///
/// Unlike the global `count()` which counts traversers in the stream,
/// `count_local()` counts elements *within* each traverser's collection value.
/// This implements Gremlin's `count(local)` semantics.
///
/// # Behavior
///
/// - `Value::List`: Returns the number of elements in the list
/// - `Value::Map`: Returns the number of entries in the map
/// - `Value::String`: Returns the length of the string
/// - Other values: Returns 1
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().out().fold().count(local)  // Count items in each folded list
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Count elements in a folded list
/// let count = __.count_local();
/// ```
#[inline]
pub fn count_local() -> Traversal<Value, Value> {
    use crate::traversal::transform::CountLocalStep;
    Traversal::<Value, Value>::new().add_step(CountLocalStep::new())
}

/// Sum elements within each collection value (local scope).
///
/// Unlike the global `sum()` which sums across all traversers,
/// `sum_local()` sums elements *within* each traverser's collection value.
/// This implements Gremlin's `sum(local)` semantics.
///
/// # Behavior
///
/// - `Value::List`: Sums all numeric elements in the list
/// - `Value::Int`/`Value::Float`: Returns the value unchanged
/// - Other values: Returns 0
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().values("scores").fold().sum(local)  // Sum scores within each list
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Sum elements in a folded list
/// let total = __.sum_local();
/// ```
#[inline]
pub fn sum_local() -> Traversal<Value, Value> {
    use crate::traversal::transform::SumLocalStep;
    Traversal::<Value, Value>::new().add_step(SumLocalStep::new())
}

/// Extract keys from Map values.
///
/// For each traverser with a Map value, extracts the keys.
/// Single-entry maps return the key directly; multi-entry maps
/// return a List of keys. Non-Map values are filtered out.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().group().by(label).unfold().select(keys)
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Get group keys after grouping
/// let keys = __.select_keys();
/// ```
#[inline]
pub fn select_keys() -> Traversal<Value, Value> {
    use crate::traversal::transform::SelectKeysStep;
    Traversal::<Value, Value>::new().add_step(SelectKeysStep::new())
}

/// Extract values from Map values.
///
/// For each traverser with a Map value, extracts the values.
/// Single-entry maps return the value directly; multi-entry maps
/// return a List of values. Non-Map values are filtered out.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// g.V().group().by(label).unfold().select(values)
/// ```
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Get group values after grouping
/// let values = __.select_values();
/// ```
#[inline]
pub fn select_values() -> Traversal<Value, Value> {
    use crate::traversal::transform::SelectValuesStep;
    Traversal::<Value, Value>::new().add_step(SelectValuesStep::new())
}

/// Sort traversers using a fluent builder.
///
/// This is a **barrier step** - it collects ALL input before producing sorted output.
/// Returns an `OrderBuilder` for configuring sort keys.
///
/// # Example
///
/// ```ignore
/// // Sort by natural order
/// let sorted = __.order().build();
///
/// // Sort by property
/// let sorted = __.order().by_key_desc("age").build();
/// ```
pub fn order() -> OrderBuilder<Value> {
    OrderBuilder::new(vec![])
}

/// Evaluate a mathematical expression.
///
/// The expression can reference the current value using `_` and labeled
/// path values using their label names. Use `by()` to specify which
/// property to extract from labeled elements.
///
/// Uses the `mathexpr` crate for full expression parsing and evaluation,
/// supporting:
/// - Operators: `+`, `-`, `*`, `/`, `%`, `^`
/// - Functions: `sqrt`, `abs`, `sin`, `cos`, `tan`, `log`, `exp`, `pow`, `min`, `max`, etc.
/// - Constants: `pi`, `e`
/// - Parentheses for grouping
///
/// # Examples
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Double current values
/// let doubled = __.math("_ * 2").build();
///
/// // Calculate square root of sum
/// let sqrt = __.math("sqrt(_ ^ 2 + 1)").build();
///
/// // With labeled path values (requires by() for each variable)
/// let diff = __.math("a - b")
///     .by("a", "age")
///     .by("b", "age")
///     .build();
/// ```
#[cfg(feature = "gql")]
pub fn math(expression: &str) -> crate::traversal::transform::MathBuilder<Value> {
    crate::traversal::transform::MathBuilder::new(vec![], expression)
}

/// Create a projection with named keys.
///
/// The `project()` step creates a map with specific named keys. Each key's value
/// is defined by a `by()` modulator, which can extract a property or execute
/// a sub-traversal.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// .project('name', 'age', 'friends')
///   .by('name')
///   .by('age')
///   .by(out('knows').count())
/// ```
///
/// # Example
///
/// ```ignore
/// use __; // Anonymous traversal module
///
/// // Use in a where clause to project data
/// let projection = __.project(&["name", "friend_count"])
///     .by_key("name")
///     .by(__.out("knows").count())
///     .build();
/// ```
///
/// # Arguments
///
/// * `keys` - The keys for the projection map
///
/// # Returns
///
/// A `ProjectBuilder` that requires `by()` clauses to be added for each key.
pub fn project(keys: &[&str]) -> ProjectBuilder<Value> {
    let key_strings: Vec<String> = keys.iter().map(|k| k.to_string()).collect();
    ProjectBuilder::new(vec![], key_strings)
}

/// Group traversers by a key and collect values.
///
/// The `group()` step is a **barrier step** that collects all input traversers,
/// groups them by a key, and produces a single `Value::Map` output.
///
/// # Gremlin Equivalent
///
/// ```groovy
/// .group().by(label)  // Group by label
/// .group().by("age").by("name")  // Group by age, collect names
/// ```
///
/// # Example
///
/// ```ignore
/// use __; // Anonymous traversal module
///
/// // Group by label
/// let groups = __.group().by_label().by_value().build();
///
/// // Group by property
/// let groups = __.group().by_key("age").by_value_key("name").build();
/// ```
///
/// # Returns
///
/// A `GroupBuilder` that allows configuring the grouping key and value collector.
pub fn group() -> crate::traversal::aggregate::GroupBuilder<Value> {
    use crate::traversal::aggregate::GroupBuilder;
    GroupBuilder::new(vec![])
}

/// Count traversers grouped by a key (anonymous traversal factory).
///
/// Creates a `GroupCountBuilder` for use in anonymous traversals.
/// The result is a single `Value::Map` where keys are the grouping keys
/// and values are integer counts.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Count by label
/// let count_step = __.group_count().by_label().build();
///
/// // Count by property
/// let age_count_step = __.group_count().by_key("age").build();
/// ```
///
/// # Returns
///
/// A `GroupCountBuilder` that allows configuring the grouping key.
pub fn group_count() -> crate::traversal::aggregate::GroupCountBuilder<Value> {
    use crate::traversal::aggregate::GroupCountBuilder;
    GroupCountBuilder::new(vec![])
}

/// Extract the element ID.
///
/// # Example
///
/// ```ignore
/// let ids = __.id();
/// ```
#[inline]
pub fn id() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(IdStep::new())
}

/// Extract the element label.
///
/// # Example
///
/// ```ignore
/// let labels = __.label();
/// ```
#[inline]
pub fn label() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(LabelStep::new())
}

/// Extract the key from property map objects.
///
/// # Example
///
/// ```ignore
/// let keys = __.key();
/// ```
#[inline]
pub fn key() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(KeyStep::new())
}

/// Extract the value from property map objects.
///
/// # Example
///
/// ```ignore
/// let values = __.value();
/// ```
#[inline]
pub fn value() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ValueStep::new())
}

/// Extract the current loop depth.
///
/// # Example
///
/// ```ignore
/// // Use in until condition
/// let vertices = g.v()
///     .repeat(__.out())
///     .until(__.loops().is_(p::gte(3)))
///     .to_list();
/// ```
#[inline]
pub fn loops() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(LoopsStep::new())
}

/// Annotate each element with its position index.
///
/// # Example
///
/// ```ignore
/// // Get elements with indices
/// let indexed = g.v()
///     .flat_map(__.index())
///     .to_list();
/// ```
#[inline]
pub fn index() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(IndexStep::new())
}

/// Replace values with a constant.
///
/// # Example
///
/// ```ignore
/// let markers = __.constant("found");
/// ```
pub fn constant(value: impl Into<Value>) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(ConstantStep::new(value))
}

/// Convert the path to a list.
///
/// # Example
///
/// ```ignore
/// let paths = __.path();
/// ```
#[inline]
pub fn path() -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(PathStep::new())
}

/// Transform values using a closure.
///
/// # Example
///
/// ```ignore
/// let doubled = __.map(|_ctx, v| {
///     if let Value::Int(n) = v {
///         Value::Int(n * 2)
///     } else {
///         v.clone()
///     }
/// });
/// ```
pub fn map<F>(f: F) -> Traversal<Value, Value>
where
    F: Fn(&ExecutionContext, &Value) -> Value + Clone + Send + Sync + 'static,
{
    Traversal::<Value, Value>::new().add_step(MapStep::new(f))
}

/// Transform values to multiple values using a closure.
///
/// # Example
///
/// ```ignore
/// let expanded = __.flat_map(|_ctx, v| {
///     if let Value::Int(n) = v {
///         (0..*n).map(Value::Int).collect()
///     } else {
///         vec![]
///     }
/// });
/// ```
pub fn flat_map<F>(f: F) -> Traversal<Value, Value>
where
    F: Fn(&ExecutionContext, &Value) -> Vec<Value> + Clone + Send + Sync + 'static,
{
    Traversal::<Value, Value>::new().add_step(FlatMapStep::new(f))
}

/// Label the current position in the path.
///
/// # Example
///
/// ```ignore
/// let labeled = __.as_("start");
/// ```
pub fn as_(label: &str) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(AsStep::new(label))
}

/// Select multiple labeled values from the path.
///
/// # Example
///
/// ```ignore
/// let selected = __.select(&["a", "b"]);
/// ```
pub fn select(labels: &[&str]) -> Traversal<Value, Value> {
    let labels: Vec<String> = labels.iter().map(|s| s.to_string()).collect();
    Traversal::<Value, Value>::new().add_step(SelectStep::new(labels))
}

/// Select a single labeled value from the path.
///
/// # Example
///
/// ```ignore
/// let selected = __.select_one("start");
/// ```
pub fn select_one(label: &str) -> Traversal<Value, Value> {
    Traversal::<Value, Value>::new().add_step(SelectStep::single(label))
}

// -------------------------------------------------------------------------
// Filter Steps using Anonymous Traversals
// -------------------------------------------------------------------------

/// Filter by sub-traversal existence.
///
/// Emits input traverser only if the sub-traversal produces at least one result.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Keep only vertices that have outgoing edges
/// let with_out = __.where_(__.out());
/// ```
pub fn where_(sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::branch::WhereStep;
    Traversal::<Value, Value>::new().add_step(WhereStep::new(sub))
}

/// Filter by sub-traversal non-existence.
///
/// Emits input traverser only if the sub-traversal produces NO results.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Keep only leaf vertices (no outgoing edges)
/// let leaves = __.not(__.out());
/// ```
pub fn not(sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::branch::NotStep;
    Traversal::<Value, Value>::new().add_step(NotStep::new(sub))
}

/// Filter by multiple sub-traversals (AND logic).
///
/// Emits input traverser only if ALL sub-traversals produce at least one result.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Keep vertices that have both outgoing AND incoming edges
/// let connected = __.and_(vec![__.out(), __.in_()]);
/// ```
pub fn and_(subs: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
    use crate::traversal::branch::AndStep;
    Traversal::<Value, Value>::new().add_step(AndStep::new(subs))
}

/// Filter by multiple sub-traversals (OR logic).
///
/// Emits input traverser if ANY sub-traversal produces at least one result.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Keep vertices that are either "person" OR "software"
/// let entities = __.or_(vec![__.has_label("person"), __.has_label("software")]);
/// ```
pub fn or_(subs: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
    use crate::traversal::branch::OrStep;
    Traversal::<Value, Value>::new().add_step(OrStep::new(subs))
}

// -------------------------------------------------------------------------
// Branch Steps using Anonymous Traversals
// -------------------------------------------------------------------------

/// Execute multiple branches and merge results.
///
/// All branches receive each input traverser; results are merged.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Get neighbors in both directions
/// let neighbors = __.union(vec![__.out(), __.in_()]);
/// ```
pub fn union(branches: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
    use crate::traversal::branch::UnionStep;
    Traversal::<Value, Value>::new().add_step(UnionStep::new(branches))
}

/// Try branches in order, return first non-empty result.
///
/// Short-circuits on first successful branch.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Try to get nickname, fall back to name
/// let names = __.coalesce(vec![__.values("nickname"), __.values("name")]);
/// ```
pub fn coalesce(branches: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
    use crate::traversal::branch::CoalesceStep;
    Traversal::<Value, Value>::new().add_step(CoalesceStep::new(branches))
}

/// Conditional branching.
///
/// Evaluates condition; if it produces results, executes if_true, otherwise if_false.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // If person, get friends; otherwise get all neighbors
/// let results = __.choose(__.has_label("person"), __.out_labels(&["knows"]), __.out());
/// ```
pub fn choose(
    condition: Traversal<Value, Value>,
    if_true: Traversal<Value, Value>,
    if_false: Traversal<Value, Value>,
) -> Traversal<Value, Value> {
    use crate::traversal::branch::ChooseStep;
    Traversal::<Value, Value>::new().add_step(ChooseStep::new(condition, if_true, if_false))
}

/// Optional traversal with fallback to input.
///
/// If sub-traversal produces results, emit those; otherwise emit input.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Try to traverse to friends, keep original if none found
/// let results = __.optional(__.out_labels(&["knows"]));
/// ```
pub fn optional(sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::branch::OptionalStep;
    Traversal::<Value, Value>::new().add_step(OptionalStep::new(sub))
}

/// Execute sub-traversal in isolated scope.
///
/// Aggregations operate independently for each input traverser.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Count neighbors per vertex
/// let counts = __.local(__.out().limit(1));
/// ```
pub fn local(sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::branch::LocalStep;
    Traversal::<Value, Value>::new().add_step(LocalStep::new(sub))
}

// -------------------------------------------------------------------------
// Mutation Steps
// -------------------------------------------------------------------------

/// Create a new vertex with the specified label.
///
/// This is a **spawning step** - it produces a traverser for the newly
/// created vertex, ignoring any input traversers. The actual vertex
/// creation happens when the traversal is executed via `MutationExecutor`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Create a pending vertex (actual creation happens at execution time)
/// let vertex_traversal = __.add_v("person")
///     .property("name", "Alice")
///     .property("age", 30);
/// ```
pub fn add_v(label: impl Into<String>) -> Traversal<Value, Value> {
    use crate::traversal::mutation::AddVStep;
    Traversal::<Value, Value>::new().add_step(AddVStep::new(label))
}

/// Create a new edge with the specified label.
///
/// This step requires both `from` and `to` endpoints to be specified
/// using the builder methods on the returned step. The actual edge
/// creation happens when the traversal is executed via `MutationExecutor`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
/// use interstellar::value::VertexId;
///
/// // Create a pending edge between two vertices
/// let edge_step = __.add_e("knows")
///     .from_vertex(VertexId(1))
///     .to_vertex(VertexId(2))
///     .property("since", 2020);
/// ```
pub fn add_e(label: impl Into<String>) -> crate::traversal::mutation::AddEStep {
    crate::traversal::mutation::AddEStep::new(label)
}

/// Add or update a property on the current element.
///
/// This step modifies the current traverser's element (vertex or edge)
/// by setting a property value. The actual property update happens
/// when the traversal is executed via `MutationExecutor`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Add a property to current element
/// let with_name = __.property("name", "Alice");
/// ```
pub fn property(key: impl Into<String>, value: impl Into<Value>) -> Traversal<Value, Value> {
    use crate::traversal::mutation::PropertyStep;
    Traversal::<Value, Value>::new().add_step(PropertyStep::new(key, value))
}

/// Delete the current element (vertex or edge).
///
/// When a vertex is dropped, all its incident edges are also dropped.
/// The actual deletion happens when the traversal is executed via
/// `MutationExecutor`.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Mark elements for deletion
/// let deleted = __.drop();
/// ```
pub fn drop() -> Traversal<Value, Value> {
    use crate::traversal::mutation::DropStep;
    Traversal::<Value, Value>::new().add_step(DropStep::new())
}

// -------------------------------------------------------------------------
// Branch Steps
// -------------------------------------------------------------------------

/// Create a branch step for anonymous traversals.
///
/// This creates a `Traversal` with a `BranchStep` that evaluates the given
/// branch traversal for each input and routes to option branches based on
/// the resulting key.
///
/// Note: This returns a traversal with a BranchStep that has no options.
/// For full branch/option functionality in anonymous traversals, you typically
/// configure options when using `BoundTraversal::branch()` instead.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Create a basic branch step (options added via bound traversal)
/// let branch_traversal = __.branch(__.label());
/// ```
pub fn branch(branch_traversal: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::branch::BranchStep;
    Traversal::<Value, Value>::new().add_step(BranchStep::new(branch_traversal))
}

// -------------------------------------------------------------------------
// Side Effect Steps
// -------------------------------------------------------------------------

/// Store traverser values in a side-effect collection.
///
/// This is a **lazy step** - values are stored as they pass through the iterator,
/// not all at once. The traverser values pass through unchanged.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Store values as they pass through
/// let stored = __.store("x");
/// ```
pub fn store(key: impl Into<String>) -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::StoreStep;
    Traversal::<Value, Value>::new().add_step(StoreStep::new(key))
}

/// Aggregate all traverser values into a side-effect collection.
///
/// This is a **barrier step** - it collects ALL values before continuing.
/// All input traversers are collected, stored, then re-emitted.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Aggregate all values
/// let aggregated = __.aggregate("all");
/// ```
pub fn aggregate(key: impl Into<String>) -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::AggregateStep;
    Traversal::<Value, Value>::new().add_step(AggregateStep::new(key))
}

/// Retrieve side-effect data by key.
///
/// For a single key, returns the collection as a `Value::List`.
/// Consumes all input traversers before producing the result.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Retrieve stored data
/// let capped = __.cap("x");
/// ```
pub fn cap(key: impl Into<String>) -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::CapStep;
    Traversal::<Value, Value>::new().add_step(CapStep::new(key))
}

/// Execute a sub-traversal for its side effects.
///
/// The sub-traversal is executed for each input traverser, but its output
/// is discarded. The original traverser passes through unchanged.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Execute side effect traversal
/// let with_side_effect = __.side_effect(__.out().store("neighbors"));
/// ```
pub fn side_effect(traversal: Traversal<Value, Value>) -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::SideEffectStep;
    Traversal::<Value, Value>::new().add_step(SideEffectStep::new(traversal))
}

/// Profile the traversal step timing and counts.
///
/// Records the number of traversers and elapsed time in milliseconds
/// to the side-effects under the default key "~profile".
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Profile traversal step
/// let profiled = __.profile();
/// ```
pub fn profile() -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::ProfileStep;
    Traversal::<Value, Value>::new().add_step(ProfileStep::new())
}

/// Profile the traversal with a custom key.
///
/// Like `profile()`, but stores data under the specified key instead
/// of the default "~profile".
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Profile with custom key
/// let profiled = __.profile_as("my_profile");
/// ```
pub fn profile_as(key: impl Into<String>) -> Traversal<Value, Value> {
    use crate::traversal::sideeffect::ProfileStep;
    Traversal::<Value, Value>::new().add_step(ProfileStep::with_key(key))
}

// =============================================================================
// AnonymousTraversal Struct - Enables `__.method()` syntax
// =============================================================================

/// Anonymous traversal factory for Gremlin-style `__.method()` syntax.
///
/// This zero-sized struct provides method-based access to all anonymous
/// traversal functions. Use the static `__` instance for fluent syntax.
///
/// # Example
///
/// ```ignore
/// use interstellar::traversal::__;
///
/// // Gremlin-style syntax
/// let friends = __.out_labels(&["knows"]);
///
/// // Chain anonymous traversals
/// let complex = __.out().has_label("person").values("name");
///
/// // Use in parent traversals
/// let results = g.v()
///     .has_label("person")
///     .where_(__.out_labels(&["knows"]))
///     .to_list();
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct AnonymousTraversal;

/// Static instance for `__.method()` syntax.
///
/// This is the primary way to create anonymous traversals using Gremlin-style syntax.
#[allow(non_upper_case_globals)]
pub static __: AnonymousTraversal = AnonymousTraversal;

impl AnonymousTraversal {
    // -------------------------------------------------------------------------
    // Identity
    // -------------------------------------------------------------------------

    /// Create an identity traversal that passes input through unchanged.
    #[inline]
    pub fn identity(&self) -> Traversal<Value, Value> {
        identity()
    }

    // -------------------------------------------------------------------------
    // Navigation - Vertex to Vertex
    // -------------------------------------------------------------------------

    /// Traverse to outgoing adjacent vertices.
    #[inline]
    pub fn out(&self) -> Traversal<Value, Value> {
        out()
    }

    /// Traverse to outgoing adjacent vertices via edges with given labels.
    #[inline]
    pub fn out_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        out_labels(labels)
    }

    /// Traverse to incoming adjacent vertices.
    #[inline]
    pub fn in_(&self) -> Traversal<Value, Value> {
        in_()
    }

    /// Traverse to incoming adjacent vertices via edges with given labels.
    #[inline]
    pub fn in_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        in_labels(labels)
    }

    /// Traverse to adjacent vertices in both directions.
    #[inline]
    pub fn both(&self) -> Traversal<Value, Value> {
        both()
    }

    /// Traverse to adjacent vertices in both directions via edges with given labels.
    #[inline]
    pub fn both_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        both_labels(labels)
    }

    // -------------------------------------------------------------------------
    // Navigation - Vertex to Edge
    // -------------------------------------------------------------------------

    /// Traverse to outgoing edges.
    #[inline]
    pub fn out_e(&self) -> Traversal<Value, Value> {
        out_e()
    }

    /// Traverse to outgoing edges with given labels.
    #[inline]
    pub fn out_e_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        out_e_labels(labels)
    }

    /// Traverse to incoming edges.
    #[inline]
    pub fn in_e(&self) -> Traversal<Value, Value> {
        in_e()
    }

    /// Traverse to incoming edges with given labels.
    #[inline]
    pub fn in_e_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        in_e_labels(labels)
    }

    /// Traverse to all incident edges (both directions).
    #[inline]
    pub fn both_e(&self) -> Traversal<Value, Value> {
        both_e()
    }

    /// Traverse to all incident edges with given labels.
    #[inline]
    pub fn both_e_labels(&self, labels: &[&str]) -> Traversal<Value, Value> {
        both_e_labels(labels)
    }

    // -------------------------------------------------------------------------
    // Navigation - Edge to Vertex
    // -------------------------------------------------------------------------

    /// Get the source (outgoing) vertex of an edge.
    #[inline]
    pub fn out_v(&self) -> Traversal<Value, Value> {
        out_v()
    }

    /// Get the target (incoming) vertex of an edge.
    #[inline]
    pub fn in_v(&self) -> Traversal<Value, Value> {
        in_v()
    }

    /// Get both vertices of an edge.
    #[inline]
    pub fn both_v(&self) -> Traversal<Value, Value> {
        both_v()
    }

    /// Get the "other" vertex of an edge.
    #[inline]
    pub fn other_v(&self) -> Traversal<Value, Value> {
        other_v()
    }

    // -------------------------------------------------------------------------
    // Filter Steps
    // -------------------------------------------------------------------------

    /// Filter elements by label.
    #[inline]
    pub fn has_label(&self, label: impl Into<String>) -> Traversal<Value, Value> {
        has_label(label)
    }

    /// Filter elements by any of the given labels.
    #[inline]
    pub fn has_label_any(&self, labels: &[&str]) -> Traversal<Value, Value> {
        has_label_any(labels)
    }

    /// Filter elements by property existence.
    #[inline]
    pub fn has(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        has(key)
    }

    /// Filter elements by property absence.
    #[inline]
    pub fn has_not(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        has_not(key)
    }

    /// Filter elements by property value equality.
    #[inline]
    pub fn has_value(
        &self,
        key: impl Into<String>,
        value: impl Into<Value>,
    ) -> Traversal<Value, Value> {
        has_value(key, value)
    }

    /// Filter elements by ID.
    #[inline]
    pub fn has_id(&self, id: impl Into<Value>) -> Traversal<Value, Value> {
        has_id(id)
    }

    /// Filter elements by multiple IDs.
    #[inline]
    pub fn has_ids<I, T>(&self, ids: I) -> Traversal<Value, Value>
    where
        I: IntoIterator<Item = T>,
        T: Into<Value>,
    {
        has_ids(ids)
    }

    /// Filter elements by property value using a predicate.
    #[inline]
    pub fn has_where(
        &self,
        key: impl Into<String>,
        predicate: impl Predicate + 'static,
    ) -> Traversal<Value, Value> {
        has_where(key, predicate)
    }

    /// Filter by testing the current value against a predicate.
    #[inline]
    pub fn is_(&self, predicate: impl Predicate + 'static) -> Traversal<Value, Value> {
        is_(predicate)
    }

    /// Filter by testing the current value for equality.
    #[inline]
    pub fn is_eq(&self, value: impl Into<Value>) -> Traversal<Value, Value> {
        is_eq(value)
    }

    /// Filter elements using a custom predicate.
    #[inline]
    pub fn filter<F>(&self, predicate: F) -> Traversal<Value, Value>
    where
        F: Fn(&ExecutionContext, &Value) -> bool + Clone + Send + Sync + 'static,
    {
        filter(predicate)
    }

    /// Deduplicate traversers by value.
    #[inline]
    pub fn dedup(&self) -> Traversal<Value, Value> {
        dedup()
    }

    /// Deduplicate traversers by property value.
    #[inline]
    pub fn dedup_by_key(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        dedup_by_key(key)
    }

    /// Deduplicate traversers by element label.
    #[inline]
    pub fn dedup_by_label(&self) -> Traversal<Value, Value> {
        dedup_by_label()
    }

    /// Deduplicate traversers by sub-traversal result.
    #[inline]
    pub fn dedup_by(&self, sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
        dedup_by(sub)
    }

    /// Limit the number of traversers.
    #[inline]
    pub fn limit(&self, count: usize) -> Traversal<Value, Value> {
        limit(count)
    }

    /// Skip the first n traversers.
    #[inline]
    pub fn skip(&self, count: usize) -> Traversal<Value, Value> {
        skip(count)
    }

    /// Select traversers within a range.
    #[inline]
    pub fn range(&self, start: usize, end: usize) -> Traversal<Value, Value> {
        range(start, end)
    }

    /// Filter to only simple paths (no repeated elements).
    #[inline]
    pub fn simple_path(&self) -> Traversal<Value, Value> {
        simple_path()
    }

    /// Filter to only cyclic paths (at least one repeated element).
    #[inline]
    pub fn cyclic_path(&self) -> Traversal<Value, Value> {
        cyclic_path()
    }

    /// Return only the last element from the traversal.
    #[inline]
    pub fn tail(&self) -> Traversal<Value, Value> {
        tail()
    }

    /// Return only the last n elements from the traversal.
    #[inline]
    pub fn tail_n(&self, count: usize) -> Traversal<Value, Value> {
        tail_n(count)
    }

    /// Probabilistic filter using random coin flip.
    #[inline]
    pub fn coin(&self, probability: f64) -> Traversal<Value, Value> {
        coin(probability)
    }

    /// Randomly sample n elements using reservoir sampling.
    #[inline]
    pub fn sample(&self, count: usize) -> Traversal<Value, Value> {
        sample(count)
    }

    /// Filter property objects by key name.
    #[inline]
    pub fn has_key(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        has_key(key)
    }

    /// Filter property objects by any of the specified key names.
    #[inline]
    pub fn has_key_any<I, S>(&self, keys: I) -> Traversal<Value, Value>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        has_key_any(keys)
    }

    /// Filter property objects by value.
    #[inline]
    pub fn has_prop_value(&self, value: impl Into<Value>) -> Traversal<Value, Value> {
        has_prop_value(value)
    }

    /// Filter property objects by any of the specified values.
    #[inline]
    pub fn has_prop_value_any<I, V>(&self, values: I) -> Traversal<Value, Value>
    where
        I: IntoIterator<Item = V>,
        V: Into<Value>,
    {
        has_prop_value_any(values)
    }

    /// Filter traversers by testing their current value against a predicate.
    #[inline]
    pub fn where_p(
        &self,
        predicate: impl crate::traversal::predicate::Predicate + 'static,
    ) -> Traversal<Value, Value> {
        where_p(predicate)
    }

    // -------------------------------------------------------------------------
    // Transform Steps
    // -------------------------------------------------------------------------

    /// Extract property values.
    #[inline]
    pub fn values(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        values(key)
    }

    /// Extract multiple property values.
    #[inline]
    pub fn values_multi<I, S>(&self, keys: I) -> Traversal<Value, Value>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        values_multi(keys)
    }

    /// Extract all property objects.
    #[inline]
    pub fn properties(&self) -> Traversal<Value, Value> {
        properties()
    }

    /// Extract specific property objects.
    #[inline]
    pub fn properties_keys(&self, keys: &[&str]) -> Traversal<Value, Value> {
        properties_keys(keys)
    }

    /// Get all properties as a map with list-wrapped values.
    #[inline]
    pub fn value_map(&self) -> Traversal<Value, Value> {
        value_map()
    }

    /// Get specific properties as a map with list-wrapped values.
    #[inline]
    pub fn value_map_keys(&self, keys: &[&str]) -> Traversal<Value, Value> {
        value_map_keys(keys)
    }

    /// Get all properties as a map including id and label tokens.
    #[inline]
    pub fn value_map_with_tokens(&self) -> Traversal<Value, Value> {
        value_map_with_tokens()
    }

    /// Get complete element representation as a map.
    #[inline]
    pub fn element_map(&self) -> Traversal<Value, Value> {
        element_map()
    }

    /// Get element representation with specific properties.
    #[inline]
    pub fn element_map_keys(&self, keys: &[&str]) -> Traversal<Value, Value> {
        element_map_keys(keys)
    }

    /// Get all properties as a map of property objects.
    #[inline]
    pub fn property_map(&self) -> Traversal<Value, Value> {
        property_map()
    }

    /// Get specific properties as a map of property objects.
    #[inline]
    pub fn property_map_keys(&self, keys: &[&str]) -> Traversal<Value, Value> {
        property_map_keys(keys)
    }

    /// Unroll collections into individual elements.
    #[inline]
    pub fn unfold(&self) -> Traversal<Value, Value> {
        unfold()
    }

    /// Calculate the arithmetic mean (average) of numeric values.
    #[inline]
    pub fn mean(&self) -> Traversal<Value, Value> {
        mean()
    }

    /// Collect all traversers into a single list value.
    #[inline]
    pub fn fold(&self) -> Traversal<Value, Value> {
        fold()
    }

    /// Sum all numeric input values.
    #[inline]
    pub fn sum(&self) -> Traversal<Value, Value> {
        sum()
    }

    /// Count all input traversers.
    #[inline]
    pub fn count(&self) -> Traversal<Value, Value> {
        count()
    }

    /// Find the minimum value across all traversers.
    #[inline]
    pub fn min(&self) -> Traversal<Value, Value> {
        min()
    }

    /// Find the maximum value across all traversers.
    #[inline]
    pub fn max(&self) -> Traversal<Value, Value> {
        max()
    }

    /// Count elements within each collection value (local scope).
    #[inline]
    pub fn count_local(&self) -> Traversal<Value, Value> {
        count_local()
    }

    /// Sum elements within each collection value (local scope).
    #[inline]
    pub fn sum_local(&self) -> Traversal<Value, Value> {
        sum_local()
    }

    /// Extract keys from Map values.
    #[inline]
    pub fn select_keys(&self) -> Traversal<Value, Value> {
        select_keys()
    }

    /// Extract values from Map values.
    #[inline]
    pub fn select_values(&self) -> Traversal<Value, Value> {
        select_values()
    }

    /// Sort traversers using a fluent builder.
    #[inline]
    pub fn order(&self) -> OrderBuilder<Value> {
        order()
    }

    /// Evaluate a mathematical expression.
    #[cfg(feature = "gql")]
    #[inline]
    pub fn math(&self, expression: &str) -> crate::traversal::transform::MathBuilder<Value> {
        math(expression)
    }

    /// Create a projection with named keys.
    #[inline]
    pub fn project(&self, keys: &[&str]) -> ProjectBuilder<Value> {
        project(keys)
    }

    /// Group traversers by a key and collect values.
    #[inline]
    pub fn group(&self) -> crate::traversal::aggregate::GroupBuilder<Value> {
        group()
    }

    /// Count traversers grouped by a key.
    #[inline]
    pub fn group_count(&self) -> crate::traversal::aggregate::GroupCountBuilder<Value> {
        group_count()
    }

    /// Extract the element ID.
    #[inline]
    pub fn id(&self) -> Traversal<Value, Value> {
        id()
    }

    /// Extract the element label.
    #[inline]
    pub fn label(&self) -> Traversal<Value, Value> {
        label()
    }

    /// Extract the key from property map objects.
    #[inline]
    pub fn key(&self) -> Traversal<Value, Value> {
        key()
    }

    /// Extract the value from property map objects.
    #[inline]
    pub fn value(&self) -> Traversal<Value, Value> {
        value()
    }

    /// Extract the current loop depth.
    #[inline]
    pub fn loops(&self) -> Traversal<Value, Value> {
        loops()
    }

    /// Annotate each element with its position index.
    #[inline]
    pub fn index(&self) -> Traversal<Value, Value> {
        index()
    }

    /// Replace values with a constant.
    #[inline]
    pub fn constant(&self, value: impl Into<Value>) -> Traversal<Value, Value> {
        constant(value)
    }

    /// Convert the path to a list.
    #[inline]
    pub fn path(&self) -> Traversal<Value, Value> {
        path()
    }

    /// Transform values using a closure.
    #[inline]
    pub fn map<F>(&self, f: F) -> Traversal<Value, Value>
    where
        F: Fn(&ExecutionContext, &Value) -> Value + Clone + Send + Sync + 'static,
    {
        map(f)
    }

    /// Transform values to multiple values using a closure.
    #[inline]
    pub fn flat_map<F>(&self, f: F) -> Traversal<Value, Value>
    where
        F: Fn(&ExecutionContext, &Value) -> Vec<Value> + Clone + Send + Sync + 'static,
    {
        flat_map(f)
    }

    /// Label the current position in the path.
    #[inline]
    pub fn as_(&self, label: &str) -> Traversal<Value, Value> {
        as_(label)
    }

    /// Select multiple labeled values from the path.
    #[inline]
    pub fn select(&self, labels: &[&str]) -> Traversal<Value, Value> {
        select(labels)
    }

    /// Select a single labeled value from the path.
    #[inline]
    pub fn select_one(&self, label: &str) -> Traversal<Value, Value> {
        select_one(label)
    }

    // -------------------------------------------------------------------------
    // Filter Steps using Anonymous Traversals
    // -------------------------------------------------------------------------

    /// Filter by sub-traversal existence.
    #[inline]
    pub fn where_(&self, sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
        where_(sub)
    }

    /// Filter by sub-traversal non-existence.
    #[inline]
    pub fn not(&self, sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
        not(sub)
    }

    /// Filter by multiple sub-traversals (AND logic).
    #[inline]
    pub fn and_(&self, subs: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
        and_(subs)
    }

    /// Filter by multiple sub-traversals (OR logic).
    #[inline]
    pub fn or_(&self, subs: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
        or_(subs)
    }

    // -------------------------------------------------------------------------
    // Branch Steps using Anonymous Traversals
    // -------------------------------------------------------------------------

    /// Execute multiple branches and merge results.
    #[inline]
    pub fn union(&self, branches: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
        union(branches)
    }

    /// Try branches in order, return first non-empty result.
    #[inline]
    pub fn coalesce(&self, branches: Vec<Traversal<Value, Value>>) -> Traversal<Value, Value> {
        coalesce(branches)
    }

    /// Conditional branching.
    #[inline]
    pub fn choose(
        &self,
        condition: Traversal<Value, Value>,
        if_true: Traversal<Value, Value>,
        if_false: Traversal<Value, Value>,
    ) -> Traversal<Value, Value> {
        choose(condition, if_true, if_false)
    }

    /// Optional traversal with fallback to input.
    #[inline]
    pub fn optional(&self, sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
        optional(sub)
    }

    /// Execute sub-traversal in isolated scope.
    #[inline]
    pub fn local(&self, sub: Traversal<Value, Value>) -> Traversal<Value, Value> {
        local(sub)
    }

    // -------------------------------------------------------------------------
    // Mutation Steps
    // -------------------------------------------------------------------------

    /// Create a new vertex with the specified label.
    #[inline]
    pub fn add_v(&self, label: impl Into<String>) -> Traversal<Value, Value> {
        add_v(label)
    }

    /// Create a new edge with the specified label.
    #[inline]
    pub fn add_e(&self, label: impl Into<String>) -> crate::traversal::mutation::AddEStep {
        add_e(label)
    }

    /// Add or update a property on the current element.
    #[inline]
    pub fn property(
        &self,
        key: impl Into<String>,
        value: impl Into<Value>,
    ) -> Traversal<Value, Value> {
        property(key, value)
    }

    /// Delete the current element (vertex or edge).
    #[inline]
    pub fn drop(&self) -> Traversal<Value, Value> {
        drop()
    }

    // -------------------------------------------------------------------------
    // Branch Steps
    // -------------------------------------------------------------------------

    /// Create a branch step for anonymous traversals.
    #[inline]
    pub fn branch(&self, branch_traversal: Traversal<Value, Value>) -> Traversal<Value, Value> {
        branch(branch_traversal)
    }

    // -------------------------------------------------------------------------
    // Side Effect Steps
    // -------------------------------------------------------------------------

    /// Store traverser values in a side-effect collection.
    #[inline]
    pub fn store(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        store(key)
    }

    /// Aggregate all traverser values into a side-effect collection.
    #[inline]
    pub fn aggregate(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        aggregate(key)
    }

    /// Retrieve side-effect data by key.
    #[inline]
    pub fn cap(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        cap(key)
    }

    /// Execute a sub-traversal for its side effects.
    #[inline]
    pub fn side_effect(&self, traversal: Traversal<Value, Value>) -> Traversal<Value, Value> {
        side_effect(traversal)
    }

    /// Profile the traversal step timing and counts.
    #[inline]
    pub fn profile(&self) -> Traversal<Value, Value> {
        profile()
    }

    /// Profile the traversal with a custom key.
    #[inline]
    pub fn profile_as(&self, key: impl Into<String>) -> Traversal<Value, Value> {
        profile_as(key)
    }
}