tensorlogic-oxirs-bridge 0.1.0

RDF/GraphQL/SHACL integration and provenance tracking for TensorLogic
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
use anyhow::{anyhow, Result};
use std::collections::HashMap;
use tensorlogic_ir::{TLExpr, Term};

use super::types::{
    AggregateFunction, BindExpr, FilterCondition, GraphPattern, PatternElement, QueryType,
    SelectElement, SparqlQuery, TriplePattern,
};

/// SPARQL query parser and compiler
pub struct SparqlCompiler {
    /// Map of predicate IRIs to TensorLogic predicate names
    predicate_mapping: HashMap<String, String>,
}

impl SparqlCompiler {
    pub fn new() -> Self {
        SparqlCompiler {
            predicate_mapping: HashMap::new(),
        }
    }

    /// Add a mapping from IRI to predicate name
    ///
    /// Example: map `"http://example.org/knows"` to `"knows"`
    pub fn add_predicate_mapping(&mut self, iri: String, predicate_name: String) {
        self.predicate_mapping.insert(iri, predicate_name);
    }

    /// Parse a SPARQL query (SELECT, ASK, DESCRIBE, or CONSTRUCT)
    ///
    /// Supports SPARQL 1.1 syntax including:
    /// ```sparql
    /// # SELECT query
    /// SELECT DISTINCT ?x ?y WHERE {
    ///   ?x <http://example.org/knows> ?y .
    ///   OPTIONAL { ?x <http://example.org/age> ?age }
    ///   FILTER(?age > 18)
    /// } LIMIT 10
    ///
    /// # ASK query
    /// ASK WHERE {
    ///   ?x <http://example.org/knows> ?y .
    /// }
    ///
    /// # DESCRIBE query
    /// DESCRIBE ?x WHERE {
    ///   ?x <http://example.org/knows> ?y .
    /// }
    ///
    /// # CONSTRUCT query
    /// CONSTRUCT { ?x <http://example.org/friend> ?y }
    /// WHERE { ?x <http://example.org/knows> ?y }
    /// ```
    ///
    /// Note: This is a simplified parser for demonstration.
    /// For production, use a dedicated SPARQL parser.
    pub fn parse_query(&self, sparql: &str) -> Result<SparqlQuery> {
        // Normalize the query by collapsing whitespace and removing newlines within clauses
        let normalized = sparql
            .lines()
            .map(|l| l.trim())
            .filter(|l| !l.is_empty())
            .collect::<Vec<_>>()
            .join(" ");

        // Determine query type
        let query_type = self.parse_query_type(&normalized)?;

        // Parse WHERE clause
        let where_pattern = self.parse_where_clause(&normalized)?;

        // Parse GROUP BY and HAVING
        let group_by = self.parse_group_by(&normalized);
        let having = self.parse_having(&normalized)?;

        // Parse solution modifiers
        let limit = self.parse_limit(&normalized);
        let offset = self.parse_offset(&normalized);
        let order_by = self.parse_order_by(&normalized);

        Ok(SparqlQuery {
            query_type,
            where_pattern,
            group_by,
            having,
            limit,
            offset,
            order_by,
        })
    }

    /// Parse GROUP BY clause
    fn parse_group_by(&self, normalized: &str) -> Vec<String> {
        let mut group_by = Vec::new();

        if let Some(group_pos) = normalized.find("GROUP BY") {
            // Find the end of GROUP BY (next clause or end of query)
            let remaining = &normalized[group_pos + 8..];
            let end_pos = remaining
                .find("HAVING")
                .or_else(|| remaining.find("ORDER BY"))
                .or_else(|| remaining.find("LIMIT"))
                .or_else(|| remaining.find("OFFSET"))
                .unwrap_or(remaining.len());

            let group_part = remaining[..end_pos].trim();
            for token in group_part.split_whitespace() {
                if let Some(var_name) = token.strip_prefix('?') {
                    group_by.push(var_name.to_string());
                }
            }
        }

        group_by
    }

    /// Parse HAVING clause
    fn parse_having(&self, normalized: &str) -> Result<Vec<FilterCondition>> {
        let mut conditions = Vec::new();

        if let Some(having_pos) = normalized.find("HAVING") {
            // Find the end of HAVING (next clause or end of query)
            let remaining = &normalized[having_pos + 6..];
            let end_pos = remaining
                .find("ORDER BY")
                .or_else(|| remaining.find("LIMIT"))
                .or_else(|| remaining.find("OFFSET"))
                .unwrap_or(remaining.len());

            let having_part = remaining[..end_pos].trim();

            // Parse conditions similar to FILTER
            if !having_part.is_empty() {
                if let Some(filter) = self.parse_filter(&format!("FILTER{}", having_part))? {
                    conditions.push(filter);
                }
            }
        }

        Ok(conditions)
    }

