sklears-core 0.1.1

Core traits, types, and utilities for sklears machine learning library
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
/// Code coverage reporting and enforcement system for sklears
///
/// This module provides comprehensive code coverage analysis, reporting, and enforcement
/// to ensure high-quality testing across the sklears ecosystem. It supports:
///
/// - **Coverage Collection**: Integration with multiple coverage tools (llvm-cov, tarpaulin)
/// - **Coverage Analysis**: Detailed analysis of coverage by module, function, and line
/// - **Coverage Reporting**: Multiple output formats (HTML, JSON, XML, text)
/// - **Coverage Enforcement**: Configurable thresholds and quality gates
/// - **Differential Coverage**: Coverage analysis for changes/PRs only
/// - **CI/CD Integration**: Seamless integration with continuous integration pipelines
///
/// # Key Features
///
/// ## Coverage Metrics
/// - Line coverage: Percentage of executed lines
/// - Branch coverage: Percentage of executed conditional branches
/// - Function coverage: Percentage of called functions
/// - Region coverage: LLVM's more granular coverage regions
///
/// ## Quality Gates
/// - Minimum coverage thresholds per module
/// - Coverage regression detection
/// - Untested critical code detection
/// - Coverage trend analysis
///
/// ## Reporting
/// - Interactive HTML reports with drill-down capability
/// - JSON/XML reports for CI/CD integration
/// - Badge generation for documentation
/// - Coverage history tracking
///
/// # Examples
///
/// ## Basic Coverage Analysis
///
/// ```rust,no_run
/// use sklears_core::code_coverage::{CoverageCollector, CoverageConfig};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = CoverageConfig::default()
///     .with_minimum_coverage(80.0);
///
/// let mut collector = CoverageCollector::new(config);
/// let report = collector.collect_and_analyze()?;
///
/// println!("Overall coverage: {:.1}%", report.overall_coverage());
///
/// if !report.meets_quality_gates() {
///     eprintln!("Coverage quality gates not met!");
///     std::process::exit(1);
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## CI/CD Integration
///
/// ```rust,no_run
/// use sklears_core::code_coverage::{CoverageCI, CIDConfig};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let ci_config = CIDConfig::default();
///
/// let ci = CoverageCI::new(ci_config);
/// let result = ci.run_coverage_check();
///
/// match result {
///     Ok(report) => {
///         println!("Coverage check passed: {:.1}%", report.coverage);
///     }
///     Err(failures) => {
///         eprintln!("Coverage failures:");
///         for failure in &failures {
///             eprintln!("  - {}", failure);
///         }
///         std::process::exit(1);
///     }
/// }
/// # Ok(())
/// # }
/// ```
use crate::error::{Result, SklearsError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

/// Main code coverage collector and analyzer
#[derive(Debug)]
pub struct CoverageCollector {
    config: CoverageConfig,
    collected_data: Option<RawCoverageData>,
}

/// Configuration for coverage collection and analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageConfig {
    /// Minimum overall coverage percentage required
    pub minimum_coverage: f64,
    /// Minimum coverage per module
    pub module_thresholds: HashMap<String, f64>,
    /// Output formats to generate
    pub output_formats: Vec<String>,
    /// Patterns to exclude from coverage
    pub exclude_patterns: Vec<String>,
    /// Include patterns (if empty, includes all)
    pub include_patterns: Vec<String>,
    /// Directory for coverage output
    pub output_directory: PathBuf,
    /// Coverage tool to use
    pub coverage_tool: CoverageTool,
    /// Whether to fail on coverage regression
    pub fail_on_regression: bool,
    /// Historical coverage data for regression detection
    pub baseline_coverage: Option<f64>,
}

impl Default for CoverageConfig {
    fn default() -> Self {
        Self {
            minimum_coverage: 80.0,
            module_thresholds: HashMap::new(),
            output_formats: vec!["html".to_string(), "json".to_string()],
            exclude_patterns: vec![
                "tests/*".to_string(),
                "benches/*".to_string(),
                "examples/*".to_string(),
            ],
            include_patterns: Vec::new(),
            output_directory: PathBuf::from("target/coverage"),
            coverage_tool: CoverageTool::LlvmCov,
            fail_on_regression: true,
            baseline_coverage: None,
        }
    }
}

impl CoverageConfig {
    /// Create a new coverage configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Set minimum overall coverage threshold
    pub fn with_minimum_coverage(mut self, threshold: f64) -> Self {
        self.minimum_coverage = threshold;
        self
    }

