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
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
//! Plugin Testing Utilities
//!
//! This module provides comprehensive testing infrastructure for plugin development,
//! validation, and quality assurance. It includes mock implementations, test fixtures,
//! performance testing tools, and validation frameworks.

use super::core_traits::Plugin;
use super::security::{DigitalSignature, Permission, PublisherInfo, SecurityPolicy};
use super::types_config::{
    PluginCapability, PluginCategory, PluginConfig, PluginMetadata, PluginParameter,
};
use super::validation::{PluginManifest, PluginValidator, ValidationReport};
use crate::error::Result;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::time::{Duration, Instant, SystemTime};

/// Mock plugin implementation for testing
///
/// MockPlugin provides a configurable test implementation of the Plugin trait
/// that can be used for unit testing, integration testing, and validation scenarios.
///
/// # Features
///
/// - Configurable metadata and behavior
/// - Simulation of various plugin states and conditions
/// - Built-in test data generation
/// - Error injection capabilities
///
/// # Examples
///
/// ```rust,ignore
/// use sklears_core::plugin::{MockPlugin, PluginCategory, PluginCapability};
/// use std::any::TypeId;
///
/// // Create a basic mock plugin
/// let mut mock = MockPlugin::new("test_plugin");
/// mock.metadata.category = PluginCategory::Algorithm;
/// mock.metadata.capabilities.push(PluginCapability::Parallel);
///
/// // Add supported types
/// mock.add_supported_type(TypeId::of::<f64>());
///
/// // Configure error behavior
/// mock.set_initialization_error(Some("Test error"));
///
/// // Use in tests
/// assert_eq!(mock.id(), "test_plugin");
/// assert!(mock.is_compatible(TypeId::of::<f64>()));
/// ```
#[derive(Debug, Clone)]
pub struct MockPlugin {
    /// Plugin identifier
    pub id: String,
    /// Plugin metadata
    pub metadata: PluginMetadata,
    /// Configuration for the plugin
    pub config: Option<PluginConfig>,
    /// Whether plugin is initialized
    pub initialized: bool,
    /// Simulated initialization error
    pub initialization_error: Option<String>,
    /// Simulated validation error
    pub validation_error: Option<String>,
    /// Simulated cleanup error
    pub cleanup_error: Option<String>,
    /// Call counters for testing
    pub call_counts: HashMap<String, usize>,
    /// Artificial delays for performance testing
    pub artificial_delays: HashMap<String, Duration>,
}

impl MockPlugin {
    /// Create a new mock plugin with default settings
    ///
    /// # Arguments
    ///
    /// * `id` - The plugin identifier
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sklears_core::plugin::MockPlugin;
    ///
    /// let mock = MockPlugin::new("test_algorithm");
    /// assert_eq!(mock.id(), "test_algorithm");
    /// ```
    pub fn new(id: &str) -> Self {
        Self {
            id: id.to_string(),
            metadata: PluginMetadata {
                name: format!("Mock Plugin {}", id),
                version: "1.0.0".to_string(),
                description: "A mock plugin for testing".to_string(),
                author: "Test Framework".to_string(),
                category: PluginCategory::Algorithm,
                supported_types: vec![TypeId::of::<f64>(), TypeId::of::<f32>()],
                dependencies: Vec::new(),
                capabilities: vec![PluginCapability::Parallel],
                min_sdk_version: "0.1.0".to_string(),
            },
            config: None,
            initialized: false,
            initialization_error: None,
            validation_error: None,
            cleanup_error: None,
            call_counts: HashMap::new(),
            artificial_delays: HashMap::new(),
        }
    }

    /// Create a mock plugin for a specific algorithm category
    ///
    /// # Arguments
    ///
    /// * `id` - The plugin identifier
    /// * `category` - The plugin category
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sklears_core::plugin::{MockPlugin, PluginCategory};
    ///
    /// let transformer = MockPlugin::for_category("scaler", PluginCategory::Transformer);
    /// assert_eq!(transformer.metadata.category, PluginCategory::Transformer);
    /// ```
    pub fn for_category(id: &str, category: PluginCategory) -> Self {
        let mut mock = Self::new(id);
        mock.metadata.category = category.clone();
        mock.metadata.name = format!("Mock {} Plugin", Self::category_name(&category));
        mock
    }

