lance-graph 0.5.4

Graph query engine for Lance datasets with Cypher support
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! Cypher query parser
//!
//! This module provides parsing functionality for Cypher queries using nom parser combinators.
//! It supports a subset of Cypher syntax focused on graph pattern matching and property access.

use crate::ast::*;
use crate::error::{GraphError, Result};
use nom::{
    branch::alt,
    bytes::complete::{tag, tag_no_case, take_while1},
    character::complete::{char, digit0, digit1, multispace0, multispace1, one_of},
    combinator::{map, map_res, opt, peek, recognize},
    multi::{many0, separated_list0, separated_list1},
    sequence::{delimited, pair, preceded, tuple},
    IResult,
};
use std::collections::HashMap;

/// Parse a complete Cypher query
pub fn parse_cypher_query(input: &str) -> Result<CypherQuery> {
    let (remaining, query) = cypher_query(input).map_err(|e| GraphError::ParseError {
        message: format!("Failed to parse Cypher query: {}", e),
        position: 0,
        location: snafu::Location::new(file!(), line!(), column!()),
    })?;

    if !remaining.trim().is_empty() {
        return Err(GraphError::ParseError {
            message: format!("Unexpected input after query: {}", remaining),
            position: input.len() - remaining.len(),
            location: snafu::Location::new(file!(), line!(), column!()),
        });
    }

    Ok(query)
}

// Top-level parser for a complete Cypher query
fn cypher_query(input: &str) -> IResult<&str, CypherQuery> {
    let (input, _) = multispace0(input)?;
    let (input, reading_clauses) = many0(reading_clause)(input)?;
    let (input, pre_with_where) = opt(where_clause)(input)?;

    // Optional WITH clause with optional post-WITH MATCH and WHERE
    let (input, with_result) = opt(with_clause)(input)?;
    // Only try to parse post-WITH clauses if we have a WITH clause
    let (input, post_with_reading_clauses, post_with_where) = match with_result {
        Some(_) => {
            let (input, readings) = many0(reading_clause)(input)?;
            let (input, where_cl) = opt(where_clause)(input)?;
            (input, readings, where_cl)
        }
        None => (input, vec![], None),
    };

    let (input, return_clause) = return_clause(input)?;
    let (input, order_by) = opt(order_by_clause)(input)?;
    let (input, (skip, limit)) = pagination_clauses(input)?;
    let (input, _) = multispace0(input)?;

    Ok((
        input,
        CypherQuery {
            reading_clauses,
            where_clause: pre_with_where,
            with_clause: with_result,
            post_with_reading_clauses,
            post_with_where_clause: post_with_where,
            return_clause,
            limit,
            order_by,
            skip,
        },
    ))
}

// Parse a reading clause (MATCH or UNWIND)
fn reading_clause(input: &str) -> IResult<&str, ReadingClause> {
    alt((
        map(match_clause, ReadingClause::Match),
        map(unwind_clause, ReadingClause::Unwind),
    ))(input)
}

// Parse a MATCH clause
fn match_clause(input: &str) -> IResult<&str, MatchClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("MATCH")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, patterns) = separated_list0(comma_ws, graph_pattern)(input)?;

    Ok((input, MatchClause { patterns }))
}

// Parse an UNWIND clause
fn unwind_clause(input: &str) -> IResult<&str, UnwindClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("UNWIND")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, expression) = value_expression(input)?;
    let (input, _) = multispace1(input)?;
    let (input, _) = tag_no_case("AS")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, alias) = identifier(input)?;

    Ok((
        input,
        UnwindClause {
            expression,
            alias: alias.to_string(),
        },
    ))
}

// Parse a graph pattern (node or path)
fn graph_pattern(input: &str) -> IResult<&str, GraphPattern> {
    alt((
        map(path_pattern, GraphPattern::Path),
        map(node_pattern, GraphPattern::Node),
    ))(input)
}

// Parse a path pattern (only if there are segments)
fn path_pattern(input: &str) -> IResult<&str, PathPattern> {
    let (input, start_node) = node_pattern(input)?;
    let (input, segments) = many0(path_segment)(input)?;

    // Only succeed if we actually have path segments
    if segments.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        input,
        PathPattern {
            start_node,
            segments,
        },
    ))
}

// Parse a path segment (relationship + node)
fn path_segment(input: &str) -> IResult<&str, PathSegment> {
    let (input, relationship) = relationship_pattern(input)?;
    let (input, end_node) = node_pattern(input)?;

    Ok((
        input,
        PathSegment {
            relationship,
            end_node,
        },
    ))
}

// Parse a node pattern: (variable:Label {prop: value})
fn node_pattern(input: &str) -> IResult<&str, NodePattern> {
    let (input, _) = multispace0(input)?;
    let (input, _) = char('(')(input)?;
    let (input, _) = multispace0(input)?;
    let (input, variable) = opt(identifier)(input)?;
    let (input, labels) = many0(preceded(char(':'), identifier))(input)?;
    let (input, _) = multispace0(input)?;
    let (input, properties) = opt(property_map)(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(')')(input)?;

    Ok((
        input,
        NodePattern {
            variable: variable.map(|s| s.to_string()),
            labels: labels.into_iter().map(|s| s.to_string()).collect(),
            properties: properties.unwrap_or_default(),
        },
    ))
}

// Parse a relationship pattern: -[variable:TYPE {prop: value}]->
fn relationship_pattern(input: &str) -> IResult<&str, RelationshipPattern> {
    let (input, _) = multispace0(input)?;

    // Parse direction and bracket content
    let (input, (direction, content)) = alt((
        // Outgoing: -[...]->
        map(
            tuple((
                char('-'),
                delimited(char('['), relationship_content, char(']')),
                tag("->"),
            )),
            |(_, content, _)| (RelationshipDirection::Outgoing, content),
        ),
        // Incoming: <-[...]-
        map(
            tuple((
                tag("<-"),
                delimited(char('['), relationship_content, char(']')),
                char('-'),
            )),
            |(_, content, _)| (RelationshipDirection::Incoming, content),
        ),
        // Undirected: -[...]-
        map(
            tuple((
                char('-'),
                delimited(char('['), relationship_content, char(']')),
                char('-'),
            )),
            |(_, content, _)| (RelationshipDirection::Undirected, content),
        ),
    ))(input)?;

    let (variable, types, properties, length) = content;

    Ok((
        input,
        RelationshipPattern {
            variable: variable.map(|s| s.to_string()),
            types: types.into_iter().map(|s| s.to_string()).collect(),
            direction,
            properties: properties.unwrap_or_default(),
            length,
        },
    ))
}

// Type alias for complex relationship content return type
type RelationshipContentResult<'a> = (
    Option<&'a str>,
    Vec<&'a str>,
    Option<HashMap<String, PropertyValue>>,
    Option<LengthRange>,
);

