sarif_rust 0.3.0

A comprehensive Rust library for parsing, generating, and manipulating SARIF (Static Analysis Results Interchange Format) v2.1.0 files
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
//! Query and filtering API for SARIF data
//!
//! This module provides a comprehensive query interface for SARIF logs,
//! allowing users to filter, search, and aggregate SARIF data efficiently.

use crate::parser::{SarifError, SarifResult as ParseResult};
use crate::types::{Level, ReportingDescriptor, Result as SarifResult, Run, SarifLog};
use crate::utils::indexing::{ResultLocation, SarifIndex};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::time::Instant;

/// Query builder for SARIF data
#[derive(Debug, Clone)]
pub struct SarifQuery {
    /// Tool name filters
    pub tool_filters: ToolFilters,

    /// Rule filters
    pub rule_filters: RuleFilters,

    /// Result filters
    pub result_filters: ResultFilters,

    /// Location filters
    pub location_filters: LocationFilters,

    /// Text search filters
    pub text_filters: TextFilters,

    /// Aggregation settings
    pub aggregation: AggregationSettings,

    /// Result ordering
    pub ordering: ResultOrdering,

    /// Pagination settings
    pub pagination: PaginationSettings,
}

/// Tool-specific filters
#[derive(Debug, Clone)]
pub struct ToolFilters {
    /// Include only these tool names
    pub include_tools: Option<HashSet<String>>,

    /// Exclude these tool names
    pub exclude_tools: HashSet<String>,

    /// Tool version patterns
    pub version_patterns: Vec<String>,

    /// Tool organization filters
    pub organizations: Option<HashSet<String>>,
}

/// Rule-specific filters
#[derive(Debug, Clone)]
pub struct RuleFilters {
    /// Include only these rule IDs
    pub include_rules: Option<HashSet<String>>,

    /// Exclude these rule IDs
    pub exclude_rules: HashSet<String>,

    /// Rule categories
    pub categories: Option<HashSet<String>>,

    /// Rule tags
    pub tags: Option<HashSet<String>>,

    /// Default configuration levels
    pub config_levels: Option<HashSet<String>>,
}

/// Result-specific filters
#[derive(Debug, Clone)]
pub struct ResultFilters {
    /// Include only these levels
    pub levels: Option<HashSet<Level>>,

    /// Minimum level (inclusive)
    pub min_level: Option<Level>,

    /// Result kinds
    pub kinds: Option<HashSet<String>>,

    /// Has fixes available
    pub has_fixes: Option<bool>,

    /// Result GUIDs
    pub guids: Option<HashSet<String>>,

    /// Result correlation GUIDs
    pub correlation_guids: Option<HashSet<String>>,
}

/// Location-specific filters
#[derive(Debug, Clone)]
pub struct LocationFilters {
    /// File path patterns (glob-style)
    pub file_patterns: Vec<String>,

    /// Exclude file patterns
    pub exclude_file_patterns: Vec<String>,

    /// Line range filters
    pub line_ranges: Vec<LineRange>,

    /// Logical locations
    pub logical_locations: Option<HashSet<String>>,

    /// URI schemes
    pub uri_schemes: Option<HashSet<String>>,
}

/// Line range specification
#[derive(Debug, Clone)]
pub struct LineRange {
    /// Start line (inclusive)
    pub start: u32,

    /// End line (inclusive, None means unbounded)
    pub end: Option<u32>,

    /// File pattern this range applies to
    pub file_pattern: Option<String>,
}

/// Text search filters
#[derive(Debug, Clone)]
pub struct TextFilters {
    /// Message text search
    pub message_text: Option<TextSearch>,

    /// Rule description search
    pub rule_description: Option<TextSearch>,

    /// File content search
    pub file_content: Option<TextSearch>,

    /// Snippet content search
    pub snippet_content: Option<TextSearch>,
}

/// Text search configuration
#[derive(Debug, Clone)]
pub struct TextSearch {
    /// Search pattern
    pub pattern: String,

    /// Case sensitive search
    pub case_sensitive: bool,

    /// Use regex pattern
    pub use_regex: bool,

    /// Match whole words only
    pub whole_words: bool,
}

/// Aggregation settings
#[derive(Debug, Clone)]
pub struct AggregationSettings {
    /// Group by fields
    pub group_by: Vec<GroupByField>,

    /// Count settings
    pub counts: CountSettings,

    /// Include statistics
    pub include_stats: bool,
}

/// Fields to group results by
#[derive(Debug, Clone, PartialEq)]
pub enum GroupByField {
    Tool,
    Rule,
    Level,
    File,
    Category,
    Tag,
}

/// Count configuration
#[derive(Debug, Clone)]
pub struct CountSettings {
    /// Include result counts
    pub results: bool,