    /// Parse an aggregate function
    fn parse_aggregate(&self, text: &str) -> Option<(AggregateFunction, String)> {
        let text = text.trim();

        // Check for AS alias
        let (func_part, alias) = if let Some(as_pos) = text.to_uppercase().find(" AS ") {
            let alias_start = as_pos + 4;
            let alias = text[alias_start..]
                .trim()
                .trim_matches(|c| c == '?' || c == ')')
                .to_string();
            (text[..as_pos].trim(), Some(alias))
        } else {
            (text, None)
        };

        // Parse aggregate function
        let upper = func_part.to_uppercase();

        if upper.starts_with("COUNT(") {
            let inner = func_part[6..].trim_end_matches(')').trim();
            let distinct = inner.to_uppercase().starts_with("DISTINCT");
            let var_part = if distinct { inner[8..].trim() } else { inner };
            let variable = if var_part == "*" {
                None
            } else {
                Some(var_part.trim_start_matches('?').to_string())
            };
            return Some((
                AggregateFunction::Count { variable, distinct },
                alias.unwrap_or_else(|| "count".to_string()),
            ));
        }

        if upper.starts_with("SUM(") {
            let inner = func_part[4..].trim_end_matches(')').trim();
            let distinct = inner.to_uppercase().starts_with("DISTINCT");
            let var_part = if distinct { inner[8..].trim() } else { inner };
            let variable = var_part.trim_start_matches('?').to_string();
            return Some((
                AggregateFunction::Sum { variable, distinct },
                alias.unwrap_or_else(|| "sum".to_string()),
            ));
        }

        if upper.starts_with("AVG(") {
            let inner = func_part[4..].trim_end_matches(')').trim();
            let distinct = inner.to_uppercase().starts_with("DISTINCT");
            let var_part = if distinct { inner[8..].trim() } else { inner };
            let variable = var_part.trim_start_matches('?').to_string();
            return Some((
                AggregateFunction::Avg { variable, distinct },
                alias.unwrap_or_else(|| "avg".to_string()),
            ));
        }

        if upper.starts_with("MIN(") {
            let inner = func_part[4..].trim_end_matches(')').trim();
            let variable = inner.trim_start_matches('?').to_string();
            return Some((
                AggregateFunction::Min { variable },
                alias.unwrap_or_else(|| "min".to_string()),
            ));
        }

        if upper.starts_with("MAX(") {
            let inner = func_part[4..].trim_end_matches(')').trim();
            let variable = inner.trim_start_matches('?').to_string();
            return Some((
                AggregateFunction::Max { variable },
                alias.unwrap_or_else(|| "max".to_string()),
            ));
        }

        if upper.starts_with("GROUP_CONCAT(") {
            let inner = func_part[13..].trim_end_matches(')').trim();
            let distinct = inner.to_uppercase().starts_with("DISTINCT");
            let var_part = if distinct { inner[8..].trim() } else { inner };
            // Check for SEPARATOR
            let (variable, separator) =
                if let Some(sep_pos) = var_part.to_uppercase().find("; SEPARATOR") {
                    let var = var_part[..sep_pos]
                        .trim()
                        .trim_start_matches('?')
                        .to_string();
                    let sep_start = var_part.find('=').map(|p| p + 1).unwrap_or(sep_pos);
                    let sep = var_part[sep_start..].trim().trim_matches('"').to_string();
                    (var, Some(sep))
                } else {
                    (var_part.trim_start_matches('?').to_string(), None)
                };
            return Some((
                AggregateFunction::GroupConcat {
                    variable,
                    separator,
                    distinct,
                },
                alias.unwrap_or_else(|| "group_concat".to_string()),
            ));
        }

        if upper.starts_with("SAMPLE(") {
            let inner = func_part[7..].trim_end_matches(')').trim();
            let variable = inner.trim_start_matches('?').to_string();
            return Some((
                AggregateFunction::Sample { variable },
                alias.unwrap_or_else(|| "sample".to_string()),
            ));
        }

        None
    }

