trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
//! Configuration Unification for TrustformeRS Core
//!
//! This module provides unified configuration structures and patterns
//! that standardize configuration management across all modules.

#![allow(unused_variables)] // Config unification

use super::{validators, ConfigSerializable, StandardConfig};
use crate::errors::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Unified configuration base that all specific configs should inherit from
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UnifiedConfig {
    /// Configuration metadata
    pub metadata: ConfigMetadata,
    /// Resource limitations
    pub resources: ResourceConfig,
    /// Logging configuration
    pub logging: LoggingConfig,
    /// Performance settings
    pub performance: PerformanceConfig,
    /// Security settings
    pub security: SecurityConfig,
    /// Environment-specific settings
    pub environment: EnvironmentConfig,
}

impl StandardConfig for UnifiedConfig {
    fn validate(&self) -> Result<()> {
        self.metadata.validate()?;
        self.resources.validate()?;
        self.logging.validate()?;
        self.performance.validate()?;
        self.security.validate()?;
        self.environment.validate()?;
        Ok(())
    }
}

/// Configuration metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigMetadata {
    /// Configuration name/identifier
    pub name: String,
    /// Human-readable description
    pub description: Option<String>,
    /// Configuration version
    pub version: String,
    /// Tags for categorization
    pub tags: Vec<String>,
    /// Whether this configuration is enabled
    pub enabled: bool,
    /// Creation timestamp
    #[serde(default = "chrono::Utc::now")]
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Last modification timestamp
    #[serde(default = "chrono::Utc::now")]
    pub modified_at: chrono::DateTime<chrono::Utc>,
    /// Author/creator information
    pub author: Option<String>,
    /// Configuration source (file, environment, default, etc.)
    pub source: ConfigSource,
    /// Configuration priority (higher priority configs override lower)
    pub priority: u32,
}

impl Default for ConfigMetadata {
    fn default() -> Self {
        let now = chrono::Utc::now();
        Self {
            name: "default".to_string(),
            description: None,
            version: "1.0.0".to_string(),
            tags: Vec::new(),
            enabled: true,
            created_at: now,
            modified_at: now,
            author: None,
            source: ConfigSource::Default,
            priority: 100,
        }
    }
}

impl StandardConfig for ConfigMetadata {
    fn validate(&self) -> Result<()> {
        validators::non_empty_string(&self.name, "name")?;
        validators::non_empty_string(&self.version, "version")?;
        Ok(())
    }
}

/// Source of configuration
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ConfigSource {
    Default,
    File,
    Environment,
    Database,
    Remote,
    CommandLine,
    Code,
}

/// Unified resource configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResourceConfig {
    /// Memory limits
    pub memory: MemoryLimits,
    /// CPU limits
    pub cpu: CpuLimits,
    /// GPU limits
    pub gpu: GpuLimits,
    /// Storage limits
    pub storage: StorageLimits,
    /// Network limits
    pub network: NetworkLimits,
    /// Timeout settings
    pub timeouts: TimeoutConfig,
}

impl StandardConfig for ResourceConfig {
    fn validate(&self) -> Result<()> {
        self.memory.validate()?;
        self.cpu.validate()?;
        self.gpu.validate()?;
        self.storage.validate()?;
        self.network.validate()?;
        self.timeouts.validate()?;
        Ok(())
    }
}

/// Memory configuration limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryLimits {
    /// Maximum heap memory in bytes
    pub max_heap_bytes: Option<u64>,
    /// Maximum GPU memory in bytes
    pub max_gpu_bytes: Option<u64>,
    /// Maximum shared memory in bytes
    pub max_shared_bytes: Option<u64>,
    /// Memory warning threshold (percentage)
    pub warning_threshold_percent: f64,
    /// Enable memory monitoring
    pub monitoring_enabled: bool,
    /// Memory pressure detection
    pub pressure_detection: bool,
}

impl Default for MemoryLimits {
    fn default() -> Self {
        Self {
            max_heap_bytes: None,
            max_gpu_bytes: None,
            max_shared_bytes: None,
            warning_threshold_percent: 80.0,
            monitoring_enabled: true,
            pressure_detection: true,
        }
    }
}