    /// Add a supported type to the plugin
    ///
    /// # Arguments
    ///
    /// * `type_id` - The TypeId to add as supported
    pub fn add_supported_type(&mut self, type_id: TypeId) {
        if !self.metadata.supported_types.contains(&type_id) {
            self.metadata.supported_types.push(type_id);
        }
    }

    /// Remove a supported type from the plugin
    ///
    /// # Arguments
    ///
    /// * `type_id` - The TypeId to remove
    pub fn remove_supported_type(&mut self, type_id: TypeId) {
        self.metadata.supported_types.retain(|&t| t != type_id);
    }

    /// Set an initialization error to simulate failure
    ///
    /// # Arguments
    ///
    /// * `error` - Optional error message (None to clear)
    pub fn set_initialization_error(&mut self, error: Option<&str>) {
        self.initialization_error = error.map(|s| s.to_string());
    }

    /// Set a validation error to simulate failure
    ///
    /// # Arguments
    ///
    /// * `error` - Optional error message (None to clear)
    pub fn set_validation_error(&mut self, error: Option<&str>) {
        self.validation_error = error.map(|s| s.to_string());
    }

    /// Set a cleanup error to simulate failure
    ///
    /// # Arguments
    ///
    /// * `error` - Optional error message (None to clear)
    pub fn set_cleanup_error(&mut self, error: Option<&str>) {
        self.cleanup_error = error.map(|s| s.to_string());
    }

    /// Add an artificial delay for a specific method
    ///
    /// # Arguments
    ///
    /// * `method` - The method name
    /// * `delay` - The delay duration
    pub fn add_artificial_delay(&mut self, method: &str, delay: Duration) {
        self.artificial_delays.insert(method.to_string(), delay);
    }

    /// Get the call count for a specific method
    ///
    /// # Arguments
    ///
    /// * `method` - The method name
    ///
    /// # Returns
    ///
    /// The number of times the method was called
    pub fn get_call_count(&self, method: &str) -> usize {
        self.call_counts.get(method).copied().unwrap_or(0)
    }

    /// Reset all call counts
    pub fn reset_call_counts(&mut self) {
        self.call_counts.clear();
    }

    /// Increment call count and apply artificial delay
    fn record_call(&mut self, method: &str) {
        *self.call_counts.entry(method.to_string()).or_insert(0) += 1;

        if let Some(delay) = self.artificial_delays.get(method) {
            std::thread::sleep(*delay);
        }
    }

    /// Get category name as string
    fn category_name(category: &PluginCategory) -> &str {
        match category {
            PluginCategory::Algorithm => "Algorithm",
            PluginCategory::Transformer => "Transformer",
            PluginCategory::DataProcessor => "DataProcessor",
            PluginCategory::Evaluator => "Evaluator",
            PluginCategory::Visualizer => "Visualizer",
            PluginCategory::Custom(name) => name,
        }
    }
}

impl Plugin for MockPlugin {
    fn id(&self) -> &str {
        &self.id
    }

    fn metadata(&self) -> PluginMetadata {
        self.metadata.clone()
    }

    fn initialize(&mut self, config: &PluginConfig) -> Result<()> {
        self.record_call("initialize");

        if let Some(ref error) = self.initialization_error {
            return Err(crate::error::SklearsError::InvalidOperation(error.clone()));
        }

        self.config = Some(config.clone());
        self.initialized = true;
        Ok(())
    }

    fn is_compatible(&self, input_type: TypeId) -> bool {
        self.metadata.supported_types.contains(&input_type)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn validate_config(&self, _config: &PluginConfig) -> Result<()> {
        if let Some(ref error) = self.validation_error {
            return Err(crate::error::SklearsError::InvalidOperation(error.clone()));
        }
        Ok(())
    }

    fn cleanup(&mut self) -> Result<()> {
        self.record_call("cleanup");

        if let Some(ref error) = self.cleanup_error {
            return Err(crate::error::SklearsError::InvalidOperation(error.clone()));
        }

        self.initialized = false;
        self.config = None;
        Ok(())
    }
}

/// Plugin test fixture for comprehensive testing scenarios
///
/// PluginTestFixture provides a complete testing environment with pre-configured
/// plugins, validation scenarios, and test data for thorough plugin testing.
///
/// # Examples
///
/// ```rust,ignore
/// use sklears_core::plugin::PluginTestFixture;
///
/// let fixture = PluginTestFixture::new();
/// let plugins = fixture.create_test_plugins();
/// assert!(!plugins.is_empty());
///
/// let manifests = fixture.create_test_manifests();
/// assert!(!manifests.is_empty());
/// ```
#[derive(Debug)]
pub struct PluginTestFixture {
    /// Security policy for testing
    pub security_policy: SecurityPolicy,
    /// Test plugins
    pub plugins: Vec<Box<dyn Plugin>>,
    /// Test manifests
    pub manifests: Vec<PluginManifest>,
}

impl PluginTestFixture {
    /// Create a new test fixture
    pub fn new() -> Self {
        Self {
            security_policy: SecurityPolicy::permissive(),
            plugins: Vec::new(),
            manifests: Vec::new(),
        }
    }