    /// Set output formats
    pub fn with_output_format(mut self, formats: Vec<&str>) -> Self {
        self.output_formats = formats.into_iter().map(String::from).collect();
        self
    }

    /// Set exclude patterns
    pub fn with_exclude_patterns(mut self, patterns: Vec<&str>) -> Self {
        self.exclude_patterns = patterns.into_iter().map(String::from).collect();
        self
    }

    /// Set module-specific coverage thresholds
    pub fn with_module_threshold(mut self, module: &str, threshold: f64) -> Self {
        self.module_thresholds.insert(module.to_string(), threshold);
        self
    }

    /// Set baseline coverage for regression detection
    pub fn with_baseline_coverage(mut self, baseline: f64) -> Self {
        self.baseline_coverage = Some(baseline);
        self
    }
}

/// Supported coverage tools
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CoverageTool {
    /// LLVM-based coverage (cargo llvm-cov)
    LlvmCov,
    /// Tarpaulin coverage tool
    Tarpaulin,
    /// Manual instrumentation
    Manual,
}

/// Raw coverage data collected from coverage tools
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawCoverageData {
    pub tool: String,
    pub timestamp: u64,
    pub files: Vec<FileCoverage>,
    pub summary: CoverageSummary,
}

/// Coverage data for a single file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileCoverage {
    pub path: String,
    pub functions: Vec<FunctionCoverage>,
    pub lines: Vec<LineCoverage>,
    pub branches: Vec<BranchCoverage>,
    pub summary: CoverageSummary,
}

/// Coverage data for a function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCoverage {
    pub name: String,
    pub line_start: u32,
    pub line_end: u32,
    pub execution_count: u64,
    pub covered: bool,
}

/// Coverage data for a line
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineCoverage {
    pub line_number: u32,
    pub execution_count: u64,
    pub covered: bool,
}

/// Coverage data for a branch
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchCoverage {
    pub line_number: u32,
    pub branch_id: u32,
    pub taken_count: u64,
    pub total_count: u64,
    pub covered: bool,
}

/// Coverage summary statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageSummary {
    pub lines_covered: u32,
    pub lines_total: u32,
    pub functions_covered: u32,
    pub functions_total: u32,
    pub branches_covered: u32,
    pub branches_total: u32,
}

impl CoverageSummary {
    /// Calculate line coverage percentage
    pub fn line_coverage(&self) -> f64 {
        if self.lines_total == 0 {
            100.0
        } else {
            (self.lines_covered as f64 / self.lines_total as f64) * 100.0
        }
    }

    /// Calculate function coverage percentage
    pub fn function_coverage(&self) -> f64 {
        if self.functions_total == 0 {
            100.0
        } else {
            (self.functions_covered as f64 / self.functions_total as f64) * 100.0
        }
    }

    /// Calculate branch coverage percentage
    pub fn branch_coverage(&self) -> f64 {
        if self.branches_total == 0 {
            100.0
        } else {
            (self.branches_covered as f64 / self.branches_total as f64) * 100.0
        }
    }
}

/// Comprehensive coverage analysis report
#[derive(Debug, Serialize, Deserialize)]
pub struct CoverageReport {
    pub timestamp: u64,
    pub config: CoverageConfig,
    pub overall_summary: CoverageSummary,
    pub module_summaries: HashMap<String, CoverageSummary>,
    pub quality_gates: QualityGatesResult,
    pub recommendations: Vec<CoverageRecommendation>,
    pub trends: Option<CoverageTrends>,
}

impl CoverageReport {
    /// Get overall coverage percentage
    pub fn overall_coverage(&self) -> f64 {
        self.overall_summary.line_coverage()
    }

    /// Check if all quality gates are met
    pub fn meets_quality_gates(&self) -> bool {
        self.quality_gates.passed
    }

    /// Generate a human-readable summary
    pub fn summary(&self) -> String {
        format!(
            "Coverage Report Summary:\n\
            - Overall coverage: {:.1}%\n\
            - Lines covered: {}/{}\n\
            - Functions covered: {}/{}\n\
            - Branches covered: {}/{}\n\
            - Quality gates: {}\n\
            - Recommendations: {}",
            self.overall_coverage(),
            self.overall_summary.lines_covered,
            self.overall_summary.lines_total,
            self.overall_summary.functions_covered,
            self.overall_summary.functions_total,
            self.overall_summary.branches_covered,
            self.overall_summary.branches_total,
            if self.quality_gates.passed {
                "PASSED"
            } else {
                "FAILED"
            },
            self.recommendations.len()
        )
    }
}

