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
/// Automated performance reporting system for sklears
///
/// This module provides comprehensive automated performance reporting capabilities,
/// enabling continuous performance monitoring, regression detection, and detailed
/// analysis of algorithm performance characteristics across different datasets
/// and configurations.
///
/// # Key Features
///
/// - **Automated Report Generation**: Scheduled and triggered performance reports
/// - **Regression Detection**: Statistical analysis to identify performance regressions
/// - **Performance Trend Analysis**: Historical performance tracking and visualization
/// - **Comparative Analysis**: Side-by-side comparison with reference implementations
/// - **Resource Usage Monitoring**: Memory, CPU, and I/O performance tracking
/// - **CI/CD Integration**: Seamless integration with continuous integration pipelines
/// - **Multi-format Output**: HTML, PDF, JSON, and CSV report formats
/// - **Alerting System**: Configurable alerts for performance degradation
///
/// # Report Types
///
/// ## Performance Regression Reports
/// - Statistical significance testing for performance changes
/// - Confidence intervals and effect size analysis
/// - Historical baseline comparison
/// - Automated flagging of concerning changes
///
/// ## Algorithm Performance Profiles
/// - Scalability analysis across different data sizes
/// - Memory usage patterns and optimization opportunities
/// - Performance breakdown by algorithm components
/// - Comparative analysis against reference implementations
///
/// ## Resource Utilization Reports
/// - CPU utilization patterns and bottleneck identification
/// - Memory allocation patterns and leak detection
/// - I/O performance analysis
/// - Thread utilization and parallelization effectiveness
///
/// # Examples
///
/// ## Automated CI/CD Integration
///
/// ```rust,ignore
/// use sklears_core::performance_reporting::{PerformanceReporter, ReportConfig};
///
/// # fn main() -> sklears_core::error::Result<()> {
/// let config = ReportConfig::default();
/// let mut reporter = PerformanceReporter::new(config);
/// let report = reporter.run_ci_analysis()?;
/// println!("Report generated at {:?}", report.timestamp);
/// # Ok(())
/// # }
/// ```
use crate::benchmarking::{BenchmarkConfig, BenchmarkResults, BenchmarkSuite};
use crate::error::{Result, SklearsError};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Main performance reporting and analysis system
#[derive(Debug)]
pub struct PerformanceReporter {
    config: ReportConfig,
    database: PerformanceDatabase,
    analyzers: Vec<Box<dyn PerformanceAnalyzer>>,
}

impl PerformanceReporter {
    /// Create a new performance reporter with configuration
    pub fn new(config: ReportConfig) -> Self {
        let database = PerformanceDatabase::new(&config.database_path);
        let analyzers: Vec<Box<dyn PerformanceAnalyzer>> = vec![
            Box::new(RegressionAnalyzer::new(&config)),
            Box::new(TrendAnalyzer::new(&config)),
            Box::new(ResourceAnalyzer::new(&config)),
            Box::new(ScalabilityAnalyzer::new(&config)),
        ];

        Self {
            config,
            database,
            analyzers,
        }
    }

    /// Run a complete performance analysis for CI/CD
    pub fn run_ci_analysis(&mut self) -> Result<PerformanceReport> {
        println!("Starting automated performance analysis...");

        // Run benchmarks
        let benchmark_results = self.run_benchmarks()?;

        // Store results in database
        self.database.store_results(&benchmark_results)?;

        // Run all analyzers
        let mut analysis_results = Vec::new();
        for analyzer in &self.analyzers {
            let result = analyzer.analyze(&benchmark_results, &self.database)?;
            analysis_results.push(result);
        }

        // Generate comprehensive report
        let report = self.generate_report(benchmark_results, analysis_results)?;

        // Check for regressions and alert if necessary
        if report.has_regressions() && self.config.alert_config.enabled {
            self.send_alerts(&report)?;
        }

        // Save report to filesystem
        self.save_report(&report)?;

        Ok(report)
    }