    /// Create test fixture with strict security policy
    pub fn with_strict_security() -> Self {
        Self {
            security_policy: SecurityPolicy::strict(),
            plugins: Vec::new(),
            manifests: Vec::new(),
        }
    }

    /// Create a set of test plugins covering various scenarios
    ///
    /// # Returns
    ///
    /// Vector of test plugins with different configurations and behaviors.
    pub fn create_test_plugins(&self) -> Vec<Box<dyn Plugin>> {
        vec![
            Box::new(MockPlugin::for_category(
                "linear_regression",
                PluginCategory::Algorithm,
            )),
            Box::new(MockPlugin::for_category(
                "standard_scaler",
                PluginCategory::Transformer,
            )),
            Box::new(MockPlugin::for_category(
                "csv_loader",
                PluginCategory::DataProcessor,
            )),
            Box::new(MockPlugin::for_category(
                "accuracy_metric",
                PluginCategory::Evaluator,
            )),
            Box::new(MockPlugin::for_category(
                "plot_generator",
                PluginCategory::Visualizer,
            )),
        ]
    }

    /// Create test manifests for validation testing
    ///
    /// # Returns
    ///
    /// Vector of plugin manifests with various security profiles and configurations.
    pub fn create_test_manifests(&self) -> Vec<PluginManifest> {
        vec![
            self.create_safe_manifest(),
            self.create_risky_manifest(),
            self.create_invalid_manifest(),
            self.create_signed_manifest(),
        ]
    }

    /// Create a safe plugin manifest for testing
    fn create_safe_manifest(&self) -> PluginManifest {
        PluginManifest {
            metadata: PluginMetadata {
                name: "SafePlugin".to_string(),
                version: "1.0.0".to_string(),
                description: "A safe test plugin".to_string(),
                author: "Test Suite".to_string(),
                category: PluginCategory::Algorithm,
                supported_types: vec![TypeId::of::<f64>()],
                dependencies: Vec::new(),
                capabilities: vec![PluginCapability::Parallel],
                min_sdk_version: "0.1.0".to_string(),
            },
            permissions: vec![Permission::FileSystemRead, Permission::GpuAccess],
            api_usage: None,
            contains_unsafe_code: false,
            dependencies: Vec::new(),
            code_analysis: None,
            signature: None,
            content_hash: "safe_hash_123".to_string(),
            publisher: PublisherInfo {
                name: "Trusted Publisher".to_string(),
                email: "trusted@example.com".to_string(),
                website: Some("https://trusted.example.com".to_string()),
                verified: true,
                trust_score: 9,
            },
            marketplace: super::validation::MarketplaceInfo {
                url: "https://marketplace.example.com/safe-plugin".to_string(),
                downloads: 1000,
                rating: 4.5,
                reviews: 50,
                last_updated: "2024-01-15".to_string(),
            },
        }
    }