/// Quality gates evaluation result
#[derive(Debug, Serialize, Deserialize)]
pub struct QualityGatesResult {
    pub passed: bool,
    pub failures: Vec<QualityGateFailure>,
    pub warnings: Vec<QualityGateWarning>,
}

/// A quality gate failure
#[derive(Debug, Serialize, Deserialize)]
pub struct QualityGateFailure {
    pub rule: String,
    pub expected: f64,
    pub actual: f64,
    pub module: Option<String>,
}

/// A quality gate warning
#[derive(Debug, Serialize, Deserialize)]
pub struct QualityGateWarning {
    pub message: String,
    pub severity: WarningSeverity,
}

/// Warning severity levels
#[derive(Debug, Serialize, Deserialize)]
pub enum WarningSeverity {
    Info,
    Warning,
    Error,
}

/// Coverage improvement recommendations
#[derive(Debug, Serialize, Deserialize)]
pub struct CoverageRecommendation {
    pub priority: RecommendationPriority,
    pub category: RecommendationCategory,
    pub description: String,
    pub affected_files: Vec<String>,
    pub estimated_impact: f64, // Estimated coverage improvement
}

/// Recommendation priority levels
#[derive(Debug, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
pub enum RecommendationPriority {
    Critical,
    High,
    Medium,
    Low,
}

/// Recommendation categories
#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationCategory {
    UncoveredCriticalCode,
    MissingBranchTests,
    UncoveredErrorPaths,
    LowFunctionCoverage,
    TestGaps,
}

/// Coverage trends over time
#[derive(Debug, Serialize, Deserialize)]
pub struct CoverageTrends {
    pub historical_data: Vec<HistoricalCoveragePoint>,
    pub trend_direction: TrendDirection,
    pub trend_strength: f64, // 0.0 to 1.0
}

/// Historical coverage data point
#[derive(Debug, Serialize, Deserialize)]
pub struct HistoricalCoveragePoint {
    pub timestamp: u64,
    pub coverage: f64,
    pub commit_hash: Option<String>,
}

/// Coverage trend direction
#[derive(Debug, Serialize, Deserialize)]
pub enum TrendDirection {
    Improving,
    Stable,
    Declining,
}

impl CoverageCollector {
    /// Create a new coverage collector
    pub fn new(config: CoverageConfig) -> Self {
        Self {
            config,
            collected_data: None,
        }
    }

    /// Collect coverage data and generate analysis report
    pub fn collect_and_analyze(&mut self) -> Result<CoverageReport> {
        // Collect raw coverage data
        self.collect_coverage_data()?;

        // Analyze the collected data
        let report = self.analyze_coverage()?;

        // Generate output files
        self.generate_outputs(&report)?;

        Ok(report)
    }

    /// Collect raw coverage data using the configured tool
    fn collect_coverage_data(&mut self) -> Result<()> {
        let raw_data = match self.config.coverage_tool {
            CoverageTool::LlvmCov => self.collect_llvm_cov_data()?,
            CoverageTool::Tarpaulin => self.collect_tarpaulin_data()?,
            CoverageTool::Manual => self.collect_manual_data()?,
        };

        self.collected_data = Some(raw_data);
        Ok(())
    }