    /// Run performance benchmarks
    fn run_benchmarks(&self) -> Result<BenchmarkResults> {
        let benchmark_config = BenchmarkConfig::new()
            .with_dataset_sizes(self.config.benchmark_sizes.clone())
            .with_iterations(self.config.benchmark_iterations)
            .with_accuracy_tolerance(self.config.accuracy_tolerance)
            .with_memory_profiling(true);

        let mut suite = BenchmarkSuite::new(benchmark_config);

        // Add configured algorithms
        for algorithm in &self.config.algorithms {
            match algorithm.as_str() {
                "linear_regression" => {
                    suite.add_benchmark(
                        "linear_regression",
                        crate::benchmarking::AlgorithmBenchmark::linear_regression(),
                    );
                }
                "random_forest" => {
                    suite.add_benchmark(
                        "random_forest",
                        crate::benchmarking::AlgorithmBenchmark::random_forest(),
                    );
                }
                "k_means" => {
                    suite.add_benchmark(
                        "k_means",
                        crate::benchmarking::AlgorithmBenchmark::k_means(),
                    );
                }
                _ => {
                    println!("Warning: Unknown algorithm '{algorithm}'");
                }
            }
        }

        suite.run()
    }

    /// Generate comprehensive performance report
    fn generate_report(
        &self,
        results: BenchmarkResults,
        analyses: Vec<AnalysisResult>,
    ) -> Result<PerformanceReport> {
        let timestamp = Utc::now();
        let mut report = PerformanceReport {
            timestamp,
            config: self.config.clone(),
            benchmark_results: results,
            analysis_results: analyses,
            summary: ReportSummary::default(),
            output_path: PathBuf::new(),
        };

        // Generate summary
        report.summary = self.generate_summary(&report)?;

        Ok(report)
    }

    /// Generate report summary with key findings
    fn generate_summary(&self, report: &PerformanceReport) -> Result<ReportSummary> {
        let mut summary = ReportSummary::default();

        // Count regressions and improvements
        for analysis in &report.analysis_results {
            match &analysis.analysis_type {
                AnalysisType::Regression(regression) => {
                    summary.total_regressions += regression.flagged_algorithms.len();
                    summary.total_improvements += regression.improved_algorithms.len();
                }
                AnalysisType::Trend(trend) => {
                    summary.performance_trend = trend.overall_trend.clone();
                }
                AnalysisType::Resource(resource) => {
                    summary.memory_efficiency = resource.memory_efficiency_score;
                    summary.cpu_efficiency = resource.cpu_efficiency_score;
                }
                AnalysisType::Scalability(scalability) => {
                    summary.scalability_score = scalability.overall_score;
                }
            }
        }

        // Determine overall health
        summary.overall_health = if summary.total_regressions > 0 {
            HealthStatus::Poor
        } else if summary.total_improvements > 0 {
            HealthStatus::Good
        } else {
            HealthStatus::Stable
        };

        Ok(summary)
    }

    /// Save report to filesystem in multiple formats
    fn save_report(&self, report: &PerformanceReport) -> Result<()> {
        let base_path = &self.config.output_directory;
        std::fs::create_dir_all(base_path).map_err(|e| {
            SklearsError::InvalidInput(format!("Cannot create output directory: {e}"))
        })?;

        let timestamp_str = report.timestamp.format("%Y%m%d_%H%M%S").to_string();

        // Save JSON report
        if self.config.output_formats.contains(&OutputFormat::Json) {
            let json_path = base_path.join(format!("performance_report_{timestamp_str}.json"));
            let json_data = serde_json::to_string_pretty(report)
                .map_err(|e| SklearsError::InvalidInput(format!("Cannot serialize report: {e}")))?;
            std::fs::write(&json_path, json_data).map_err(|e| {
                SklearsError::InvalidInput(format!("Cannot write JSON report: {e}"))
            })?;
        }

        // Save HTML report
        if self.config.output_formats.contains(&OutputFormat::Html) {
            let html_path = base_path.join(format!("performance_report_{timestamp_str}.html"));
            let html_content = self.generate_html_report(report)?;
            std::fs::write(&html_path, html_content).map_err(|e| {
                SklearsError::InvalidInput(format!("Cannot write HTML report: {e}"))
            })?;
        }

        // Save CSV summary
        if self.config.output_formats.contains(&OutputFormat::Csv) {
            let csv_path = base_path.join(format!("performance_summary_{timestamp_str}.csv"));
            let csv_content = self.generate_csv_summary(report)?;
            std::fs::write(&csv_path, csv_content)
                .map_err(|e| SklearsError::InvalidInput(format!("Cannot write CSV report: {e}")))?;
        }

        Ok(())
    }