    /// Create a risky plugin manifest for testing security validation
    fn create_risky_manifest(&self) -> PluginManifest {
        PluginManifest {
            metadata: PluginMetadata {
                name: "RiskyPlugin".to_string(),
                version: "1.0.0".to_string(),
                description: "A risky test plugin".to_string(),
                author: "Unknown".to_string(),
                category: PluginCategory::Algorithm,
                supported_types: vec![TypeId::of::<f64>()],
                dependencies: Vec::new(),
                capabilities: Vec::new(),
                min_sdk_version: "0.1.0".to_string(),
            },
            permissions: vec![
                Permission::FileSystemWrite,
                Permission::NetworkAccess,
                Permission::SystemCommands,
            ],
            api_usage: Some(super::validation::ApiUsageInfo {
                calls: vec!["std::process::Command".to_string()],
                network_access: vec!["http://api.example.com".to_string()],
                filesystem_access: vec![std::env::temp_dir().display().to_string()],
            }),
            contains_unsafe_code: true,
            dependencies: Vec::new(),
            code_analysis: Some(super::validation::CodeAnalysisInfo {
                cyclomatic_complexity: 25,
                suspicious_patterns: vec!["eval".to_string()],
                potential_memory_issues: 2,
                lines_of_code: 1500,
                test_coverage: 45.0,
            }),
            signature: None,
            content_hash: "risky_hash_456".to_string(),
            publisher: PublisherInfo {
                name: "Unknown Publisher".to_string(),
                email: "unknown@example.com".to_string(),
                website: None,
                verified: false,
                trust_score: 2,
            },
            marketplace: super::validation::MarketplaceInfo {
                url: "https://marketplace.example.com/risky-plugin".to_string(),
                downloads: 10,
                rating: 2.0,
                reviews: 5,
                last_updated: "2023-06-01".to_string(),
            },
        }
    }

    /// Create an invalid plugin manifest for testing error handling
    fn create_invalid_manifest(&self) -> PluginManifest {
        PluginManifest {
            metadata: PluginMetadata {
                name: "".to_string(),           // Invalid empty name
                version: "invalid".to_string(), // Invalid version format
                description: "Invalid plugin".to_string(),
                author: "".to_string(), // Invalid empty author
                category: PluginCategory::Algorithm,
                supported_types: Vec::new(),
                dependencies: Vec::new(),
                capabilities: Vec::new(),
                min_sdk_version: "999.0.0".to_string(), // Invalid high version
            },
            permissions: vec![Permission::Custom("invalid_permission".to_string())],
            api_usage: None,
            contains_unsafe_code: true,
            dependencies: Vec::new(),
            code_analysis: None,
            signature: None,
            content_hash: "".to_string(), // Invalid empty hash
            publisher: PublisherInfo {
                name: "".to_string(),
                email: "invalid-email".to_string(), // Invalid email format
                website: None,
                verified: false,
                trust_score: 15, // Invalid trust score > 10
            },
            marketplace: super::validation::MarketplaceInfo {
                url: "".to_string(),
                downloads: 0,
                rating: 0.0,
                reviews: 0,
                last_updated: "".to_string(),
            },
        }
    }

    /// Create a signed plugin manifest for testing signature validation
    fn create_signed_manifest(&self) -> PluginManifest {
        let mut manifest = self.create_safe_manifest();
        manifest.signature = Some(DigitalSignature {
            algorithm: "RSA-SHA256".to_string(),
            signature: vec![0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0],
            public_key_fingerprint: "SHA256:test_fingerprint_123".to_string(),
            timestamp: SystemTime::now(),
            signer_certificate: Some(
                "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----".to_string(),
            ),
        });
        manifest
    }

    /// Create test plugin configurations
    ///
    /// # Returns
    ///
    /// Vector of plugin configurations for testing various scenarios.
    pub fn create_test_configs(&self) -> Vec<PluginConfig> {
        vec![
            self.create_minimal_config(),
            self.create_full_config(),
            self.create_invalid_config(),
        ]
    }

    /// Create a minimal plugin configuration
    fn create_minimal_config(&self) -> PluginConfig {
        PluginConfig::default()
    }

    /// Create a comprehensive plugin configuration
    fn create_full_config(&self) -> PluginConfig {
        let mut config = PluginConfig::default();

        // Add various parameter types
        config
            .parameters
            .insert("learning_rate".to_string(), PluginParameter::Float(0.01));
        config
            .parameters
            .insert("max_iterations".to_string(), PluginParameter::Int(1000));
        config
            .parameters
            .insert("use_bias".to_string(), PluginParameter::Bool(true));
        config.parameters.insert(
            "algorithm".to_string(),
            PluginParameter::String("adam".to_string()),
        );
        config.parameters.insert(
            "layer_sizes".to_string(),
            PluginParameter::IntArray(vec![100, 50, 10]),
        );
        config.parameters.insert(
            "dropout_rates".to_string(),
            PluginParameter::FloatArray(vec![0.2, 0.3, 0.5]),
        );

        // Runtime settings
        config.runtime_settings.num_threads = Some(4);
        config.runtime_settings.memory_limit = Some(1024 * 1024 * 1024); // 1GB
        config.runtime_settings.timeout_ms = Some(30000); // 30 seconds
        config.runtime_settings.use_gpu = true;

        // Plugin-specific settings
        config
            .plugin_settings
            .insert("backend".to_string(), "cuda".to_string());
        config
            .plugin_settings
            .insert("precision".to_string(), "float32".to_string());

        config
    }