impl StandardConfig for MemoryLimits {
    fn validate(&self) -> Result<()> {
        validators::numeric_range(
            self.warning_threshold_percent,
            0.0,
            100.0,
            "warning_threshold_percent",
        )?;
        Ok(())
    }
}

/// CPU configuration limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuLimits {
    /// Maximum CPU cores to use
    pub max_cores: Option<usize>,
    /// CPU usage limit (percentage)
    pub max_usage_percent: Option<f64>,
    /// Thread pool size
    pub thread_pool_size: Option<usize>,
    /// CPU affinity settings
    pub affinity: Vec<usize>,
    /// NUMA node preferences
    pub numa_nodes: Vec<usize>,
}

impl Default for CpuLimits {
    fn default() -> Self {
        Self {
            max_cores: None,
            max_usage_percent: Some(80.0),
            thread_pool_size: None,
            affinity: Vec::new(),
            numa_nodes: Vec::new(),
        }
    }
}

impl StandardConfig for CpuLimits {
    fn validate(&self) -> Result<()> {
        if let Some(usage) = self.max_usage_percent {
            validators::numeric_range(usage, 0.0, 100.0, "max_usage_percent")?;
        }
        if let Some(cores) = self.max_cores {
            validators::positive(cores, "max_cores")?;
        }
        Ok(())
    }
}

/// GPU configuration limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuLimits {
    /// Maximum number of GPUs to use
    pub max_devices: Option<usize>,
    /// Specific GPU device IDs to use
    pub device_ids: Vec<usize>,
    /// GPU memory limit per device in bytes
    pub memory_per_device_bytes: Option<u64>,
    /// GPU usage limit per device (percentage)
    pub max_usage_percent: Option<f64>,
    /// Enable GPU monitoring
    pub monitoring_enabled: bool,
}

impl Default for GpuLimits {
    fn default() -> Self {
        Self {
            max_devices: None,
            device_ids: Vec::new(),
            memory_per_device_bytes: None,
            max_usage_percent: Some(90.0),
            monitoring_enabled: true,
        }
    }
}

impl StandardConfig for GpuLimits {
    fn validate(&self) -> Result<()> {
        if let Some(usage) = self.max_usage_percent {
            validators::numeric_range(usage, 0.0, 100.0, "max_usage_percent")?;
        }
        Ok(())
    }
}

/// Storage configuration limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageLimits {
    /// Maximum disk space in bytes
    pub max_disk_bytes: Option<u64>,
    /// Temporary directory path
    pub temp_dir: Option<PathBuf>,
    /// Cache directory path
    pub cache_dir: Option<PathBuf>,
    /// Maximum cache size in bytes
    pub max_cache_bytes: Option<u64>,
    /// Disk usage warning threshold (percentage)
    pub warning_threshold_percent: f64,
}

impl Default for StorageLimits {
    fn default() -> Self {
        Self {
            max_disk_bytes: None,
            temp_dir: Some(std::env::temp_dir()),
            cache_dir: None,
            max_cache_bytes: Some(1024 * 1024 * 1024), // 1GB
            warning_threshold_percent: 85.0,
        }
    }
}

impl StandardConfig for StorageLimits {
    fn validate(&self) -> Result<()> {
        validators::numeric_range(
            self.warning_threshold_percent,
            0.0,
            100.0,
            "warning_threshold_percent",
        )?;

        if let Some(temp_dir) = &self.temp_dir {
            if !temp_dir.exists() {
                return Err(anyhow::anyhow!(
                    "Temp directory does not exist: {}",
                    temp_dir.display()
                )
                .into());
            }
        }

        Ok(())
    }
}

/// Network configuration limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkLimits {
    /// Maximum bandwidth in bytes per second
    pub max_bandwidth_bps: Option<u64>,
    /// Connection timeout in milliseconds
    pub connection_timeout_ms: u64,
    /// Request timeout in milliseconds
    pub request_timeout_ms: u64,
    /// Maximum concurrent connections
    pub max_connections: Option<usize>,
    /// Retry attempts
    pub max_retries: u32,
}