    /// Parse the query type (SELECT, ASK, DESCRIBE, CONSTRUCT)
    fn parse_query_type(&self, normalized: &str) -> Result<QueryType> {
        if normalized.contains("ASK") {
            Ok(QueryType::Ask)
        } else if let Some(describe_pos) = normalized.find("DESCRIBE") {
            // Parse DESCRIBE resources
            let where_pos = normalized.find("WHERE").unwrap_or(normalized.len());
            let describe_part = normalized[describe_pos + 8..where_pos].trim();
            let mut resources = Vec::new();

            for token in describe_part.split_whitespace() {
                if token.starts_with('?') || token.starts_with('<') {
                    resources.push(
                        token
                            .trim_matches(|c| c == '?' || c == '<' || c == '>')
                            .to_string(),
                    );
                }
            }

            Ok(QueryType::Describe { resources })
        } else if normalized.contains("CONSTRUCT") {
            // Parse CONSTRUCT template
            let template = self.parse_construct_template(normalized)?;
            Ok(QueryType::Construct { template })
        } else if let Some(select_pos) = normalized.find("SELECT") {
            // Parse SELECT variables and aggregates
            let where_pos = normalized.find("WHERE").unwrap_or(normalized.len());
            let select_part = normalized[select_pos + 6..where_pos].trim();

            let distinct = select_part.starts_with("DISTINCT");
            let vars_part = if distinct {
                &select_part[8..]
            } else {
                select_part
            };

            let mut select_vars = Vec::new();
            let mut projections = Vec::new();

            // Split on commas or parentheses to handle aggregates
            let mut current_token = String::new();
            let mut paren_depth = 0;

            for c in vars_part.chars() {
                match c {
                    '(' => {
                        paren_depth += 1;
                        current_token.push(c);
                    }
                    ')' => {
                        paren_depth -= 1;
                        current_token.push(c);
                    }
                    ' ' | ',' if paren_depth == 0 => {
                        if !current_token.trim().is_empty() {
                            let token = current_token.trim();
                            // Strip outer parentheses for aggregate expressions
                            let token = if token.starts_with('(') && token.ends_with(')') {
                                &token[1..token.len() - 1]
                            } else {
                                token
                            };
                            if let Some((agg_func, alias)) = self.parse_aggregate(token) {
                                projections.push(SelectElement::Aggregate {
                                    function: agg_func,
                                    alias: Some(alias.clone()),
                                });
                                select_vars.push(alias);
                            } else if let Some(var_name) = token.strip_prefix('?') {
                                projections.push(SelectElement::Variable(var_name.to_string()));
                                select_vars.push(var_name.to_string());
                            } else if token == "*" {
                                projections.push(SelectElement::Variable("*".to_string()));
                                select_vars.push("*".to_string());
                            }
                        }
                        current_token.clear();
                    }
                    _ => current_token.push(c),
                }
            }

            // Handle the last token
            if !current_token.trim().is_empty() {
                let token = current_token.trim();
                // Strip outer parentheses for aggregate expressions
                let token = if token.starts_with('(') && token.ends_with(')') {
                    &token[1..token.len() - 1]
                } else {
                    token
                };
                if let Some((agg_func, alias)) = self.parse_aggregate(token) {
                    projections.push(SelectElement::Aggregate {
                        function: agg_func,
                        alias: Some(alias.clone()),
                    });
                    select_vars.push(alias);
                } else if let Some(var_name) = token.strip_prefix('?') {
                    projections.push(SelectElement::Variable(var_name.to_string()));
                    select_vars.push(var_name.to_string());
                } else if token == "*" {
                    projections.push(SelectElement::Variable("*".to_string()));
                    select_vars.push("*".to_string());
                }
            }

            Ok(QueryType::Select {
                projections,
                select_vars,
                distinct,
            })
        } else {
            Err(anyhow!("Unable to determine query type"))
        }
    }

    /// Parse CONSTRUCT template patterns
    fn parse_construct_template(&self, normalized: &str) -> Result<Vec<TriplePattern>> {
        let construct_pos = normalized
            .find("CONSTRUCT")
            .ok_or_else(|| anyhow!("No CONSTRUCT found"))?;
        let where_pos = normalized.find("WHERE").unwrap_or(normalized.len());

        // Find template content between { and }
        let template_start = normalized[construct_pos..where_pos]
            .find('{')
            .ok_or_else(|| anyhow!("No opening brace in CONSTRUCT template"))?;
        let template_end = normalized[construct_pos..where_pos]
            .rfind('}')
            .ok_or_else(|| anyhow!("No closing brace in CONSTRUCT template"))?;

        let template_content =
            &normalized[construct_pos + template_start + 1..construct_pos + template_end];

        let mut patterns = Vec::new();
        for statement in self.split_sparql_statements(template_content) {
            if let Some(pattern) = self.parse_triple_pattern(statement)? {
                patterns.push(pattern);
            }
        }

        Ok(patterns)
    }

    /// Parse WHERE clause into graph patterns
    fn parse_where_clause(&self, normalized: &str) -> Result<GraphPattern> {
        // Find WHERE clause content (between { and })
        if let Some(where_start) = normalized.find("WHERE") {
            if let Some(brace_start) = normalized[where_start..].find('{') {
                let content_start = where_start + brace_start + 1;

                // Find matching closing brace
                let closing_brace = self.find_matching_brace(&normalized[content_start..])?;
                let where_content = &normalized[content_start..content_start + closing_brace];

                return self.parse_graph_pattern(where_content);
            }
        }

        Err(anyhow!("No WHERE clause found"))
    }