// Parse relationship content inside brackets
fn relationship_content(input: &str) -> IResult<&str, RelationshipContentResult<'_>> {
    let (input, _) = multispace0(input)?;
    let (input, variable) = opt(identifier)(input)?;
    let (input, types) = many0(preceded(char(':'), identifier))(input)?;
    let (input, _) = multispace0(input)?;
    let (input, length) = opt(length_range)(input)?;
    let (input, _) = multispace0(input)?;
    let (input, properties) = opt(property_map)(input)?;
    let (input, _) = multispace0(input)?;

    Ok((input, (variable, types, properties, length)))
}

// Parse a property map: {key: value, key2: value2}
fn property_map(input: &str) -> IResult<&str, HashMap<String, PropertyValue>> {
    let (input, _) = multispace0(input)?;
    let (input, _) = char('{')(input)?;
    let (input, _) = multispace0(input)?;
    let (input, pairs) = separated_list0(comma_ws, property_pair)(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char('}')(input)?;

    Ok((input, pairs.into_iter().collect()))
}

// Parse a property key-value pair
fn property_pair(input: &str) -> IResult<&str, (String, PropertyValue)> {
    let (input, _) = multispace0(input)?;
    let (input, key) = identifier(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(':')(input)?;
    let (input, _) = multispace0(input)?;
    let (input, value) = property_value(input)?;

    Ok((input, (key.to_string(), value)))
}

// Parse a property value
fn property_value(input: &str) -> IResult<&str, PropertyValue> {
    alt((
        map(string_literal, PropertyValue::String),
        map(float_literal, PropertyValue::Float), // Try float BEFORE integer (more specific)
        map(integer_literal, PropertyValue::Integer),
        map(boolean_literal, PropertyValue::Boolean),
        map(tag("null"), |_| PropertyValue::Null),
        map(parameter, PropertyValue::Parameter),
    ))(input)
}

// Parse a WHERE clause
fn where_clause(input: &str) -> IResult<&str, WhereClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("WHERE")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, expression) = boolean_expression(input)?;

    Ok((input, WhereClause { expression }))
}

// Parse a boolean expression with OR precedence
fn boolean_expression(input: &str) -> IResult<&str, BooleanExpression> {
    boolean_or_expression(input)
}

fn boolean_or_expression(input: &str) -> IResult<&str, BooleanExpression> {
    let (input, first) = boolean_and_expression(input)?;
    let (input, rest) = many0(preceded(
        tuple((multispace0, tag_no_case("OR"), multispace1)),
        boolean_and_expression,
    ))(input)?;
    let expr = rest.into_iter().fold(first, |acc, item| {
        BooleanExpression::Or(Box::new(acc), Box::new(item))
    });
    Ok((input, expr))
}

fn boolean_and_expression(input: &str) -> IResult<&str, BooleanExpression> {
    let (input, first) = boolean_not_expression(input)?;
    let (input, rest) = many0(preceded(
        tuple((multispace0, tag_no_case("AND"), multispace1)),
        boolean_not_expression,
    ))(input)?;
    let expr = rest.into_iter().fold(first, |acc, item| {
        BooleanExpression::And(Box::new(acc), Box::new(item))
    });
    Ok((input, expr))
}

fn boolean_not_expression(input: &str) -> IResult<&str, BooleanExpression> {
    let (input, _) = multispace0(input)?;
    alt((
        map(
            preceded(
                tuple((tag_no_case("NOT"), multispace1)),
                boolean_not_expression,
            ),
            |expr| BooleanExpression::Not(Box::new(expr)),
        ),
        boolean_primary_expression,
    ))(input)
}

fn boolean_primary_expression(input: &str) -> IResult<&str, BooleanExpression> {
    let (input, _) = multispace0(input)?;
    alt((
        map(
            delimited(
                tuple((char('('), multispace0)),
                boolean_expression,
                tuple((multispace0, char(')'))),
            ),
            |expr| expr,
        ),
        comparison_expression,
    ))(input)
}

fn comparison_expression(input: &str) -> IResult<&str, BooleanExpression> {
    let (input, _) = multispace0(input)?;
    let (input, left) = value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let left_clone = left.clone();

    if let Ok((input_after_in, (_, _, list))) =
        tuple((tag_no_case("IN"), multispace0, value_expression_list))(input)
    {
        return Ok((
            input_after_in,
            BooleanExpression::In {
                expression: left,
                list,
            },
        ));
    }
    // Match LIKE pattern
    if let Ok((input_after_like, (_, _, pattern))) =
        tuple((tag_no_case("LIKE"), multispace0, string_literal))(input)
    {
        return Ok((
            input_after_like,
            BooleanExpression::Like {
                expression: left,
                pattern,
            },
        ));
    }
    // Match ILIKE pattern (case-insensitive LIKE)
    if let Ok((input_after_ilike, (_, _, pattern))) =
        tuple((tag_no_case("ILIKE"), multispace0, string_literal))(input)
    {
        return Ok((
            input_after_ilike,
            BooleanExpression::ILike {
                expression: left,
                pattern,
            },
        ));
    }
    // Match CONTAINS substring
    if let Ok((input_after_contains, (_, _, substring))) =
        tuple((tag_no_case("CONTAINS"), multispace0, string_literal))(input)
    {
        return Ok((
            input_after_contains,
            BooleanExpression::Contains {
                expression: left,
                substring,
            },
        ));
    }
    // Match STARTS WITH prefix (note: multi-word operator)
    if let Ok((input_after_starts, (_, _, _, _, prefix))) = tuple((
        tag_no_case("STARTS"),
        multispace1,
        tag_no_case("WITH"),
        multispace0,
        string_literal,
    ))(input)
    {
        return Ok((
            input_after_starts,
            BooleanExpression::StartsWith {
                expression: left,
                prefix,
            },
        ));
    }
    // Match ENDS WITH suffix (note: multi-word operator)
    if let Ok((input_after_ends, (_, _, _, _, suffix))) = tuple((
        tag_no_case("ENDS"),
        multispace1,
        tag_no_case("WITH"),
        multispace0,
        string_literal,
    ))(input)
    {
        return Ok((
            input_after_ends,
            BooleanExpression::EndsWith {
                expression: left,
                suffix,
            },
        ));
    }
    // Match is null
    if let Ok((rest, ())) = is_null_comparison(input) {
        return Ok((rest, BooleanExpression::IsNull(left_clone)));
    }
    // Match is not null
    if let Ok((rest, ())) = is_not_null_comparison(input) {
        return Ok((rest, BooleanExpression::IsNotNull(left_clone)));
    }

    let (input, operator) = comparison_operator(input)?;
    let (input, _) = multispace0(input)?;
    let (input, right) = value_expression(input)?;

    Ok((
        input,
        BooleanExpression::Comparison {
            left: left_clone,
            operator,
            right,
        },
    ))
}