impl Default for NetworkLimits {
    fn default() -> Self {
        Self {
            max_bandwidth_bps: None,
            connection_timeout_ms: 30_000, // 30 seconds
            request_timeout_ms: 300_000,   // 5 minutes
            max_connections: Some(100),
            max_retries: 3,
        }
    }
}

impl StandardConfig for NetworkLimits {
    fn validate(&self) -> Result<()> {
        validators::positive(self.connection_timeout_ms, "connection_timeout_ms")?;
        validators::positive(self.request_timeout_ms, "request_timeout_ms")?;
        Ok(())
    }
}

/// Timeout configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeoutConfig {
    /// Default operation timeout in milliseconds
    pub default_timeout_ms: u64,
    /// Training timeout in milliseconds
    pub training_timeout_ms: Option<u64>,
    /// Inference timeout in milliseconds
    pub inference_timeout_ms: Option<u64>,
    /// Export timeout in milliseconds
    pub export_timeout_ms: Option<u64>,
    /// Model loading timeout in milliseconds
    pub loading_timeout_ms: Option<u64>,
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            default_timeout_ms: 300_000, // 5 minutes
            training_timeout_ms: None,
            inference_timeout_ms: Some(30_000), // 30 seconds
            export_timeout_ms: Some(1_800_000), // 30 minutes
            loading_timeout_ms: Some(600_000),  // 10 minutes
        }
    }
}

impl StandardConfig for TimeoutConfig {
    fn validate(&self) -> Result<()> {
        validators::positive(self.default_timeout_ms, "default_timeout_ms")?;
        Ok(())
    }
}

/// Unified logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level
    pub level: LogLevel,
    /// Log format
    pub format: LogFormat,
    /// Log outputs
    pub outputs: Vec<LogOutput>,
    /// Include timestamps
    pub include_timestamps: bool,
    /// Include source file information
    pub include_source: bool,
    /// Include thread information
    pub include_thread: bool,
    /// Maximum log file size in bytes
    pub max_file_size_bytes: Option<u64>,
    /// Maximum number of log files to keep
    pub max_files: Option<usize>,
    /// Log rotation strategy
    pub rotation: LogRotation,
    /// Structured logging fields
    pub structured_fields: HashMap<String, String>,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            format: LogFormat::Text,
            outputs: vec![LogOutput::Stdout],
            include_timestamps: true,
            include_source: false,
            include_thread: false,
            max_file_size_bytes: Some(10 * 1024 * 1024), // 10 MB
            max_files: Some(5),
            rotation: LogRotation::Size,
            structured_fields: HashMap::new(),
        }
    }
}

impl StandardConfig for LoggingConfig {}

/// Log levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum LogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

/// Log formats
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum LogFormat {
    Text,
    Json,
    Pretty,
    Compact,
}

/// Log outputs
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum LogOutput {
    Stdout,
    Stderr,
    File(PathBuf),
    Syslog,
    Network(String),
}

/// Log rotation strategies
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum LogRotation {
    None,
    Size,
    Time,
    Daily,
    Weekly,
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Enable performance monitoring
    pub monitoring_enabled: bool,
    /// Profiling level
    pub profiling_level: ProfilingLevel,
    /// Benchmark settings
    pub benchmarking: BenchmarkConfig,
    /// Optimization settings
    pub optimization: OptimizationConfig,
    /// Cache settings
    pub caching: CacheConfig,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            monitoring_enabled: true,
            profiling_level: ProfilingLevel::Basic,
            benchmarking: BenchmarkConfig::default(),
            optimization: OptimizationConfig::default(),
            caching: CacheConfig::default(),
        }
    }
}

impl StandardConfig for PerformanceConfig {}

/// Profiling levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ProfilingLevel {
    None,
    Basic,
    Detailed,
    Comprehensive,
}

/// Benchmark configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkConfig {
    /// Enable automatic benchmarking
    pub auto_benchmark: bool,
    /// Benchmark frequency
    pub frequency: BenchmarkFrequency,
    /// Warmup iterations
    pub warmup_iterations: usize,
    /// Measurement iterations
    pub measurement_iterations: usize,
    /// Statistical confidence level
    pub confidence_level: f64,
}