    /// Include file counts
    pub files: bool,

    /// Include tool counts
    pub tools: bool,

    /// Include rule counts
    pub rules: bool,
}

/// Result ordering specification
#[derive(Debug, Clone)]
pub struct ResultOrdering {
    /// Primary sort field
    pub primary: OrderField,

    /// Secondary sort fields
    pub secondary: Vec<OrderField>,
}

/// Ordering field specification
#[derive(Debug, Clone)]
pub struct OrderField {
    /// Field to sort by
    pub field: SortField,

    /// Sort direction
    pub direction: SortDirection,
}

/// Fields that can be sorted by
#[derive(Debug, Clone, PartialEq)]
pub enum SortField {
    Tool,
    Rule,
    Level,
    File,
    Line,
    Column,
    Message,
    Timestamp,
}

/// Sort direction
#[derive(Debug, Clone, PartialEq)]
pub enum SortDirection {
    Ascending,
    Descending,
}

/// Pagination settings
#[derive(Debug, Clone)]
pub struct PaginationSettings {
    /// Page number (0-based)
    pub page: usize,

    /// Page size (number of results per page)
    pub page_size: usize,

    /// Maximum total results to process
    pub max_results: Option<usize>,
}

/// Query execution results
#[derive(Debug, Clone)]
pub struct QueryResults {
    /// Matching results with their locations
    pub results: Vec<(SarifResult, ResultLocation)>,

    /// Aggregated data
    pub aggregations: QueryAggregations,

    /// Query execution statistics
    pub stats: QueryStats,

    /// Total number of results (before pagination)
    pub total_count: usize,

    /// Whether there are more results available
    pub has_more: bool,
}

/// Aggregated query results
#[derive(Debug, Clone)]
pub struct QueryAggregations {
    /// Results grouped by specified fields
    pub groups: HashMap<String, GroupedResults>,

    /// Count summaries
    pub counts: CountSummary,

    /// Level distribution
    pub level_distribution: HashMap<Level, usize>,

    /// Tool distribution
    pub tool_distribution: HashMap<String, usize>,

    /// File distribution
    pub file_distribution: HashMap<String, usize>,
}

/// Results grouped by a specific key
#[derive(Debug, Clone)]
pub struct GroupedResults {
    /// Group key
    pub key: String,

    /// Results in this group
    pub results: Vec<(SarifResult, ResultLocation)>,

    /// Count of results in this group
    pub count: usize,
}

/// Count summary
#[derive(Debug, Clone)]
pub struct CountSummary {
    /// Total results
    pub total_results: usize,

    /// Unique files
    pub unique_files: usize,

    /// Unique tools
    pub unique_tools: usize,

    /// Unique rules
    pub unique_rules: usize,
}

/// Query execution statistics
#[derive(Debug, Clone)]
pub struct QueryStats {
    /// Query execution time
    pub execution_time: std::time::Duration,

    /// Number of results evaluated
    pub results_evaluated: usize,

    /// Number of results matched
    pub results_matched: usize,

    /// Index lookup time
    pub index_lookup_time: std::time::Duration,

    /// Filtering time
    pub filtering_time: std::time::Duration,

    /// Aggregation time
    pub aggregation_time: std::time::Duration,
}

/// SARIF query executor
pub struct SarifQueryExecutor {
    /// SARIF index for fast lookups
    index: SarifIndex,

    /// Original SARIF log for detailed access
    log: SarifLog,
}

impl SarifQueryExecutor {
    /// Create a new query executor with a SARIF log
    pub fn new(log: SarifLog) -> ParseResult<Self> {
        let index = SarifIndex::from_sarif_log(&log);
        Ok(Self { index, log })
    }

    /// Create query executor from an existing index and log
    pub fn from_index(index: SarifIndex, log: SarifLog) -> Self {
        Self { index, log }
    }

    /// Execute a query against the SARIF data
    pub fn execute(&self, query: &SarifQuery) -> ParseResult<QueryResults> {
        let start_time = Instant::now();
        let mut stats = QueryStats {
            execution_time: std::time::Duration::ZERO,
            results_evaluated: 0,
            results_matched: 0,
            index_lookup_time: std::time::Duration::ZERO,
            filtering_time: std::time::Duration::ZERO,
            aggregation_time: std::time::Duration::ZERO,
        };

        // Step 1: Get candidate results from index
        let index_start = Instant::now();
        let candidates = self.get_candidates(query)?;
        stats.index_lookup_time = index_start.elapsed();
        stats.results_evaluated = candidates.len();

        // Step 2: Apply filters
        let filter_start = Instant::now();
        let filtered_results = self.apply_filters(&candidates, query)?;
        stats.filtering_time = filter_start.elapsed();
        stats.results_matched = filtered_results.len();

        // Step 3: Apply ordering
        let ordered_results = self.apply_ordering(filtered_results, query);

        // Step 4: Apply pagination
        let total_count = ordered_results.len();
        let (paginated_results, has_more) = self.apply_pagination(ordered_results, query);

        // Step 5: Generate aggregations
        let agg_start = Instant::now();
        let aggregations = if query.aggregation.include_stats {
            self.generate_aggregations(&paginated_results, query)?
        } else {
            QueryAggregations::empty()
        };
        stats.aggregation_time = agg_start.elapsed();

        stats.execution_time = start_time.elapsed();

        Ok(QueryResults {
            results: paginated_results,
            aggregations,
            stats,
            total_count,
            has_more,
        })
    }