// Parse a comparison operator
fn comparison_operator(input: &str) -> IResult<&str, ComparisonOperator> {
    alt((
        map(tag("="), |_| ComparisonOperator::Equal),
        map(tag("<>"), |_| ComparisonOperator::NotEqual),
        map(tag("!="), |_| ComparisonOperator::NotEqual),
        map(tag("<="), |_| ComparisonOperator::LessThanOrEqual),
        map(tag(">="), |_| ComparisonOperator::GreaterThanOrEqual),
        map(tag("<"), |_| ComparisonOperator::LessThan),
        map(tag(">"), |_| ComparisonOperator::GreaterThan),
    ))(input)
}

// Parse a basic value expression (without vector functions to avoid circular dependency)
fn basic_value_expression(input: &str) -> IResult<&str, ValueExpression> {
    alt((
        parse_vector_literal, // Try vector literal first [0.1, 0.2]
        parse_parameter,      // Try $parameter
        function_call,        // Regular function calls
        map(property_value, ValueExpression::Literal), // Try literals BEFORE property references
        map(property_reference, ValueExpression::Property),
        map(identifier, |id| ValueExpression::Variable(id.to_string())),
    ))(input)
}

// Parse a value expression
// Optimization: Use peek to avoid expensive backtracking for non-vector queries
fn value_expression(input: &str) -> IResult<&str, ValueExpression> {
    // Peek at first identifier to dispatch to correct parser
    // This eliminates failed parser attempts for every non-vector expression
    if let Ok((_, first_ident)) = peek(identifier)(input) {
        let ident_lower = first_ident.to_lowercase();

        match ident_lower.as_str() {
            "vector_distance" => return parse_vector_distance(input),
            "vector_similarity" => return parse_vector_similarity(input),
            _ => {} // Not a vector function, continue to basic expressions
        }
    }

    // Fast path for common expressions
    basic_value_expression(input)
}

// Parse distance metric: cosine, l2, dot
fn parse_distance_metric(input: &str) -> IResult<&str, DistanceMetric> {
    alt((
        map(tag_no_case("cosine"), |_| DistanceMetric::Cosine),
        map(tag_no_case("l2"), |_| DistanceMetric::L2),
        map(tag_no_case("dot"), |_| DistanceMetric::Dot),
    ))(input)
}

// Parse vector_distance(expr, expr, metric)
fn parse_vector_distance(input: &str) -> IResult<&str, ValueExpression> {
    let (input, _) = tag_no_case("vector_distance")(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char('(')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse left expression - use basic_value_expression to avoid circular dependency
    let (input, left) = basic_value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(',')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse right expression - use basic_value_expression to avoid circular dependency
    let (input, right) = basic_value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(',')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse metric
    let (input, metric) = parse_distance_metric(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(')')(input)?;

    Ok((
        input,
        ValueExpression::VectorDistance {
            left: Box::new(left),
            right: Box::new(right),
            metric,
        },
    ))
}

// Parse vector_similarity(expr, expr, metric)
fn parse_vector_similarity(input: &str) -> IResult<&str, ValueExpression> {
    let (input, _) = tag_no_case("vector_similarity")(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char('(')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse left expression - use basic_value_expression to avoid circular dependency
    let (input, left) = basic_value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(',')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse right expression - use basic_value_expression to avoid circular dependency
    let (input, right) = basic_value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(',')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse metric
    let (input, metric) = parse_distance_metric(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(')')(input)?;

    Ok((
        input,
        ValueExpression::VectorSimilarity {
            left: Box::new(left),
            right: Box::new(right),
            metric,
        },
    ))
}

// Parse parameter reference: $name
fn parse_parameter(input: &str) -> IResult<&str, ValueExpression> {
    let (input, name) = parameter(input)?;
    Ok((input, ValueExpression::Parameter(name)))
}

// Parse a function call: function_name(args)
fn function_call(input: &str) -> IResult<&str, ValueExpression> {
    let (input, name) = identifier(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char('(')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse optional DISTINCT keyword
    let (input, distinct) = opt(tag_no_case("DISTINCT"))(input)?;
    let distinct = distinct.is_some();
    let (input, _) = if distinct {
        multispace1(input)?
    } else {
        (input, "")
    };

    // Handle COUNT(*) special case - only allow * for COUNT function
    if let Ok((input_after_star, _)) = char::<_, nom::error::Error<&str>>('*')(input) {
        // Validate that this is COUNT function
        if name.to_lowercase() == "count" {
            let (input, _) = multispace0(input_after_star)?;
            let (input, _) = char(')')(input)?;
            return Ok((
                input,
                ValueExpression::AggregateFunction {
                    name: name.to_string(),
                    args: vec![ValueExpression::Variable("*".to_string())],
                    distinct,
                },
            ));
        } else {
            // Not COUNT - fail parsing to try regular argument parsing
            // This will naturally fail since * is not a valid value_expression
        }
    }

    // Parse regular function arguments
    let (input, args) = separated_list0(
        tuple((multispace0, char(','), multispace0)),
        value_expression,
    )(input)?;
    let (input, _) = multispace0(input)?;
    let (input, _) = char(')')(input)?;

    // Route based on function type
    use crate::ast::{classify_function, FunctionType};
    match classify_function(name) {
        FunctionType::Aggregate => Ok((
            input,
            ValueExpression::AggregateFunction {
                name: name.to_string(),
                args,
                distinct,
            },
        )),
        FunctionType::Scalar => {
            // Validate: reject DISTINCT on scalar functions at parse time
            if distinct {
                return Err(nom::Err::Failure(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            Ok((
                input,
                ValueExpression::ScalarFunction {
                    name: name.to_string(),
                    args,
                },
            ))
        }
        FunctionType::Unknown => {
            // Default to ScalarFunction for unknown functions
            // They'll be handled as NULL in expression conversion
            if distinct {
                return Err(nom::Err::Failure(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            Ok((
                input,
                ValueExpression::ScalarFunction {
                    name: name.to_string(),
                    args,
                },
            ))
        }
    }
}

fn value_expression_list(input: &str) -> IResult<&str, Vec<ValueExpression>> {
    delimited(
        tuple((char('['), multispace0)),
        separated_list1(
            tuple((multispace0, char(','), multispace0)),
            value_expression,
        ),
        tuple((multispace0, char(']'))),
    )(input)
}

// Parse a float32 literal for vectors
fn float32_literal(input: &str) -> IResult<&str, f32> {
    map_res(
        recognize(tuple((
            opt(char('-')),
            alt((
                // Scientific notation: 1e-3, 2.5e2
                recognize(tuple((
                    digit1,
                    opt(tuple((char('.'), digit0))),
                    one_of("eE"),
                    opt(one_of("+-")),
                    digit1,
                ))),
                // Regular float: 1.23 or integer: 123
                recognize(tuple((digit1, opt(tuple((char('.'), digit0)))))),
            )),
        ))),
        |s: &str| s.parse::<f32>(),
    )(input)
}

// Parse vector literal: [0.1, 0.2, 0.3]
fn parse_vector_literal(input: &str) -> IResult<&str, ValueExpression> {
    let (input, _) = char('[')(input)?;
    let (input, _) = multispace0(input)?;

    let (input, values) = separated_list1(
        tuple((multispace0, char(','), multispace0)),
        float32_literal,
    )(input)?;

    let (input, _) = multispace0(input)?;
    let (input, _) = char(']')(input)?;

    Ok((input, ValueExpression::VectorLiteral(values)))
}

// Parse a property reference: variable.property
fn property_reference(input: &str) -> IResult<&str, PropertyRef> {
    let (input, variable) = identifier(input)?;
    let (input, _) = char('.')(input)?;
    let (input, property) = identifier(input)?;

    Ok((
        input,
        PropertyRef {
            variable: variable.to_string(),
            property: property.to_string(),
        },
    ))
}

// Parse a WITH clause (intermediate projection/aggregation)
fn with_clause(input: &str) -> IResult<&str, WithClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("WITH")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, items) = separated_list0(comma_ws, return_item)(input)?;
    let (input, order_by) = opt(order_by_clause)(input)?;
    let (input, limit) = opt(limit_clause)(input)?;

    Ok((
        input,
        WithClause {
            items,
            order_by,
            limit,
        },
    ))
}

// Parse a RETURN clause
fn return_clause(input: &str) -> IResult<&str, ReturnClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("RETURN")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, distinct) = opt(tag_no_case("DISTINCT"))(input)?;
    let (input, _) = if distinct.is_some() {
        multispace1(input)?
    } else {
        (input, "")
    };
    let (input, items) = separated_list0(comma_ws, return_item)(input)?;

    Ok((
        input,
        ReturnClause {
            distinct: distinct.is_some(),
            items,
        },
    ))
}

// Parse a return item
fn return_item(input: &str) -> IResult<&str, ReturnItem> {
    let (input, expression) = value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, alias) = opt(preceded(
        tuple((tag_no_case("AS"), multispace1)),
        identifier,
    ))(input)?;

    Ok((
        input,
        ReturnItem {
            expression,
            alias: alias.map(|s| s.to_string()),
        },
    ))
}

// Match IS NULL in WHERE clause
fn is_null_comparison(input: &str) -> IResult<&str, ()> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("IS")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, _) = tag_no_case("NULL")(input)?;
    let (input, _) = multispace0(input)?;

    Ok((input, ()))
}

// Match IS NOT NULL in WHERE clause
fn is_not_null_comparison(input: &str) -> IResult<&str, ()> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("IS")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, _) = tag_no_case("NOT")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, _) = tag_no_case("NULL")(input)?;
    let (input, _) = multispace0(input)?;

    Ok((input, ()))
}

// Parse an ORDER BY clause
fn order_by_clause(input: &str) -> IResult<&str, OrderByClause> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("ORDER")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, _) = tag_no_case("BY")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, items) = separated_list0(comma_ws, order_by_item)(input)?;

    Ok((input, OrderByClause { items }))
}