impl Default for BenchmarkConfig {
    fn default() -> Self {
        Self {
            auto_benchmark: false,
            frequency: BenchmarkFrequency::Never,
            warmup_iterations: 3,
            measurement_iterations: 10,
            confidence_level: 0.95,
        }
    }
}

/// Benchmark frequency
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum BenchmarkFrequency {
    Never,
    OnStartup,
    Daily,
    Weekly,
    OnConfigChange,
    OnDemand,
}

/// Optimization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationConfig {
    /// Optimization level
    pub level: OptimizationLevel,
    /// Enable specific optimizations
    pub optimizations: HashMap<String, bool>,
    /// Target hardware
    pub target_hardware: Option<String>,
    /// Precision settings
    pub precision: PrecisionConfig,
}

impl Default for OptimizationConfig {
    fn default() -> Self {
        let mut optimizations = HashMap::new();
        optimizations.insert("simd".to_string(), true);
        optimizations.insert("vectorization".to_string(), true);
        optimizations.insert("loop_unrolling".to_string(), true);
        optimizations.insert("kernel_fusion".to_string(), true);

        Self {
            level: OptimizationLevel::Balanced,
            optimizations,
            target_hardware: None,
            precision: PrecisionConfig::default(),
        }
    }
}

/// Optimization levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum OptimizationLevel {
    None,
    Basic,
    Balanced,
    Aggressive,
    Maximum,
}

/// Precision configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrecisionConfig {
    /// Default precision
    pub default_precision: PrecisionType,
    /// Mixed precision enabled
    pub mixed_precision: bool,
    /// Automatic precision selection
    pub auto_precision: bool,
    /// Precision loss threshold
    pub loss_threshold: f64,
}

impl Default for PrecisionConfig {
    fn default() -> Self {
        Self {
            default_precision: PrecisionType::FP32,
            mixed_precision: false,
            auto_precision: false,
            loss_threshold: 1e-6,
        }
    }
}

/// Precision types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PrecisionType {
    FP16,
    BF16,
    FP32,
    FP64,
    INT8,
    INT16,
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Enable caching
    pub enabled: bool,
    /// Cache size in bytes
    pub size_bytes: Option<u64>,
    /// Cache eviction policy
    pub eviction_policy: CacheEvictionPolicy,
    /// Cache TTL in seconds
    pub ttl_seconds: Option<u64>,
    /// Cache directory
    pub cache_dir: Option<PathBuf>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            size_bytes: Some(1024 * 1024 * 1024), // 1GB
            eviction_policy: CacheEvictionPolicy::LRU,
            ttl_seconds: Some(3600), // 1 hour
            cache_dir: None,
        }
    }
}

/// Cache eviction policies
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum CacheEvictionPolicy {
    LRU,
    LFU,
    FIFO,
    Random,
    TTL,
}

/// Security configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Enable security features
    pub enabled: bool,
    /// Security level
    pub level: SecurityLevel,
    /// Encryption settings
    pub encryption: EncryptionConfig,
    /// Authentication settings
    pub authentication: AuthenticationConfig,
    /// Access control settings
    pub access_control: AccessControlConfig,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            level: SecurityLevel::Standard,
            encryption: EncryptionConfig::default(),
            authentication: AuthenticationConfig::default(),
            access_control: AccessControlConfig::default(),
        }
    }
}

impl StandardConfig for SecurityConfig {}

/// Security levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SecurityLevel {
    Minimal,
    Standard,
    High,
    Maximum,
}

/// Encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionConfig {
    /// Enable encryption at rest
    pub at_rest: bool,
    /// Enable encryption in transit
    pub in_transit: bool,
    /// Encryption algorithm
    pub algorithm: Option<String>,
    /// Key management
    pub key_management: KeyManagementConfig,
}