    /// Parse a graph pattern (handles OPTIONAL, UNION, FILTER)
    fn parse_graph_pattern(&self, content: &str) -> Result<GraphPattern> {
        let content = content.trim();

        if content.is_empty() {
            return Err(anyhow!("Empty graph pattern"));
        }

        // Check for UNION (top-level only)
        if let Some(union_pos) = content.find("UNION") {
            // Ensure it's not inside braces
            let before_union = &content[..union_pos];
            let open_braces = before_union.matches('{').count();
            let close_braces = before_union.matches('}').count();

            if open_braces == close_braces {
                // UNION is at top level
                let left_part = before_union.trim();
                let right_part = content[union_pos + 5..].trim();

                let left_pattern = self.parse_graph_pattern(left_part)?;
                let right_pattern = self.parse_graph_pattern(right_part)?;

                return Ok(GraphPattern::Union(
                    Box::new(left_pattern),
                    Box::new(right_pattern),
                ));
            }
        }

        // Parse statements using split_sparql_statements
        let mut patterns = Vec::new();
        let statements = self.split_sparql_statements(content);

        for statement in statements {
            let statement = statement.trim();

            if statement.is_empty() {
                continue;
            }

            // Check for OPTIONAL
            if statement.starts_with("OPTIONAL") {
                // Find the content in braces
                if let Some(brace_start_pos) = statement.find('{') {
                    let content_start = brace_start_pos + 1;
                    if let Ok(closing_offset) =
                        self.find_matching_brace(&statement[content_start..])
                    {
                        let optional_content =
                            &statement[content_start..content_start + closing_offset];
                        let inner_pattern = self.parse_graph_pattern(optional_content)?;
                        patterns.push(GraphPattern::Optional(Box::new(inner_pattern)));
                        continue;
                    }
                }
            }

            // Check for FILTER
            if statement.starts_with("FILTER") {
                if let Some(filter) = self.parse_filter(statement)? {
                    patterns.push(GraphPattern::Filter(filter));
                }
                continue;
            }

            // Check for BIND
            if statement.starts_with("BIND") {
                patterns.push(self.parse_bind(statement)?);
                continue;
            }

            // Check for VALUES
            if statement.starts_with("VALUES") {
                patterns.push(self.parse_values(statement)?);
                continue;
            }

            // Check for nested braces (subgraph pattern)
            if statement.starts_with('{') && statement.ends_with('}') {
                let inner = &statement[1..statement.len() - 1];
                let inner_pattern = self.parse_graph_pattern(inner)?;
                patterns.push(inner_pattern);
                continue;
            }

            // Parse as triple pattern
            if let Some(pattern) = self.parse_triple_pattern(statement)? {
                patterns.push(GraphPattern::Triple(pattern));
            }
        }

        if patterns.is_empty() {
            Err(anyhow!("Empty graph pattern in content: {}", content))
        } else if patterns.len() == 1 {
            Ok(patterns
                .into_iter()
                .next()
                .expect("patterns is non-empty, len==1 guaranteed"))
        } else {
            Ok(GraphPattern::Group(patterns))
        }
    }