// Parse an order by item
fn order_by_item(input: &str) -> IResult<&str, OrderByItem> {
    let (input, expression) = value_expression(input)?;
    let (input, _) = multispace0(input)?;
    let (input, direction) = opt(alt((
        map(tag_no_case("ASC"), |_| SortDirection::Ascending),
        map(tag_no_case("DESC"), |_| SortDirection::Descending),
    )))(input)?;

    Ok((
        input,
        OrderByItem {
            expression,
            direction: direction.unwrap_or(SortDirection::Ascending),
        },
    ))
}

// Parse a LIMIT clause
fn limit_clause(input: &str) -> IResult<&str, u64> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("LIMIT")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, limit) = integer_literal(input)?;

    Ok((input, limit as u64))
}

// Parse a SKIP clause
fn skip_clause(input: &str) -> IResult<&str, u64> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag_no_case("SKIP")(input)?;
    let (input, _) = multispace1(input)?;
    let (input, skip) = integer_literal(input)?;

    Ok((input, skip as u64))
}

// Parse pagination clauses (SKIP and LIMIT)
fn pagination_clauses(input: &str) -> IResult<&str, (Option<u64>, Option<u64>)> {
    let (mut remaining, _) = multispace0(input)?;
    let mut skip: Option<u64> = None;
    let mut limit: Option<u64> = None;

    loop {
        let before = remaining;

        if skip.is_none() {
            if let Ok((i, s)) = skip_clause(remaining) {
                skip = Some(s);
                remaining = i;
                continue;
            }
        }

        if limit.is_none() {
            if let Ok((i, l)) = limit_clause(remaining) {
                limit = Some(l);
                remaining = i;
                continue;
            }
        }

        if before == remaining {
            break;
        }
    }

    Ok((remaining, (skip, limit)))
}

// Helper parsers

// Parse an identifier
fn identifier(input: &str) -> IResult<&str, &str> {
    take_while1(|c: char| c.is_alphanumeric() || c == '_')(input)
}

// Parse a string literal
fn string_literal(input: &str) -> IResult<&str, String> {
    alt((double_quoted_string, single_quoted_string))(input)
}

fn double_quoted_string(input: &str) -> IResult<&str, String> {
    let (input, _) = char('"')(input)?;
    let (input, content) = take_while1(|c| c != '"')(input)?;
    let (input, _) = char('"')(input)?;
    Ok((input, content.to_string()))
}

fn single_quoted_string(input: &str) -> IResult<&str, String> {
    let (input, _) = char('\'')(input)?;
    let (input, content) = take_while1(|c| c != '\'')(input)?;
    let (input, _) = char('\'')(input)?;
    Ok((input, content.to_string()))
}

// Parse an integer literal
fn integer_literal(input: &str) -> IResult<&str, i64> {
    let (input, digits) = recognize(pair(
        opt(char('-')),
        take_while1(|c: char| c.is_ascii_digit()),
    ))(input)?;

    Ok((input, digits.parse().unwrap()))
}

// Parse a float literal
fn float_literal(input: &str) -> IResult<&str, f64> {
    let (input, number) = recognize(tuple((
        opt(char('-')),
        take_while1(|c: char| c.is_ascii_digit()),
        char('.'),
        take_while1(|c: char| c.is_ascii_digit()),
    )))(input)?;

    Ok((input, number.parse().unwrap()))
}

// Parse a boolean literal
fn boolean_literal(input: &str) -> IResult<&str, bool> {
    alt((
        map(tag_no_case("true"), |_| true),
        map(tag_no_case("false"), |_| false),
    ))(input)
}

// Parse a parameter reference
fn parameter(input: &str) -> IResult<&str, String> {
    // Only support $param syntax
    map(preceded(char('$'), identifier), |s| s.to_string())(input)
}

