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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! Semantic analysis for graph queries
//!
//! This module implements the semantic analysis phase of the query pipeline:
//! Parse → **Semantic Analysis** → Logical Plan → Physical Plan
//!
//! Semantic analysis validates the query and enriches the AST with type information.

use crate::ast::*;
use crate::case_insensitive::CaseInsensitiveLookup;
use crate::config::GraphConfig;
use crate::error::{GraphError, Result};
use std::collections::{HashMap, HashSet};

/// Semantic analyzer - validates and enriches the AST
pub struct SemanticAnalyzer {
    config: GraphConfig,
    variables: HashMap<String, VariableInfo>,
    current_scope: ScopeType,
}

/// Information about a variable in the query
#[derive(Debug, Clone)]
pub struct VariableInfo {
    pub name: String,
    pub variable_type: VariableType,
    pub labels: Vec<String>,
    pub properties: HashSet<String>,
    pub defined_in: ScopeType,
}

/// Type of a variable
#[derive(Debug, Clone, PartialEq)]
pub enum VariableType {
    Node,
    Relationship,
    Path,
    Property,
}

/// Scope where a variable is defined
#[derive(Debug, Clone, PartialEq)]
pub enum ScopeType {
    Match,
    Where,
    With,
    PostWithWhere,
    Return,
    OrderBy,
}

/// Semantic analysis result with validated and enriched AST
#[derive(Debug, Clone)]
pub struct SemanticResult {
    /// The AST with parameters substituted and validated
    pub ast: CypherQuery,
    pub variables: HashMap<String, VariableInfo>,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

impl SemanticAnalyzer {
    pub fn new(config: GraphConfig) -> Self {
        Self {
            config,
            variables: HashMap::new(),
            current_scope: ScopeType::Match,
        }
    }

    /// Analyze a Cypher query AST
    pub fn analyze(
        &mut self,
        query: &CypherQuery,
        parameters: &HashMap<String, serde_json::Value>,
    ) -> Result<SemanticResult> {
        // Clone the query to perform parameter substitution
        let mut analyzed_query = query.clone();

        // Perform parameter substitution
        self.substitute_parameters(&mut analyzed_query, parameters)?;

        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Phase 1: Variable discovery in READING clauses (MATCH/UNWIND)
        self.current_scope = ScopeType::Match;
        for clause in &analyzed_query.reading_clauses {
            match clause {
                ReadingClause::Match(match_clause) => {
                    if let Err(e) = self.analyze_match_clause(match_clause) {
                        errors.push(format!("MATCH clause error: {}", e));
                    }
                }
                ReadingClause::Unwind(unwind_clause) => {
                    if let Err(e) = self.analyze_unwind_clause(unwind_clause) {
                        errors.push(format!("UNWIND clause error: {}", e));
                    }
                }
            }
        }

        // Phase 2: Validate WHERE clause (before WITH)
        if let Some(where_clause) = &analyzed_query.where_clause {
            self.current_scope = ScopeType::Where;
            if let Err(e) = self.analyze_where_clause(where_clause) {
                errors.push(format!("WHERE clause error: {}", e));
            }
        }

        // Phase 3: Validate WITH clause if present
        if let Some(with_clause) = &analyzed_query.with_clause {
            self.current_scope = ScopeType::With;
            if let Err(e) = self.analyze_with_clause(with_clause) {
                errors.push(format!("WITH clause error: {}", e));
            }
        }

        // Phase 4: Variable discovery in post-WITH READING clauses (query chaining)
        self.current_scope = ScopeType::Match;
        for clause in &analyzed_query.post_with_reading_clauses {
            match clause {
                ReadingClause::Match(match_clause) => {
                    if let Err(e) = self.analyze_match_clause(match_clause) {
                        errors.push(format!("Post-WITH MATCH clause error: {}", e));
                    }
                }
                ReadingClause::Unwind(unwind_clause) => {
                    if let Err(e) = self.analyze_unwind_clause(unwind_clause) {
                        errors.push(format!("Post-WITH UNWIND clause error: {}", e));
                    }
                }
            }
        }

        // Phase 4: Validate post-WITH WHERE clause if present
        if let Some(post_where) = &analyzed_query.post_with_where_clause {
            self.current_scope = ScopeType::PostWithWhere;
            if let Err(e) = self.analyze_where_clause(post_where) {
                errors.push(format!("Post-WITH WHERE clause error: {}", e));
            }
        }

        // Phase 5: Validate RETURN clause
        self.current_scope = ScopeType::Return;
        if let Err(e) = self.analyze_return_clause(&analyzed_query.return_clause) {
            errors.push(format!("RETURN clause error: {}", e));
        }

        // Phase 6: Validate ORDER BY clause
        if let Some(order_by) = &analyzed_query.order_by {
            self.current_scope = ScopeType::OrderBy;
            if let Err(e) = self.analyze_order_by_clause(order_by) {
                errors.push(format!("ORDER BY clause error: {}", e));
            }
        }

        // Phase 7: Schema validation
        self.validate_schema(&mut warnings);

        // Phase 8: Type checking
        self.validate_types(&mut errors);

        Ok(SemanticResult {
            ast: analyzed_query,
            variables: self.variables.clone(),
            errors,
            warnings,
        })
    }

    /// Analyze MATCH clause and discover variables
    fn analyze_match_clause(&mut self, match_clause: &MatchClause) -> Result<()> {
        for pattern in &match_clause.patterns {
            self.analyze_graph_pattern(pattern)?;
        }
        Ok(())
    }