    /// Generate HTML report content
    fn generate_html_report(&self, report: &PerformanceReport) -> Result<String> {
        let mut html = String::new();

        html.push_str("<!DOCTYPE html>\n<html>\n<head>\n");
        html.push_str("<title>Sklears Performance Report</title>\n");
        html.push_str("<style>\n");
        html.push_str("body { font-family: Arial, sans-serif; margin: 40px; }\n");
        html.push_str("table { border-collapse: collapse; width: 100%; }\n");
        html.push_str("th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n");
        html.push_str("th { background-color: #f2f2f2; }\n");
        html.push_str(".regression { background-color: #ffebee; }\n");
        html.push_str(".improvement { background-color: #e8f5e8; }\n");
        html.push_str(".stable { background-color: #f0f0f0; }\n");
        html.push_str("</style>\n</head>\n<body>\n");

        // Header
        html.push_str("<h1>Sklears Performance Report</h1>\n");
        html.push_str(&format!(
            "<p>Generated: {}</p>\n",
            report.timestamp.format("%Y-%m-%d %H:%M:%S UTC")
        ));

        // Summary section
        html.push_str("<h2>Executive Summary</h2>\n");
        html.push_str("<table>\n");
        html.push_str("<tr><th>Metric</th><th>Value</th><th>Status</th></tr>\n");
        html.push_str(&format!(
            "<tr><td>Overall Health</td><td>{:?}</td><td class=\"{}\">{:?}</td></tr>\n",
            report.summary.overall_health,
            self.health_status_class(&report.summary.overall_health),
            report.summary.overall_health
        ));
        html.push_str(&format!("<tr><td>Performance Regressions</td><td>{}</td><td class=\"regression\">{}</td></tr>\n", 
            report.summary.total_regressions,
            if report.summary.total_regressions > 0 { "ALERT" } else { "OK" }));
        html.push_str(&format!("<tr><td>Performance Improvements</td><td>{}</td><td class=\"improvement\">{}</td></tr>\n", 
            report.summary.total_improvements,
            if report.summary.total_improvements > 0 { "GOOD" } else { "NONE" }));
        html.push_str(&format!(
            "<tr><td>Memory Efficiency</td><td>{:.2}</td><td>{}</td></tr>\n",
            report.summary.memory_efficiency,
            if report.summary.memory_efficiency > 0.8 {
                "GOOD"
            } else {
                "NEEDS IMPROVEMENT"
            }
        ));
        html.push_str("</table>\n");

        // Detailed results section
        html.push_str("<h2>Detailed Results</h2>\n");
        for analysis in &report.analysis_results {
            html.push_str(&format!("<h3>{}</h3>\n", analysis.analyzer_name));
            html.push_str(&format!("<p>{}</p>\n", analysis.description));

            // Add specific analysis content based on type
            if let AnalysisType::Regression(regression) = &analysis.analysis_type {
                if !regression.flagged_algorithms.is_empty() {
                    html.push_str("<h4>Performance Regressions Detected</h4>\n");
                    html.push_str("<ul>\n");
                    for algorithm in &regression.flagged_algorithms {
                        html.push_str(&format!(
                            "<li class=\"regression\">{}: {:.2}% slower</li>\n",
                            algorithm.name, algorithm.performance_change
                        ));
                    }
                    html.push_str("</ul>\n");
                }
            }
        }

        html.push_str("</body>\n</html>");
        Ok(html)
    }

    /// Generate CSV summary content
    fn generate_csv_summary(&self, report: &PerformanceReport) -> Result<String> {
        let mut csv = String::new();
        csv.push_str("Metric,Value,Status\n");
        csv.push_str(&format!(
            "Overall Health,{:?},{}\n",
            report.summary.overall_health,
            if matches!(report.summary.overall_health, HealthStatus::Good) {
                "GOOD"
            } else {
                "ALERT"
            }
        ));
        csv.push_str(&format!(
            "Total Regressions,{},{}\n",
            report.summary.total_regressions,
            if report.summary.total_regressions > 0 {
                "ALERT"
            } else {
                "OK"
            }
        ));
        csv.push_str(&format!(
            "Total Improvements,{},{}\n",
            report.summary.total_improvements,
            if report.summary.total_improvements > 0 {
                "GOOD"
            } else {
                "NONE"
            }
        ));
        csv.push_str(&format!(
            "Memory Efficiency,{:.2},{}\n",
            report.summary.memory_efficiency,
            if report.summary.memory_efficiency > 0.8 {
                "GOOD"
            } else {
                "NEEDS_IMPROVEMENT"
            }
        ));
        Ok(csv)
    }