impl Default for EncryptionConfig {
    fn default() -> Self {
        Self {
            at_rest: false,
            in_transit: true,
            algorithm: Some("AES-256-GCM".to_string()),
            key_management: KeyManagementConfig::default(),
        }
    }
}

/// Key management configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyManagementConfig {
    /// Key rotation enabled
    pub rotation_enabled: bool,
    /// Key rotation interval in days
    pub rotation_interval_days: Option<u32>,
    /// Key storage location
    pub storage_location: KeyStorageLocation,
}

impl Default for KeyManagementConfig {
    fn default() -> Self {
        Self {
            rotation_enabled: false,
            rotation_interval_days: Some(90),
            storage_location: KeyStorageLocation::Local,
        }
    }
}

/// Key storage locations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum KeyStorageLocation {
    Local,
    Environment,
    Vault,
    HSM,
    Cloud,
}

/// Authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticationConfig {
    /// Authentication method
    pub method: AuthenticationMethod,
    /// Session timeout in seconds
    pub session_timeout_seconds: Option<u64>,
    /// Multi-factor authentication
    pub mfa_enabled: bool,
}

impl Default for AuthenticationConfig {
    fn default() -> Self {
        Self {
            method: AuthenticationMethod::None,
            session_timeout_seconds: Some(3600), // 1 hour
            mfa_enabled: false,
        }
    }
}

/// Authentication methods
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthenticationMethod {
    None,
    ApiKey,
    JWT,
    OAuth2,
    LDAP,
    SAML,
}

/// Access control configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessControlConfig {
    /// Access control model
    pub model: AccessControlModel,
    /// Default permissions
    pub default_permissions: Vec<String>,
    /// Permission inheritance
    pub inheritance_enabled: bool,
}

impl Default for AccessControlConfig {
    fn default() -> Self {
        Self {
            model: AccessControlModel::None,
            default_permissions: vec!["read".to_string()],
            inheritance_enabled: true,
        }
    }
}

/// Access control models
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AccessControlModel {
    None,
    RBAC, // Role-Based Access Control
    ABAC, // Attribute-Based Access Control
    DAC,  // Discretionary Access Control
    MAC,  // Mandatory Access Control
}

/// Environment configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentConfig {
    /// Environment type
    pub environment_type: EnvironmentType,
    /// Environment variables
    pub variables: HashMap<String, String>,
    /// Feature flags
    pub feature_flags: HashMap<String, bool>,
    /// Debug settings
    pub debug: DebugConfig,
}

impl Default for EnvironmentConfig {
    fn default() -> Self {
        Self {
            environment_type: EnvironmentType::Development,
            variables: HashMap::new(),
            feature_flags: HashMap::new(),
            debug: DebugConfig::default(),
        }
    }
}

impl StandardConfig for EnvironmentConfig {}

/// Environment types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EnvironmentType {
    Development,
    Testing,
    Staging,
    Production,
}

/// Debug configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebugConfig {
    /// Enable debug mode
    pub enabled: bool,
    /// Debug level
    pub level: DebugLevel,
    /// Enable verbose output
    pub verbose: bool,
    /// Enable stack traces
    pub stack_traces: bool,
    /// Debug output format
    pub output_format: DebugOutputFormat,
}

impl Default for DebugConfig {
    fn default() -> Self {
        Self {
            enabled: cfg!(debug_assertions),
            level: DebugLevel::Info,
            verbose: false,
            stack_traces: cfg!(debug_assertions),
            output_format: DebugOutputFormat::Pretty,
        }
    }
}

/// Debug levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DebugLevel {
    None,
    Basic,
    Info,
    Verbose,
    Trace,
}

/// Debug output formats
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DebugOutputFormat {
    Plain,
    Pretty,
    Json,
    Structured,
}

/// Configuration manager for handling unified configurations
pub struct ConfigManager {
    configs: HashMap<String, UnifiedConfig>,
    active_config: Option<String>,
}

impl ConfigManager {
    /// Create a new configuration manager
    pub fn new() -> Self {
        Self {
            configs: HashMap::new(),
            active_config: None,
        }
    }