    /// Create an invalid plugin configuration for testing error handling
    fn create_invalid_config(&self) -> PluginConfig {
        let mut config = PluginConfig::default();

        // Invalid runtime settings
        config.runtime_settings.num_threads = Some(0); // Invalid: zero threads
        config.runtime_settings.timeout_ms = Some(0); // Invalid: zero timeout
        config.runtime_settings.memory_limit = Some(0); // Invalid: zero memory

        config
    }
}

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

/// Performance testing utilities for plugins
///
/// PluginPerformanceTester provides tools for measuring plugin performance,
/// memory usage, and identifying bottlenecks in plugin implementations.
///
/// # Examples
///
/// ```rust,ignore
/// use sklears_core::plugin::{PluginPerformanceTester, MockPlugin};
///
/// let mut tester = PluginPerformanceTester::new();
/// let mut plugin = MockPlugin::new("test_plugin");
///
/// let result = tester.benchmark_initialization(&mut plugin);
/// println!("Initialization took: {:?}", result.duration);
/// ```
#[derive(Debug)]
pub struct PluginPerformanceTester {
    /// Test configurations for benchmarking
    pub test_configs: Vec<PluginConfig>,
    /// Maximum allowed duration for operations
    pub max_duration: Duration,
    /// Memory usage baseline
    pub memory_baseline: usize,
}

impl PluginPerformanceTester {
    /// Create a new performance tester
    pub fn new() -> Self {
        Self {
            test_configs: Vec::new(),
            max_duration: Duration::from_secs(10),
            memory_baseline: 0,
        }
    }

    /// Create performance tester with custom timeout
    ///
    /// # Arguments
    ///
    /// * `max_duration` - Maximum allowed duration for operations
    pub fn with_timeout(max_duration: Duration) -> Self {
        Self {
            test_configs: Vec::new(),
            max_duration,
            memory_baseline: 0,
        }
    }

    /// Benchmark plugin initialization
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to benchmark
    ///
    /// # Returns
    ///
    /// Performance metrics for the initialization operation.
    pub fn benchmark_initialization(&mut self, plugin: &mut dyn Plugin) -> PerformanceResult {
        let config = PluginConfig::default();
        let start = Instant::now();
        let memory_start = self.get_memory_usage();

        let result = plugin.initialize(&config);

        let duration = start.elapsed();
        let memory_end = self.get_memory_usage();
        let memory_used = memory_end.saturating_sub(memory_start);

        PerformanceResult {
            operation: "initialization".to_string(),
            duration,
            memory_used,
            success: result.is_ok(),
            error: result.err().map(|e| e.to_string()),
            within_limits: duration <= self.max_duration,
        }
    }

    /// Benchmark plugin validation
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to benchmark
    /// * `config` - The configuration to validate
    ///
    /// # Returns
    ///
    /// Performance metrics for the validation operation.
    pub fn benchmark_validation(
        &self,
        plugin: &dyn Plugin,
        config: &PluginConfig,
    ) -> PerformanceResult {
        let start = Instant::now();
        let memory_start = self.get_memory_usage();

        let result = plugin.validate_config(config);

        let duration = start.elapsed();
        let memory_end = self.get_memory_usage();
        let memory_used = memory_end.saturating_sub(memory_start);

        PerformanceResult {
            operation: "validation".to_string(),
            duration,
            memory_used,
            success: result.is_ok(),
            error: result.err().map(|e| e.to_string()),
            within_limits: duration <= self.max_duration,
        }
    }