    /// Get candidate results from the index
    fn get_candidates(
        &self,
        query: &SarifQuery,
    ) -> ParseResult<Vec<(SarifResult, ResultLocation)>> {
        let mut candidates = Vec::new();

        // Start with all results if no specific filters
        if query.tool_filters.include_tools.is_none()
            && query.rule_filters.include_rules.is_none()
            && query.result_filters.guids.is_none()
        {
            // Get all results
            for (result, location) in self.index.results.values() {
                candidates.push((result.clone(), location.clone()));
            }
        } else {
            // Use index to get specific subsets
            if let Some(ref tool_names) = query.tool_filters.include_tools {
                for tool_name in tool_names {
                    if let Some(run_indices) = self.index.tool_to_runs.get(tool_name) {
                        for &run_index in run_indices {
                            if let Some(run) = self.log.runs.get(run_index)
                                && let Some(ref results) = run.results
                            {
                                for (result_index, result) in results.iter().enumerate() {
                                    let location = ResultLocation {
                                        run_index,
                                        result_index,
                                        guid: result.guid.clone(),
                                        rule_id: result.rule_id.clone(),
                                        primary_artifact_uri: None,
                                    };
                                    candidates.push((result.clone(), location));
                                }
                            }
                        }
                    }
                }
            }

            if let Some(ref rule_ids) = query.rule_filters.include_rules {
                for rule_id in rule_ids {
                    if let Some(result_guids) = self.index.rule_to_results.get(rule_id) {
                        for result_guid in result_guids {
                            if let Some((result, location)) = self.index.results.get(result_guid) {
                                candidates.push((result.clone(), location.clone()));
                            }
                        }
                    }
                }
            }

            if let Some(ref guids) = query.result_filters.guids {
                for guid in guids {
                    if let Some((result, location)) = self.index.results.get(guid) {
                        candidates.push((result.clone(), location.clone()));
                    }
                }
            }
        }

        // Remove duplicates
        candidates.sort_by(|a, b| {
            a.1.run_index
                .cmp(&b.1.run_index)
                .then_with(|| a.1.result_index.cmp(&b.1.result_index))
        });
        candidates.dedup_by(|a, b| {
            a.1.run_index == b.1.run_index && a.1.result_index == b.1.result_index
        });

        Ok(candidates)
    }

    /// Apply all filters to candidate results
    fn apply_filters(
        &self,
        candidates: &[(SarifResult, ResultLocation)],
        query: &SarifQuery,
    ) -> ParseResult<Vec<(SarifResult, ResultLocation)>> {
        let mut filtered = Vec::new();

        for (result, location) in candidates {
            if self.matches_filters(result, location, query)? {
                filtered.push((result.clone(), location.clone()));
            }
        }

        Ok(filtered)
    }

    /// Check if a result matches all query filters
    fn matches_filters(
        &self,
        result: &SarifResult,
        location: &ResultLocation,
        query: &SarifQuery,
    ) -> ParseResult<bool> {
        // Get the run for context
        let run = &self.log.runs[location.run_index];

        // Tool filters
        if !self.matches_tool_filters(&run, &query.tool_filters) {
            return Ok(false);
        }

        // Rule filters
        if !self.matches_rule_filters(result, &run, &query.rule_filters)? {
            return Ok(false);
        }

        // Result filters
        if !self.matches_result_filters(result, &query.result_filters) {
            return Ok(false);
        }

        // Location filters
        if !self.matches_location_filters(result, &query.location_filters)? {
            return Ok(false);
        }

        // Text filters
        if !self.matches_text_filters(result, &run, &query.text_filters)? {
            return Ok(false);
        }

        Ok(true)
    }