    /// Add a configuration
    pub fn add_config(&mut self, name: String, config: UnifiedConfig) -> Result<()> {
        config.validate()?;
        self.configs.insert(name, config);
        Ok(())
    }

    /// Get a configuration by name
    pub fn get_config(&self, name: &str) -> Option<&UnifiedConfig> {
        self.configs.get(name)
    }

    /// Set active configuration
    pub fn set_active(&mut self, name: String) -> Result<()> {
        if !self.configs.contains_key(&name) {
            return Err(anyhow::anyhow!("Configuration '{}' not found", name).into());
        }
        self.active_config = Some(name);
        Ok(())
    }

    /// Get active configuration
    pub fn get_active(&self) -> Option<&UnifiedConfig> {
        self.active_config.as_ref().and_then(|name| self.configs.get(name))
    }

    /// Merge configurations (later configs override earlier ones)
    pub fn merge_configs(&self, names: &[String]) -> Result<UnifiedConfig> {
        if names.is_empty() {
            return Ok(UnifiedConfig::default());
        }

        let mut result = self
            .get_config(&names[0])
            .ok_or_else(|| anyhow::anyhow!("Configuration '{}' not found", names[0]))?
            .clone();

        for name in &names[1..] {
            let config = self
                .get_config(name)
                .ok_or_else(|| anyhow::anyhow!("Configuration '{}' not found", name))?;
            result = merge_unified_configs(result, config.clone())?;
        }

        Ok(result)
    }

    /// Load configuration from file
    pub fn load_from_file(&mut self, name: String, path: &std::path::Path) -> Result<()> {
        let config = UnifiedConfig::load_from_file(path)?;
        self.add_config(name, config)
    }

    /// Save configuration to file
    pub fn save_to_file(&self, name: &str, path: &std::path::Path) -> Result<()> {
        let config = self
            .get_config(name)
            .ok_or_else(|| anyhow::anyhow!("Configuration '{}' not found", name))?;
        config.save_to_file(path)
    }
}

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

/// Merge two unified configurations (second overrides first)
pub fn merge_unified_configs(
    base: UnifiedConfig,
    override_config: UnifiedConfig,
) -> Result<UnifiedConfig> {
    // For now, we'll do a simple override merge
    // In a more sophisticated implementation, we might merge nested structures
    Ok(override_config)
}

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

    #[test]
    fn test_unified_config_creation() {
        let config = UnifiedConfig::default();
        assert!(config.validate().is_ok());
        assert_eq!(config.metadata.name, "default");
        assert!(config.metadata.enabled);
    }

    #[test]
    fn test_config_serialization() {
        let config = UnifiedConfig::default();
        let json = config.to_json().expect("operation failed in test");
        let deserialized = UnifiedConfig::from_json(&json).expect("operation failed in test");

        assert_eq!(config.metadata.name, deserialized.metadata.name);
        assert_eq!(config.metadata.enabled, deserialized.metadata.enabled);
    }

    #[test]
    fn test_config_manager() {
        let mut manager = ConfigManager::new();
        let config = UnifiedConfig::default();

        manager.add_config("test".to_string(), config).expect("add operation failed");
        manager.set_active("test".to_string()).expect("operation failed in test");

        let active = manager.get_active().expect("operation failed in test");
        assert_eq!(active.metadata.name, "default");
    }

    #[test]
    fn test_config_file_operations() {
        let temp_dir = tempdir().expect("temp file creation failed");
        let config_path = temp_dir.path().join("test_config.json");

        let config = UnifiedConfig::default();
        config.save_to_file(&config_path).expect("operation failed in test");

        let loaded_config =
            UnifiedConfig::load_from_file(&config_path).expect("operation failed in test");
        assert_eq!(config.metadata.name, loaded_config.metadata.name);
    }

    #[test]
    fn test_validation() {
        let mut config = UnifiedConfig::default();
        config.metadata.name = "".to_string(); // Invalid empty name

        let result = config.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_resource_limits_validation() {
        let limits = MemoryLimits {
            warning_threshold_percent: 150.0, // Invalid percentage
            ..Default::default()
        };

        let result = limits.validate();
        assert!(result.is_err());
    }
}