    fn health_status_class(&self, status: &HealthStatus) -> &'static str {
        match status {
            HealthStatus::Good => "improvement",
            HealthStatus::Stable => "stable",
            HealthStatus::Poor => "regression",
        }
    }

    /// Send alerts for performance issues
    fn send_alerts(&self, report: &PerformanceReport) -> Result<()> {
        if !self.config.alert_config.enabled {
            return Ok(());
        }

        let alert_message = format!(
            "Performance Alert: {} regressions detected in sklears performance analysis.\nReport timestamp: {}",
            report.summary.total_regressions,
            report.timestamp.format("%Y-%m-%d %H:%M:%S UTC")
        );

        // Email alerts
        if self.config.alert_config.email_notifications {
            self.send_email_alert(&alert_message)?;
        }

        // Slack alerts
        if let Some(ref webhook) = self.config.alert_config.slack_webhook {
            self.send_slack_alert(webhook, &alert_message)?;
        }

        Ok(())
    }

    fn send_email_alert(&self, message: &str) -> Result<()> {
        // In a real implementation, this would integrate with an email service
        println!("EMAIL ALERT: {message}");
        Ok(())
    }

    fn send_slack_alert(&self, webhook: &str, message: &str) -> Result<()> {
        // In a real implementation, this would send HTTP POST to Slack webhook
        println!("SLACK ALERT to {webhook}: {message}");
        Ok(())
    }
}

/// Configuration for performance reporting
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportConfig {
    pub database_path: PathBuf,
    pub output_directory: PathBuf,
    pub output_formats: Vec<OutputFormat>,
    pub algorithms: Vec<String>,
    pub benchmark_sizes: Vec<usize>,
    pub benchmark_iterations: usize,
    pub accuracy_tolerance: f64,
    pub baseline_branch: Option<String>,
    pub regression_threshold: RegressionThreshold,
    pub alert_config: AlertConfig,
}

impl ReportConfig {
    /// Create a new report configuration
    pub fn new() -> Self {
        Self {
            database_path: PathBuf::from("performance_history.db"),
            output_directory: PathBuf::from("performance_reports"),
            output_formats: vec![OutputFormat::Html, OutputFormat::Json],
            algorithms: vec![
                "linear_regression".to_string(),
                "random_forest".to_string(),
                "k_means".to_string(),
            ],
            benchmark_sizes: vec![1000, 5000, 10000],
            benchmark_iterations: 5,
            accuracy_tolerance: 1e-6,
            baseline_branch: None,
            regression_threshold: RegressionThreshold::Percentage(5.0),
            alert_config: AlertConfig::default(),
        }
    }

    /// Set baseline branch for comparison
    pub fn with_baseline_branch(mut self, branch: &str) -> Self {
        self.baseline_branch = Some(branch.to_string());
        self
    }

    /// Set regression threshold
    pub fn with_regression_threshold(mut self, threshold: RegressionThreshold) -> Self {
        self.regression_threshold = threshold;
        self
    }

    /// Set alert configuration
    pub fn with_alert_config(mut self, config: AlertConfig) -> Self {
        self.alert_config = config;
        self
    }
}

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

/// Output format options for reports
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OutputFormat {
    Html,
    Json,
    Csv,
    Pdf,
}

/// Thresholds for detecting performance regressions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RegressionThreshold {
    /// Absolute time difference in milliseconds
    Absolute(f64),
    /// Percentage change threshold
    Percentage(f64),
    /// Statistical significance based on confidence interval
    Statistical { confidence_level: f64 },
}