    /// Check tool filters
    fn matches_tool_filters(&self, run: &Run, filters: &ToolFilters) -> bool {
        let tool_name = &run.tool.driver.name;

        // Include tool filter
        if let Some(ref include_tools) = filters.include_tools
            && !include_tools.contains(tool_name)
        {
            return false;
        }

        // Exclude tool filter
        if filters.exclude_tools.contains(tool_name) {
            return false;
        }

        // Version pattern filter
        if !filters.version_patterns.is_empty() {
            if let Some(ref version) = run.tool.driver.version {
                let matches_version = filters.version_patterns.iter().any(|pattern| {
                    if let Ok(regex) = Regex::new(pattern) {
                        regex.is_match(version)
                    } else {
                        version.contains(pattern)
                    }
                });
                if !matches_version {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Organization filter
        if let Some(ref organizations) = filters.organizations {
            if let Some(ref organization) = run.tool.driver.organization {
                if !organizations.contains(organization) {
                    return false;
                }
            } else {
                return false;
            }
        }

        true
    }

    /// Check rule filters
    fn matches_rule_filters(
        &self,
        result: &SarifResult,
        run: &Run,
        filters: &RuleFilters,
    ) -> ParseResult<bool> {
        // Rule ID filters
        if let Some(ref rule_id) = result.rule_id {
            if let Some(ref include_rules) = filters.include_rules
                && !include_rules.contains(rule_id)
            {
                return Ok(false);
            }

            if filters.exclude_rules.contains(rule_id) {
                return Ok(false);
            }

            // Get rule metadata for additional filters
            let rule_metadata = self.get_rule_metadata(rule_id, run);

            // Category filter
            if let Some(ref categories) = filters.categories {
                if let Some(ref rule) = rule_metadata
                    && let Some(ref props) = rule.properties
                    && let Some(category) = props.get("category")
                    && let Some(category_str) = category.as_str()
                    && !categories.contains(category_str)
                {
                    return Ok(false);
                } else if rule_metadata.is_none() {
                    return Ok(false);
                }
            }

            // Tag filter
            if let Some(ref tags) = filters.tags {
                if let Some(ref rule) = rule_metadata
                    && let Some(ref rule_tags) = rule.properties
                    && let Some(tag_array) = rule_tags.get("tags")
                    && let Some(tag_vec) = tag_array.as_array()
                {
                    let rule_tag_strings: HashSet<String> = tag_vec
                        .iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect();
                    if !tags.intersection(&rule_tag_strings).any(|_| true) {
                        return Ok(false);
                    }
                } else if rule_metadata.is_none() {
                    return Ok(false);
                }
            }
        }

        Ok(true)
    }

    /// Check result filters
    fn matches_result_filters(&self, result: &SarifResult, filters: &ResultFilters) -> bool {
        // Level filters
        if let Some(ref levels) = filters.levels {
            if let Some(ref level) = result.level {
                if !levels.contains(level) {
                    return false;
                }
            } else {
                // Default level is Warning
                if !levels.contains(&Level::Warning) {
                    return false;
                }
            }
        }

        // Minimum level filter
        if let Some(ref min_level) = filters.min_level {
            let result_level = result.level.as_ref().unwrap_or(&Level::Warning);
            if !self.is_level_at_least(result_level, min_level) {
                return false;
            }
        }

        // Kind filter
        if let Some(ref kinds) = filters.kinds
            && let Some(ref kind) = result.kind
            && !kinds.contains(&kind.to_string())
        {
            return false;
        }

        // Has fixes filter
        if let Some(has_fixes) = filters.has_fixes {
            let result_has_fixes =
                result.fixes.is_some() && !result.fixes.as_ref().unwrap().is_empty();
            if has_fixes != result_has_fixes {
                return false;
            }
        }

        // GUID filter
        if let Some(ref guids) = filters.guids {
            if let Some(ref guid) = result.guid {
                if !guids.contains(guid) {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Correlation GUID filter
        if let Some(ref correlation_guids) = filters.correlation_guids {
            if let Some(ref correlation_guid) = result.correlation_guid {
                if !correlation_guids.contains(correlation_guid) {
                    return false;
                }
            } else {
                return false;
            }
        }

        true
    }

    /// Check location filters
    fn matches_location_filters(
        &self,
        result: &SarifResult,
        filters: &LocationFilters,
    ) -> ParseResult<bool> {
        if let Some(ref locations) = result.locations {
            for location in locations {
                if let Some(ref physical_location) = location.physical_location {
                    // File pattern filters
                    if let Some(ref artifact_location) = physical_location.artifact_location
                        && let Some(ref uri) = artifact_location.uri
                    {
                        // Include patterns
                        if !filters.file_patterns.is_empty() {
                            let matches_include = filters
                                .file_patterns
                                .iter()
                                .any(|pattern| self.matches_glob_pattern(uri, pattern));
                            if !matches_include {
                                continue;
                            }
                        }

                        // Exclude patterns
                        if filters
                            .exclude_file_patterns
                            .iter()
                            .any(|pattern| self.matches_glob_pattern(uri, pattern))
                        {
                            continue;
                        }

                        // Line range filters
                        if !filters.line_ranges.is_empty()
                            && let Some(ref region) = physical_location.region
                            && let Some(start_line) = region.start_line
                        {
                            let matches_line_range = filters.line_ranges.iter().any(|range| {
                                if let Some(ref file_pattern) = range.file_pattern
                                    && !self.matches_glob_pattern(uri, file_pattern)
                                {
                                    return false;
                                }
                                let line = start_line as u32;
                                line >= range.start && range.end.map_or(true, |end| line <= end)
                            });
                            if !matches_line_range {
                                continue;
                            }
                        }

                        return Ok(true);
                    }
                }

                // Logical location filters
                if let Some(ref logical_locations) = location.logical_locations {
                    for logical_location in logical_locations {
                        if let Some(ref filter_logical_locations) = filters.logical_locations {
                            if let Some(ref name) = logical_location.name
                                && filter_logical_locations.contains(name)
                            {
                                return Ok(true);
                            }
                            if let Some(ref fully_qualified_name) =
                                logical_location.fully_qualified_name
                                && filter_logical_locations.contains(fully_qualified_name)
                            {
                                return Ok(true);
                            }
                        }
                    }
                }
            }

            // If we have location filters but no locations matched, exclude
            if !filters.file_patterns.is_empty()
                || !filters.exclude_file_patterns.is_empty()
                || !filters.line_ranges.is_empty()
                || filters.logical_locations.is_some()
            {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Check text filters
    fn matches_text_filters(
        &self,
        result: &SarifResult,
        run: &Run,
        filters: &TextFilters,
    ) -> ParseResult<bool> {
        // Message text search
        if let Some(ref message_search) = filters.message_text {
            if let Some(ref text) = result.message.text {
                if !self.matches_text_search(text, message_search)? {
                    return Ok(false);
                }
            } else {
                return Ok(false);
            }
        }

        // Rule description search
        if let Some(ref rule_description_search) = filters.rule_description {
            if let Some(ref rule_id) = result.rule_id {
                if let Some(rule) = self.get_rule_metadata(rule_id, run) {
                    if let Some(ref short_description) = rule.short_description {
                        if !self
                            .matches_text_search(&short_description.text, rule_description_search)?
                        {
                            return Ok(false);
                        }
                    } else {
                        return Ok(false);
                    }
                } else {
                    return Ok(false);
                }
            } else {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Apply ordering to results
    fn apply_ordering(
        &self,
        mut results: Vec<(SarifResult, ResultLocation)>,
        query: &SarifQuery,
    ) -> Vec<(SarifResult, ResultLocation)> {
        results.sort_by(|a, b| {
            // Primary sort
            let primary_cmp =
                self.compare_by_field(&a.0, &a.1, &b.0, &b.1, &query.ordering.primary);
            if primary_cmp != std::cmp::Ordering::Equal {
                return primary_cmp;
            }

            // Secondary sorts
            for secondary in &query.ordering.secondary {
                let secondary_cmp = self.compare_by_field(&a.0, &a.1, &b.0, &b.1, secondary);
                if secondary_cmp != std::cmp::Ordering::Equal {
                    return secondary_cmp;
                }
            }

            std::cmp::Ordering::Equal
        });

        results
    }

    /// Apply pagination to results
    fn apply_pagination(
        &self,
        results: Vec<(SarifResult, ResultLocation)>,
        query: &SarifQuery,
    ) -> (Vec<(SarifResult, ResultLocation)>, bool) {
        let start_index = query.pagination.page * query.pagination.page_size;
        let end_index = start_index + query.pagination.page_size;

        // Apply max_results limit first
        let limited_results = if let Some(max) = query.pagination.max_results {
            results.into_iter().take(max).collect()
        } else {
            results
        };

        let total_len = limited_results.len();
        let has_more = end_index < total_len;

        let paginated = limited_results
            .into_iter()
            .skip(start_index)
            .take(query.pagination.page_size)
            .collect();

        (paginated, has_more)
    }

    /// Generate aggregations for the results
    fn generate_aggregations(
        &self,
        results: &[(SarifResult, ResultLocation)],
        query: &SarifQuery,
    ) -> ParseResult<QueryAggregations> {
        let mut groups = HashMap::new();
        let mut level_dist = HashMap::new();
        let mut tool_dist = HashMap::new();
        let mut file_dist = HashMap::new();
        let mut unique_files = HashSet::new();
        let mut unique_tools = HashSet::new();
        let mut unique_rules = HashSet::new();

        for (result, location) in results {
            let run = &self.log.runs[location.run_index];

            // Collect for grouping
            for group_field in &query.aggregation.group_by {
                let group_key = self.get_group_key(result, run, group_field);
                let group_entry =
                    groups
                        .entry(group_key.clone())
                        .or_insert_with(|| GroupedResults {
                            key: group_key,
                            results: Vec::new(),
                            count: 0,
                        });
                group_entry.results.push((result.clone(), location.clone()));
                group_entry.count += 1;
            }

            // Level distribution
            let level = result.level.as_ref().unwrap_or(&Level::Warning);
            *level_dist.entry(level.clone()).or_insert(0) += 1;

            // Tool distribution
            let tool_name = &run.tool.driver.name;
            *tool_dist.entry(tool_name.clone()).or_insert(0) += 1;
            unique_tools.insert(tool_name.clone());

            // File distribution
            if let Some(ref locations) = result.locations {
                for loc in locations {
                    if let Some(ref phys_loc) = loc.physical_location
                        && let Some(ref artifact_loc) = phys_loc.artifact_location
                        && let Some(ref uri) = artifact_loc.uri
                    {
                        *file_dist.entry(uri.clone()).or_insert(0) += 1;
                        unique_files.insert(uri.clone());
                    }
                }
            }

            // Rule tracking
            if let Some(ref rule_id) = result.rule_id {
                unique_rules.insert(rule_id.clone());
            }
        }

        let counts = CountSummary {
            total_results: results.len(),
            unique_files: unique_files.len(),
            unique_tools: unique_tools.len(),
            unique_rules: unique_rules.len(),
        };

        Ok(QueryAggregations {
            groups,
            counts,
            level_distribution: level_dist,
            tool_distribution: tool_dist,
            file_distribution: file_dist,
        })
    }

    // Helper methods

    fn get_rule_metadata(&self, rule_id: &str, _run: &Run) -> Option<&ReportingDescriptor> {
        self.index.rules.get(rule_id)
    }

    fn is_level_at_least(&self, level: &Level, min_level: &Level) -> bool {
        let level_value = match level {
            Level::None => 0,
            Level::Note => 1,
            Level::Warning => 2,
            Level::Error => 3,
        };

        let min_value = match min_level {
            Level::None => 0,
            Level::Note => 1,
            Level::Warning => 2,
            Level::Error => 3,
        };

        level_value >= min_value
    }

    fn matches_glob_pattern(&self, text: &str, pattern: &str) -> bool {
        // Simple glob matching (could be enhanced with a proper glob library)
        if pattern == "*" {
            return true;
        }

        if pattern.contains('*') {
            let parts: Vec<&str> = pattern.split('*').collect();
            if parts.len() == 2 {
                let prefix = parts[0];
                let suffix = parts[1];
                return text.starts_with(prefix) && text.ends_with(suffix);
            }
        }

        text == pattern
    }

    fn matches_text_search(&self, text: &str, search: &TextSearch) -> ParseResult<bool> {
        let search_text = if search.case_sensitive {
            text.to_string()
        } else {
            text.to_lowercase()
        };

        let pattern = if search.case_sensitive {
            search.pattern.clone()
        } else {
            search.pattern.to_lowercase()
        };

        if search.use_regex {
            let regex = Regex::new(&pattern)
                .map_err(|e| SarifError::custom(format!("Invalid regex pattern: {}", e)))?;
            Ok(regex.is_match(&search_text))
        } else if search.whole_words {
            // Simple word boundary matching
            let words: Vec<&str> = search_text.split_whitespace().collect();
            Ok(words.contains(&pattern.as_str()))
        } else {
            Ok(search_text.contains(&pattern))
        }
    }

    fn compare_by_field(
        &self,
        a_result: &SarifResult,
        a_location: &ResultLocation,
        b_result: &SarifResult,
        b_location: &ResultLocation,
        order: &OrderField,
    ) -> std::cmp::Ordering {

        let comparison = match order.field {
            SortField::Tool => {
                let a_tool = &self.log.runs[a_location.run_index].tool.driver.name;
                let b_tool = &self.log.runs[b_location.run_index].tool.driver.name;
                a_tool.cmp(b_tool)
            }
            SortField::Rule => {
                let a_rule = a_result.rule_id.as_deref().unwrap_or("");
                let b_rule = b_result.rule_id.as_deref().unwrap_or("");
                a_rule.cmp(b_rule)
            }
            SortField::Level => {
                let a_level = a_result.level.as_ref().unwrap_or(&Level::Warning);
                let b_level = b_result.level.as_ref().unwrap_or(&Level::Warning);
                a_level.cmp(b_level)
            }
            SortField::File => {
                let a_file = self.get_file_path(a_result);
                let b_file = self.get_file_path(b_result);
                a_file.cmp(&b_file)
            }
            SortField::Line => {
                let a_line = self.get_line_number(a_result);
                let b_line = self.get_line_number(b_result);
                a_line.cmp(&b_line)
            }
            SortField::Column => {
                let a_col = self.get_column_number(a_result);
                let b_col = self.get_column_number(b_result);
                a_col.cmp(&b_col)
            }
            SortField::Message => {
                let a_msg = a_result.message.text.as_deref().unwrap_or("");
                let b_msg = b_result.message.text.as_deref().unwrap_or("");
                a_msg.cmp(b_msg)
            }
            SortField::Timestamp => {
                // Use result index as timestamp proxy
                a_location.result_index.cmp(&b_location.result_index)
            }
        };

        match order.direction {
            SortDirection::Ascending => comparison,
            SortDirection::Descending => comparison.reverse(),
        }
    }

    fn get_group_key(&self, result: &SarifResult, run: &Run, field: &GroupByField) -> String {
        match field {
            GroupByField::Tool => run.tool.driver.name.clone(),
            GroupByField::Rule => result.rule_id.as_deref().unwrap_or("unknown").to_string(),
            GroupByField::Level => {
                format!("{:?}", result.level.as_ref().unwrap_or(&Level::Warning))
            }
            GroupByField::File => self.get_file_path(result),
            GroupByField::Category => {
                if let Some(ref rule_id) = result.rule_id
                    && let Some(rule) = self.get_rule_metadata(rule_id, run)
                    && let Some(ref props) = rule.properties
                    && let Some(category) = props.get("category")
                    && let Some(cat_str) = category.as_str()
                {
                    return cat_str.to_string();
                }
                "unknown".to_string()
            }
            GroupByField::Tag => {
                if let Some(ref rule_id) = result.rule_id
                    && let Some(rule) = self.get_rule_metadata(rule_id, run)
                    && let Some(ref props) = rule.properties
                    && let Some(tags) = props.get("tags")
                    && let Some(tag_array) = tags.as_array()
                    && let Some(first_tag) = tag_array.first()
                    && let Some(tag_str) = first_tag.as_str()
                {
                    return tag_str.to_string();
                }
                "unknown".to_string()
            }
        }
    }

    fn get_file_path(&self, result: &SarifResult) -> String {
        if let Some(ref locations) = result.locations {
            for location in locations {
                if let Some(ref physical_location) = location.physical_location
                    && let Some(ref artifact_location) = physical_location.artifact_location
                    && let Some(ref uri) = artifact_location.uri
                {
                    return uri.clone();
                }
            }
        }
        "unknown".to_string()
    }

    fn get_line_number(&self, result: &SarifResult) -> i32 {
        if let Some(ref locations) = result.locations {
            for location in locations {
                if let Some(ref physical_location) = location.physical_location
                    && let Some(ref region) = physical_location.region
                    && let Some(line) = region.start_line
                {
                    return line;
                }
            }
        }
        0
    }

    fn get_column_number(&self, result: &SarifResult) -> i32 {
        if let Some(ref locations) = result.locations {
            for location in locations {
                if let Some(ref physical_location) = location.physical_location
                    && let Some(ref region) = physical_location.region
                    && let Some(column) = region.start_column
                {
                    return column;
                }
            }
        }
        0
    }
}

impl QueryAggregations {
    fn empty() -> Self {
        Self {
            groups: HashMap::new(),
            counts: CountSummary {
                total_results: 0,
                unique_files: 0,
                unique_tools: 0,
                unique_rules: 0,
            },
            level_distribution: HashMap::new(),
            tool_distribution: HashMap::new(),
            file_distribution: HashMap::new(),
        }
    }
}

// Default implementations

impl Default for SarifQuery {
    fn default() -> Self {
        Self {
            tool_filters: ToolFilters::default(),
            rule_filters: RuleFilters::default(),
            result_filters: ResultFilters::default(),
            location_filters: LocationFilters::default(),
            text_filters: TextFilters::default(),
            aggregation: AggregationSettings::default(),
            ordering: ResultOrdering::default(),
            pagination: PaginationSettings::default(),
        }
    }
}

impl Default for ToolFilters {
    fn default() -> Self {
        Self {
            include_tools: None,
            exclude_tools: HashSet::new(),
            version_patterns: Vec::new(),
            organizations: None,
        }
    }
}

impl Default for RuleFilters {
    fn default() -> Self {
        Self {
            include_rules: None,
            exclude_rules: HashSet::new(),
            categories: None,
            tags: None,
            config_levels: None,
        }
    }
}

impl Default for ResultFilters {
    fn default() -> Self {
        Self {
            levels: None,
            min_level: None,
            kinds: None,
            has_fixes: None,
            guids: None,
            correlation_guids: None,
        }
    }
}

impl Default for LocationFilters {
    fn default() -> Self {
        Self {
            file_patterns: Vec::new(),
            exclude_file_patterns: Vec::new(),
            line_ranges: Vec::new(),
            logical_locations: None,
            uri_schemes: None,
        }
    }
}

impl Default for TextFilters {
    fn default() -> Self {
        Self {
            message_text: None,
            rule_description: None,
            file_content: None,
            snippet_content: None,
        }
    }
}

impl Default for AggregationSettings {
    fn default() -> Self {
        Self {
            group_by: Vec::new(),
            counts: CountSettings {
                results: true,
                files: true,
                tools: true,
                rules: true,
            },
            include_stats: false,
        }
    }
}

impl Default for ResultOrdering {
    fn default() -> Self {
        Self {
            primary: OrderField {
                field: SortField::File,
                direction: SortDirection::Ascending,
            },
            secondary: vec![
                OrderField {
                    field: SortField::Line,
                    direction: SortDirection::Ascending,
                },
                OrderField {
                    field: SortField::Column,
                    direction: SortDirection::Ascending,
                },
            ],
        }
    }
}

impl Default for PaginationSettings {
    fn default() -> Self {
        Self {
            page: 0,
            page_size: 100,
            max_results: None,
        }
    }
}

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

    #[test]
    fn test_basic_query() {
        let log = SarifLogBuilder::single_error("test-tool", "Test error", "test.rs", 10)
            .build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();
        let query = SarifQuery::default();

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.total_count, 1);
        assert_eq!(results.results.len(), 1);
        assert!(!results.has_more);
    }

    #[test]
    fn test_tool_filter() {
        let log1 =
            SarifLogBuilder::single_error("tool1", "Error 1", "file1.rs", 10).build_unchecked();
        let log2 =
            SarifLogBuilder::single_error("tool2", "Error 2", "file2.rs", 20).build_unchecked();

        // Merge logs for testing
        let merged_log = SarifLogBuilder::new()
            .add_run(log1.runs.into_iter().next().unwrap())
            .add_run(log2.runs.into_iter().next().unwrap())
            .build_unchecked();

        let executor = SarifQueryExecutor::new(merged_log).unwrap();

        let mut include_tools = HashSet::new();
        include_tools.insert("tool1".to_string());

        let query = SarifQuery {
            tool_filters: ToolFilters {
                include_tools: Some(include_tools),
                ..Default::default()
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.total_count, 1);
        assert_eq!(
            results.results[0].0.message.text,
            Some("Error 1".to_string())
        );
    }

    #[test]
    fn test_level_filter() {
        let log = SarifLogBuilder::single_warning("test-tool", "Warning", "test.rs", 10)
            .build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();

        let mut levels = HashSet::new();
        levels.insert(Level::Error);

        let query = SarifQuery {
            result_filters: ResultFilters {
                levels: Some(levels),
                ..Default::default()
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.total_count, 0);
    }

    #[test]
    fn test_file_pattern_filter() {
        let log = SarifLogBuilder::single_error("test-tool", "Error", "src/main.rs", 10)
            .build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();

        let query = SarifQuery {
            location_filters: LocationFilters {
                file_patterns: vec!["src/*".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.total_count, 1);
    }

    #[test]
    fn test_pagination() {
        let log = SarifLogBuilder::new()
            .add_simple_run("tool", None::<String>)
            .build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();

        let query = SarifQuery {
            pagination: PaginationSettings {
                page: 0,
                page_size: 50,
                max_results: Some(100),
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.results.len(), 0); // Empty run
        assert!(!results.has_more);
    }

    #[test]
    fn test_aggregation() {
        let log =
            SarifLogBuilder::single_error("test-tool", "Error", "test.rs", 10).build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();

        let query = SarifQuery {
            aggregation: AggregationSettings {
                group_by: vec![GroupByField::Tool, GroupByField::Level],
                include_stats: true,
                ..Default::default()
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.aggregations.counts.total_results, 1);
        assert_eq!(results.aggregations.counts.unique_tools, 1);
        assert!(
            results
                .aggregations
                .tool_distribution
                .contains_key("test-tool")
        );
    }

    #[test]
    fn test_text_search() {
        let log = SarifLogBuilder::single_error("test-tool", "Memory leak detected", "test.rs", 10)
            .build_unchecked();

        let executor = SarifQueryExecutor::new(log).unwrap();

        let query = SarifQuery {
            text_filters: TextFilters {
                message_text: Some(TextSearch {
                    pattern: "memory".to_string(),
                    case_sensitive: false,
                    use_regex: false,
                    whole_words: false,
                }),
                ..Default::default()
            },
            ..Default::default()
        };

        let results = executor.execute(&query).unwrap();

        assert_eq!(results.total_count, 1);
    }
}