verdure-context 0.0.5

An ecosystem framework for Rust.
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
//! Configuration management system
//!
//! This module provides configuration management functionality for the Verdure context system.
//! It supports hierarchical configuration sources, property binding, type-safe configuration
//! access, and integration with environment profiles.

use std::any::TypeId;
use crate::error::{ContextError, ContextResult};
use dashmap::{DashMap, DashSet};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use verdure_ioc::ComponentInstance;

pub trait ConfigInitializer {
    fn from_config_manager(config_manager: Arc<ConfigManager>) -> ContextResult<Self>
    where
        Self: Sized;

    fn config_module_key() -> &'static str;
}

pub struct ConfigFactory {
    pub type_id: fn() -> TypeId,
    pub create_fn: fn(Arc<ConfigManager>) -> ContextResult<ComponentInstance>,
}

inventory::collect!(ConfigFactory);

/// Configuration file formats
#[derive(Debug, Clone, Copy)]
enum ConfigFileFormat {
    Toml,
    Yaml,
    Properties,
}

/// Configuration source types
///
/// `ConfigSource` represents different sources from which configuration
/// can be loaded, supporting various formats and locations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConfigSource {
    /// Configuration from a TOML file
    TomlFile(String),
    /// Configuration from a YAML file
    YamlFile(String),
    /// Configuration from a Properties file
    PropertiesFile(String),
    /// Configuration from any file (auto-detect format)
    ConfigFile(String),
    /// Configuration from environment variables
    Environment,
    /// Configuration from command line arguments
    CommandLine,
    /// In-memory configuration properties
    Properties(HashMap<String, String>),
}

/// Configuration value types
///
/// `ConfigValue` represents different types of configuration values
/// that can be stored and retrieved from the configuration system.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConfigValue {
    /// String value
    String(String),
    /// Integer value
    Integer(i64),
    /// Float value
    Float(f64),
    /// Boolean value
    Boolean(bool),
    /// Array of values
    Array(Vec<ConfigValue>),
    /// Nested object/map
    Object(HashMap<String, ConfigValue>),
}

impl ConfigValue {
    /// Converts the value to a string if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    ///
    /// let value = ConfigValue::String("hello".to_string());
    /// assert_eq!(value.as_string(), Some("hello".to_string()));
    ///
    /// let value = ConfigValue::Integer(42);
    /// assert_eq!(value.as_string(), Some("42".to_string()));
    /// ```
    pub fn as_string(&self) -> Option<String> {
        match self {
            ConfigValue::String(s) => Some(s.clone()),
            ConfigValue::Integer(i) => Some(i.to_string()),
            ConfigValue::Float(f) => Some(f.to_string()),
            ConfigValue::Boolean(b) => Some(b.to_string()),
            _ => None,
        }
    }