    /// Run a comprehensive performance test suite
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to test
    ///
    /// # Returns
    ///
    /// Vector of performance results for all operations.
    pub fn run_performance_suite(&mut self, plugin: &mut dyn Plugin) -> Vec<PerformanceResult> {
        let mut results = Vec::new();

        // Test initialization
        results.push(self.benchmark_initialization(plugin));

        // Test validation with different configs
        let fixture = PluginTestFixture::new();
        for config in fixture.create_test_configs() {
            results.push(self.benchmark_validation(plugin, &config));
        }

        // Test cleanup
        results.push(self.benchmark_cleanup(plugin));

        results
    }

    /// Benchmark plugin cleanup
    fn benchmark_cleanup(&self, plugin: &mut dyn Plugin) -> PerformanceResult {
        let start = Instant::now();
        let memory_start = self.get_memory_usage();

        let result = plugin.cleanup();

        let duration = start.elapsed();
        let memory_end = self.get_memory_usage();
        let memory_used = memory_end.saturating_sub(memory_start);

        PerformanceResult {
            operation: "cleanup".to_string(),
            duration,
            memory_used,
            success: result.is_ok(),
            error: result.err().map(|e| e.to_string()),
            within_limits: duration <= self.max_duration,
        }
    }

    /// Get current memory usage (placeholder implementation)
    fn get_memory_usage(&self) -> usize {
        // In a real implementation, this would measure actual memory usage
        // For now, return a placeholder value
        1024 * 1024 // 1MB placeholder
    }
}

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

/// Performance measurement result
#[derive(Debug, Clone)]
pub struct PerformanceResult {
    /// Operation name
    pub operation: String,
    /// Time taken for the operation
    pub duration: Duration,
    /// Memory used during operation
    pub memory_used: usize,
    /// Whether the operation succeeded
    pub success: bool,
    /// Error message if operation failed
    pub error: Option<String>,
    /// Whether the operation completed within time limits
    pub within_limits: bool,
}

impl PerformanceResult {
    /// Check if the performance result indicates good performance
    pub fn is_good_performance(&self) -> bool {
        self.success && self.within_limits
    }

    /// Get a performance score (0-100)
    pub fn performance_score(&self) -> u8 {
        if !self.success {
            return 0;
        }

        let time_score = if self.within_limits { 50 } else { 0 };
        let memory_score = if self.memory_used < 10 * 1024 * 1024 {
            50
        } else {
            25
        }; // < 10MB is good

        (time_score + memory_score).min(100)
    }
}

/// Validation test runner for comprehensive plugin testing
///
/// ValidationTestRunner executes a complete test suite including security
/// validation, performance testing, and compatibility checks.
///
/// # Examples
///
/// ```rust,ignore
/// use sklears_core::plugin::{ValidationTestRunner, MockPlugin};
///
/// let runner = ValidationTestRunner::new();
/// let plugin = MockPlugin::new("test_plugin");
/// let fixture = runner.create_test_fixture();
///
/// let report = runner.run_validation_tests(&plugin, &fixture.create_test_manifests()[0]);
/// println!("Validation passed: {}", !report.has_errors());
/// ```
#[derive(Debug)]
pub struct ValidationTestRunner {
    /// Plugin validator
    validator: PluginValidator,
    /// Performance tester
    performance_tester: PluginPerformanceTester,
    /// Test fixture
    fixture: PluginTestFixture,
}

impl ValidationTestRunner {
    /// Create a new validation test runner
    pub fn new() -> Self {
        Self {
            validator: PluginValidator::new(),
            performance_tester: PluginPerformanceTester::new(),
            fixture: PluginTestFixture::new(),
        }
    }

    /// Create test runner with strict security
    pub fn with_strict_security() -> Self {
        Self {
            validator: PluginValidator::new(),
            performance_tester: PluginPerformanceTester::new(),
            fixture: PluginTestFixture::with_strict_security(),
        }
    }

    /// Run comprehensive validation tests
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to test
    /// * `manifest` - The plugin manifest to validate
    ///
    /// # Returns
    ///
    /// Comprehensive validation report.
    pub fn run_validation_tests(
        &self,
        plugin: &dyn Plugin,
        manifest: &PluginManifest,
    ) -> ValidationReport {
        self.validator
            .validate_comprehensive(plugin, manifest)
            .unwrap_or_else(|_| {
                let mut report = ValidationReport::new();
                report.add_error(super::validation::ValidationError::InvalidMetadata(
                    "Failed to run validation tests".to_string(),
                ));
                report
            })
    }