    /// Analyze UNWIND clause and register variables
    fn analyze_unwind_clause(&mut self, unwind_clause: &UnwindClause) -> Result<()> {
        self.analyze_value_expression(&unwind_clause.expression)?;

        // Register the aliased variable (normalize to lowercase for case-insensitive behavior)
        let var_name = &unwind_clause.alias;
        let var_name_lower = var_name.to_lowercase();
        if let Some(existing) = self.variables.get_mut(&var_name_lower) {
            // Shadowing or redefinition - in Cypher variables can be bound multiple times in some contexts
            // But here we enforce uniqueness of types mostly.
            // For now, treat UNWIND alias as a Property type variable.
            if existing.variable_type != VariableType::Property {
                return Err(GraphError::PlanError {
                    message: format!("Variable '{}' redefined with different type", var_name),
                    location: snafu::Location::new(file!(), line!(), column!()),
                });
            }
        } else {
            let var_info = VariableInfo {
                name: var_name.clone(),
                variable_type: VariableType::Property,
                labels: vec![],
                properties: HashSet::new(),
                defined_in: self.current_scope.clone(),
            };
            self.variables.insert(var_name_lower, var_info);
        }
        Ok(())
    }

    /// Analyze a graph pattern and register variables
    fn analyze_graph_pattern(&mut self, pattern: &GraphPattern) -> Result<()> {
        match pattern {
            GraphPattern::Node(node) => {
                self.register_node_variable(node)?;
            }
            GraphPattern::Path(path) => {
                // Register start node
                self.register_node_variable(&path.start_node)?;

                // Register variables in each segment
                for segment in &path.segments {
                    // Validate relationship length constraints if present
                    self.validate_length_range(&segment.relationship)?;
                    // Register relationship variable if present
                    if let Some(rel_var) = &segment.relationship.variable {
                        self.register_relationship_variable(rel_var, &segment.relationship)?;
                    }

                    // Register end node
                    self.register_node_variable(&segment.end_node)?;
                }
            }
        }
        Ok(())
    }