    /// Collect coverage data using llvm-cov
    fn collect_llvm_cov_data(&self) -> Result<RawCoverageData> {
        // Run cargo llvm-cov to collect coverage
        let output = Command::new("cargo")
            .args([
                "llvm-cov",
                "--json",
                "--output-path",
                &format!("{}/llvm-cov.json", self.config.output_directory.display()),
            ])
            .output()
            .map_err(|e| SklearsError::InvalidOperation(format!("Failed to run llvm-cov: {e}")))?;

        if !output.status.success() {
            return Err(SklearsError::InvalidOperation(format!(
                "llvm-cov failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        // For now, return simulated data
        Ok(self.simulate_coverage_data("llvm-cov"))
    }

    /// Collect coverage data using tarpaulin
    fn collect_tarpaulin_data(&self) -> Result<RawCoverageData> {
        let output = Command::new("cargo")
            .args([
                "tarpaulin",
                "--out",
                "Json",
                "--output-dir",
                &self.config.output_directory.to_string_lossy(),
            ])
            .output()
            .map_err(|e| SklearsError::InvalidOperation(format!("Failed to run tarpaulin: {e}")))?;

        if !output.status.success() {
            return Err(SklearsError::InvalidOperation(format!(
                "tarpaulin failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        // For now, return simulated data
        Ok(self.simulate_coverage_data("tarpaulin"))
    }

    /// Collect coverage data manually
    fn collect_manual_data(&self) -> Result<RawCoverageData> {
        // Manual coverage collection would analyze source files and test files
        Ok(self.simulate_coverage_data("manual"))
    }

    /// Simulate coverage data for demonstration
    fn simulate_coverage_data(&self, tool: &str) -> RawCoverageData {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("expected valid value")
            .as_secs();

        RawCoverageData {
            tool: tool.to_string(),
            timestamp,
            files: vec![FileCoverage {
                path: "src/lib.rs".to_string(),
                functions: vec![FunctionCoverage {
                    name: "example_function".to_string(),
                    line_start: 10,
                    line_end: 20,
                    execution_count: 5,
                    covered: true,
                }],
                lines: vec![
                    LineCoverage {
                        line_number: 15,
                        execution_count: 5,
                        covered: true,
                    },
                    LineCoverage {
                        line_number: 16,
                        execution_count: 0,
                        covered: false,
                    },
                ],
                branches: vec![BranchCoverage {
                    line_number: 17,
                    branch_id: 1,
                    taken_count: 3,
                    total_count: 5,
                    covered: true,
                }],
                summary: CoverageSummary {
                    lines_covered: 45,
                    lines_total: 50,
                    functions_covered: 8,
                    functions_total: 10,
                    branches_covered: 12,
                    branches_total: 15,
                },
            }],
            summary: CoverageSummary {
                lines_covered: 850,
                lines_total: 1000,
                functions_covered: 75,
                functions_total: 90,
                branches_covered: 120,
                branches_total: 150,
            },
        }
    }

    /// Analyze collected coverage data
    fn analyze_coverage(&self) -> Result<CoverageReport> {
        let data = self.collected_data.as_ref().ok_or_else(|| {
            SklearsError::InvalidOperation("No coverage data collected".to_string())
        })?;

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("expected valid value")
            .as_secs();

        // Analyze quality gates
        let quality_gates = self.evaluate_quality_gates(&data.summary);

        // Generate recommendations
        let recommendations = self.generate_recommendations(data);

        // Calculate module summaries
        let mut module_summaries = HashMap::new();
        for file in &data.files {
            let module_name = self.extract_module_name(&file.path);
            module_summaries.insert(module_name, file.summary.clone());
        }

        Ok(CoverageReport {
            timestamp,
            config: self.config.clone(),
            overall_summary: data.summary.clone(),
            module_summaries,
            quality_gates,
            recommendations,
            trends: None, // Would be populated with historical data
        })
    }

    /// Evaluate quality gates against coverage data
    fn evaluate_quality_gates(&self, summary: &CoverageSummary) -> QualityGatesResult {
        let mut failures = Vec::new();
        let mut warnings = Vec::new();

        // Check overall coverage threshold
        let overall_coverage = summary.line_coverage();
        if overall_coverage < self.config.minimum_coverage {
            failures.push(QualityGateFailure {
                rule: "Minimum overall coverage".to_string(),
                expected: self.config.minimum_coverage,
                actual: overall_coverage,
                module: None,
            });
        }

        // Check for coverage regression
        if let Some(baseline) = self.config.baseline_coverage {
            if overall_coverage < baseline - 1.0 {
                // Allow 1% tolerance
                failures.push(QualityGateFailure {
                    rule: "Coverage regression".to_string(),
                    expected: baseline,
                    actual: overall_coverage,
                    module: None,
                });
            }
        }

        // Check function coverage
        let function_coverage = summary.function_coverage();
        if function_coverage < 80.0 {
            warnings.push(QualityGateWarning {
                message: format!("Low function coverage: {function_coverage:.1}%"),
                severity: WarningSeverity::Warning,
            });
        }

        QualityGatesResult {
            passed: failures.is_empty(),
            failures,
            warnings,
        }
    }

    /// Generate coverage improvement recommendations
    fn generate_recommendations(&self, data: &RawCoverageData) -> Vec<CoverageRecommendation> {
        let mut recommendations = Vec::new();

        // Analyze uncovered lines
        for file in &data.files {
            let uncovered_lines: Vec<_> = file.lines.iter().filter(|line| !line.covered).collect();

            if !uncovered_lines.is_empty() {
                recommendations.push(CoverageRecommendation {
                    priority: RecommendationPriority::Medium,
                    category: RecommendationCategory::TestGaps,
                    description: format!(
                        "Add tests for {} uncovered lines in {}",
                        uncovered_lines.len(),
                        file.path
                    ),
                    affected_files: vec![file.path.clone()],
                    estimated_impact: (uncovered_lines.len() as f64 / file.lines.len() as f64)
                        * 100.0,
                });
            }
        }

        // Sort by priority and estimated impact
        recommendations.sort_by(|a, b| {
            a.priority.cmp(&b.priority).then_with(|| {
                b.estimated_impact
                    .partial_cmp(&a.estimated_impact)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
        });

        recommendations
    }

    /// Extract module name from file path
    fn extract_module_name(&self, path: &str) -> String {
        if let Some(pos) = path.rfind('/') {
            if let Some(dot_pos) = path[pos..].find('.') {
                return path[pos + 1..pos + dot_pos].to_string();
            }
        }
        path.to_string()
    }

    /// Generate output files in requested formats
    fn generate_outputs(&self, report: &CoverageReport) -> Result<()> {
        fs::create_dir_all(&self.config.output_directory).map_err(|e| {
            SklearsError::InvalidOperation(format!("Failed to create output directory: {e}"))
        })?;

        for format in &self.config.output_formats {
            match format.as_str() {
                "json" => self.generate_json_output(report)?,
                "html" => self.generate_html_output(report)?,
                "xml" => self.generate_xml_output(report)?,
                "text" => self.generate_text_output(report)?,
                _ => {
                    eprintln!("Warning: Unknown output format '{format}'");
                }
            }
        }

        Ok(())
    }

    /// Generate JSON output
    fn generate_json_output(&self, report: &CoverageReport) -> Result<()> {
        let json = serde_json::to_string_pretty(report).map_err(|e| {
            SklearsError::InvalidOperation(format!("Failed to serialize JSON: {e}"))
        })?;

        let path = self.config.output_directory.join("coverage.json");
        fs::write(path, json).map_err(|e| {
            SklearsError::InvalidOperation(format!("Failed to write JSON output: {e}"))
        })
    }

    /// Generate HTML output
    fn generate_html_output(&self, report: &CoverageReport) -> Result<()> {
        let html = self.generate_html_content(report);
        let path = self.config.output_directory.join("coverage.html");
        fs::write(path, html).map_err(|e| {
            SklearsError::InvalidOperation(format!("Failed to write HTML output: {e}"))
        })
    }

    /// Generate XML output
    fn generate_xml_output(&self, report: &CoverageReport) -> Result<()> {
        let xml = self.generate_xml_content(report);
        let path = self.config.output_directory.join("coverage.xml");
        fs::write(path, xml)
            .map_err(|e| SklearsError::InvalidOperation(format!("Failed to write XML output: {e}")))
    }

    /// Generate text output
    fn generate_text_output(&self, report: &CoverageReport) -> Result<()> {
        let text = report.summary();
        let path = self.config.output_directory.join("coverage.txt");
        fs::write(path, text).map_err(|e| {
            SklearsError::InvalidOperation(format!("Failed to write text output: {e}"))
        })
    }

    /// Generate HTML content
    fn generate_html_content(&self, report: &CoverageReport) -> String {
        format!(
            r#"<!DOCTYPE html>
<html>
<head>
    <title>Code Coverage Report</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        .summary {{ background: #f5f5f5; padding: 20px; border-radius: 5px; }}
        .metric {{ margin: 10px 0; }}
        .pass {{ color: green; }}
        .fail {{ color: red; }}
        .warning {{ color: orange; }}
        table {{ border-collapse: collapse; width: 100%; margin-top: 20px; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
        .coverage-bar {{ 
            width: 100px; 
            height: 20px; 
            background: #ddd; 
            border-radius: 10px; 
            overflow: hidden; 
        }}
        .coverage-fill {{ 
            height: 100%; 
            background: linear-gradient(to right, #ff4444, #ffaa00, #44ff44); 
        }}
    </style>
</head>
<body>
    <h1>Code Coverage Report</h1>
    
    <div class="summary">
        <h2>Summary</h2>
        <div class="metric">Overall Coverage: <strong>{:.1}%</strong></div>
        <div class="metric">Lines: {}/{} ({:.1}%)</div>
        <div class="metric">Functions: {}/{} ({:.1}%)</div>
        <div class="metric">Branches: {}/{} ({:.1}%)</div>
        <div class="metric">Quality Gates: <span class="{}">{}</span></div>
    </div>

    <h2>Quality Gates</h2>
    {}

    <h2>Recommendations</h2>
    {}

    <p><em>Generated at: {}</em></p>
</body>
</html>"#,
            report.overall_coverage(),
            report.overall_summary.lines_covered,
            report.overall_summary.lines_total,
            report.overall_summary.line_coverage(),
            report.overall_summary.functions_covered,
            report.overall_summary.functions_total,
            report.overall_summary.function_coverage(),
            report.overall_summary.branches_covered,
            report.overall_summary.branches_total,
            report.overall_summary.branch_coverage(),
            if report.quality_gates.passed {
                "pass"
            } else {
                "fail"
            },
            if report.quality_gates.passed {
                "PASSED"
            } else {
                "FAILED"
            },
            if report.quality_gates.failures.is_empty() {
                "<p class=\"pass\">All quality gates passed!</p>".to_string()
            } else {
                format!(
                    "<ul>{}</ul>",
                    report
                        .quality_gates
                        .failures
                        .iter()
                        .map(|f| format!(
                            "<li class=\"fail\">{}: Expected {:.1}%, got {:.1}%</li>",
                            f.rule, f.expected, f.actual
                        ))
                        .collect::<Vec<_>>()
                        .join("")
                )
            },
            if report.recommendations.is_empty() {
                "<p>No recommendations at this time.</p>".to_string()
            } else {
                format!(
                    "<ul>{}</ul>",
                    report
                        .recommendations
                        .iter()
                        .map(|r| format!("<li>{}</li>", r.description))
                        .collect::<Vec<_>>()
                        .join("")
                )
            },
            chrono::DateTime::from_timestamp(report.timestamp as i64, 0)
                .unwrap_or_default()
                .format("%Y-%m-%d %H:%M:%S UTC")
        )
    }

    /// Generate XML content (simplified Cobertura format)
    fn generate_xml_content(&self, report: &CoverageReport) -> String {
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<coverage timestamp="{}" lines-covered="{}" lines-valid="{}" line-rate="{:.4}">
    <packages>
        <package name="sklears" line-rate="{:.4}" branch-rate="{:.4}">
            <classes>
                {}
            </classes>
        </package>
    </packages>
</coverage>"#,
            report.timestamp,
            report.overall_summary.lines_covered,
            report.overall_summary.lines_total,
            report.overall_summary.line_coverage() / 100.0,
            report.overall_summary.line_coverage() / 100.0,
            report.overall_summary.branch_coverage() / 100.0,
            report
                .module_summaries
                .iter()
                .map(|(name, summary)| {
                    format!(
                        r#"<class name="{}" line-rate="{:.4}" branch-rate="{:.4}"></class>"#,
                        name,
                        summary.line_coverage() / 100.0,
                        summary.branch_coverage() / 100.0
                    )
                })
                .collect::<Vec<_>>()
                .join("\n                ")
        )
    }
}

/// CI/CD specific coverage functionality
#[derive(Debug)]
pub struct CoverageCI {
    config: CIDConfig,
}

/// Configuration for CI/CD coverage checks
#[derive(Debug, Clone)]
pub struct CIDConfig {
    pub pr_coverage_threshold: f64,
    pub diff_coverage_threshold: f64,
    pub failure_on_regression: bool,
    pub post_results_to_pr: bool,
    pub badge_generation: bool,
}

impl Default for CIDConfig {
    fn default() -> Self {
        Self {
            pr_coverage_threshold: 80.0,
            diff_coverage_threshold: 90.0,
            failure_on_regression: true,
            post_results_to_pr: false,
            badge_generation: true,
        }
    }
}

impl CIDConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_pr_coverage_threshold(mut self, threshold: f64) -> Self {
        self.pr_coverage_threshold = threshold;
        self
    }

    pub fn with_diff_coverage_threshold(mut self, threshold: f64) -> Self {
        self.diff_coverage_threshold = threshold;
        self
    }

    pub fn with_failure_on_regression(mut self, enabled: bool) -> Self {
        self.failure_on_regression = enabled;
        self
    }
}

/// CI/CD coverage check result
#[derive(Debug)]
pub struct CICoverageResult {
    pub coverage: f64,
    pub diff_coverage: Option<f64>,
    pub passed: bool,
    pub failures: Vec<String>,
}

impl CoverageCI {
    pub fn new(config: CIDConfig) -> Self {
        Self { config }
    }

    /// Run coverage check for CI/CD pipeline
    pub fn run_coverage_check(&self) -> std::result::Result<CICoverageResult, Vec<String>> {
        let mut failures = Vec::new();

        // Collect coverage data
        let coverage_config =
            CoverageConfig::new().with_minimum_coverage(self.config.pr_coverage_threshold);

        let mut collector = CoverageCollector::new(coverage_config);
        let report = match collector.collect_and_analyze() {
            Ok(report) => report,
            Err(e) => {
                failures.push(format!("Failed to collect coverage: {e}"));
                return Err(failures);
            }
        };

        let coverage = report.overall_coverage();

        // Check PR coverage threshold
        if coverage < self.config.pr_coverage_threshold {
            failures.push(format!(
                "Coverage {:.1}% below PR threshold {:.1}%",
                coverage, self.config.pr_coverage_threshold
            ));
        }

        // Check quality gates
        if !report.meets_quality_gates() {
            for failure in &report.quality_gates.failures {
                failures.push(format!(
                    "{}: {:.1}% < {:.1}%",
                    failure.rule, failure.actual, failure.expected
                ));
            }
        }

        let result = CICoverageResult {
            coverage,
            diff_coverage: None, // Would be calculated from git diff
            passed: failures.is_empty(),
            failures: failures.clone(),
        };

        if failures.is_empty() {
            Ok(result)
        } else {
            Err(failures)
        }
    }
}

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

    #[test]
    fn test_coverage_config_creation() {
        let config = CoverageConfig::new()
            .with_minimum_coverage(85.0)
            .with_output_format(vec!["json", "html"])
            .with_exclude_patterns(vec!["tests/*"]);

        assert_eq!(config.minimum_coverage, 85.0);
        assert_eq!(config.output_formats, vec!["json", "html"]);
        assert_eq!(config.exclude_patterns, vec!["tests/*"]);
    }

    #[test]
    fn test_coverage_summary_calculations() {
        let summary = CoverageSummary {
            lines_covered: 80,
            lines_total: 100,
            functions_covered: 9,
            functions_total: 10,
            branches_covered: 15,
            branches_total: 20,
        };

        assert_eq!(summary.line_coverage(), 80.0);
        assert_eq!(summary.function_coverage(), 90.0);
        assert_eq!(summary.branch_coverage(), 75.0);
    }

    #[test]
    fn test_quality_gates_evaluation() {
        let config = CoverageConfig::new().with_minimum_coverage(85.0);
        let collector = CoverageCollector::new(config);

        let summary = CoverageSummary {
            lines_covered: 80,
            lines_total: 100,
            functions_covered: 8,
            functions_total: 10,
            branches_covered: 12,
            branches_total: 15,
        };

        let result = collector.evaluate_quality_gates(&summary);
        assert!(!result.passed);
        assert_eq!(result.failures.len(), 1);
        assert_eq!(result.failures[0].rule, "Minimum overall coverage");
    }

    #[test]
    fn test_coverage_collector_creation() {
        let config = CoverageConfig::new();
        let collector = CoverageCollector::new(config);
        assert!(collector.collected_data.is_none());
    }

    #[test]
    fn test_ci_config_creation() {
        let config = CIDConfig::new()
            .with_pr_coverage_threshold(85.0)
            .with_diff_coverage_threshold(95.0)
            .with_failure_on_regression(false);

        assert_eq!(config.pr_coverage_threshold, 85.0);
        assert_eq!(config.diff_coverage_threshold, 95.0);
        assert!(!config.failure_on_regression);
    }

    #[test]
    fn test_coverage_ci_creation() {
        let config = CIDConfig::new();
        let ci = CoverageCI::new(config);
        assert_eq!(ci.config.pr_coverage_threshold, 80.0);
    }

    #[test]
    fn test_recommendation_priority_ordering() {
        let critical = RecommendationPriority::Critical;
        let high = RecommendationPriority::High;
        let medium = RecommendationPriority::Medium;
        let low = RecommendationPriority::Low;

        assert!(critical < high);
        assert!(high < medium);
        assert!(medium < low);
    }
}