// Parse comma with optional whitespace
fn comma_ws(input: &str) -> IResult<&str, ()> {
    let (input, _) = multispace0(input)?;
    let (input, _) = char(',')(input)?;
    let (input, _) = multispace0(input)?;
    Ok((input, ()))
}

// Parse variable-length path syntax: *1..2, *..3, *2.., *
fn length_range(input: &str) -> IResult<&str, LengthRange> {
    let (input, _) = char('*')(input)?;
    let (input, _) = multispace0(input)?;

    // Parse different length patterns
    alt((
        // *min..max (e.g., *1..3)
        map(
            tuple((
                nom::character::complete::u32,
                tag(".."),
                nom::character::complete::u32,
            )),
            |(min, _, max)| LengthRange {
                min: Some(min),
                max: Some(max),
            },
        ),
        // *..max (e.g., *..3)
        map(preceded(tag(".."), nom::character::complete::u32), |max| {
            LengthRange {
                min: None,
                max: Some(max),
            }
        }),
        // *min.. (e.g., *2..)
        map(
            tuple((nom::character::complete::u32, tag(".."))),
            |(min, _)| LengthRange {
                min: Some(min),
                max: None,
            },
        ),
        // *min (e.g., *2)
        map(nom::character::complete::u32, |min| LengthRange {
            min: Some(min),
            max: Some(min),
        }),
        // * (unlimited)
        map(multispace0, |_| LengthRange {
            min: None,
            max: None,
        }),
    ))(input)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{BooleanExpression, ComparisonOperator, PropertyValue, ValueExpression};

    #[test]
    fn test_parse_simple_node_query() {
        let query = "MATCH (n:Person) RETURN n.name";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.reading_clauses.len(), 1);
        assert_eq!(result.return_clause.items.len(), 1);
    }

    #[test]
    fn test_parse_node_with_properties() {
        let query = r#"MATCH (n:Person {name: "John", age: 30}) RETURN n"#;
        let result = parse_cypher_query(query).unwrap();

        if let ReadingClause::Match(match_clause) = &result.reading_clauses[0] {
            if let GraphPattern::Node(node) = &match_clause.patterns[0] {
                assert_eq!(node.labels, vec!["Person"]);
                assert_eq!(node.properties.len(), 2);
            } else {
                panic!("Expected node pattern");
            }
        } else {
            panic!("Expected match clause");
        }
    }

    #[test]
    fn test_parse_simple_relationship_query() {
        let query = "MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN a.name, b.name";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.reading_clauses.len(), 1);
        assert_eq!(result.return_clause.items.len(), 2);

        if let ReadingClause::Match(match_clause) = &result.reading_clauses[0] {
            if let GraphPattern::Path(path) = &match_clause.patterns[0] {
                assert_eq!(path.segments.len(), 1);
                assert_eq!(path.segments[0].relationship.types, vec!["KNOWS"]);
            } else {
                panic!("Expected path pattern");
            }
        } else {
            panic!("Expected match clause");
        }
    }

    #[test]
    fn test_parse_variable_length_path() {
        let query = "MATCH (a:Person)-[:FRIEND_OF*1..2]-(b:Person) RETURN a.name, b.name";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.reading_clauses.len(), 1);

        if let ReadingClause::Match(match_clause) = &result.reading_clauses[0] {
            if let GraphPattern::Path(path) = &match_clause.patterns[0] {
                assert_eq!(path.segments.len(), 1);
                assert_eq!(path.segments[0].relationship.types, vec!["FRIEND_OF"]);

                let length = path.segments[0].relationship.length.as_ref().unwrap();
                assert_eq!(length.min, Some(1));
                assert_eq!(length.max, Some(2));
            } else {
                panic!("Expected path pattern");
            }
        } else {
            panic!("Expected match clause");
        }
    }

    #[test]
    fn test_parse_query_with_where_clause() {
        let query = "MATCH (n:Person) WHERE n.age > 30 RETURN n.name";
        let result = parse_cypher_query(query).unwrap();

        assert!(result.where_clause.is_some());
    }

    #[test]
    fn test_parse_query_with_single_quoted_literal() {
        let query = "MATCH (n:Person) WHERE n.name = 'Alice' RETURN n.name";
        let result = parse_cypher_query(query).unwrap();

        assert!(result.where_clause.is_some());
    }

    #[test]
    fn test_parse_query_with_and_conditions() {
        let query = "MATCH (src:Entity)-[rel:RELATIONSHIP]->(dst:Entity) WHERE rel.relationship_type = 'WORKS_ON' AND dst.name_lower = 'presto' RETURN src.name, src.entity_id";
        let result = parse_cypher_query(query).unwrap();

        let where_clause = result.where_clause.expect("Expected WHERE clause");
        match where_clause.expression {
            BooleanExpression::And(left, right) => {
                match *left {
                    BooleanExpression::Comparison {
                        left: ValueExpression::Property(ref prop),
                        operator,
                        right: ValueExpression::Literal(PropertyValue::String(ref value)),
                    } => {
                        assert_eq!(prop.variable, "rel");
                        assert_eq!(prop.property, "relationship_type");
                        assert_eq!(operator, ComparisonOperator::Equal);
                        assert_eq!(value, "WORKS_ON");
                    }
                    _ => panic!("Expected comparison for relationship_type filter"),
                }

                match *right {
                    BooleanExpression::Comparison {
                        left: ValueExpression::Property(ref prop),
                        operator,
                        right: ValueExpression::Literal(PropertyValue::String(ref value)),
                    } => {
                        assert_eq!(prop.variable, "dst");
                        assert_eq!(prop.property, "name_lower");
                        assert_eq!(operator, ComparisonOperator::Equal);
                        assert_eq!(value, "presto");
                    }
                    _ => panic!("Expected comparison for destination name filter"),
                }
            }
            other => panic!("Expected AND expression, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_query_with_in_clause() {
        let query = "MATCH (src:Entity)-[rel:RELATIONSHIP]->(dst:Entity) WHERE rel.relationship_type IN ['WORKS_FOR', 'PART_OF'] RETURN src.name";
        let result = parse_cypher_query(query).unwrap();

        let where_clause = result.where_clause.expect("Expected WHERE clause");
        match where_clause.expression {
            BooleanExpression::In { expression, list } => {
                match expression {
                    ValueExpression::Property(prop_ref) => {
                        assert_eq!(prop_ref.variable, "rel");
                        assert_eq!(prop_ref.property, "relationship_type");
                    }
                    _ => panic!("Expected property reference in IN expression"),
                }
                assert_eq!(list.len(), 2);
                match &list[0] {
                    ValueExpression::Literal(PropertyValue::String(val)) => {
                        assert_eq!(val, "WORKS_FOR");
                    }
                    _ => panic!("Expected first list item to be a string literal"),
                }
                match &list[1] {
                    ValueExpression::Literal(PropertyValue::String(val)) => {
                        assert_eq!(val, "PART_OF");
                    }
                    _ => panic!("Expected second list item to be a string literal"),
                }
            }
            other => panic!("Expected IN expression, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_query_with_is_null() {
        let query = "MATCH (n:Person) WHERE n.age IS NULL RETURN n.name";
        let result = parse_cypher_query(query).unwrap();

        let where_clause = result.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::IsNull(expr) => match expr {
                ValueExpression::Property(prop_ref) => {
                    assert_eq!(prop_ref.variable, "n");
                    assert_eq!(prop_ref.property, "age");
                }
                _ => panic!("Expected property reference in IS NULL expression"),
            },
            other => panic!("Expected IS NULL expression, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_query_with_is_not_null() {
        let query = "MATCH (n:Person) WHERE n.age IS NOT NULL RETURN n.name";
        let result = parse_cypher_query(query).unwrap();

        let where_clause = result.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::IsNotNull(expr) => match expr {
                ValueExpression::Property(prop_ref) => {
                    assert_eq!(prop_ref.variable, "n");
                    assert_eq!(prop_ref.property, "age");
                }
                _ => panic!("Expected property reference in IS NOT NULL expression"),
            },
            other => panic!("Expected IS NOT NULL expression, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_query_with_limit() {
        let query = "MATCH (n:Person) RETURN n.name LIMIT 10";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.limit, Some(10));
    }

    #[test]
    fn test_parse_query_with_skip() {
        let query = "MATCH (n:Person) RETURN n.name SKIP 5";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.skip, Some(5));
        assert_eq!(result.limit, None);
    }

    #[test]
    fn test_parse_query_with_skip_and_limit() {
        let query = "MATCH (n:Person) RETURN n.name SKIP 5 LIMIT 10";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.skip, Some(5));
        assert_eq!(result.limit, Some(10));
    }

    #[test]
    fn test_parse_query_with_skip_and_order_by() {
        let query = "MATCH (n:Person) RETURN n.name ORDER BY n.age SKIP 5";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.skip, Some(5));
        assert!(result.order_by.is_some());
    }

    #[test]
    fn test_parse_query_with_skip_order_by_and_limit() {
        let query = "MATCH (n:Person) RETURN n.name ORDER BY n.age SKIP 5 LIMIT 10";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.skip, Some(5));
        assert_eq!(result.limit, Some(10));
        assert!(result.order_by.is_some());
    }

    #[test]
    fn test_parse_count_star() {
        let query = "MATCH (n:Person) RETURN count(*) AS total";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.return_clause.items.len(), 1);
        let item = &result.return_clause.items[0];
        assert_eq!(item.alias, Some("total".to_string()));

        match &item.expression {
            ValueExpression::AggregateFunction { name, args, .. } => {
                assert_eq!(name, "count");
                assert_eq!(args.len(), 1);
                match &args[0] {
                    ValueExpression::Variable(v) => assert_eq!(v, "*"),
                    _ => panic!("Expected Variable(*) in count(*)"),
                }
            }
            _ => panic!("Expected AggregateFunction expression"),
        }
    }

    #[test]
    fn test_parse_count_property() {
        let query = "MATCH (n:Person) RETURN count(n.age)";
        let result = parse_cypher_query(query).unwrap();

        assert_eq!(result.return_clause.items.len(), 1);
        let item = &result.return_clause.items[0];

        match &item.expression {
            ValueExpression::AggregateFunction { name, args, .. } => {
                assert_eq!(name, "count");
                assert_eq!(args.len(), 1);
                match &args[0] {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "age");
                    }
                    _ => panic!("Expected Property in count(n.age)"),
                }
            }
            _ => panic!("Expected AggregateFunction expression"),
        }
    }

    #[test]
    fn test_parse_non_count_function_rejects_star() {
        // FOO(*) should fail to parse since * is only allowed for COUNT
        let query = "MATCH (n:Person) RETURN foo(*)";
        let result = parse_cypher_query(query);
        assert!(result.is_err(), "foo(*) should not parse successfully");
    }

    #[test]
    fn test_parse_count_with_multiple_args() {
        // COUNT with multiple arguments parses successfully
        // but will be rejected during semantic validation
        let query = "MATCH (n:Person) RETURN count(n.age, n.name)";
        let result = parse_cypher_query(query);
        assert!(
            result.is_ok(),
            "Parser should accept multiple args (validation happens in semantic phase)"
        );

        // Verify the AST structure
        let ast = result.unwrap();
        match &ast.return_clause.items[0].expression {
            ValueExpression::AggregateFunction { name, args, .. } => {
                assert_eq!(name, "count");
                assert_eq!(args.len(), 2);
            }
            _ => panic!("Expected AggregateFunction expression"),
        }
    }

    #[test]
    fn test_parser_rejects_distinct_on_scalar() {
        // Parser should reject DISTINCT on scalar functions at parse time
        let query = "RETURN toLower(DISTINCT p.name)";
        let result = parse_cypher_query(query);
        assert!(
            result.is_err(),
            "Parser should reject DISTINCT on scalar functions"
        );

        let query2 = "RETURN upper(DISTINCT p.name)";
        let result2 = parse_cypher_query(query2);
        assert!(
            result2.is_err(),
            "Parser should reject DISTINCT on scalar functions"
        );
    }

    #[test]
    fn test_parse_like_pattern() {
        let query = "MATCH (n:Person) WHERE n.name LIKE 'A%' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "LIKE pattern should parse successfully");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Like {
                expression,
                pattern,
            } => {
                match expression {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "name");
                    }
                    _ => panic!("Expected property expression"),
                }
                assert_eq!(pattern, "A%");
            }
            _ => panic!("Expected LIKE expression"),
        }
    }

    #[test]
    fn test_parse_like_with_double_quotes() {
        let query = r#"MATCH (n:Person) WHERE n.email LIKE "%@example.com" RETURN n.email"#;
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "LIKE with double quotes should parse");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Like { pattern, .. } => {
                assert_eq!(pattern, "%@example.com");
            }
            _ => panic!("Expected LIKE expression"),
        }
    }

    #[test]
    fn test_parse_like_in_complex_where() {
        let query = "MATCH (n:Person) WHERE n.age > 20 AND n.name LIKE 'J%' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "LIKE in complex WHERE should parse");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::And(left, right) => {
                // Left should be age > 20
                match *left {
                    BooleanExpression::Comparison { .. } => {}
                    _ => panic!("Expected comparison on left"),
                }
                // Right should be LIKE
                match *right {
                    BooleanExpression::Like { pattern, .. } => {
                        assert_eq!(pattern, "J%");
                    }
                    _ => panic!("Expected LIKE expression on right"),
                }
            }
            _ => panic!("Expected AND expression"),
        }
    }

    #[test]
    fn test_parse_contains() {
        let query = "MATCH (n:Person) WHERE n.name CONTAINS 'Jo' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        let query = result.unwrap();
        assert!(query.where_clause.is_some());

        match &query.where_clause.unwrap().expression {
            BooleanExpression::Contains {
                expression,
                substring,
            } => {
                assert_eq!(substring, "Jo");
                match expression {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "name");
                    }
                    _ => panic!("Expected property reference"),
                }
            }
            _ => panic!("Expected CONTAINS expression"),
        }
    }

    #[test]
    fn test_parse_starts_with() {
        let query = "MATCH (n:Person) WHERE n.name STARTS WITH 'Alice' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        let query = result.unwrap();
        assert!(query.where_clause.is_some());

        match &query.where_clause.unwrap().expression {
            BooleanExpression::StartsWith { expression, prefix } => {
                assert_eq!(prefix, "Alice");
                match expression {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "name");
                    }
                    _ => panic!("Expected property reference"),
                }
            }
            _ => panic!("Expected STARTS WITH expression"),
        }
    }

    #[test]
    fn test_parse_ends_with() {
        let query = "MATCH (n:Person) WHERE n.email ENDS WITH '@example.com' RETURN n.email";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        let query = result.unwrap();
        assert!(query.where_clause.is_some());

        match &query.where_clause.unwrap().expression {
            BooleanExpression::EndsWith { expression, suffix } => {
                assert_eq!(suffix, "@example.com");
                match expression {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "email");
                    }
                    _ => panic!("Expected property reference"),
                }
            }
            _ => panic!("Expected ENDS WITH expression"),
        }
    }

    #[test]
    fn test_parse_contains_case_insensitive_keyword() {
        let query = "MATCH (n:Person) WHERE n.name contains 'test' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        match &result.unwrap().where_clause.unwrap().expression {
            BooleanExpression::Contains { substring, .. } => {
                assert_eq!(substring, "test");
            }
            _ => panic!("Expected CONTAINS expression"),
        }
    }

    #[test]
    fn test_parse_string_operators_in_complex_where() {
        let query =
            "MATCH (n:Person) WHERE n.name CONTAINS 'Jo' AND n.email ENDS WITH '.com' RETURN n";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        match &result.unwrap().where_clause.unwrap().expression {
            BooleanExpression::And(left, right) => {
                // Left should be CONTAINS
                match **left {
                    BooleanExpression::Contains { ref substring, .. } => {
                        assert_eq!(substring, "Jo");
                    }
                    _ => panic!("Expected CONTAINS expression on left"),
                }
                // Right should be ENDS WITH
                match **right {
                    BooleanExpression::EndsWith { ref suffix, .. } => {
                        assert_eq!(suffix, ".com");
                    }
                    _ => panic!("Expected ENDS WITH expression on right"),
                }
            }
            _ => panic!("Expected AND expression"),
        }
    }

    #[test]
    fn test_parse_ilike_pattern() {
        let query = "MATCH (n:Person) WHERE n.name ILIKE 'alice%' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "ILIKE pattern should parse successfully");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::ILike {
                expression,
                pattern,
            } => {
                match expression {
                    ValueExpression::Property(prop) => {
                        assert_eq!(prop.variable, "n");
                        assert_eq!(prop.property, "name");
                    }
                    _ => panic!("Expected property expression"),
                }
                assert_eq!(pattern, "alice%");
            }
            _ => panic!("Expected ILIKE expression"),
        }
    }

    #[test]
    fn test_parse_like_and_ilike_together() {
        let query =
            "MATCH (n:Person) WHERE n.name LIKE 'Alice%' OR n.name ILIKE 'bob%' RETURN n.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "LIKE and ILIKE together should parse");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Or(left, right) => {
                // Left should be LIKE (case-sensitive)
                match *left {
                    BooleanExpression::Like { pattern, .. } => {
                        assert_eq!(pattern, "Alice%");
                    }
                    _ => panic!("Expected LIKE expression on left"),
                }
                // Right should be ILIKE (case-insensitive)
                match *right {
                    BooleanExpression::ILike { pattern, .. } => {
                        assert_eq!(pattern, "bob%");
                    }
                    _ => panic!("Expected ILIKE expression on right"),
                }
            }
            _ => panic!("Expected OR expression"),
        }
    }

    #[test]
    fn test_parse_vector_distance() {
        let query = "MATCH (p:Person) WHERE vector_distance(p.embedding, $query_vec, cosine) < 0.5 RETURN p.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "vector_distance should parse successfully");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        // Verify it's a comparison with vector_distance
        match where_clause.expression {
            BooleanExpression::Comparison { left, operator, .. } => {
                match left {
                    ValueExpression::VectorDistance {
                        left,
                        right,
                        metric,
                    } => {
                        assert_eq!(metric, DistanceMetric::Cosine);
                        // Verify left is property reference
                        assert!(matches!(*left, ValueExpression::Property(_)));
                        // Verify right is parameter
                        assert!(matches!(*right, ValueExpression::Parameter(_)));
                    }
                    _ => panic!("Expected VectorDistance"),
                }
                assert_eq!(operator, ComparisonOperator::LessThan);
            }
            _ => panic!("Expected comparison"),
        }
    }

    #[test]
    fn test_parse_vector_similarity() {
        let query =
            "MATCH (p:Person) WHERE vector_similarity(p.embedding, $vec, l2) > 0.8 RETURN p";
        let result = parse_cypher_query(query);
        assert!(
            result.is_ok(),
            "vector_similarity should parse successfully"
        );

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Comparison { left, operator, .. } => {
                match left {
                    ValueExpression::VectorSimilarity { metric, .. } => {
                        assert_eq!(metric, DistanceMetric::L2);
                    }
                    _ => panic!("Expected VectorSimilarity"),
                }
                assert_eq!(operator, ComparisonOperator::GreaterThan);
            }
            _ => panic!("Expected comparison"),
        }
    }

    #[test]
    fn test_parse_parameter() {
        let query = "MATCH (p:Person) WHERE p.age = $min_age RETURN p";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "Parameter should parse successfully");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Comparison { right, .. } => match right {
                ValueExpression::Parameter(name) => {
                    assert_eq!(name, "min_age");
                }
                _ => panic!("Expected Parameter"),
            },
            _ => panic!("Expected comparison"),
        }
    }

    #[test]
    fn test_parse_multiple_parameters() {
        let query = "MATCH (p:Person) WHERE p.age > $min_age AND p.age < $max_age RETURN p";
        let result = parse_cypher_query(query);
        assert!(
            result.is_ok(),
            "Multiple parameters should parse successfully"
        );

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::And(left, right) => {
                // Check left: p.age > $min_age
                match *left {
                    BooleanExpression::Comparison {
                        right: val_right, ..
                    } => match val_right {
                        ValueExpression::Parameter(name) => {
                            assert_eq!(name, "min_age");
                        }
                        _ => panic!("Expected Parameter min_age"),
                    },
                    _ => panic!("Expected comparison on left"),
                }

                // Check right: p.age < $max_age
                match *right {
                    BooleanExpression::Comparison {
                        right: val_right, ..
                    } => match val_right {
                        ValueExpression::Parameter(name) => {
                            assert_eq!(name, "max_age");
                        }
                        _ => panic!("Expected Parameter max_age"),
                    },
                    _ => panic!("Expected comparison on right"),
                }
            }
            _ => panic!("Expected AND expression"),
        }
    }

    #[test]
    fn test_parse_parameter_formats() {
        // Test $param (should succeed)
        let query = "MATCH (p:Person) WHERE p.age > $min_age RETURN p";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "$param should parse successfully");
    }

    #[test]
    fn test_vector_distance_metrics() {
        for metric in &["cosine", "l2", "dot"] {
            let query = format!(
                "MATCH (p:Person) RETURN vector_distance(p.emb, $v, {}) AS dist",
                metric
            );
            let result = parse_cypher_query(&query);
            assert!(result.is_ok(), "Failed to parse metric: {}", metric);

            let ast = result.unwrap();
            let return_item = &ast.return_clause.items[0];

            match &return_item.expression {
                ValueExpression::VectorDistance {
                    metric: parsed_metric,
                    ..
                } => {
                    let expected = match *metric {
                        "cosine" => DistanceMetric::Cosine,
                        "l2" => DistanceMetric::L2,
                        "dot" => DistanceMetric::Dot,
                        _ => panic!("Unexpected metric"),
                    };
                    assert_eq!(*parsed_metric, expected);
                }
                _ => panic!("Expected VectorDistance"),
            }
        }
    }

    #[test]
    fn test_vector_search_in_order_by() {
        let query = "MATCH (p:Person) RETURN p.name ORDER BY vector_distance(p.embedding, $query_vec, cosine) ASC LIMIT 10";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "vector_distance in ORDER BY should parse");

        let ast = result.unwrap();
        let order_by = ast.order_by.expect("Expected ORDER BY clause");

        assert_eq!(order_by.items.len(), 1);
        match &order_by.items[0].expression {
            ValueExpression::VectorDistance { .. } => {
                // Success
            }
            _ => panic!("Expected VectorDistance in ORDER BY"),
        }
    }

    #[test]
    fn test_hybrid_query_with_vector_and_property_filters() {
        let query = "MATCH (p:Person) WHERE p.age > 25 AND vector_similarity(p.embedding, $query_vec, cosine) > 0.7 RETURN p.name";
        let result = parse_cypher_query(query);
        assert!(result.is_ok(), "Hybrid query should parse");

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        // Should be an AND expression
        match where_clause.expression {
            BooleanExpression::And(left, right) => {
                // Left should be age > 25
                match *left {
                    BooleanExpression::Comparison { .. } => {}
                    _ => panic!("Expected comparison on left"),
                }
                // Right should be vector_similarity > 0.7
                match *right {
                    BooleanExpression::Comparison { left, .. } => match left {
                        ValueExpression::VectorSimilarity { .. } => {}
                        _ => panic!("Expected VectorSimilarity"),
                    },
                    _ => panic!("Expected comparison on right"),
                }
            }
            _ => panic!("Expected AND expression"),
        }
    }

    #[test]
    fn test_parse_vector_literal() {
        let result = parse_vector_literal("[0.1, 0.2, 0.3]");
        assert!(result.is_ok());
        let (_, expr) = result.unwrap();
        match expr {
            ValueExpression::VectorLiteral(vec) => {
                assert_eq!(vec.len(), 3);
                assert_eq!(vec[0], 0.1);
                assert_eq!(vec[1], 0.2);
                assert_eq!(vec[2], 0.3);
            }
            _ => panic!("Expected VectorLiteral"),
        }
    }

    #[test]
    fn test_parse_vector_literal_with_negative_values() {
        let result = parse_vector_literal("[-0.1, 0.2, -0.3]");
        assert!(result.is_ok());
        let (_, expr) = result.unwrap();
        match expr {
            ValueExpression::VectorLiteral(vec) => {
                assert_eq!(vec.len(), 3);
                assert_eq!(vec[0], -0.1);
                assert_eq!(vec[2], -0.3);
            }
            _ => panic!("Expected VectorLiteral"),
        }
    }

    #[test]
    fn test_parse_vector_literal_scientific_notation() {
        let result = parse_vector_literal("[1e-3, 2.5e2, -3e-1]");
        assert!(result.is_ok());
        let (_, expr) = result.unwrap();
        match expr {
            ValueExpression::VectorLiteral(vec) => {
                assert_eq!(vec.len(), 3);
                assert!((vec[0] - 0.001).abs() < 1e-6);
                assert!((vec[1] - 250.0).abs() < 1e-6);
                assert!((vec[2] - (-0.3)).abs() < 1e-6);
            }
            _ => panic!("Expected VectorLiteral"),
        }
    }

    #[test]
    fn test_vector_distance_with_literal() {
        let query =
            "MATCH (p:Person) WHERE vector_distance(p.embedding, [0.1, 0.2], l2) < 0.5 RETURN p";
        let result = parse_cypher_query(query);
        assert!(result.is_ok());

        let ast = result.unwrap();
        let where_clause = ast.where_clause.expect("Expected WHERE clause");

        match where_clause.expression {
            BooleanExpression::Comparison { left, operator, .. } => {
                match left {
                    ValueExpression::VectorDistance {
                        left,
                        right,
                        metric,
                    } => {
                        // Left should be property reference
                        assert!(matches!(*left, ValueExpression::Property(_)));
                        // Right should be vector literal
                        match *right {
                            ValueExpression::VectorLiteral(vec) => {
                                assert_eq!(vec.len(), 2);
                                assert_eq!(vec[0], 0.1);
                                assert_eq!(vec[1], 0.2);
                            }
                            _ => panic!("Expected VectorLiteral"),
                        }
                        assert_eq!(metric, DistanceMetric::L2);
                    }
                    _ => panic!("Expected VectorDistance"),
                }
                assert_eq!(operator, ComparisonOperator::LessThan);
            }
            _ => panic!("Expected comparison"),
        }
    }

    // UNWIND parser tests
    #[test]
    fn test_parse_unwind_simple() {
        let query = "UNWIND [1, 2, 3] AS num RETURN num";
        let ast = parse_cypher_query(query);
        assert!(ast.is_ok(), "Failed to parse simple UNWIND query");
    }

    #[test]
    fn test_parse_unwind_after_match() {
        let query = "MATCH (n) UNWIND n.list AS item RETURN item";
        let ast = parse_cypher_query(query);
        assert!(ast.is_ok(), "Failed to parse UNWIND after MATCH");
    }
}