    /// Register a node variable
    fn register_node_variable(&mut self, node: &NodePattern) -> Result<()> {
        if let Some(var_name) = &node.variable {
            // Normalize to lowercase for case-insensitive behavior
            let var_name_lower = var_name.to_lowercase();
            if let Some(existing) = self.variables.get_mut(&var_name_lower) {
                if existing.variable_type != VariableType::Node {
                    return Err(GraphError::PlanError {
                        message: format!("Variable '{}' redefined with different type", var_name),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }
                for label in &node.labels {
                    if !existing.labels.contains(label) {
                        existing.labels.push(label.clone());
                    }
                }
                for prop in node.properties.keys() {
                    existing.properties.insert(prop.clone());
                }
            } else {
                let var_info = VariableInfo {
                    name: var_name.clone(),
                    variable_type: VariableType::Node,
                    labels: node.labels.clone(),
                    properties: node.properties.keys().cloned().collect(),
                    defined_in: self.current_scope.clone(),
                };
                self.variables.insert(var_name_lower, var_info);
            }
        }
        Ok(())
    }

    /// Register a relationship variable
    fn register_relationship_variable(
        &mut self,
        var_name: &str,
        rel: &RelationshipPattern,
    ) -> Result<()> {
        // Normalize to lowercase for case-insensitive behavior
        let var_name_lower = var_name.to_lowercase();
        if let Some(existing) = self.variables.get_mut(&var_name_lower) {
            if existing.variable_type != VariableType::Relationship {
                return Err(GraphError::PlanError {
                    message: format!("Variable '{}' redefined with different type", var_name),
                    location: snafu::Location::new(file!(), line!(), column!()),
                });
            }
            for rel_type in &rel.types {
                if !existing.labels.contains(rel_type) {
                    existing.labels.push(rel_type.clone());
                }
            }
            for prop in rel.properties.keys() {
                existing.properties.insert(prop.clone());
            }
        } else {
            let var_info = VariableInfo {
                name: var_name.to_string(),
                variable_type: VariableType::Relationship,
                labels: rel.types.clone(), // Relationship types are like labels
                properties: rel.properties.keys().cloned().collect(),
                defined_in: self.current_scope.clone(),
            };
            self.variables.insert(var_name_lower, var_info);
        }
        Ok(())
    }

    /// Analyze WHERE clause
    fn analyze_where_clause(&mut self, where_clause: &WhereClause) -> Result<()> {
        self.analyze_boolean_expression(&where_clause.expression)
    }

    /// Analyze boolean expression and check variable references
    fn analyze_boolean_expression(&mut self, expr: &BooleanExpression) -> Result<()> {
        match expr {
            BooleanExpression::Comparison { left, right, .. } => {
                self.analyze_value_expression(left)?;
                self.analyze_value_expression(right)?;
            }
            BooleanExpression::And(left, right) | BooleanExpression::Or(left, right) => {
                self.analyze_boolean_expression(left)?;
                self.analyze_boolean_expression(right)?;
            }
            BooleanExpression::Not(inner) => {
                self.analyze_boolean_expression(inner)?;
            }
            BooleanExpression::Exists(prop_ref) => {
                self.validate_property_reference(prop_ref)?;
            }
            BooleanExpression::In { expression, list } => {
                self.analyze_value_expression(expression)?;
                for item in list {
                    self.analyze_value_expression(item)?;
                }
            }
            BooleanExpression::Like { expression, .. } => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::ILike { expression, .. } => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::Contains { expression, .. } => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::StartsWith { expression, .. } => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::EndsWith { expression, .. } => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::IsNull(expression) => {
                self.analyze_value_expression(expression)?;
            }
            BooleanExpression::IsNotNull(expression) => {
                self.analyze_value_expression(expression)?;
            }
        }
        Ok(())
    }

    /// Analyze value expression and check variable references
    fn analyze_value_expression(&mut self, expr: &ValueExpression) -> Result<()> {
        match expr {
            ValueExpression::Property(prop_ref) => {
                self.validate_property_reference(prop_ref)?;
            }
            ValueExpression::Literal(_) => {
                // Literals are always valid
            }
            ValueExpression::Variable(var) => {
                // Use case-insensitive lookup
                if !self.variables.contains_key_ci(var) {
                    return Err(GraphError::PlanError {
                        message: format!("Undefined variable: '{}'", var),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }
            }
            ValueExpression::ScalarFunction { name, args } => {
                let function_name = name.to_lowercase();
                // Validate arity and known functions
                match function_name.as_str() {
                    "tolower" | "lower" | "toupper" | "upper" => {
                        if args.len() != 1 {
                            return Err(GraphError::PlanError {
                                message: format!(
                                    "{} requires exactly 1 argument, got {}",
                                    name.to_uppercase(),
                                    args.len()
                                ),
                                location: snafu::Location::new(file!(), line!(), column!()),
                            });
                        }
                    }
                    _ => {
                        // Unknown scalar function - reject early with helpful error
                        return Err(GraphError::UnsupportedFeature {
                            feature: format!(
                                "Cypher function '{}' is not implemented. Supported scalar functions: toLower, lower, toUpper, upper. Supported aggregate functions: COUNT, SUM, AVG, MIN, MAX, COLLECT.",
                                name
                            ),
                            location: snafu::Location::new(file!(), line!(), column!()),
                        });
                    }
                }

                // Validate arguments recursively
                for arg in args {
                    self.analyze_value_expression(arg)?;
                }
            }
            ValueExpression::AggregateFunction {
                name,
                args,
                distinct,
            } => {
                let function_name = name.to_lowercase();
                // Validate known aggregate functions
                match function_name.as_str() {
                    "count" | "sum" | "avg" | "min" | "max" | "collect" => {
                        // DISTINCT is only supported for COUNT
                        // Other aggregates silently ignore it in execution, so reject early
                        if *distinct && function_name != "count" {
                            return Err(GraphError::UnsupportedFeature {
                                feature: format!(
                                    "DISTINCT is only supported with COUNT, not {}",
                                    function_name.to_uppercase()
                                ),
                                location: snafu::Location::new(file!(), line!(), column!()),
                            });
                        }

                        // COUNT(DISTINCT *) is semantically meaningless
                        // It would count distinct values of lit(1) which is always 1
                        if *distinct && function_name == "count" {
                            if let Some(ValueExpression::Variable(v)) = args.first() {
                                if v == "*" {
                                    return Err(GraphError::PlanError {
                                        message: "COUNT(DISTINCT *) is not supported. \
                                            Use COUNT(*) to count all rows, or \
                                            COUNT(DISTINCT property) to count distinct values."
                                            .to_string(),
                                        location: snafu::Location::new(file!(), line!(), column!()),
                                    });
                                }
                            }
                        }
                        // All aggregates require exactly 1 argument
                        if args.len() != 1 {
                            return Err(GraphError::PlanError {
                                message: format!(
                                    "{} requires exactly 1 argument, got {}",
                                    function_name.to_uppercase(),
                                    args.len()
                                ),
                                location: snafu::Location::new(file!(), line!(), column!()),
                            });
                        }

                        // Additional validation for SUM, AVG, MIN, MAX: they require properties, not bare variables
                        // Only COUNT and COLLECT allow bare variables (COUNT(*), COUNT(p), COLLECT(p))
                        if matches!(function_name.as_str(), "sum" | "avg" | "min" | "max") {
                            if let Some(ValueExpression::Variable(v)) = args.first() {
                                return Err(GraphError::PlanError {
                                    message: format!(
                                        "{}({}) is invalid - {} requires a property like {}({}.property). You cannot {} a node/entity.",
                                        function_name.to_uppercase(), v, function_name.to_uppercase(), function_name.to_uppercase(), v, function_name
                                    ),
                                    location: snafu::Location::new(file!(), line!(), column!()),
                                });
                            }
                        }
                    }
                    _ => {
                        // Unknown aggregate function - reject early
                        return Err(GraphError::UnsupportedFeature {
                            feature: format!(
                                "Cypher aggregate function '{}' is not implemented. Supported aggregate functions: COUNT, SUM, AVG, MIN, MAX, COLLECT.",
                                name
                            ),
                            location: snafu::Location::new(file!(), line!(), column!()),
                        });
                    }
                }

                // Validate arguments recursively.
                // Special-case COUNT(*) where '*' isn't a real variable.
                for arg in args {
                    if function_name == "count"
                        && matches!(arg, ValueExpression::Variable(v) if v == "*")
                    {
                        continue;
                    }
                    self.analyze_value_expression(arg)?;
                }
            }
            ValueExpression::Arithmetic { left, right, .. } => {
                // Validate arithmetic operands recursively
                self.analyze_value_expression(left)?;
                self.analyze_value_expression(right)?;

                // If both sides are literals, ensure they are numeric
                let is_numeric_literal = |pv: &PropertyValue| {
                    matches!(pv, PropertyValue::Integer(_) | PropertyValue::Float(_))
                };

                if let (ValueExpression::Literal(l1), ValueExpression::Literal(l2)) =
                    (&**left, &**right)
                {
                    if !(is_numeric_literal(l1) && is_numeric_literal(l2)) {
                        return Err(GraphError::PlanError {
                            message: "Arithmetic requires numeric literal operands".to_string(),
                            location: snafu::Location::new(file!(), line!(), column!()),
                        });
                    }
                }
            }
            ValueExpression::VectorDistance { left, right, .. } => {
                // Validate vector distance function arguments
                self.analyze_value_expression(left)?;
                self.analyze_value_expression(right)?;

                // Check that at least one argument references a property
                let has_property = matches!(**left, ValueExpression::Property(_))
                    || matches!(**right, ValueExpression::Property(_));

                if !has_property {
                    return Err(GraphError::PlanError {
                        message: "vector_distance() requires at least one argument to be a property reference".to_string(),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }
            }
            ValueExpression::VectorSimilarity { left, right, .. } => {
                // Validate vector similarity function arguments
                self.analyze_value_expression(left)?;
                self.analyze_value_expression(right)?;

                // Check that at least one argument references a property
                let has_property = matches!(**left, ValueExpression::Property(_))
                    || matches!(**right, ValueExpression::Property(_));

                if !has_property {
                    return Err(GraphError::PlanError {
                        message: "vector_similarity() requires at least one argument to be a property reference".to_string(),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }
            }
            ValueExpression::VectorLiteral(values) => {
                // Validate non-empty
                if values.is_empty() {
                    return Err(GraphError::PlanError {
                        message: "Vector literal cannot be empty".to_string(),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }

                // Note: Very large vectors (>4096 dimensions) may impact performance
                // but we don't enforce a hard limit here
            }
            ValueExpression::Parameter(_) => {
                // Parameters are always valid (resolved at runtime)
            }
        }
        Ok(())
    }

    fn register_projection_alias(&mut self, alias: &str) {
        // Use case-insensitive lookup and store normalized key
        if self.variables.contains_key_ci(alias) {
            return;
        }

        let var_info = VariableInfo {
            name: alias.to_string(),
            variable_type: VariableType::Property,
            labels: vec![],
            properties: HashSet::new(),
            defined_in: self.current_scope.clone(),
        };
        self.variables.insert(alias.to_lowercase(), var_info);
    }

    /// Validate property reference
    fn validate_property_reference(&self, prop_ref: &PropertyRef) -> Result<()> {
        // Use case-insensitive lookup
        if !self.variables.contains_key_ci(&prop_ref.variable) {
            return Err(GraphError::PlanError {
                message: format!("Undefined variable: '{}'", prop_ref.variable),
                location: snafu::Location::new(file!(), line!(), column!()),
            });
        }
        Ok(())
    }

    /// Analyze RETURN clause
    fn analyze_return_clause(&mut self, return_clause: &ReturnClause) -> Result<()> {
        for item in &return_clause.items {
            self.analyze_value_expression(&item.expression)?;
            if let Some(alias) = &item.alias {
                self.register_projection_alias(alias);
            }
        }
        Ok(())
    }

    /// Analyze WITH clause
    fn analyze_with_clause(&mut self, with_clause: &WithClause) -> Result<()> {
        // Validate WITH item expressions (similar to RETURN)
        for item in &with_clause.items {
            self.analyze_value_expression(&item.expression)?;
            if let Some(alias) = &item.alias {
                self.register_projection_alias(alias);
            }
        }
        // Validate ORDER BY within WITH if present
        if let Some(order_by) = &with_clause.order_by {
            for item in &order_by.items {
                self.analyze_value_expression(&item.expression)?;
            }
        }
        Ok(())
    }

    /// Analyze ORDER BY clause
    fn analyze_order_by_clause(&mut self, order_by: &OrderByClause) -> Result<()> {
        for item in &order_by.items {
            self.analyze_value_expression(&item.expression)?;
        }
        Ok(())
    }

    /// Validate schema references against configuration
    fn validate_schema(&self, warnings: &mut Vec<String>) {
        for var_info in self.variables.values() {
            match var_info.variable_type {
                VariableType::Node => {
                    for label in &var_info.labels {
                        if self.config.get_node_mapping(label).is_none() {
                            warnings.push(format!("Node label '{}' not found in schema", label));
                        }
                    }
                }
                VariableType::Relationship => {
                    for rel_type in &var_info.labels {
                        if self.config.get_relationship_mapping(rel_type).is_none() {
                            warnings.push(format!(
                                "Relationship type '{}' not found in schema",
                                rel_type
                            ));
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Validate types and operations
    fn validate_types(&self, errors: &mut Vec<String>) {
        // TODO: Implement type checking
        // - Check that properties exist on nodes/relationships
        // - Check that comparison operations are valid for data types
        // - Check that arithmetic operations are valid

        // Check that properties referenced in patterns exist in schema when property fields are defined
        for var_info in self.variables.values() {
            match var_info.variable_type {
                VariableType::Node => {
                    // Collect property_fields from all known label mappings that specify properties
                    let mut label_property_sets: Vec<&[String]> = Vec::new();
                    for label in &var_info.labels {
                        if let Some(mapping) = self.config.get_node_mapping(label) {
                            if !mapping.property_fields.is_empty() {
                                label_property_sets.push(&mapping.property_fields);
                            }
                        }
                    }

                    if !label_property_sets.is_empty() {
                        'prop: for prop in &var_info.properties {
                            // Property is valid if present in at least one label's property_fields
                            // Use case-insensitive comparison
                            let prop_lower = prop.to_lowercase();
                            for fields in &label_property_sets {
                                if fields.iter().any(|f| f.to_lowercase() == prop_lower) {
                                    continue 'prop;
                                }
                            }
                            errors.push(format!(
                                "Property '{}' not found on labels {:?}",
                                prop, var_info.labels
                            ));
                        }
                    }
                }
                VariableType::Relationship => {
                    // Collect property_fields from all known relationship mappings that specify properties
                    let mut rel_property_sets: Vec<&[String]> = Vec::new();
                    for rel_type in &var_info.labels {
                        if let Some(mapping) = self.config.get_relationship_mapping(rel_type) {
                            if !mapping.property_fields.is_empty() {
                                rel_property_sets.push(&mapping.property_fields);
                            }
                        }
                    }

                    if !rel_property_sets.is_empty() {
                        'prop_rel: for prop in &var_info.properties {
                            // Use case-insensitive comparison for relationship properties
                            let prop_lower = prop.to_lowercase();
                            for fields in &rel_property_sets {
                                if fields.iter().any(|f| f.to_lowercase() == prop_lower) {
                                    continue 'prop_rel;
                                }
                            }
                            errors.push(format!(
                                "Property '{}' not found on relationship types {:?}",
                                prop, var_info.labels
                            ));
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

impl SemanticAnalyzer {
    fn validate_length_range(&self, rel: &RelationshipPattern) -> Result<()> {
        if let Some(len) = &rel.length {
            if let (Some(min), Some(max)) = (len.min, len.max) {
                if min > max {
                    return Err(GraphError::PlanError {
                        message: "Invalid path length range: min > max".to_string(),
                        location: snafu::Location::new(file!(), line!(), column!()),
                    });
                }
            }
        }
        Ok(())
    }
    /// Substitute parameters with literal values in the AST
    fn substitute_parameters(
        &self,
        query: &mut CypherQuery,
        parameters: &HashMap<String, serde_json::Value>,
    ) -> Result<()> {
        crate::parameter_substitution::substitute_parameters(query, parameters)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{
        ArithmeticOperator, BooleanExpression, CypherQuery, GraphPattern, LengthRange, MatchClause,
        NodePattern, PathPattern, PathSegment, PropertyRef, PropertyValue, RelationshipDirection,
        RelationshipPattern, ReturnClause, ReturnItem, ValueExpression, WhereClause,
    };
    use crate::config::{GraphConfig, NodeMapping};

    fn test_config() -> GraphConfig {
        GraphConfig::builder()
            .with_node_label("Person", "id")
            .with_node_label("Employee", "id")
            .with_node_label("Company", "id")
            .with_relationship("KNOWS", "src_id", "dst_id")
            .build()
            .unwrap()
    }

    // Helper: analyze a query that only has a single RETURN expression
    fn analyze_return_expr(expr: ValueExpression) -> Result<SemanticResult> {
        let query = CypherQuery {
            reading_clauses: vec![],
            where_clause: None,
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![ReturnItem {
                    expression: expr,
                    alias: None,
                }],
            },
            limit: None,
            order_by: None,
            skip: None,
        };
        let mut analyzer = SemanticAnalyzer::new(test_config());
        analyzer.analyze(&query, &HashMap::new())
    }

    // Helper: analyze a query with a single MATCH (var:label) and a RETURN expression
    fn analyze_return_with_match(
        var: &str,
        label: &str,
        expr: ValueExpression,
    ) -> Result<SemanticResult> {
        let node = NodePattern::new(Some(var.to_string())).with_label(label);
        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node)],
            })],
            where_clause: None,
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![ReturnItem {
                    expression: expr,
                    alias: None,
                }],
            },
            limit: None,
            order_by: None,
            skip: None,
        };
        let mut analyzer = SemanticAnalyzer::new(test_config());
        analyzer.analyze(&query, &HashMap::new())
    }

    #[test]
    fn test_merge_node_variable_metadata() {
        // MATCH (n:Person {age: 30}), (n:Employee {dept: "X"})
        let node1 = NodePattern::new(Some("n".to_string()))
            .with_label("Person")
            .with_property("age", PropertyValue::Integer(30));
        let node2 = NodePattern::new(Some("n".to_string()))
            .with_label("Employee")
            .with_property("dept", PropertyValue::String("X".to_string()));

        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node1), GraphPattern::Node(node2)],
            })],
            where_clause: None,
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result.errors.is_empty());
        let n = result.variables.get("n").expect("variable n present");
        // Labels merged
        assert!(n.labels.contains(&"Person".to_string()));
        assert!(n.labels.contains(&"Employee".to_string()));
        // Properties unioned
        assert!(n.properties.contains("age"));
        assert!(n.properties.contains("dept"));
    }

    #[test]
    fn test_invalid_length_range_collects_error() {
        let start = NodePattern::new(Some("a".to_string())).with_label("Person");
        let end = NodePattern::new(Some("b".to_string())).with_label("Person");
        let mut rel = RelationshipPattern::new(RelationshipDirection::Outgoing)
            .with_variable("r")
            .with_type("KNOWS");
        rel.length = Some(LengthRange {
            min: Some(3),
            max: Some(2),
        });

        let path = PathPattern {
            start_node: start,
            segments: vec![PathSegment {
                relationship: rel,
                end_node: end,
            }],
        };

        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Path(path)],
            })],
            where_clause: None,
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Invalid path length range")));
    }

    #[test]
    fn test_undefined_variable_in_where() {
        // MATCH (n:Person) WHERE EXISTS(m.name)
        let node = NodePattern::new(Some("n".to_string())).with_label("Person");
        let where_clause = WhereClause {
            expression: BooleanExpression::Exists(PropertyRef::new("m", "name")),
        };
        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node)],
            })],
            where_clause: Some(where_clause),
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Undefined variable: 'm'")));
    }