    /// Run performance tests
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to test
    ///
    /// # Returns
    ///
    /// Vector of performance results.
    pub fn run_performance_tests(&mut self, plugin: &mut dyn Plugin) -> Vec<PerformanceResult> {
        self.performance_tester.run_performance_suite(plugin)
    }

    /// Run compatibility tests
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to test
    ///
    /// # Returns
    ///
    /// Compatibility test results.
    pub fn run_compatibility_tests(&self, plugin: &dyn Plugin) -> CompatibilityTestResult {
        let mut supported_types = Vec::new();
        let mut unsupported_types = Vec::new();

        // Test common types
        let test_types = vec![
            TypeId::of::<f32>(),
            TypeId::of::<f64>(),
            TypeId::of::<i32>(),
            TypeId::of::<i64>(),
            TypeId::of::<String>(),
        ];

        for type_id in test_types {
            if plugin.is_compatible(type_id) {
                supported_types.push(type_id);
            } else {
                unsupported_types.push(type_id);
            }
        }

        let compatibility_score = (supported_types.len() as f32 / 5.0 * 100.0) as u8;

        CompatibilityTestResult {
            supported_types,
            unsupported_types,
            total_types_tested: 5,
            compatibility_score,
        }
    }

    /// Create a test fixture for the runner
    pub fn create_test_fixture(&self) -> &PluginTestFixture {
        &self.fixture
    }

    /// Run complete test suite
    ///
    /// # Arguments
    ///
    /// * `plugin` - The plugin to test
    /// * `manifest` - The plugin manifest
    ///
    /// # Returns
    ///
    /// Complete test results.
    pub fn run_complete_test_suite(
        &mut self,
        plugin: &mut dyn Plugin,
        manifest: &PluginManifest,
    ) -> CompleteTestResult {
        let validation_report = self.run_validation_tests(plugin, manifest);
        let performance_results = self.run_performance_tests(plugin);
        let compatibility_result = self.run_compatibility_tests(plugin);

        let overall_score = self.calculate_overall_score(
            &validation_report,
            &performance_results,
            &compatibility_result,
        );

        CompleteTestResult {
            validation_report,
            performance_results,
            compatibility_result,
            overall_score,
            test_passed: overall_score >= 70, // 70% minimum score to pass
        }
    }

    /// Calculate overall test score
    fn calculate_overall_score(
        &self,
        validation: &ValidationReport,
        performance: &[PerformanceResult],
        compatibility: &CompatibilityTestResult,
    ) -> u8 {
        let validation_score = if validation.has_errors() { 0 } else { 40 };

        let avg_performance = if performance.is_empty() {
            0
        } else {
            performance
                .iter()
                .map(|r| r.performance_score() as u32)
                .sum::<u32>()
                / performance.len() as u32
        };
        let performance_score = (avg_performance as f32 * 0.3) as u8;

        let compatibility_score = (compatibility.compatibility_score as f32 * 0.3) as u8;

        (validation_score + performance_score + compatibility_score).min(100)
    }
}

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

/// Compatibility test result
#[derive(Debug, Clone)]
pub struct CompatibilityTestResult {
    /// Types that the plugin supports
    pub supported_types: Vec<TypeId>,
    /// Types that the plugin doesn't support
    pub unsupported_types: Vec<TypeId>,
    /// Total number of types tested
    pub total_types_tested: usize,
    /// Compatibility score (0-100)
    pub compatibility_score: u8,
}

/// Complete test result containing all test outcomes
#[derive(Debug)]
pub struct CompleteTestResult {
    /// Validation test results
    pub validation_report: ValidationReport,
    /// Performance test results
    pub performance_results: Vec<PerformanceResult>,
    /// Compatibility test results
    pub compatibility_result: CompatibilityTestResult,
    /// Overall test score (0-100)
    pub overall_score: u8,
    /// Whether the plugin passed all tests
    pub test_passed: bool,
}

impl CompleteTestResult {
    /// Get a summary of the test results
    pub fn summary(&self) -> String {
        format!(
            "Plugin Test Summary:\n\
             - Validation: {} errors, {} warnings\n\
             - Performance: {}/{} operations within limits\n\
             - Compatibility: {:.1}% type support\n\
             - Overall Score: {}/100\n\
             - Result: {}",
            self.validation_report.errors.len(),
            self.validation_report.warnings.len(),
            self.performance_results
                .iter()
                .filter(|r| r.within_limits)
                .count(),
            self.performance_results.len(),
            self.compatibility_result.compatibility_score,
            self.overall_score,
            if self.test_passed { "PASSED" } else { "FAILED" }
        )
    }
}

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