/// Alert configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AlertConfig {
    pub enabled: bool,
    pub email_notifications: bool,
    pub email_recipients: Vec<String>,
    pub slack_webhook: Option<String>,
    pub custom_webhooks: Vec<String>,
}

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

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

    pub fn with_slack_webhook(mut self, webhook: &str) -> Self {
        self.slack_webhook = Some(webhook.to_string());
        self
    }
}

/// Complete performance report
#[derive(Debug, Serialize, Deserialize)]
pub struct PerformanceReport {
    pub timestamp: DateTime<Utc>,
    pub config: ReportConfig,
    pub benchmark_results: BenchmarkResults,
    pub analysis_results: Vec<AnalysisResult>,
    pub summary: ReportSummary,
    pub output_path: PathBuf,
}

impl PerformanceReport {
    /// Check if the report contains performance regressions
    pub fn has_regressions(&self) -> bool {
        self.summary.total_regressions > 0
    }

    /// Get the output path for the report
    pub fn output_path(&self) -> &Path {
        &self.output_path
    }
}

/// Summary of key performance metrics
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ReportSummary {
    pub overall_health: HealthStatus,
    pub total_regressions: usize,
    pub total_improvements: usize,
    pub memory_efficiency: f64,
    pub cpu_efficiency: f64,
    pub scalability_score: f64,
    pub performance_trend: TrendDirection,
}

/// Overall health status
#[derive(Debug, Default, Serialize, Deserialize)]
pub enum HealthStatus {
    Good,
    #[default]
    Stable,
    Poor,
}

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

/// Database for storing historical performance data
#[derive(Debug)]
#[allow(dead_code)]
pub struct PerformanceDatabase {
    path: PathBuf,
    data: BTreeMap<DateTime<Utc>, BenchmarkResults>,
}

impl PerformanceDatabase {
    pub fn new(path: &Path) -> Self {
        Self {
            path: path.to_path_buf(),
            data: BTreeMap::new(),
        }
    }

    pub fn store_results(&mut self, results: &BenchmarkResults) -> Result<()> {
        let timestamp = Utc::now();
        self.data.insert(timestamp, results.clone());

        // In a real implementation, this would persist to disk
        Ok(())
    }

    pub fn get_historical_data(&self, time_range: TimeRange) -> Vec<&BenchmarkResults> {
        let cutoff = match time_range {
            TimeRange::Days(days) => Utc::now() - chrono::Duration::days(days as i64),
            TimeRange::Weeks(weeks) => Utc::now() - chrono::Duration::weeks(weeks as i64),
            TimeRange::Months(months) => Utc::now() - chrono::Duration::days(months as i64 * 30),
        };

        self.data
            .range(cutoff..)
            .map(|(_, results)| results)
            .collect()
    }
}

/// Time range for historical analysis
#[derive(Debug, Clone, Copy)]
pub enum TimeRange {
    Days(u32),
    Weeks(u32),
    Months(u32),
}

/// Generic trait for performance analyzers
pub trait PerformanceAnalyzer: std::fmt::Debug {
    fn analyze(
        &self,
        results: &BenchmarkResults,
        database: &PerformanceDatabase,
    ) -> Result<AnalysisResult>;
}

/// Result from a performance analyzer
#[derive(Debug, Serialize, Deserialize)]
pub struct AnalysisResult {
    pub analyzer_name: String,
    pub analysis_type: AnalysisType,
    pub description: String,
    pub timestamp: DateTime<Utc>,
}

/// Different types of performance analysis
#[derive(Debug, Serialize, Deserialize)]
pub enum AnalysisType {
    Regression(RegressionAnalysis),
    Trend(TrendAnalysis),
    Resource(ResourceAnalysis),
    Scalability(ScalabilityAnalysis),
}

/// Regression analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct RegressionAnalysis {
    pub flagged_algorithms: Vec<AlgorithmRegression>,
    pub improved_algorithms: Vec<AlgorithmRegression>,
    pub stable_algorithms: Vec<String>,
}

/// Algorithm-specific regression information
#[derive(Debug, Serialize, Deserialize)]
pub struct AlgorithmRegression {
    pub name: String,
    pub performance_change: f64, // Percentage change
    pub confidence_level: f64,
    pub baseline_timing: Duration,
    pub current_timing: Duration,
}