    /// Find matching closing brace
    fn find_matching_brace(&self, content: &str) -> Result<usize> {
        let mut depth = 1;
        let chars: Vec<char> = content.chars().collect();

        for (i, &c) in chars.iter().enumerate() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(i);
                    }
                }
                _ => {}
            }
        }

        Err(anyhow!("No matching closing brace found"))
    }

    /// Parse LIMIT modifier
    fn parse_limit(&self, normalized: &str) -> Option<usize> {
        if let Some(limit_pos) = normalized.find("LIMIT") {
            let after_limit = &normalized[limit_pos + 5..].trim();
            if let Some(num_str) = after_limit.split_whitespace().next() {
                return num_str.parse().ok();
            }
        }
        None
    }

    /// Parse OFFSET modifier
    fn parse_offset(&self, normalized: &str) -> Option<usize> {
        if let Some(offset_pos) = normalized.find("OFFSET") {
            let after_offset = &normalized[offset_pos + 6..].trim();
            if let Some(num_str) = after_offset.split_whitespace().next() {
                return num_str.parse().ok();
            }
        }
        None
    }

    /// Parse ORDER BY modifier
    fn parse_order_by(&self, normalized: &str) -> Vec<String> {
        if let Some(order_pos) = normalized.find("ORDER BY") {
            let after_order = &normalized[order_pos + 8..];

            // Find the end of ORDER BY clause (either LIMIT, OFFSET, or end of string)
            let limit_offset = after_order.find("LIMIT").unwrap_or(after_order.len());
            let offset_offset = after_order.find("OFFSET").unwrap_or(after_order.len());
            let end_offset = limit_offset.min(offset_offset);

            let order_part = after_order[..end_offset].trim();
            return order_part
                .split_whitespace()
                .filter_map(|s| s.strip_prefix('?').map(|v| v.to_string()))
                .collect();
        }
        Vec::new()
    }

    /// Split SPARQL WHERE content into statements, respecting URI boundaries,
    /// brace blocks (VALUES/OPTIONAL bodies), and parenthesised expressions.
    ///
    /// Only splits on '.' that appear at brace-depth == 0 and paren-depth == 0
    /// and outside of '<…>' URI delimiters or '"…"' string literals.
    fn split_sparql_statements<'a>(&self, content: &'a str) -> Vec<&'a str> {
        let mut statements = Vec::new();
        let mut current_start = 0;
        let mut inside_uri = false;
        let mut inside_string = false;
        let mut brace_depth: usize = 0;
        let mut paren_depth: usize = 0;

        for (byte_pos, ch) in content.char_indices() {
            match ch {
                '<' if !inside_string && brace_depth == 0 && paren_depth == 0 => {
                    inside_uri = true;
                }
                '>' if !inside_string && inside_uri => {
                    inside_uri = false;
                }
                '"' if !inside_uri => {
                    inside_string = !inside_string;
                }
                '{' if !inside_uri && !inside_string => {
                    brace_depth = brace_depth.saturating_add(1);
                }
                '}' if !inside_uri && !inside_string => {
                    brace_depth = brace_depth.saturating_sub(1);
                }
                '(' if !inside_uri && !inside_string => {
                    paren_depth = paren_depth.saturating_add(1);
                }
                ')' if !inside_uri && !inside_string => {
                    paren_depth = paren_depth.saturating_sub(1);
                }
                '.' if !inside_uri && !inside_string && brace_depth == 0 && paren_depth == 0 => {
                    let stmt = &content[current_start..byte_pos];
                    if !stmt.trim().is_empty() {
                        statements.push(stmt);
                    }
                    current_start = byte_pos + ch.len_utf8();
                }
                _ => {}
            }
        }

        // Add the last statement if there's anything left
        if current_start < content.len() {
            let statement = &content[current_start..];
            if !statement.trim().is_empty() {
                statements.push(statement);
            }
        }

        statements
    }

    /// Parse a triple pattern
    fn parse_triple_pattern(&self, line: &str) -> Result<Option<TriplePattern>> {
        // Remove trailing dot and split by whitespace
        let line = line.trim_end_matches('.').trim();
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() < 3 {
            return Ok(None);
        }

        let subject = self.parse_pattern_element(parts[0])?;
        let predicate = self.parse_pattern_element(parts[1])?;
        let object = self.parse_pattern_element(parts[2])?;

        Ok(Some(TriplePattern {
            subject,
            predicate,
            object,
        }))
    }

    /// Parse a pattern element (variable or constant)
    fn parse_pattern_element(&self, s: &str) -> Result<PatternElement> {
        if let Some(var_name) = s.strip_prefix('?') {
            Ok(PatternElement::Variable(var_name.to_string()))
        } else if let Some(iri) = s.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
            Ok(PatternElement::Constant(iri.to_string()))
        } else if let Some(literal) = s.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
            Ok(PatternElement::Constant(literal.to_string()))
        } else {
            Ok(PatternElement::Constant(s.to_string()))
        }
    }

    /// Parse a FILTER clause
    fn parse_filter(&self, line: &str) -> Result<Option<FilterCondition>> {
        let filter_content = line
            .strip_prefix("FILTER")
            .and_then(|s| s.trim().strip_prefix('('))
            .and_then(|s| s.trim().strip_suffix(')'))
            .map(|s| s.trim());

        if let Some(content) = filter_content {
            // Check for built-in functions
            if content.starts_with("BOUND(") {
                if let Some(var_end) = content.find(')') {
                    let var = &content[6..var_end].trim_start_matches('?');
                    return Ok(Some(FilterCondition::Bound(var.to_string())));
                }
            } else if content.starts_with("isIRI(") || content.starts_with("isURI(") {
                // Both isIRI and isURI have the same length (6 characters including parenthesis)
                let start_pos = 6;
                if let Some(var_end) = content.find(')') {
                    let var = &content[start_pos..var_end].trim_start_matches('?');
                    return Ok(Some(FilterCondition::IsIri(var.to_string())));
                }
            } else if content.starts_with("isLiteral(") {
                if let Some(var_end) = content.find(')') {
                    let var = &content[10..var_end].trim_start_matches('?');
                    return Ok(Some(FilterCondition::IsLiteral(var.to_string())));
                }
            } else if content.starts_with("regex(") {
                // regex(?var, "pattern")
                if let Some(comma_pos) = content.find(',') {
                    let var = content[6..comma_pos].trim().trim_start_matches('?');
                    let pattern_part = content[comma_pos + 1..]
                        .trim()
                        .trim_end_matches(')')
                        .trim_matches('"');
                    return Ok(Some(FilterCondition::Regex(
                        var.to_string(),
                        pattern_part.to_string(),
                    )));
                }
            }

            // Check for comparison operators
            if content.contains(">=") {
                let parts: Vec<&str> = content.split(">=").map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::GreaterOrEqual(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            } else if content.contains("<=") {
                let parts: Vec<&str> = content.split("<=").map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::LessOrEqual(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            } else if content.contains(">") && !content.contains(">=") {
                let parts: Vec<&str> = content.split('>').map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::GreaterThan(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            } else if content.contains("<") && !content.contains("<=") {
                let parts: Vec<&str> = content.split('<').map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::LessThan(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            } else if content.contains("!=") {
                let parts: Vec<&str> = content.split("!=").map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::NotEquals(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            } else if content.contains("=")
                && !content.contains("!=")
                && !content.contains(">=")
                && !content.contains("<=")
            {
                let parts: Vec<&str> = content.split('=').map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    return Ok(Some(FilterCondition::Equals(
                        parts[0].trim_start_matches('?').to_string(),
                        parts[1].trim_matches('"').to_string(),
                    )));
                }
            }
        }

        Ok(None)
    }

    /// Parse a BIND clause: `BIND ( <element> AS ?<var> )`
    fn parse_bind(&self, stmt: &str) -> Result<GraphPattern> {
        // Strip "BIND" prefix then the outer parentheses
        let inner = stmt.trim_start_matches("BIND").trim();
        let inner = inner
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .ok_or_else(|| anyhow!("malformed BIND clause: {}", stmt))?
            .trim();

        // Split on " AS " (case-insensitive by trying both forms)
        let (lhs, rhs) = inner
            .split_once(" AS ")
            .or_else(|| inner.split_once(" as "))
            .ok_or_else(|| anyhow!("BIND missing AS: {}", stmt))?;

        let lhs = lhs.trim();
        let rhs = rhs.trim().trim_start_matches('?');
        let elem = self.parse_pattern_element(lhs)?;
        Ok(GraphPattern::Bind(BindExpr::Term(elem), rhs.to_string()))
    }

    /// Parse a VALUES clause: single or multi-variable form.
    fn parse_values(&self, stmt: &str) -> Result<GraphPattern> {
        let rest = stmt.trim_start_matches("VALUES").trim();

        // Find the opening brace
        let brace_start = rest
            .find('{')
            .ok_or_else(|| anyhow!("VALUES missing '{{': {}", stmt))?;
        let var_part = rest[..brace_start].trim();
        let body = rest[brace_start + 1..].trim().trim_end_matches('}').trim();

        // Parse variable list
        let vars: Vec<String> = if var_part.starts_with('(') {
            var_part
                .trim_start_matches('(')
                .trim_end_matches(')')
                .split_whitespace()
                .map(|v| v.trim_start_matches('?').to_string())
                .collect()
        } else {
            vec![var_part.trim_start_matches('?').to_string()]
        };

        let n = vars.len();

        // Parse rows
        let rows: Result<Vec<Vec<PatternElement>>> = if n == 1 {
            // Single-var: bare terms separated by whitespace
            body.split_whitespace()
                .map(|t| Ok(vec![self.parse_pattern_element(t)?]))
                .collect()
        } else {
            // Multi-var: groups of ( t1 t2 … )
            let mut rows = Vec::new();
            let mut remaining = body;
            while let Some(start) = remaining.find('(') {
                let end = remaining[start..]
                    .find(')')
                    .map(|i| start + i)
                    .ok_or_else(|| anyhow!("VALUES row missing ')'"))?;
                let row_str = remaining[start + 1..end].trim();
                let row: Result<Vec<PatternElement>> = row_str
                    .split_whitespace()
                    .map(|t| self.parse_pattern_element(t))
                    .collect();
                let row = row?;
                if row.len() != n {
                    return Err(anyhow!(
                        "VALUES row has {} terms but {} vars declared",
                        row.len(),
                        n
                    ));
                }
                rows.push(row);
                remaining = &remaining[end + 1..];
            }
            Ok(rows)
        };

        Ok(GraphPattern::Values(vars, rows?))
    }

    /// Compile a SPARQL query to TensorLogic expression
    ///
    /// Converts SPARQL patterns to TLExpr predicates and filters to constraints.
    /// Supports all query types (SELECT, ASK, DESCRIBE, CONSTRUCT) and advanced
    /// patterns (OPTIONAL, UNION).
    ///
    /// ## Example
    ///
    /// ```
    /// use tensorlogic_oxirs_bridge::sparql::SparqlCompiler;
    ///
    /// let mut compiler = SparqlCompiler::new();
    /// compiler.add_predicate_mapping(
    ///     "http://example.org/knows".to_string(),
    ///     "knows".to_string()
    /// );
    ///
    /// // SELECT query
    /// let query = r#"
    ///     SELECT ?x ?y WHERE {
    ///       ?x <http://example.org/knows> ?y .
    ///     }
    /// "#;
    ///
    /// let sparql_query = compiler.parse_query(query).expect("unwrap");
    /// let tl_expr = compiler.compile_to_tensorlogic(&sparql_query).expect("unwrap");
    ///
    /// // ASK query
    /// let ask_query = r#"
    ///     ASK WHERE {
    ///       ?x <http://example.org/knows> ?y .
    ///     }
    /// "#;
    ///
    /// let sparql_ask = compiler.parse_query(ask_query).expect("unwrap");
    /// let ask_expr = compiler.compile_to_tensorlogic(&sparql_ask).expect("unwrap");
    /// ```
    pub fn compile_to_tensorlogic(&self, query: &SparqlQuery) -> Result<TLExpr> {
        // Compile WHERE clause pattern
        let where_expr = self.compile_graph_pattern(&query.where_pattern)?;

        // For ASK queries, wrap in EXISTS quantifier
        match &query.query_type {
            QueryType::Ask => {
                // ASK is essentially EXISTS over all variables in the pattern
                Ok(where_expr) // The pattern itself represents existence
            }
            QueryType::Select { select_vars, .. } => {
                // For SELECT, the expression is the WHERE clause
                // Variable projection happens at execution time
                if select_vars.is_empty() || select_vars.contains(&"*".to_string()) {
                    Ok(where_expr)
                } else {
                    // Could add quantifiers for non-selected variables here
                    Ok(where_expr)
                }
            }
            QueryType::Describe { .. } => {
                // DESCRIBE returns all triples about specified resources
                Ok(where_expr)
            }
            QueryType::Construct { template: _ } => {
                // CONSTRUCT applies template pattern after WHERE clause matches
                // For now, we return the WHERE clause; template application
                // would happen at execution time
                Ok(where_expr)
            }
        }
    }

    /// Compile a graph pattern to TLExpr
    fn compile_graph_pattern(&self, pattern: &GraphPattern) -> Result<TLExpr> {
        match pattern {
            GraphPattern::Triple(triple) => self.compile_triple_pattern(triple),

            GraphPattern::Group(patterns) => {
                if patterns.is_empty() {
                    return Err(anyhow!("Empty pattern group"));
                }

                let mut exprs: Vec<TLExpr> = Vec::new();
                for p in patterns {
                    exprs.push(self.compile_graph_pattern(p)?);
                }

                // Combine with AND
                Ok(exprs
                    .into_iter()
                    .reduce(TLExpr::and)
                    .expect("exprs is non-empty, checked above"))
            }

            GraphPattern::Optional(inner) => {
                // OPTIONAL in SPARQL is like left-outer join
                // In logic, we can represent as: pattern OR TRUE
                // This ensures the outer pattern succeeds even if inner fails
                let inner_expr = self.compile_graph_pattern(inner)?;

                // Use OR with a trivially true expression
                // This gives "optional" semantics - the pattern can match or not
                Ok(TLExpr::or(inner_expr.clone(), TLExpr::pred("true", vec![])))
            }

            GraphPattern::Union(left, right) => {
                // UNION is disjunction
                let left_expr = self.compile_graph_pattern(left)?;
                let right_expr = self.compile_graph_pattern(right)?;
                Ok(TLExpr::or(left_expr, right_expr))
            }

            GraphPattern::Filter(filter_cond) => self.compile_filter_condition(filter_cond),

            GraphPattern::Bind(expr, var) => {
                // Lower BIND to an equality predicate: equals(var, term)
                let term = match expr {
                    BindExpr::Term(PatternElement::Variable(v)) => Term::var(v),
                    BindExpr::Term(PatternElement::Constant(c)) => Term::constant(c),
                };
                Ok(TLExpr::pred("equals", vec![Term::var(var), term]))
            }

            GraphPattern::Values(vars, rows) => {
                // Lower VALUES to disjunction of equality conjunctions.
                // Each row becomes an AND of equals(var, term), rows are OR-ed.
                if rows.is_empty() {
                    return Err(anyhow!("VALUES clause has no rows"));
                }
                let row_exprs: Result<Vec<TLExpr>> = rows
                    .iter()
                    .map(|row| {
                        let eq_exprs: Result<Vec<TLExpr>> = vars
                            .iter()
                            .zip(row.iter())
                            .map(|(var, elem)| {
                                let term = match elem {
                                    PatternElement::Variable(v) => Term::var(v),
                                    PatternElement::Constant(c) => Term::constant(c),
                                };
                                Ok(TLExpr::pred("equals", vec![Term::var(var), term]))
                            })
                            .collect();
                        let eq_exprs = eq_exprs?;
                        eq_exprs
                            .into_iter()
                            .reduce(TLExpr::and)
                            .ok_or_else(|| anyhow!("VALUES row is empty"))
                    })
                    .collect();
                row_exprs?
                    .into_iter()
                    .reduce(TLExpr::or)
                    .ok_or_else(|| anyhow!("VALUES clause produced no expressions"))
            }
        }
    }

    /// Compile a triple pattern to TLExpr
    fn compile_triple_pattern(&self, pattern: &TriplePattern) -> Result<TLExpr> {
        let pred_name = match &pattern.predicate {
            PatternElement::Constant(iri) => {
                // Try to map IRI to predicate name
                self.predicate_mapping
                    .get(iri)
                    .cloned()
                    .unwrap_or_else(|| Self::iri_to_name(iri))
            }
            PatternElement::Variable(v) => {
                return Err(anyhow!("Variable predicates not supported: ?{}", v));
            }
        };

        let subj_term = match &pattern.subject {
            PatternElement::Variable(v) => Term::var(v),
            PatternElement::Constant(c) => Term::constant(c),
        };

        let obj_term = match &pattern.object {
            PatternElement::Variable(v) => Term::var(v),
            PatternElement::Constant(c) => Term::constant(c),
        };

        Ok(TLExpr::pred(&pred_name, vec![subj_term, obj_term]))
    }

    /// Compile a filter condition to TLExpr
    fn compile_filter_condition(&self, filter: &FilterCondition) -> Result<TLExpr> {
        let expr = match filter {
            FilterCondition::Equals(var, val) => {
                TLExpr::pred("equals", vec![Term::var(var), Term::constant(val)])
            }
            FilterCondition::NotEquals(var, val) => TLExpr::negate(TLExpr::pred(
                "equals",
                vec![Term::var(var), Term::constant(val)],
            )),
            FilterCondition::GreaterThan(var, val) => {
                TLExpr::pred("greaterThan", vec![Term::var(var), Term::constant(val)])
            }
            FilterCondition::LessThan(var, val) => {
                TLExpr::pred("lessThan", vec![Term::var(var), Term::constant(val)])
            }
            FilterCondition::GreaterOrEqual(var, val) => {
                TLExpr::pred("greaterOrEqual", vec![Term::var(var), Term::constant(val)])
            }
            FilterCondition::LessOrEqual(var, val) => {
                TLExpr::pred("lessOrEqual", vec![Term::var(var), Term::constant(val)])
            }
            FilterCondition::Regex(var, pattern) => {
                TLExpr::pred("matches", vec![Term::var(var), Term::constant(pattern)])
            }
            FilterCondition::Bound(var) => TLExpr::pred("bound", vec![Term::var(var)]),
            FilterCondition::IsIri(var) => TLExpr::pred("isIri", vec![Term::var(var)]),
            FilterCondition::IsLiteral(var) => TLExpr::pred("isLiteral", vec![Term::var(var)]),
        };

        Ok(expr)
    }

    /// Extract local name from IRI
    fn iri_to_name(iri: &str) -> String {
        iri.split(['/', '#']).next_back().unwrap_or(iri).to_string()
    }
}

impl Default for SparqlCompiler {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_bind_variable() {
        let compiler = SparqlCompiler::new();
        let result = compiler
            .parse_bind("BIND ( ?z AS ?y )")
            .expect("parse_bind should succeed");
        assert_eq!(
            result,
            GraphPattern::Bind(
                BindExpr::Term(PatternElement::Variable("z".to_string())),
                "y".to_string()
            )
        );
    }

    #[test]
    fn test_parse_bind_constant() {
        let compiler = SparqlCompiler::new();
        let result = compiler
            .parse_bind(r#"BIND ( "hello" AS ?greeting )"#)
            .expect("parse_bind should succeed");
        assert_eq!(
            result,
            GraphPattern::Bind(
                BindExpr::Term(PatternElement::Constant("hello".to_string())),
                "greeting".to_string()
            )
        );
    }

    #[test]
    fn test_parse_values_single_var() {
        let compiler = SparqlCompiler::new();
        let result = compiler
            .parse_values("VALUES ?x { 1 2 3 }")
            .expect("parse_values should succeed");
        assert_eq!(
            result,
            GraphPattern::Values(
                vec!["x".to_string()],
                vec![
                    vec![PatternElement::Constant("1".to_string())],
                    vec![PatternElement::Constant("2".to_string())],
                    vec![PatternElement::Constant("3".to_string())],
                ]
            )
        );
    }

    #[test]
    fn test_parse_values_multi_var() {
        let compiler = SparqlCompiler::new();
        let result = compiler
            .parse_values(r#"VALUES (?x ?y) { (1 "a") (2 "b") }"#)
            .expect("parse_values should succeed");
        assert_eq!(
            result,
            GraphPattern::Values(
                vec!["x".to_string(), "y".to_string()],
                vec![
                    vec![
                        PatternElement::Constant("1".to_string()),
                        PatternElement::Constant("a".to_string()),
                    ],
                    vec![
                        PatternElement::Constant("2".to_string()),
                        PatternElement::Constant("b".to_string()),
                    ],
                ]
            )
        );
    }

    #[test]
    fn test_filter_bound() {
        let compiler = SparqlCompiler::new();
        let filter = compiler.parse_filter("FILTER(BOUND(?x))").expect("unwrap");

        match filter {
            Some(FilterCondition::Bound(var)) => {
                assert_eq!(var, "x");
            }
            _ => panic!("Expected BOUND filter"),
        }
    }

    #[test]
    fn test_filter_is_iri() {
        let compiler = SparqlCompiler::new();
        let filter = compiler.parse_filter("FILTER(isIRI(?x))").expect("unwrap");

        match filter {
            Some(FilterCondition::IsIri(var)) => {
                assert_eq!(var, "x");
            }
            _ => panic!("Expected isIRI filter"),
        }
    }

    #[test]
    fn test_filter_regex() {
        let compiler = SparqlCompiler::new();
        let filter = compiler
            .parse_filter(r#"FILTER(regex(?name, "^John"))"#)
            .expect("unwrap");

        match filter {
            Some(FilterCondition::Regex(var, pattern)) => {
                assert_eq!(var, "name");
                assert_eq!(pattern, "^John");
            }
            _ => panic!("Expected regex filter"),
        }
    }

    #[test]
    fn test_iri_to_name() {
        assert_eq!(
            SparqlCompiler::iri_to_name("http://example.org/knows"),
            "knows"
        );
        assert_eq!(
            SparqlCompiler::iri_to_name("http://xmlns.com/foaf/0.1#Person"),
            "Person"
        );
        assert_eq!(SparqlCompiler::iri_to_name("simple"), "simple");
    }
}