    #[test]
    fn test_mock_plugin_creation() {
        let mock = MockPlugin::new("test_plugin");
        assert_eq!(mock.id(), "test_plugin");
        assert_eq!(mock.metadata.name, "Mock Plugin test_plugin");
        assert!(!mock.initialized);
    }

    #[test]
    fn test_mock_plugin_categories() {
        let algo = MockPlugin::for_category("test", PluginCategory::Algorithm);
        assert_eq!(algo.metadata.category, PluginCategory::Algorithm);

        let transformer = MockPlugin::for_category("test", PluginCategory::Transformer);
        assert_eq!(transformer.metadata.category, PluginCategory::Transformer);
    }

    #[test]
    fn test_mock_plugin_type_support() {
        let mut mock = MockPlugin::new("test");

        // Should support f64 by default
        assert!(mock.is_compatible(TypeId::of::<f64>()));

        // Add i32 support
        mock.add_supported_type(TypeId::of::<i32>());
        assert!(mock.is_compatible(TypeId::of::<i32>()));

        // Remove f64 support
        mock.remove_supported_type(TypeId::of::<f64>());
        assert!(!mock.is_compatible(TypeId::of::<f64>()));
    }

    #[test]
    fn test_mock_plugin_error_simulation() {
        let mut mock = MockPlugin::new("test");

        // Set initialization error
        mock.set_initialization_error(Some("Test error"));
        let result = mock.initialize(&PluginConfig::default());
        assert!(result.is_err());

        // Clear error
        mock.set_initialization_error(None);
        let result = mock.initialize(&PluginConfig::default());
        assert!(result.is_ok());
    }

    #[test]
    fn test_plugin_test_fixture() {
        let fixture = PluginTestFixture::new();

        let plugins = fixture.create_test_plugins();
        assert_eq!(plugins.len(), 5);

        let manifests = fixture.create_test_manifests();
        assert_eq!(manifests.len(), 4);

        let configs = fixture.create_test_configs();
        assert_eq!(configs.len(), 3);
    }

    #[test]
    fn test_performance_tester() {
        let mut tester = PluginPerformanceTester::new();
        let mut mock = MockPlugin::new("test");

        let result = tester.benchmark_initialization(&mut mock);
        assert_eq!(result.operation, "initialization");
        assert!(result.success);
    }

    #[test]
    fn test_validation_test_runner() {
        let runner = ValidationTestRunner::new();
        let mock = MockPlugin::new("test");
        let fixture = runner.create_test_fixture();
        let manifest = &fixture.create_test_manifests()[3]; // Signed manifest for validation

        let report = runner.run_validation_tests(&mock, manifest);
        assert!(!report.has_errors()); // Should pass validation
    }

    #[test]
    fn test_compatibility_tests() {
        let runner = ValidationTestRunner::new();
        let mock = MockPlugin::new("test"); // Supports f64 and f32 by default

        let result = runner.run_compatibility_tests(&mock);
        assert!(!result.supported_types.is_empty());
        assert_eq!(result.total_types_tested, 5);
        assert!(result.compatibility_score > 0);
    }

    #[test]
    fn test_performance_result_scoring() {
        let good_result = PerformanceResult {
            operation: "test".to_string(),
            duration: Duration::from_millis(10),
            memory_used: 1024, // 1KB
            success: true,
            error: None,
            within_limits: true,
        };
        assert!(good_result.is_good_performance());
        assert_eq!(good_result.performance_score(), 100);

        let bad_result = PerformanceResult {
            operation: "test".to_string(),
            duration: Duration::from_secs(20),
            memory_used: 50 * 1024 * 1024, // 50MB
            success: false,
            error: Some("Error".to_string()),
            within_limits: false,
        };
        assert!(!bad_result.is_good_performance());
        assert_eq!(bad_result.performance_score(), 0);
    }
}