    /// Converts the value to an integer if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    ///
    /// let value = ConfigValue::Integer(42);
    /// assert_eq!(value.as_integer(), Some(42));
    ///
    /// let value = ConfigValue::String("123".to_string());
    /// assert_eq!(value.as_integer(), Some(123));
    /// ```
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            ConfigValue::Integer(i) => Some(*i),
            ConfigValue::String(s) => s.parse().ok(),
            _ => None,
        }
    }

    /// Converts the value to a float if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    ///
    /// let value = ConfigValue::Float(3.14);
    /// assert_eq!(value.as_float(), Some(3.14));
    ///
    /// let value = ConfigValue::Integer(42);
    /// assert_eq!(value.as_float(), Some(42.0));
    /// ```
    pub fn as_float(&self) -> Option<f64> {
        match self {
            ConfigValue::Float(f) => Some(*f),
            ConfigValue::Integer(i) => Some(*i as f64),
            ConfigValue::String(s) => s.parse().ok(),
            _ => None,
        }
    }

    /// Converts the value to a boolean if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    ///
    /// let value = ConfigValue::Boolean(true);
    /// assert_eq!(value.as_boolean(), Some(true));
    ///
    /// let value = ConfigValue::String("true".to_string());
    /// assert_eq!(value.as_boolean(), Some(true));
    /// ```
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
            ConfigValue::Boolean(b) => Some(*b),
            ConfigValue::String(s) => match s.to_lowercase().as_str() {
                "true" | "yes" | "on" | "1" => Some(true),
                "false" | "no" | "off" | "0" => Some(false),
                _ => None,
            },
            ConfigValue::Integer(i) => Some(*i != 0),
            _ => None,
        }
    }

    /// Converts the value to an array if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    ///
    /// let value = ConfigValue::Array(vec![
    ///     ConfigValue::String("a".to_string()),
    ///     ConfigValue::String("b".to_string()),
    /// ]);
    /// assert!(value.as_array().is_some());
    /// ```
    pub fn as_array(&self) -> Option<&Vec<ConfigValue>> {
        match self {
            ConfigValue::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Converts the value to an object/map if possible
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigValue;
    /// use std::collections::HashMap;
    ///
    /// let mut obj = HashMap::new();
    /// obj.insert("key".to_string(), ConfigValue::String("value".to_string()));
    ///
    /// let value = ConfigValue::Object(obj);
    /// assert!(value.as_object().is_some());
    /// ```
    pub fn as_object(&self) -> Option<&HashMap<String, ConfigValue>> {
        match self {
            ConfigValue::Object(obj) => Some(obj),
            _ => None,
        }
    }
}

/// Configuration manager
///
/// `ConfigManager` provides comprehensive configuration management functionality,
/// including loading from multiple sources, hierarchical property resolution,
/// type-safe access, and integration with environment profiles.
///
/// # Examples
///
/// ```rust
/// use verdure_context::{ConfigManager, ConfigSource};
/// use std::collections::HashMap;
///
/// let mut manager = ConfigManager::new();
///
/// // Add configuration from properties
/// let mut props = HashMap::new();
/// props.insert("app.name".to_string(), "MyApp".to_string());
/// props.insert("app.port".to_string(), "8080".to_string());
///
/// manager.add_source(ConfigSource::Properties(props)).unwrap();
///
/// assert_eq!(manager.get_string("app.name").unwrap(), "MyApp");
/// assert_eq!(manager.get_integer("app.port").unwrap(), 8080);
/// ```
#[derive(Clone)]
pub struct ConfigManager {
    /// Configuration sources in precedence order (last added = highest precedence)
    sources: Arc<RwLock<Vec<ConfigSource>>>,
    
    /// Primary configuration cache
    cache: Arc<DashMap<String, ConfigValue>>,
    
    /// File content cache to avoid repeated file I/O
    file_cache: Arc<DashMap<String, HashMap<String, String>>>,
    
    /// Cache invalidation tracking
    dirty_keys: Arc<DashSet<String>>,
}

impl ConfigManager {
    /// Creates a new configuration manager
    pub fn new() -> Self {
        Self {
            sources: Arc::new(RwLock::new(Vec::new())),
            cache: Arc::new(DashMap::new()),
            file_cache: Arc::new(DashMap::new()),
            dirty_keys: Arc::new(DashSet::new()),
        }
    }

    /// Adds a configuration source
    pub fn add_source(&self, source: ConfigSource) -> ContextResult<()> {
        {
            let mut sources = self.sources.write();
            sources.push(source);
        }
        
        self.invalidate_cache();
        Ok(())
    }

    /// Loads configuration from a TOML file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the TOML configuration file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use verdure_context::ConfigManager;
    ///
    /// let mut manager = ConfigManager::new();
    /// manager.load_from_toml_file("config/app.toml").unwrap();
    /// ```
    pub fn load_from_toml_file<P: AsRef<Path>>(&mut self, path: P) -> ContextResult<()> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.add_source(ConfigSource::TomlFile(path_str))
    }

    /// Loads configuration from a YAML file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the YAML configuration file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use verdure_context::ConfigManager;
    ///
    /// let mut manager = ConfigManager::new();
    /// manager.load_from_yaml_file("config/app.yaml").unwrap();
    /// ```
    pub fn load_from_yaml_file<P: AsRef<Path>>(&mut self, path: P) -> ContextResult<()> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.add_source(ConfigSource::YamlFile(path_str))
    }

    /// Loads configuration from a Properties file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Properties configuration file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use verdure_context::ConfigManager;
    ///
    /// let mut manager = ConfigManager::new();
    /// manager.load_from_properties_file("config/app.properties").unwrap();
    /// ```
    pub fn load_from_properties_file<P: AsRef<Path>>(&mut self, path: P) -> ContextResult<()> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.add_source(ConfigSource::PropertiesFile(path_str))
    }

    /// Loads configuration from a file with automatic format detection
    ///
    /// The format is detected based on the file extension:
    /// - `.toml` -> TOML format
    /// - `.yaml` or `.yml` -> YAML format  
    /// - `.properties` -> Properties format
    /// - Others -> Attempts to parse as TOML first, then YAML, then Properties
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the configuration file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use verdure_context::ConfigManager;
    ///
    /// let mut manager = ConfigManager::new();
    /// manager.load_from_config_file("config/app.yaml").unwrap();
    /// manager.load_from_config_file("config/database.properties").unwrap();
    /// manager.load_from_config_file("config/server.toml").unwrap();
    /// ```
    pub fn load_from_config_file<P: AsRef<Path>>(&mut self, path: P) -> ContextResult<()> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.add_source(ConfigSource::ConfigFile(path_str))
    }

    /// Gets a configuration value by key
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key (e.g., "database.url")
    ///
    /// # Returns
    ///
    /// The configuration value if found, `None` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ConfigManager, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut manager = ConfigManager::new();
    /// let mut props = HashMap::new();
    /// props.insert("test.key".to_string(), "test.value".to_string());
    ///
    /// manager.add_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// let value = manager.get("test.key");
    /// assert!(value.is_some());
    /// ```
    /// Gets a configuration value
    pub fn get(&self, key: &str) -> Option<ConfigValue> {
        if let Some(cached) = self.cache.get(key) {
            return Some(cached.clone());
        }
        
        self.get_and_cache(key)
    }
    
    /// Internal method to compute and cache configuration values
    fn get_and_cache(&self, key: &str) -> Option<ConfigValue> {
        let sources = self.sources.read();
        for source in sources.iter().rev() {
            if let Some(value) = self.get_from_source(source, key) {
                self.cache.insert(key.to_string(), value.clone());
                return Some(value);
            }
        }
        
        None
    }

    /// Gets a configuration value as a string
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value as a string
    ///
    /// # Errors
    ///
    /// Returns an error if the key is not found or cannot be converted to a string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ConfigManager, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut manager = ConfigManager::new();
    /// let mut props = HashMap::new();
    /// props.insert("app.name".to_string(), "MyApp".to_string());
    ///
    /// manager.add_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// assert_eq!(manager.get_string("app.name").unwrap(), "MyApp");
    /// ```
    pub fn get_string(&self, key: &str) -> ContextResult<String> {
        self.get(key)
            .and_then(|v| v.as_string())
            .ok_or_else(|| ContextError::configuration_not_found(key))
    }

    /// Gets a configuration value as an integer
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value as an integer
    ///
    /// # Errors
    ///
    /// Returns an error if the key is not found or cannot be converted to an integer
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ConfigManager, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut manager = ConfigManager::new();
    /// let mut props = HashMap::new();
    /// props.insert("app.port".to_string(), "8080".to_string());
    ///
    /// manager.add_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// assert_eq!(manager.get_integer("app.port").unwrap(), 8080);
    /// ```
    pub fn get_integer(&self, key: &str) -> ContextResult<i64> {
        self.get(key)
            .and_then(|v| v.as_integer())
            .ok_or_else(|| ContextError::configuration_not_found(key))
    }

    /// Gets a configuration value as a float
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value as a float
    ///
    /// # Errors
    ///
    /// Returns an error if the key is not found or cannot be converted to a float
    pub fn get_float(&self, key: &str) -> ContextResult<f64> {
        self.get(key)
            .and_then(|v| v.as_float())
            .ok_or_else(|| ContextError::configuration_not_found(key))
    }

    /// Gets a configuration value as a boolean
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value as a boolean
    ///
    /// # Errors
    ///
    /// Returns an error if the key is not found or cannot be converted to a boolean
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ConfigManager, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut manager = ConfigManager::new();
    /// let mut props = HashMap::new();
    /// props.insert("app.debug".to_string(), "true".to_string());
    ///
    /// manager.add_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// assert_eq!(manager.get_boolean("app.debug").unwrap(), true);
    /// ```
    pub fn get_boolean(&self, key: &str) -> ContextResult<bool> {
        self.get(key)
            .and_then(|v| v.as_boolean())
            .ok_or_else(|| ContextError::configuration_not_found(key))
    }

    /// Gets a configuration value with a default fallback
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    /// * `default` - The default value to return if key is not found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ConfigManager;
    ///
    /// let manager = ConfigManager::new();
    ///
    /// assert_eq!(manager.get_string_or_default("missing.key", "default"), "default");
    /// ```
    pub fn get_string_or_default(&self, key: &str, default: &str) -> String {
        self.get_string(key).unwrap_or_else(|_| default.to_string())
    }

    /// Gets an integer configuration value with a default fallback
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    /// * `default` - The default value to return if key is not found
    pub fn get_integer_or_default(&self, key: &str, default: i64) -> i64 {
        self.get_integer(key).unwrap_or(default)
    }

    /// Gets a boolean configuration value with a default fallback
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    /// * `default` - The default value to return if key is not found
    pub fn get_boolean_or_default(&self, key: &str, default: bool) -> bool {
        self.get_boolean(key).unwrap_or(default)
    }

    /// Sets a runtime configuration value
    pub fn set(&self, key: &str, value: ConfigValue) {
        self.cache.insert(key.to_string(), value);
    }

    /// Gets the number of configuration sources
    ///
    /// # Returns
    ///
    /// The total number of configuration sources
    pub fn sources_count(&self) -> usize {
        self.sources.read().len()
    }

    /// Invalidates the configuration cache
    pub fn invalidate_cache(&self) {
        self.cache.clear();
        self.dirty_keys.clear();
    }
    
    /// Invalidates specific cache keys
    pub fn invalidate_keys(&self, keys: &[String]) {
        for key in keys {
            self.cache.remove(key);
            self.dirty_keys.insert(key.clone());
        }
    }

    // Helper method to get value from a specific source
    fn get_from_source(&self, source: &ConfigSource, key: &str) -> Option<ConfigValue> {
        match source {
            ConfigSource::Properties(props) => {
                props.get(key).map(|v| ConfigValue::String(v.clone()))
            }
            ConfigSource::Environment => {
                // Convert key to environment variable format (e.g., "app.port" -> "APP_PORT")
                let env_key = key.to_uppercase().replace('.', "_");
                std::env::var(&env_key).ok().map(|v| ConfigValue::String(v))
            }
            ConfigSource::TomlFile(path) => self
                .load_file_config(path, ConfigFileFormat::Toml)
                .and_then(|props| props.get(key).map(|v| ConfigValue::String(v.clone()))),
            ConfigSource::YamlFile(path) => self
                .load_file_config(path, ConfigFileFormat::Yaml)
                .and_then(|props| props.get(key).map(|v| ConfigValue::String(v.clone()))),
            ConfigSource::PropertiesFile(path) => self
                .load_file_config(path, ConfigFileFormat::Properties)
                .and_then(|props| props.get(key).map(|v| ConfigValue::String(v.clone()))),
            ConfigSource::ConfigFile(path) => self
                .load_file_config_auto_detect(path)
                .and_then(|props| props.get(key).map(|v| ConfigValue::String(v.clone()))),
            _ => None, // TODO: Implement other source types
        }
    }

    // Helper method to load configuration from file
    fn load_file_config(
        &self,
        path: &str,
        format: ConfigFileFormat,
    ) -> Option<HashMap<String, String>> {
        let content = std::fs::read_to_string(path).ok()?;

        match format {
            ConfigFileFormat::Toml => {
                let toml_value: toml::Value = toml::from_str(&content).ok()?;
                self.toml_value_to_config_map(&toml_value, "").ok()
            }
            ConfigFileFormat::Yaml => {
                let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content).ok()?;
                self.yaml_value_to_config_map(&yaml_value, "").ok()
            }
            ConfigFileFormat::Properties => self.parse_properties(&content).ok(),
        }
    }

    // Helper method to auto-detect file format and load configuration
    fn load_file_config_auto_detect(&self, path: &str) -> Option<HashMap<String, String>> {
        let path_lower = path.to_lowercase();

        // Try to detect format by extension first
        if path_lower.ends_with(".toml") {
            return self.load_file_config(path, ConfigFileFormat::Toml);
        } else if path_lower.ends_with(".yaml") || path_lower.ends_with(".yml") {
            return self.load_file_config(path, ConfigFileFormat::Yaml);
        } else if path_lower.ends_with(".properties") {
            return self.load_file_config(path, ConfigFileFormat::Properties);
        }

        // If extension doesn't match known formats, try parsing in order: TOML, YAML, Properties
        if let Some(config) = self.load_file_config(path, ConfigFileFormat::Toml) {
            return Some(config);
        }

        if let Some(config) = self.load_file_config(path, ConfigFileFormat::Yaml) {
            return Some(config);
        }

        self.load_file_config(path, ConfigFileFormat::Properties)
    }

    // Helper method to convert YAML value to flat configuration map
    fn yaml_value_to_config_map(
        &self,
        value: &serde_yaml::Value,
        prefix: &str,
    ) -> ContextResult<HashMap<String, String>> {
        let mut map = HashMap::new();

        match value {
            serde_yaml::Value::Mapping(mapping) => {
                for (key, val) in mapping {
                    if let Some(key_str) = key.as_str() {
                        let full_key = if prefix.is_empty() {
                            key_str.to_string()
                        } else {
                            format!("{}.{}", prefix, key_str)
                        };

                        match val {
                            serde_yaml::Value::Mapping(_) => {
                                // Recursively process nested mappings
                                let nested_map = self.yaml_value_to_config_map(val, &full_key)?;
                                map.extend(nested_map);
                            }
                            _ => {
                                // Convert primitive values to strings
                                map.insert(full_key, self.yaml_value_to_string(val));
                            }
                        }
                    }
                }
            }
            _ => {
                // For non-mapping values, use the prefix as the key
                if !prefix.is_empty() {
                    map.insert(prefix.to_string(), self.yaml_value_to_string(value));
                }
            }
        }

        Ok(map)
    }

    // Helper method to convert YAML value to string
    fn yaml_value_to_string(&self, value: &serde_yaml::Value) -> String {
        match value {
            serde_yaml::Value::String(s) => s.clone(),
            serde_yaml::Value::Number(n) => n.to_string(),
            serde_yaml::Value::Bool(b) => b.to_string(),
            serde_yaml::Value::Sequence(arr) => {
                // Convert array to comma-separated string
                arr.iter()
                    .map(|v| self.yaml_value_to_string(v))
                    .collect::<Vec<_>>()
                    .join(",")
            }
            serde_yaml::Value::Null => "".to_string(),
            _ => format!("{:?}", value),
        }
    }

    // Helper method to parse Properties format
    fn parse_properties(&self, content: &str) -> ContextResult<HashMap<String, String>> {
        let mut map = HashMap::new();

        for line in content.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') || line.starts_with('!') {
                continue;
            }

            // Find the first '=' or ':' separator
            if let Some(separator_pos) = line.find('=').or_else(|| line.find(':')) {
                let key = line[..separator_pos].trim().to_string();
                let value = line[separator_pos + 1..].trim().to_string();

                // Handle escaped characters and line continuations
                let processed_value = self.process_properties_value(&value);

                map.insert(key, processed_value);
            }
        }

        Ok(map)
    }

    // Helper method to process Properties file values (handle escaping, etc.)
    fn process_properties_value(&self, value: &str) -> String {
        // Basic processing - handle common escape sequences
        value
            .replace("\\n", "\n")
            .replace("\\t", "\t")
            .replace("\\r", "\r")
            .replace("\\\\", "\\")
    }
    fn toml_value_to_config_map(
        &self,
        value: &toml::Value,
        prefix: &str,
    ) -> ContextResult<HashMap<String, String>> {
        let mut map = HashMap::new();

        match value {
            toml::Value::Table(table) => {
                for (key, val) in table {
                    let full_key = if prefix.is_empty() {
                        key.clone()
                    } else {
                        format!("{}.{}", prefix, key)
                    };

                    match val {
                        toml::Value::Table(_) => {
                            // Recursively process nested tables
                            let nested_map = self.toml_value_to_config_map(val, &full_key)?;
                            map.extend(nested_map);
                        }
                        _ => {
                            // Convert primitive values to strings
                            map.insert(full_key, self.toml_value_to_string(val));
                        }
                    }
                }
            }
            _ => {
                // For non-table values, use the prefix as the key
                if !prefix.is_empty() {
                    map.insert(prefix.to_string(), self.toml_value_to_string(value));
                }
            }
        }

        Ok(map)
    }

    // Helper method to convert TOML value to string
    fn toml_value_to_string(&self, value: &toml::Value) -> String {
        match value {
            toml::Value::String(s) => s.clone(),
            toml::Value::Integer(i) => i.to_string(),
            toml::Value::Float(f) => f.to_string(),
            toml::Value::Boolean(b) => b.to_string(),
            toml::Value::Array(arr) => {
                // Convert array to comma-separated string
                arr.iter()
                    .map(|v| self.toml_value_to_string(v))
                    .collect::<Vec<_>>()
                    .join(",")
            }
            _ => value.to_string(),
        }
    }
}

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

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

    #[test]
    fn test_config_value_conversions() {
        // String conversion
        let value = ConfigValue::String("hello".to_string());
        assert_eq!(value.as_string(), Some("hello".to_string()));

        // Integer conversion
        let value = ConfigValue::Integer(42);
        assert_eq!(value.as_integer(), Some(42));
        assert_eq!(value.as_string(), Some("42".to_string()));
        assert_eq!(value.as_float(), Some(42.0));

        // Boolean conversion
        let value = ConfigValue::Boolean(true);
        assert_eq!(value.as_boolean(), Some(true));
        assert_eq!(value.as_string(), Some("true".to_string()));

        // String to boolean conversion
        let value = ConfigValue::String("yes".to_string());
        assert_eq!(value.as_boolean(), Some(true));

        let value = ConfigValue::String("false".to_string());
        assert_eq!(value.as_boolean(), Some(false));

        // String to integer conversion
        let value = ConfigValue::String("123".to_string());
        assert_eq!(value.as_integer(), Some(123));

        // Invalid conversions
        let value = ConfigValue::String("not_a_number".to_string());
        assert_eq!(value.as_integer(), None);

        let value = ConfigValue::Array(vec![]);
        assert_eq!(value.as_string(), None);
    }

    #[test]
    fn test_config_manager_creation() {
        let manager = ConfigManager::new();
        assert_eq!(manager.sources_count(), 0);
    }

    #[test]
    fn test_config_manager_properties_source() {
        let manager = ConfigManager::new();
        let mut props = HashMap::new();
        props.insert("app.name".to_string(), "TestApp".to_string());
        props.insert("app.port".to_string(), "8080".to_string());
        props.insert("app.debug".to_string(), "true".to_string());

        manager.add_source(ConfigSource::Properties(props)).unwrap();

        assert_eq!(manager.get_string("app.name").unwrap(), "TestApp");
        assert_eq!(manager.get_integer("app.port").unwrap(), 8080);
        assert_eq!(manager.get_boolean("app.debug").unwrap(), true);

        // Test missing key
        assert!(manager.get_string("missing.key").is_err());
    }

    #[test]
    fn test_config_manager_defaults() {
        let manager = ConfigManager::new();

        assert_eq!(
            manager.get_string_or_default("missing.key", "default"),
            "default"
        );
        assert_eq!(manager.get_integer_or_default("missing.key", 42), 42);
        assert_eq!(manager.get_boolean_or_default("missing.key", true), true);
    }

    #[test]
    fn test_config_manager_source_precedence() {
        let manager = ConfigManager::new();

        // Add first source
        let mut props1 = HashMap::new();
        props1.insert("app.name".to_string(), "App1".to_string());
        props1.insert("app.version".to_string(), "1.0".to_string());
        manager
            .add_source(ConfigSource::Properties(props1))
            .unwrap();

        // Add second source with overlapping key
        let mut props2 = HashMap::new();
        props2.insert("app.name".to_string(), "App2".to_string());
        props2.insert("app.port".to_string(), "8080".to_string());
        manager
            .add_source(ConfigSource::Properties(props2))
            .unwrap();

        // Second source should take precedence
        assert_eq!(manager.get_string("app.name").unwrap(), "App2");
        assert_eq!(manager.get_string("app.version").unwrap(), "1.0"); // Only in first source
        assert_eq!(manager.get_string("app.port").unwrap(), "8080"); // Only in second source
    }

    #[test]
    fn test_config_manager_cache() {
        let manager = ConfigManager::new();
        let mut props = HashMap::new();
        props.insert("test.key".to_string(), "test.value".to_string());

        manager.add_source(ConfigSource::Properties(props)).unwrap();

        // First access should populate cache
        assert_eq!(manager.get_string("test.key").unwrap(), "test.value");

        // Second access should use cache
        assert_eq!(manager.get_string("test.key").unwrap(), "test.value");

        // Manual cache update
        manager.set(
            "runtime.key",
            ConfigValue::String("runtime.value".to_string()),
        );
        assert_eq!(manager.get_string("runtime.key").unwrap(), "runtime.value");
    }

    #[test]
    fn test_config_manager_cache_invalidation() {
        let manager = ConfigManager::new();
        let mut props = HashMap::new();
        props.insert("test.key".to_string(), "test.value".to_string());

        manager.add_source(ConfigSource::Properties(props)).unwrap();

        // Access to populate cache
        assert_eq!(manager.get_string("test.key").unwrap(), "test.value");

        // Invalidate cache
        manager.invalidate_cache();

        // Should still work (reloaded from source)
        assert_eq!(manager.get_string("test.key").unwrap(), "test.value");
    }

    #[test]
    fn test_yaml_parsing() {
        let yaml_content = r#"
app:
  name: "TestApp"
  port: 8080
  features:
    - "auth"
    - "logging"
database:
  host: "localhost"
  port: 5432
  ssl: true
"#;

        let manager = ConfigManager::new();
        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml_content).unwrap();
        let config_map = manager.yaml_value_to_config_map(&yaml_value, "").unwrap();

        assert_eq!(config_map.get("app.name"), Some(&"TestApp".to_string()));
        assert_eq!(config_map.get("app.port"), Some(&"8080".to_string()));
        assert_eq!(
            config_map.get("database.host"),
            Some(&"localhost".to_string())
        );
        assert_eq!(config_map.get("database.ssl"), Some(&"true".to_string()));
        assert_eq!(
            config_map.get("app.features"),
            Some(&"auth,logging".to_string())
        );
    }

    #[test]
    fn test_properties_parsing() {
        let properties_content = r#"
# Application configuration
app.name=TestApp
app.port=8080
app.debug=true

# Database configuration
database.host=localhost
database.port=5432
database.ssl=true

# Comments and empty lines should be ignored
! This is another comment style
"#;

        let manager = ConfigManager::new();
        let config_map = manager.parse_properties(properties_content).unwrap();

        assert_eq!(config_map.get("app.name"), Some(&"TestApp".to_string()));
        assert_eq!(config_map.get("app.port"), Some(&"8080".to_string()));
        assert_eq!(config_map.get("app.debug"), Some(&"true".to_string()));
        assert_eq!(
            config_map.get("database.host"),
            Some(&"localhost".to_string())
        );
        assert_eq!(config_map.get("database.port"), Some(&"5432".to_string()));
        assert_eq!(config_map.get("database.ssl"), Some(&"true".to_string()));
    }

    #[test]
    fn test_properties_escape_sequences() {
        let properties_content = r#"
message.welcome=Hello\nWorld\tTest
file.path=C:\\Users\\Test
"#;

        let manager = ConfigManager::new();
        let config_map = manager.parse_properties(properties_content).unwrap();

        assert_eq!(
            config_map.get("message.welcome"),
            Some(&"Hello\nWorld\tTest".to_string())
        );
        assert_eq!(
            config_map.get("file.path"),
            Some(&"C:\\Users\\Test".to_string())
        );
    }

    #[test]
    fn test_config_source_types() {
        let manager = ConfigManager::new();

        // Test different source types
        let mut props = HashMap::new();
        props.insert("source.type".to_string(), "properties".to_string());

        manager.add_source(ConfigSource::Properties(props)).unwrap();

        assert_eq!(manager.get_string("source.type").unwrap(), "properties");
    }

    #[test]
    fn test_multiple_config_formats() {
        let manager = ConfigManager::new();

        // Add properties source
        let mut props = HashMap::new();
        props.insert("app.name".to_string(), "PropsApp".to_string());
        props.insert("app.version".to_string(), "1.0".to_string());
        manager.add_source(ConfigSource::Properties(props)).unwrap();

        // Add higher precedence properties (should override)
        let mut override_props = HashMap::new();
        override_props.insert("app.name".to_string(), "OverrideApp".to_string());
        override_props.insert("app.env".to_string(), "test".to_string());
        manager
            .add_source(ConfigSource::Properties(override_props))
            .unwrap();

        // Higher precedence source should win
        assert_eq!(manager.get_string("app.name").unwrap(), "OverrideApp");
        assert_eq!(manager.get_string("app.version").unwrap(), "1.0"); // Only in first source
        assert_eq!(manager.get_string("app.env").unwrap(), "test"); // Only in second source
    }
}