/// Trend analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct TrendAnalysis {
    pub overall_trend: TrendDirection,
    pub algorithm_trends: HashMap<String, TrendDirection>,
    pub trend_strength: f64, // 0.0 to 1.0
}

/// Resource utilization analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct ResourceAnalysis {
    pub memory_efficiency_score: f64,
    pub cpu_efficiency_score: f64,
    pub memory_peak_usage: usize,
    pub memory_leak_indicators: Vec<String>,
}

/// Scalability analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct ScalabilityAnalysis {
    pub overall_score: f64,
    pub scaling_coefficients: HashMap<String, f64>,
    pub bottleneck_analysis: Vec<String>,
}

/// Regression analyzer implementation
#[derive(Debug)]
#[allow(dead_code)]
pub struct RegressionAnalyzer {
    config: ReportConfig,
}

impl RegressionAnalyzer {
    pub fn new(config: &ReportConfig) -> Self {
        Self {
            config: config.clone(),
        }
    }
}

impl PerformanceAnalyzer for RegressionAnalyzer {
    fn analyze(
        &self,
        _results: &BenchmarkResults,
        database: &PerformanceDatabase,
    ) -> Result<AnalysisResult> {
        let _historical_data = database.get_historical_data(TimeRange::Days(30));

        let flagged_algorithms = Vec::new();
        let improved_algorithms = Vec::new();
        // For now, simulate analysis
        let stable_algorithms = vec![
            "linear_regression".to_string(),
            "random_forest".to_string(),
            "k_means".to_string(),
        ];

        let analysis = RegressionAnalysis {
            flagged_algorithms,
            improved_algorithms,
            stable_algorithms,
        };

        Ok(AnalysisResult {
            analyzer_name: "Regression Analyzer".to_string(),
            analysis_type: AnalysisType::Regression(analysis),
            description:
                "Statistical analysis of performance regressions compared to historical baselines"
                    .to_string(),
            timestamp: Utc::now(),
        })
    }
}

/// Trend analyzer implementation
#[derive(Debug)]
#[allow(dead_code)]
pub struct TrendAnalyzer {
    config: ReportConfig,
}

impl TrendAnalyzer {
    pub fn new(config: &ReportConfig) -> Self {
        Self {
            config: config.clone(),
        }
    }
}

impl PerformanceAnalyzer for TrendAnalyzer {
    fn analyze(
        &self,
        _results: &BenchmarkResults,
        _database: &PerformanceDatabase,
    ) -> Result<AnalysisResult> {
        let analysis = TrendAnalysis {
            overall_trend: TrendDirection::Stable,
            algorithm_trends: HashMap::new(),
            trend_strength: 0.8,
        };

        Ok(AnalysisResult {
            analyzer_name: "Trend Analyzer".to_string(),
            analysis_type: AnalysisType::Trend(analysis),
            description: "Analysis of performance trends over time".to_string(),
            timestamp: Utc::now(),
        })
    }
}

/// Resource analyzer implementation
#[derive(Debug)]
#[allow(dead_code)]
pub struct ResourceAnalyzer {
    config: ReportConfig,
}

impl ResourceAnalyzer {
    pub fn new(config: &ReportConfig) -> Self {
        Self {
            config: config.clone(),
        }
    }
}

impl PerformanceAnalyzer for ResourceAnalyzer {
    fn analyze(
        &self,
        _results: &BenchmarkResults,
        _database: &PerformanceDatabase,
    ) -> Result<AnalysisResult> {
        let analysis = ResourceAnalysis {
            memory_efficiency_score: 0.85,
            cpu_efficiency_score: 0.92,
            memory_peak_usage: 1024 * 1024 * 128, // 128 MB
            memory_leak_indicators: Vec::new(),
        };

        Ok(AnalysisResult {
            analyzer_name: "Resource Analyzer".to_string(),
            analysis_type: AnalysisType::Resource(analysis),
            description: "Analysis of memory and CPU resource utilization".to_string(),
            timestamp: Utc::now(),
        })
    }
}

/// Scalability analyzer implementation
#[derive(Debug)]
#[allow(dead_code)]
pub struct ScalabilityAnalyzer {
    config: ReportConfig,
}