    #[test]
    fn test_variable_redefinition_between_node_and_relationship() {
        // MATCH (n:Person)-[n:KNOWS]->(m:Person)
        let start = NodePattern::new(Some("n".to_string())).with_label("Person");
        let end = NodePattern::new(Some("m".to_string())).with_label("Person");
        let rel = RelationshipPattern::new(RelationshipDirection::Outgoing)
            .with_variable("n")
            .with_type("KNOWS");

        let path = PathPattern {
            start_node: start,
            segments: vec![PathSegment {
                relationship: rel,
                end_node: end,
            }],
        };

        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Path(path)],
            })],
            where_clause: None,
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("redefined with different type")));
    }

    #[test]
    fn test_unknown_node_label_warns() {
        // MATCH (x:Unknown)
        let node = NodePattern::new(Some("x".to_string())).with_label("Unknown");
        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node)],
            })],
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            where_clause: None,
            with_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .warnings
            .iter()
            .any(|w| w.contains("Node label 'Unknown' not found in schema")));
    }

    #[test]
    fn test_property_not_in_schema_reports_error() {
        // Configure Person with allowed property 'name' only
        let custom_config = GraphConfig::builder()
            .with_node_mapping(
                NodeMapping::new("Person", "id").with_properties(vec!["name".to_string()]),
            )
            .with_relationship("KNOWS", "src_id", "dst_id")
            .build()
            .unwrap();

        // MATCH (n:Person {age: 30})
        let node = NodePattern::new(Some("n".to_string()))
            .with_label("Person")
            .with_property("age", PropertyValue::Integer(30));
        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node)],
            })],
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            where_clause: None,
            with_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(custom_config);
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Property 'age' not found on labels [\"Person\"]")));
    }

    #[test]
    fn test_valid_length_range_ok() {
        let start = NodePattern::new(Some("a".to_string())).with_label("Person");
        let end = NodePattern::new(Some("b".to_string())).with_label("Person");
        let mut rel = RelationshipPattern::new(RelationshipDirection::Outgoing)
            .with_variable("r")
            .with_type("KNOWS");
        rel.length = Some(LengthRange {
            min: Some(2),
            max: Some(3),
        });

        let path = PathPattern {
            start_node: start,
            segments: vec![PathSegment {
                relationship: rel,
                end_node: end,
            }],
        };

        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Path(path)],
            })],
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            where_clause: None,
            with_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        assert!(result
            .errors
            .iter()
            .all(|e| !e.contains("Invalid path length range")));
    }

    #[test]
    fn test_relationship_variable_metadata_merge_across_segments() {
        // Path with two segments sharing the same relationship variable 'r'
        // (a:Person)-[r:KNOWS {since: 2020}]->(b:Person)-[r:FRIEND {level: 1}]->(c:Person)
        let start = NodePattern::new(Some("a".to_string())).with_label("Person");
        let mid = NodePattern::new(Some("b".to_string())).with_label("Person");
        let end = NodePattern::new(Some("c".to_string())).with_label("Person");

        let mut rel1 = RelationshipPattern::new(RelationshipDirection::Outgoing)
            .with_variable("r")
            .with_type("KNOWS")
            .with_property("since", PropertyValue::Integer(2020));
        rel1.length = None;

        let mut rel2 = RelationshipPattern::new(RelationshipDirection::Outgoing)
            .with_variable("r")
            .with_type("FRIEND")
            .with_property("level", PropertyValue::Integer(1));
        rel2.length = None;

        let path = PathPattern {
            start_node: start,
            segments: vec![
                PathSegment {
                    relationship: rel1,
                    end_node: mid,
                },
                PathSegment {
                    relationship: rel2,
                    end_node: end,
                },
            ],
        };

        // Custom config that knows both relationship types to avoid warnings muddying the assertion
        let custom_config = GraphConfig::builder()
            .with_node_label("Person", "id")
            .with_relationship("KNOWS", "src_id", "dst_id")
            .with_relationship("FRIEND", "src_id", "dst_id")
            .build()
            .unwrap();

        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Path(path)],
            })],
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            where_clause: None,
            with_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut analyzer = SemanticAnalyzer::new(custom_config);
        let result = analyzer.analyze(&query, &HashMap::new()).unwrap();
        let r = result.variables.get("r").expect("variable r present");
        // Types merged
        assert!(r.labels.contains(&"KNOWS".to_string()));
        assert!(r.labels.contains(&"FRIEND".to_string()));
        // Properties unioned
        assert!(r.properties.contains("since"));
        assert!(r.properties.contains("level"));
    }

    #[test]
    fn test_parameter_substitution() {
        // MATCH (n:Person) WHERE n.age > $min_age RETURN n
        let node = NodePattern::new(Some("n".to_string())).with_label("Person");
        let where_clause = WhereClause {
            expression: BooleanExpression::Comparison {
                left: ValueExpression::Property(PropertyRef::new("n", "age")),
                operator: crate::ast::ComparisonOperator::GreaterThan,
                right: ValueExpression::Parameter("min_age".to_string()),
            },
        };
        let query = CypherQuery {
            reading_clauses: vec![ReadingClause::Match(MatchClause {
                patterns: vec![GraphPattern::Node(node)],
            })],
            where_clause: Some(where_clause),
            with_clause: None,
            post_with_reading_clauses: vec![],
            post_with_where_clause: None,
            return_clause: ReturnClause {
                distinct: false,
                items: vec![ReturnItem {
                    expression: ValueExpression::Variable("n".to_string()),
                    alias: None,
                }],
            },
            limit: None,
            order_by: None,
            skip: None,
        };

        let mut parameters = HashMap::new();
        parameters.insert("min_age".to_string(), serde_json::json!(18));

        let mut analyzer = SemanticAnalyzer::new(test_config());
        let result = analyzer
            .analyze(&query, &parameters)
            .expect("Analysis failed");

        // Verify substitution in AST
        let where_clause = result.ast.where_clause.as_ref().unwrap();
        match &where_clause.expression {
            BooleanExpression::Comparison { right, .. } => match right {
                ValueExpression::Literal(PropertyValue::Integer(val)) => {
                    assert_eq!(*val, 18);
                }
                _ => panic!("Expected Integer literal, got {:?}", right),
            },
            _ => panic!("Expected Comparison expression"),
        }
    }

    #[test]
    fn test_function_argument_undefined_variable_in_return() {
        // RETURN toUpper(m.name)
        let expr = ValueExpression::ScalarFunction {
            name: "toUpper".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("m", "name"))],
        };
        let result = analyze_return_expr(expr).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Undefined variable: 'm'")));
    }

    #[test]
    fn test_function_argument_valid_variable_ok() {
        // MATCH (n:Person) RETURN toUpper(n.name)
        let expr = ValueExpression::ScalarFunction {
            name: "toUpper".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "name"))],
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_arithmetic_with_undefined_variable_in_return() {
        // RETURN x + 1
        let expr = ValueExpression::Arithmetic {
            left: Box::new(ValueExpression::Variable("x".to_string())),
            operator: ArithmeticOperator::Add,
            right: Box::new(ValueExpression::Literal(PropertyValue::Integer(1))),
        };
        let result = analyze_return_expr(expr).unwrap();
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Undefined variable: 'x'")));
    }

    #[test]
    fn test_arithmetic_with_defined_property_ok() {
        let expr = ValueExpression::Arithmetic {
            left: Box::new(ValueExpression::Literal(PropertyValue::Integer(1))),
            operator: ArithmeticOperator::Add,
            right: Box::new(ValueExpression::Property(PropertyRef::new("n", "age"))),
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        // Should not report undefined variable 'n'
        assert!(result
            .errors
            .iter()
            .all(|e| !e.contains("Undefined variable: 'n'")));
    }

    #[test]
    fn test_count_with_multiple_args_fails_validation() {
        // COUNT(n.age, n.name) should fail semantic validation
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![
                ValueExpression::Property(PropertyRef::new("n", "age")),
                ValueExpression::Property(PropertyRef::new("n", "name")),
            ],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("COUNT requires exactly 1 argument")),
            "Expected error about COUNT arity, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_count_with_zero_args_fails_validation() {
        // COUNT() with no arguments should fail
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("COUNT requires exactly 1 argument")),
            "Expected error about COUNT arity, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_count_with_one_arg_passes_validation() {
        // COUNT(n.age) should pass validation
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result
                .errors
                .iter()
                .all(|e| !e.contains("COUNT requires exactly 1 argument")),
            "COUNT with 1 arg should not produce arity error, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_count_star_passes_validation() {
        // COUNT(*) should be allowed (special-cased in semantic analysis)
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![ValueExpression::Variable("*".to_string())],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result.errors.is_empty(),
            "Expected COUNT(*) to pass semantic validation, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_unimplemented_scalar_function_fails_validation() {
        let expr = ValueExpression::ScalarFunction {
            name: "replace".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "name"))],
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        // ScalarFunction with unknown name collects an error
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.to_lowercase().contains("not implemented")),
            "Expected semantic validation to reject unimplemented function, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_sum_with_variable_fails_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "sum".to_string(),
            args: vec![ValueExpression::Variable("n".to_string())],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            !result.errors.is_empty(),
            "Expected SUM(variable) to produce validation errors"
        );
        let has_sum_error = result
            .errors
            .iter()
            .any(|e| e.contains("SUM(n) is invalid") && e.contains("requires a property"));
        assert!(
            has_sum_error,
            "Expected error about SUM requiring property, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_avg_with_variable_fails_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "avg".to_string(),
            args: vec![ValueExpression::Variable("n".to_string())],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            !result.errors.is_empty(),
            "Expected AVG(variable) to produce validation errors"
        );
        let has_avg_error = result
            .errors
            .iter()
            .any(|e| e.contains("AVG(n) is invalid") && e.contains("requires a property"));
        assert!(
            has_avg_error,
            "Expected error about AVG requiring property, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_sum_with_property_passes_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "sum".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result.errors.is_empty(),
            "SUM with property should pass validation, got errors: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_min_with_variable_fails_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "min".to_string(),
            args: vec![ValueExpression::Variable("n".to_string())],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            !result.errors.is_empty(),
            "Expected MIN(variable) to produce validation errors"
        );
        let has_min_error = result
            .errors
            .iter()
            .any(|e| e.contains("MIN(n) is invalid") && e.contains("requires a property"));
        assert!(
            has_min_error,
            "Expected error about MIN requiring property, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_max_with_variable_fails_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "max".to_string(),
            args: vec![ValueExpression::Variable("n".to_string())],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            !result.errors.is_empty(),
            "Expected MAX(variable) to produce validation errors"
        );
        let has_max_error = result
            .errors
            .iter()
            .any(|e| e.contains("MAX(n) is invalid") && e.contains("requires a property"));
        assert!(
            has_max_error,
            "Expected error about MAX requiring property, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_min_with_property_passes_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "min".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result.errors.is_empty(),
            "MIN with property should pass validation, got errors: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_max_with_property_passes_validation() {
        let expr = ValueExpression::AggregateFunction {
            name: "max".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: false,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result.errors.is_empty(),
            "MAX with property should pass validation, got errors: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_distinct_only_supported_on_count() {
        // SUM(DISTINCT n.age) should fail - DISTINCT only supported for COUNT
        let expr = ValueExpression::AggregateFunction {
            name: "sum".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: true,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("DISTINCT is only supported with COUNT")),
            "Expected error about DISTINCT only for COUNT, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_count_distinct_star_rejected() {
        // COUNT(DISTINCT *) is semantically meaningless - should be rejected
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![ValueExpression::Variable("*".to_string())],
            distinct: true,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("COUNT(DISTINCT *)")),
            "Expected error about COUNT(DISTINCT *), got: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_count_distinct_passes_validation() {
        // COUNT(DISTINCT n.age) should pass
        let expr = ValueExpression::AggregateFunction {
            name: "count".to_string(),
            args: vec![ValueExpression::Property(PropertyRef::new("n", "age"))],
            distinct: true,
        };
        let result = analyze_return_with_match("n", "Person", expr).unwrap();
        assert!(
            result.errors.is_empty(),
            "COUNT(DISTINCT) should pass validation, got errors: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_arithmetic_with_non_numeric_literal_error() {
        // RETURN "x" + 1
        let expr = ValueExpression::Arithmetic {
            left: Box::new(ValueExpression::Literal(PropertyValue::String(
                "x".to_string(),
            ))),
            operator: ArithmeticOperator::Add,
            right: Box::new(ValueExpression::Literal(PropertyValue::Integer(1))),
        };
        let result = analyze_return_expr(expr).unwrap();
        // The semantic analyzer returns Ok with errors collected in the result
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Arithmetic requires numeric literal operands")));
    }

    #[test]
    fn test_arithmetic_with_numeric_literals_ok() {
        // RETURN 1 + 2.0
        let expr = ValueExpression::Arithmetic {
            left: Box::new(ValueExpression::Literal(PropertyValue::Integer(1))),
            operator: ArithmeticOperator::Add,
            right: Box::new(ValueExpression::Literal(PropertyValue::Float(2.0))),
        };
        let result = analyze_return_expr(expr);
        assert!(result.is_ok(), "Expected Ok but got {:?}", result);
        assert!(result.unwrap().errors.is_empty());
    }

    #[test]
    fn test_vector_distance_with_property() {
        use crate::ast::DistanceMetric;

        // MATCH (p:Person) RETURN vector_distance(p.embedding, p.embedding, l2)
        let expr = ValueExpression::VectorDistance {
            left: Box::new(ValueExpression::Property(PropertyRef {
                variable: "p".to_string(),
                property: "embedding".to_string(),
            })),
            right: Box::new(ValueExpression::Property(PropertyRef {
                variable: "p".to_string(),
                property: "embedding".to_string(),
            })),
            metric: DistanceMetric::L2,
        };

        let result = analyze_return_with_match("p", "Person", expr);
        assert!(result.is_ok(), "Expected Ok but got {:?}", result);
        assert!(result.unwrap().errors.is_empty());
    }

    #[test]
    fn test_vector_distance_without_property_fails() {
        use crate::ast::DistanceMetric;

        // MATCH (p:Person) RETURN vector_distance(0.5, 0.3, l2) - both literals, should fail
        let expr = ValueExpression::VectorDistance {
            left: Box::new(ValueExpression::Literal(PropertyValue::Float(0.5))),
            right: Box::new(ValueExpression::Literal(PropertyValue::Float(0.3))),
            metric: DistanceMetric::L2,
        };

        let result = analyze_return_with_match("p", "Person", expr);
        // Semantic analyzer returns Ok but with errors in the result
        assert!(
            result.is_ok(),
            "Analyzer should return Ok with errors, got {:?}",
            result
        );
        let semantic_result = result.unwrap();
        assert!(
            !semantic_result.errors.is_empty(),
            "Expected validation errors"
        );
        assert!(semantic_result
            .errors
            .iter()
            .any(|e| e.contains("requires at least one argument to be a property")));
    }

    #[test]
    fn test_vector_similarity_with_property() {
        use crate::ast::DistanceMetric;

        // MATCH (p:Person) RETURN vector_similarity(p.embedding, p.embedding, cosine)
        let expr = ValueExpression::VectorSimilarity {
            left: Box::new(ValueExpression::Property(PropertyRef {
                variable: "p".to_string(),
                property: "embedding".to_string(),
            })),
            right: Box::new(ValueExpression::Property(PropertyRef {
                variable: "p".to_string(),
                property: "embedding".to_string(),
            })),
            metric: DistanceMetric::Cosine,
        };

        let result = analyze_return_with_match("p", "Person", expr);
        assert!(result.is_ok(), "Expected Ok but got {:?}", result);
        assert!(result.unwrap().errors.is_empty());
    }

    #[test]
    fn test_vector_similarity_one_literal_ok() {
        use crate::ast::DistanceMetric;

        // MATCH (p:Person) RETURN vector_similarity(p.embedding, 0.5, cosine)
        // One property reference is sufficient
        let expr = ValueExpression::VectorSimilarity {
            left: Box::new(ValueExpression::Property(PropertyRef {
                variable: "p".to_string(),
                property: "embedding".to_string(),
            })),
            right: Box::new(ValueExpression::Literal(PropertyValue::Float(0.5))),
            metric: DistanceMetric::Cosine,
        };

        let result = analyze_return_with_match("p", "Person", expr);
        assert!(result.is_ok(), "Expected Ok but got {:?}", result);
        assert!(result.unwrap().errors.is_empty());
    }

    #[test]
    fn test_vector_distance_all_metrics() {
        use crate::ast::DistanceMetric;

        // Test all distance metrics are accepted
        for metric in [
            DistanceMetric::L2,
            DistanceMetric::Cosine,
            DistanceMetric::Dot,
        ] {
            let expr = ValueExpression::VectorDistance {
                left: Box::new(ValueExpression::Property(PropertyRef {
                    variable: "p".to_string(),
                    property: "embedding".to_string(),
                })),
                right: Box::new(ValueExpression::Property(PropertyRef {
                    variable: "p".to_string(),
                    property: "embedding".to_string(),
                })),
                metric: metric.clone(),
            };

            let result = analyze_return_with_match("p", "Person", expr);
            assert!(
                result.is_ok(),
                "Expected Ok for metric {:?} but got {:?}",
                metric,
                result
            );
            assert!(result.unwrap().errors.is_empty());
        }
    }
}