impl ScalabilityAnalyzer {
    pub fn new(config: &ReportConfig) -> Self {
        Self {
            config: config.clone(),
        }
    }
}

impl PerformanceAnalyzer for ScalabilityAnalyzer {
    fn analyze(
        &self,
        _results: &BenchmarkResults,
        _database: &PerformanceDatabase,
    ) -> Result<AnalysisResult> {
        let analysis = ScalabilityAnalysis {
            overall_score: 0.88,
            scaling_coefficients: HashMap::new(),
            bottleneck_analysis: Vec::new(),
        };

        Ok(AnalysisResult {
            analyzer_name: "Scalability Analyzer".to_string(),
            analysis_type: AnalysisType::Scalability(analysis),
            description: "Analysis of algorithm scalability characteristics".to_string(),
            timestamp: Utc::now(),
        })
    }
}

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

    #[test]
    fn test_report_config_creation() {
        let config = ReportConfig::new()
            .with_baseline_branch("main")
            .with_regression_threshold(RegressionThreshold::Percentage(10.0));

        assert_eq!(config.baseline_branch, Some("main".to_string()));
        assert!(matches!(
            config.regression_threshold,
            RegressionThreshold::Percentage(10.0)
        ));
    }

    #[test]
    fn test_alert_config() {
        let config = AlertConfig::new()
            .with_email_notifications(true)
            .with_slack_webhook("https://hooks.slack.com/test");

        assert!(config.email_notifications);
        assert_eq!(
            config.slack_webhook,
            Some("https://hooks.slack.com/test".to_string())
        );
    }

    #[test]
    fn test_performance_database() {
        let dir = tempdir().expect("failed to create temp directory");
        let db_path = dir.path().join("test.db");
        let mut database = PerformanceDatabase::new(&db_path);

        // Create dummy benchmark results
        let config = BenchmarkConfig::new();
        let results = BenchmarkResults::new(config);

        assert!(database.store_results(&results).is_ok());

        let historical = database.get_historical_data(TimeRange::Days(1));
        assert_eq!(historical.len(), 1);
    }

    #[test]
    fn test_regression_analyzer() {
        let config = ReportConfig::new();
        let analyzer = RegressionAnalyzer::new(&config);
        let database = PerformanceDatabase::new(&PathBuf::from("test.db"));

        let benchmark_config = BenchmarkConfig::new();
        let results = BenchmarkResults::new(benchmark_config);

        let analysis = analyzer.analyze(&results, &database);
        assert!(analysis.is_ok());

        let analysis = analysis.expect("expected valid value");
        assert_eq!(analysis.analyzer_name, "Regression Analyzer");
        assert!(matches!(
            analysis.analysis_type,
            AnalysisType::Regression(_)
        ));
    }

    #[test]
    fn test_performance_reporter_creation() {
        let config = ReportConfig::new();
        let reporter = PerformanceReporter::new(config);

        assert_eq!(reporter.analyzers.len(), 4); // 4 analyzer types
    }

    #[test]
    fn test_regression_threshold_types() {
        let absolute = RegressionThreshold::Absolute(100.0);
        let percentage = RegressionThreshold::Percentage(5.0);
        let statistical = RegressionThreshold::Statistical {
            confidence_level: 0.95,
        };

        assert!(matches!(absolute, RegressionThreshold::Absolute(100.0)));
        assert!(matches!(percentage, RegressionThreshold::Percentage(5.0)));
        assert!(matches!(
            statistical,
            RegressionThreshold::Statistical {
                confidence_level: 0.95
            }
        ));
    }

    #[test]
    fn test_health_status() {
        let good = HealthStatus::Good;
        let stable = HealthStatus::Stable;
        let poor = HealthStatus::Poor;

        assert!(matches!(good, HealthStatus::Good));
        assert!(matches!(stable, HealthStatus::Stable));
        assert!(matches!(poor, HealthStatus::Poor));
    }

    #[test]
    fn test_output_formats() {
        let formats = [
            OutputFormat::Html,
            OutputFormat::Json,
            OutputFormat::Csv,
            OutputFormat::Pdf,
        ];

        assert_eq!(formats.len(), 4);
        assert!(formats.contains(&OutputFormat::Html));
        assert!(formats.contains(&OutputFormat::Json));
    }
}