dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//!     http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

//! # Configuration Management
//! 
//! This module provides a comprehensive configuration management system for Ri, supporting
//! multiple configuration sources, hot reload, and flexible configuration access.
//! 
//! ## Key Components
//! 
//! - **RiConfig**: Basic configuration storage with typed access methods
//! - **RiConfigManager**: Configuration manager that handles multiple sources and hot reload
//! - **RiConfigSource**: Internal enum for different configuration source types
//! 
//! ## Design Principles
//! 
//! 1. **Multiple Sources**: Supports configuration from files (JSON, YAML, TOML) and environment variables
//! 2. **Source Priority**: Environment variables override file configuration
//! 3. **Typed Access**: Provides type-safe methods for accessing configuration values
//! 4. **Flattened Structure**: All configuration is flattened into a single key-value store with dot notation
//! 5. **Hot Reload Support**: Simplified hot reload implementation with full support planned for future
//! 6. **Default Sources**: Automatically loads configuration from common locations
//! 
//! ## Usage
//! 
//! ```rust
//! use ri::prelude::*;
//! 
//! fn example() -> RiResult<()> {
//!     // Create a new config manager
//!     let mut config_manager = RiConfigManager::new();
//!     
//!     // Add configuration sources
//!     config_manager.add_file_source("config.yaml");
//!     config_manager.add_environment_source();
//!     
//!     // Load configuration
//!     config_manager.load()?;
//!     
//!     // Access configuration values
//!     let config = config_manager.config();
//!     let port = config.get_u64("server.port").unwrap_or(8080);
//!     let debug = config.get_bool("app.debug").unwrap_or(false);
//!     
//!     Ok(())
//! }
//! ```

use std::collections::HashMap as FxHashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use tokio::sync::RwLock as TokioRwLock;
use tokio::task::JoinHandle;
use yaml_rust::{YamlLoader, Yaml};

#[cfg(feature = "config_hot_reload")]
use notify::{RecommendedWatcher, RecursiveMode, Watcher};

#[cfg(feature = "pyo3")]
use crate::hooks::RiHookKind;
#[cfg(feature = "pyo3")]
use crate::core::RiServiceContext;

/// Basic configuration storage with typed access methods.
/// 
/// This struct provides a simple key-value store for configuration values, with
/// type-safe methods for accessing values as different types.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Clone)]
pub struct RiConfig {
    /// Internal storage for configuration values
    values: FxHashMap<String, String>,
}

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

impl RiConfig {
    /// Creates a new empty configuration.
    /// 
    /// Returns a new `RiConfig` instance with an empty key-value store.
    pub fn new() -> Self {
        RiConfig { values: FxHashMap::default() }
    }

    /// Returns a list of sensitive configuration key patterns.
    ///
    /// # Security
    ///
    /// These patterns are used to identify sensitive configuration values
    /// that should be masked when logging or displaying configuration.
    fn sensitive_key_patterns() -> Vec<&'static str> {
        vec![
            "password",
            "secret",
            "key",
            "token",
            "api_key",
            "apikey",
            "auth",
            "credential",
            "private",
            "pass",
        ]
    }

    /// Checks if a configuration key is sensitive.
    ///
    /// # Security
    ///
    /// This method checks if the key matches any sensitive patterns.
    /// Sensitive values should be masked when logging or displaying.
    pub fn is_sensitive_key(key: &str) -> bool {
        let key_lower = key.to_lowercase();
        for pattern in Self::sensitive_key_patterns() {
            if key_lower.contains(pattern) {
                return true;
            }
        }
        false
    }

    /// Masks a sensitive value for safe display.
    ///
    /// # Security
    ///
    /// This method masks the middle portion of a sensitive value,
    /// showing only the first 2 and last 2 characters.
    pub fn mask_sensitive_value(value: &str) -> String {
        if value.len() <= 4 {
            return "*".repeat(value.len().max(4));
        }
        
        let first_chars = &value[..2];
        let last_chars = &value[value.len()-2..];
        let middle_len = value.len() - 4;
        
        format!("{}{}{}", first_chars, "*".repeat(middle_len), last_chars)
    }

    /// Gets a configuration value, masking sensitive values.
    ///
    /// # Security
    ///
    /// This method returns the value, but masks it if the key is sensitive.
    /// Use this for logging or displaying configuration values.
    pub fn get_masked(&self, key: &str) -> Option<String> {
        self.values.get(key).map(|v| {
            if Self::is_sensitive_key(key) {
                Self::mask_sensitive_value(v)
            } else {
                v.clone()
            }
        })
    }

    /// Gets all configuration values with sensitive values masked.
    ///
    /// # Security
    ///
    /// This method returns all key-value pairs with sensitive values masked.
    /// Use this for logging or displaying configuration.
    pub fn all_values_masked(&self) -> FxHashMap<String, String> {
        self.values.iter()
            .map(|(k, v)| {
                if Self::is_sensitive_key(k) {
                    (k.clone(), Self::mask_sensitive_value(v))
                } else {
                    (k.clone(), v.clone())
                }
            })
            .collect()
    }

    /// Sets a configuration value.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key (typically using dot notation, e.g., "server.port")
    /// - `value`: The configuration value as a string
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.values.insert(key.into(), value.into());
    }

    /// Gets a configuration value as a string.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<&String>` containing the value if it exists
    pub fn get(&self, key: &str) -> Option<&String> {
        self.values.get(key)
    }

    /// Gets a configuration value as a string slice.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<&str>` containing the value if it exists
    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.values.get(key).map(|s| s.as_str())
    }

    /// Gets a configuration value as a boolean.
    /// 
    /// Supports the following truthy values: "true", "1", "yes", "on"
    /// Supports the following falsy values: "false", "0", "no", "off"
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<bool>` containing the parsed boolean value if the key exists and can be parsed
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        self.values.get(key).and_then(|s| {
            let v = s.trim().to_ascii_lowercase();
            match v.as_str() {
                "true" | "1" | "yes" | "on" => Some(true),
                "false" | "0" | "no" | "off" => Some(false),
                _ => None,
            }
        })
    }

    /// Gets a configuration value as a 64-bit signed integer.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<i64>` containing the parsed integer value if the key exists and can be parsed
    pub fn get_i64(&self, key: &str) -> Option<i64> {
        self.values.get(key).and_then(|s| s.trim().parse::<i64>().ok())
    }

    /// Gets a configuration value as a 64-bit signed integer with bounds checking.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// - `min`: Minimum allowed value
    /// - `max`: Maximum allowed value
    /// 
    /// # Returns
    /// 
    /// An `Option<i64>` containing the parsed and validated integer value
    pub fn get_i64_with_bounds(&self, key: &str, min: i64, max: i64) -> Option<i64> {
        self.get_i64(key).filter(|&v| v >= min && v <= max)
    }

    /// Gets a configuration value as a 64-bit unsigned integer.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<u64>` containing the parsed integer value if the key exists and can be parsed
    pub fn get_u64(&self, key: &str) -> Option<u64> {
        self.values.get(key).and_then(|s| s.trim().parse::<u64>().ok())
    }

    /// Gets a configuration value as a 64-bit unsigned integer with bounds checking.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// - `min`: Minimum allowed value (default: 0)
    /// - `max`: Maximum allowed value
    /// 
    /// # Returns
    /// 
    /// An `Option<u64>` containing the parsed and validated integer value
    pub fn get_u64_with_bounds(&self, key: &str, min: u64, max: u64) -> Option<u64> {
        self.get_u64(key).filter(|&v| v >= min && v <= max)
    }

    /// Gets a configuration value as a positive 64-bit unsigned integer (must be > 0).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<u64>` containing the positive integer value
    pub fn get_positive_u64(&self, key: &str) -> Option<u64> {
        self.get_u64(key).filter(|&v| v > 0)
    }

    /// Gets a configuration value as a port number (1-65535).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<u16>` containing the valid port number
    pub fn get_port(&self, key: &str) -> Option<u16> {
        self.get_u64_with_bounds(key, 1, 65535).map(|v| v as u16)
    }

    /// Gets a configuration value as a 32-bit floating point number.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<f32>` containing the parsed float value if the key exists and can be parsed
    pub fn get_f32(&self, key: &str) -> Option<f32> {
        self.values.get(key).and_then(|s| s.trim().parse::<f32>().ok())
    }

    /// Gets a configuration value as a 32-bit floating point number with bounds checking.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// - `min`: Minimum allowed value
    /// - `max`: Maximum allowed value
    /// 
    /// # Returns
    /// 
    /// An `Option<f32>` containing the parsed and validated float value
    pub fn get_f32_with_bounds(&self, key: &str, min: f32, max: f32) -> Option<f32> {
        self.get_f32(key).filter(|&v| v >= min && v <= max)
    }

    /// Gets a configuration value as a percentage (0.0-100.0).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<f32>` containing the percentage value
    pub fn get_percentage(&self, key: &str) -> Option<f32> {
        self.get_f32_with_bounds(key, 0.0, 100.0)
    }

    /// Gets a configuration value as a rate (0.0-1.0).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<f32>` containing the rate value
    pub fn get_rate(&self, key: &str) -> Option<f32> {
        self.get_f32_with_bounds(key, 0.0, 1.0)
    }

    /// Merges another configuration into this one.
    /// 
    /// Values from the other configuration will override existing values with the same keys.
    /// 
    /// # Parameters
    /// 
    /// - `other`: The other configuration to merge into this one
    pub fn merge(&mut self, other: &RiConfig) {
        for (k, v) in &other.values {
            self.values.insert(k.clone(), v.clone());
        }
    }

    /// Clears all configuration values.
    /// 
    /// Removes all key-value pairs from the configuration.
    pub fn clear(&mut self) {
        self.values.clear();
    }

    pub fn get_or_default<T>(&self, key: &str, default: T) -> T 
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Debug,
    {
        self.values.get(key).and_then(|s| s.trim().parse::<T>().ok()).unwrap_or(default)
    }

    pub fn get_f64(&self, key: &str) -> Option<f64> {
        self.values.get(key).and_then(|s| s.trim().parse::<f64>().ok())
    }

    pub fn get_usize(&self, key: &str) -> Option<usize> {
        self.values.get(key).and_then(|s| s.trim().parse::<usize>().ok())
    }

    pub fn get_i32(&self, key: &str) -> Option<i32> {
        self.values.get(key).and_then(|s| s.trim().parse::<i32>().ok())
    }

    pub fn get_u32(&self, key: &str) -> Option<u32> {
        self.values.get(key).and_then(|s| s.trim().parse::<u32>().ok())
    }

    /// Gets a configuration value as a 32-bit unsigned integer with bounds checking.
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// - `min`: Minimum allowed value
    /// - `max`: Maximum allowed value
    /// 
    /// # Returns
    /// 
    /// An `Option<u32>` containing the parsed and validated integer value
    pub fn get_u32_with_bounds(&self, key: &str, min: u32, max: u32) -> Option<u32> {
        self.get_u32(key).filter(|&v| v >= min && v <= max)
    }

    /// Gets a configuration value as a timeout value in seconds (1-86400).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<u32>` containing the timeout in seconds
    pub fn get_timeout_secs(&self, key: &str) -> Option<u32> {
        self.get_u32_with_bounds(key, 1, 86400)
    }

    /// Gets a configuration value as a retry count (0-100).
    /// 
    /// # Parameters
    /// 
    /// - `key`: The configuration key to look up
    /// 
    /// # Returns
    /// 
    /// An `Option<u32>` containing the retry count
    pub fn get_retry_count(&self, key: &str) -> Option<u32> {
        self.get_u32_with_bounds(key, 0, 100)
    }

    pub fn keys(&self) -> Vec<&str> {
        self.values.keys().map(|s| s.as_str()).collect()
    }

    pub fn all_values(&self) -> Vec<&str> {
        self.values.values().map(|s| s.as_str()).collect()
    }

    pub fn has_key(&self, key: &str) -> bool {
        self.values.contains_key(key)
    }

    pub fn count(&self) -> usize {
        self.values.len()
    }

    #[cfg(feature = "pyo3")]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

#[cfg(feature = "pyo3")]
/// Python constructor for RiConfig
#[pyo3::prelude::pymethods]
impl RiConfig {
    #[new]
    fn py_new() -> Self {
        Self::new()
    }
    
    #[pyo3(name = "set")]
    fn set_impl(&mut self, key: String, value: String) {
        self.set(key, value);
    }
    
    #[pyo3(name = "get")]
    fn get_impl(&self, key: String) -> Option<String> {
        self.get(&key).cloned()
    }
    
    #[pyo3(name = "get_f64")]
    fn get_f64_impl(&self, key: String) -> Option<f64> {
        self.get_f64(&key)
    }
    
    #[pyo3(name = "get_usize")]
    fn get_usize_impl(&self, key: String) -> Option<usize> {
        self.get_usize(&key)
    }
    
    #[pyo3(name = "keys")]
    fn py_keys(&self) -> Vec<String> {
        self.keys().iter().map(|s| s.to_string()).collect()
    }
    
    #[pyo3(name = "values")]
    fn py_values(&self) -> Vec<String> {
        self.all_values().iter().map(|s| s.to_string()).collect()
    }
    
    #[pyo3(name = "contains")]
    fn py_contains(&self, key: String) -> bool {
        self.has_key(&key)
    }
    
    #[pyo3(name = "len")]
    fn py_len(&self) -> usize {
        self.count()
    }
}

/// Internal enum for different configuration source types.
/// 
/// This enum represents the different types of configuration sources that the
/// `RiConfigManager` can handle.
#[derive(Clone)]
enum RiConfigSource {
    /// File-based configuration source
    File(PathBuf),
    /// Environment variable configuration source
    Environment,
}

/// Public-facing configuration manager with hot reload support.
/// 
/// This struct manages multiple configuration sources, loads configuration values,
/// and provides access to the configuration. It supports hot reload and multiple
/// configuration formats.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiConfigManager {
    /// Internal configuration storage
    config: Arc<RwLock<RiConfig>>,
    /// List of configuration sources to load from
    sources: Vec<RiConfigSource>,
    /// Optional hook bus for emitting config reload events
    #[cfg(feature = "pyo3")]
    hooks: Option<Arc<crate::hooks::RiHookBus>>,
    /// Hot reload watcher handle
    #[cfg(feature = "config_hot_reload")]
    watcher: Option<Arc<RecommendedWatcher>>,
    /// Background task handle for the watcher
    watcher_task: Arc<TokioRwLock<Option<JoinHandle<()>>>>,
    /// Monitored file paths for hot reload
    monitored_paths: Arc<TokioRwLock<Vec<PathBuf>>>,
    /// Callback for config changes
    #[cfg(feature = "config_hot_reload")]
    change_callback: Option<Arc<dyn Fn() + Send + Sync>>,
}

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

impl Clone for RiConfigManager {
    fn clone(&self) -> Self {
        RiConfigManager {
            config: self.config.clone(),
            sources: self.sources.clone(),
            #[cfg(feature = "pyo3")]
            hooks: self.hooks.clone(),
            #[cfg(feature = "config_hot_reload")]
            watcher: self.watcher.clone(),
            watcher_task: self.watcher_task.clone(),
            monitored_paths: self.monitored_paths.clone(),
            #[cfg(feature = "config_hot_reload")]
            change_callback: self.change_callback.clone(),
        }
    }
}

impl RiConfigManager {
    /// Creates a new empty configuration manager.
    /// 
    /// Returns a new `RiConfigManager` instance with no configuration sources.
    pub fn new() -> Self {
        RiConfigManager {
            config: Arc::new(RwLock::new(RiConfig::new())),
            sources: Vec::new(),
            #[cfg(feature = "pyo3")]
            hooks: None,
            #[cfg(feature = "config_hot_reload")]
            watcher: None,
            watcher_task: Arc::new(TokioRwLock::new(None)),
            monitored_paths: Arc::new(TokioRwLock::new(Vec::new())),
            #[cfg(feature = "config_hot_reload")]
            change_callback: None,
        }
    }

    /// Creates a new configuration manager with the provided hook bus.
    /// 
    /// This method allows the config manager to emit hooks when configuration is reloaded.
    /// 
    /// # Parameters
    /// 
    /// - `hooks`: The hook bus to use for emitting events
    /// 
    /// # Returns
    /// 
    /// A new `RiConfigManager` instance with the provided hook bus
    #[cfg(feature = "pyo3")]
    pub fn with_hooks(hooks: Arc<crate::hooks::RiHookBus>) -> Self {
        RiConfigManager {
            config: Arc::new(RwLock::new(RiConfig::new())),
            sources: Vec::new(),
            hooks: Some(hooks),
            #[cfg(feature = "config_hot_reload")]
            watcher: None,
            watcher_task: Arc::new(TokioRwLock::new(None)),
            monitored_paths: Arc::new(TokioRwLock::new(Vec::new())),
            #[cfg(feature = "config_hot_reload")]
            change_callback: None,
        }
    }

    /// Adds a file-based configuration source.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the configuration file
    /// 
    /// Supported file formats: JSON, YAML, TOML
    pub fn add_file_source(&mut self, path: impl AsRef<Path>) {
        self.sources.push(RiConfigSource::File(path.as_ref().to_path_buf()));
    }

    /// Adds environment variables as a configuration source.
    /// 
    /// Environment variables with the prefix `Ri_` are loaded as configuration values.
    /// Double underscores (`__`) in environment variable names are converted to dots.
    /// For example, `Ri_SERVER__PORT=8080` becomes `server.port=8080`.
    pub fn add_environment_source(&mut self) {
        self.sources.push(RiConfigSource::Environment);
    }

    /// Notifies registered hooks when configuration is reloaded.
    #[cfg(feature = "pyo3")]
    fn notify_config_reload(&self, _path: &str) {
        if let Some(hooks) = &self.hooks {
            let _ = hooks.emit_with(
                &RiHookKind::ConfigReload,
                &RiServiceContext::new_default().unwrap_or_else(|_| {
                    RiServiceContext::new_with(
                        crate::fs::RiFileSystem::new_auto_root().unwrap_or_else(|_| crate::fs::RiFileSystem::new_with_root(std::env::current_dir().unwrap_or_default())),
                        crate::log::RiLogger::new(&crate::log::RiLogConfig::default(), crate::fs::RiFileSystem::new_with_root(std::env::current_dir().unwrap_or_default())),
                        crate::config::RiConfigManager::new(),
                        crate::hooks::RiHookBus::new(),
                        None,
                    )
                }),
                Some("config_manager"),
                None,
            );
        }
    }

    /// Loads configuration from all registered sources.
    /// 
    /// This method loads configuration from all registered sources in the order they were added,
    /// with later sources overriding earlier ones.
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    pub fn load(&mut self) -> Result<(), crate::core::RiError> {
        let mut cfg = RiConfig::new();

        for source in &self.sources {
            match source {
                RiConfigSource::File(path) => {
                    self.load_file(path, &mut cfg)?;
                    #[cfg(feature = "pyo3")]
                    self.notify_config_reload(path.to_str().unwrap_or(""));
                }
                RiConfigSource::Environment => {
                    self.load_environment(&mut cfg);
                }
            }
        }

        *self.config.write().expect("Failed to lock config for writing") = cfg;
        
        Ok(())
    }

    /// Creates a new configuration manager with default sources.
    /// 
    /// This method creates a new `RiConfigManager` with the following default sources:
    /// 1. Configuration files in the `config` directory (dms.yaml, dms.yml, dms.toml, dms.json)
    /// 2. Environment variables with the prefix `Ri_`
    /// 
    /// It also loads the configuration immediately.
    /// 
    /// # Returns
    /// 
    /// A new `RiConfigManager` instance with default sources and loaded configuration
    pub fn new_default() -> Self {
        let mut manager = Self::new();
        
        // Add default configuration sources
        if let Ok(cwd) = std::env::current_dir() {
            let config_dir = cwd.join("config");
            
            // Add all supported config files in order of priority (lowest to highest)
            manager.add_file_source(config_dir.join("dms.yaml"));
            manager.add_file_source(config_dir.join("dms.yml"));
            manager.add_file_source(config_dir.join("dms.toml"));
            manager.add_file_source(config_dir.join("dms.json"));
        }
        
        // Add environment variables as highest priority
        manager.add_environment_source();
        
        // Load configuration immediately
        let _ = manager.load();
        
        manager
    }

    /// Loads configuration from a file.
    /// 
    /// This method loads configuration from a file, parses it based on its extension,
    /// and flattens it into the provided configuration object.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the configuration file
    /// - `cfg`: The configuration object to load values into
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    fn load_file(&self, path: &Path, cfg: &mut RiConfig) -> Result<(), crate::core::RiError> {
        if !path.exists() {
            return Ok(());
        }

        let text = fs::read_to_string(path)?;
        let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("");

        match extension.to_lowercase().as_str() {
            "json" => {
                if let Ok(map) = serde_json::from_str::<serde_json::Value>(&text) {
                    self.flatten_json(&map, "", cfg);
                }
            }
            "yaml" | "yml" => {
                if let Ok(yaml_docs) = YamlLoader::load_from_str(&text) {
                    for doc in yaml_docs {
                        self.flatten_yaml(&doc, "", cfg);
                    }
                }
            }
            "toml" => {
                if let Ok(toml) = toml::from_str(&text) {
                    self.flatten_toml(&toml, "", cfg);
                }
            }
            _ => {
                // Ignore unsupported file types
            }
        }

        Ok(())
    }

    /// Flattens a JSON value into the configuration.
    /// 
    /// This method recursively flattens a JSON value into the configuration using dot notation.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The JSON value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_json(&self, value: &serde_json::Value, prefix: &str, cfg: &mut RiConfig) {
        Self::flatten_json_static(value, prefix, cfg);
    }

    /// Static version of `flatten_json` for recursion.
    /// 
    /// This static method is used for recursion to avoid the "parameter is only used in recursion" warning.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The JSON value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_json_static(value: &serde_json::Value, prefix: &str, cfg: &mut RiConfig) {
        match value {
            serde_json::Value::Object(map) => {
                for (k, v) in map {
                    let new_prefix = if prefix.is_empty() {
                        k.clone()
                    } else {
                        format!("{prefix}.{k}")
                    };
                    Self::flatten_json_static(v, &new_prefix, cfg);
                }
            }
            serde_json::Value::Array(arr) => {
                for (i, v) in arr.iter().enumerate() {
                    let new_prefix = format!("{prefix}.{i}");
                    Self::flatten_json_static(v, &new_prefix, cfg);
                }
            }
            serde_json::Value::String(s) => {
                cfg.set(prefix, s);
            }
            serde_json::Value::Number(n) => {
                cfg.set(prefix, n.to_string());
            }
            serde_json::Value::Bool(b) => {
                cfg.set(prefix, b.to_string());
            }
            serde_json::Value::Null => {
                cfg.set(prefix, "");
            }
        }
    }

    /// Flattens a YAML value into the configuration.
    /// 
    /// This method recursively flattens a YAML value into the configuration using dot notation.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The YAML value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_yaml(&self, value: &Yaml, prefix: &str, cfg: &mut RiConfig) {
        Self::flatten_yaml_static(value, prefix, cfg);
    }

    /// Static version of `flatten_yaml` for recursion.
    /// 
    /// This static method is used for recursion to avoid the "parameter is only used in recursion" warning.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The YAML value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_yaml_static(value: &Yaml, prefix: &str, cfg: &mut RiConfig) {
        match value {
            Yaml::Hash(map) => {
                for (k, v) in map {
                    if let Yaml::String(key) = k {
                        let new_prefix = if prefix.is_empty() {
                            key.clone()
                        } else {
                            format!("{prefix}.{key}")
                        };
                        Self::flatten_yaml_static(v, &new_prefix, cfg);
                    }
                }
            }
            Yaml::Array(arr) => {
                for (i, v) in arr.iter().enumerate() {
                    let new_prefix = format!("{prefix}.{i}");
                    Self::flatten_yaml_static(v, &new_prefix, cfg);
                }
            }
            Yaml::String(s) => {
                cfg.set(prefix, s);
            }
            Yaml::Integer(n) => {
                cfg.set(prefix, n.to_string());
            }
            Yaml::Real(r) => {
                cfg.set(prefix, r);
            }
            Yaml::Boolean(b) => {
                cfg.set(prefix, b.to_string());
            }
            Yaml::Null => {
                cfg.set(prefix, "");
            }
            _ => {
                // Ignore other YAML types
            }
        }
    }

    /// Flattens a TOML value into the configuration.
    /// 
    /// This method recursively flattens a TOML value into the configuration using dot notation.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The TOML value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_toml(&self, value: &toml::Value, prefix: &str, cfg: &mut RiConfig) {
        Self::flatten_toml_static(value, prefix, cfg);
    }

    /// Static version of `flatten_toml` for recursion.
    /// 
    /// This static method is used for recursion to avoid the "parameter is only used in recursion" warning.
    /// 
    /// # Parameters
    /// 
    /// - `value`: The TOML value to flatten
    /// - `prefix`: The current prefix for keys (used for recursion)
    /// - `cfg`: The configuration object to load values into
    fn flatten_toml_static(value: &toml::Value, prefix: &str, cfg: &mut RiConfig) {
        match value {
            toml::Value::Table(table) => {
                for (k, v) in table {
                    let new_prefix = if prefix.is_empty() {
                        k.clone()
                    } else {
                        format!("{prefix}.{k}")
                    };
                    Self::flatten_toml_static(v, &new_prefix, cfg);
                }
            }
            toml::Value::Array(arr) => {
                for (i, v) in arr.iter().enumerate() {
                    let new_prefix = format!("{prefix}.{i}");
                    Self::flatten_toml_static(v, &new_prefix, cfg);
                }
            }
            toml::Value::String(s) => {
                cfg.set(prefix, s);
            }
            toml::Value::Integer(n) => {
                cfg.set(prefix, n.to_string());
            }
            toml::Value::Float(f) => {
                cfg.set(prefix, f.to_string());
            }
            toml::Value::Boolean(b) => {
                cfg.set(prefix, b.to_string());
            }
            toml::Value::Datetime(dt) => {
                cfg.set(prefix, dt.to_string());
            }
        }
    }

    /// Loads configuration from environment variables.
    /// 
    /// This method loads environment variables with the prefix `Ri_` into the configuration.
    /// Double underscores (`__`) in environment variable names are converted to dots.
    /// 
    /// # Parameters
    /// 
    /// - `cfg`: The configuration object to load values into
    fn load_environment(&self, cfg: &mut RiConfig) {
        for (name, value) in std::env::vars() {
            if let Some(rest) = name.strip_prefix("Ri_") {
                let key_parts: Vec<String> = rest
                    .split("__")
                    .map(|part| part.to_ascii_lowercase())
                    .collect();
                let key = key_parts.join(".");
                if !key.is_empty() {
                    cfg.set(key, value);
                }
            }
        }
    }

    /// Starts the configuration watcher for hot reload.
    /// 
    /// This method starts watching all registered file-based configuration sources
    /// for changes. When a configuration file is modified, it will be automatically
    /// reloaded and the change callback (if registered) will be invoked.
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    #[cfg(feature = "config_hot_reload")]
    pub async fn start_watcher(&mut self) -> Result<(), crate::core::RiError> {
        self.start_watcher_with_callback::<fn()>(None).await
    }

    /// Starts the configuration watcher with a custom change callback.
    /// 
    /// This method starts watching all registered file-based configuration sources
    /// for changes. When a configuration file is modified, it will be automatically
    /// reloaded and the provided callback will be invoked.
    /// 
    /// # Parameters
    /// 
    /// - `callback`: Optional callback function to invoke when configuration changes
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    #[cfg(feature = "config_hot_reload")]
    pub async fn start_watcher_with_callback<F>(&mut self, callback: Option<Arc<dyn Fn() + Send + Sync>>) -> Result<(), crate::core::RiError> {
        let (tx, mut rx) = tokio::sync::mpsc::channel::<notify::Result<notify::Event>>(100);
        
        let mut watcher = RecommendedWatcher::new(
            move |res| {
                let _ = tx.blocking_send(res);
            },
            notify::Config::default(),
        ).map_err(|e| crate::core::RiError::Config(format!("Failed to create config watcher: {}", e)))?;
        
        let mut monitored = Vec::with_capacity(self.sources.len());
        
        for source in &self.sources {
            if let RiConfigSource::File(path) = source {
                if path.exists() {
                    watcher.watch(path, RecursiveMode::NonRecursive)
                        .map_err(|e| crate::core::RiError::Config(format!("Failed to watch config file {}: {}", path.display(), e)))?;
                    monitored.push(path.clone());
                }
            }
        }
        
        let monitored_paths = self.monitored_paths.clone();
        let manager = self.clone();
        let change_callback = callback.clone();
        
        let task = tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                match event {
                    Ok(event) => {
                        if let Some(paths) = event.paths.first() {
                            let changed_path = paths.clone();
                            
                            {
                                let mut paths_guard = monitored_paths.write().await;
                                if !paths_guard.contains(&changed_path) {
                                    paths_guard.push(changed_path.clone());
                                }
                            }
                            
                            log::info!("Config file changed: {}", changed_path.display());
                            
                            if let Err(e) = manager.reload_file(&changed_path).await {
                                log::error!("Failed to reload config file {}: {}", changed_path.display(), e);
                            }
                            
                            if let Some(ref cb) = change_callback {
                                cb();
                            }
                            
                            #[cfg(feature = "pyo3")]
                            manager.notify_config_reload(changed_path.to_str().unwrap_or(""));
                        }
                    }
                    Err(e) => {
                        log::warn!("Config watcher error: {:?}", e);
                    }
                }
            }
        });
        
        self.watcher = Some(Arc::new(watcher));
        *self.watcher_task.write().await = Some(task);
        self.change_callback = callback;
        
        let mut paths_guard = self.monitored_paths.write().await;
        *paths_guard = monitored;
        
        Ok(())
    }

    /// Reloads configuration from a specific file.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the configuration file to reload
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    #[cfg(feature = "config_hot_reload")]
    async fn reload_file(&self, path: &PathBuf) -> Result<(), crate::core::RiError> {
        let mut new_config = self.config.read().expect("Failed to lock config for reading").clone();
        self.load_file(path, &mut new_config)?;
        
        *self.config.write().expect("Failed to lock config for writing") = new_config;
        
        Ok(())
    }

    /// Stops the configuration watcher.
    /// 
    /// This method stops the configuration watcher and cleans up associated resources.
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    #[cfg(feature = "config_hot_reload")]
    pub async fn stop_watcher(&mut self) -> Result<(), crate::core::RiError> {
        let task = self.watcher_task.write().await.take();
        if let Some(task) = task {
            task.abort();
        }
        
        self.watcher = None;
        
        let mut paths_guard = self.monitored_paths.write().await;
        paths_guard.clear();
        
        Ok(())
    }

    /// Gets the list of monitored configuration file paths.
    /// 
    /// # Returns
    /// 
    /// A vector of paths being monitored for changes
    pub async fn get_monitored_paths(&self) -> Vec<PathBuf> {
        self.monitored_paths.read().await.clone()
    }

    /// Starts the configuration watcher for hot reload.
    /// 
    /// This is a no-op implementation when the `config_hot_reload` feature is not enabled.
    /// 
    /// # Returns
    /// 
    /// A `Result<(), RiError>` indicating success or failure
    #[cfg(not(feature = "config_hot_reload"))]
    pub async fn start_watcher(&mut self) -> Result<(), crate::core::RiError> {
        Ok(())
    }

    /// Gets a reference to the loaded configuration.
    /// 
    /// # Returns
    /// 
    /// A `RiConfig` clone of the loaded configuration
    pub fn config(&self) -> RiConfig {
        self.config.read().expect("Failed to lock config for reading").clone()
    }

    /// Gets a mutable reference to the loaded configuration.
    /// 
    /// # Returns
    /// 
    /// A `std::sync::RwLockWriteGuard<RiConfig>` for the loaded configuration
    pub fn config_mut(&mut self) -> std::sync::RwLockWriteGuard<'_, RiConfig> {
        self.config.write().expect("Failed to lock config for writing")
    }
}

#[cfg(feature = "pyo3")]
/// Python constructor for RiConfigManager
#[pyo3::prelude::pymethods]
impl RiConfigManager {
    #[new]
    fn py_new() -> Self {
        Self::new()
    }
    
    /// Adds a file-based configuration source from Python
    ///
    /// ## Supported Formats
    ///
    /// - `.json`: JSON configuration format
    /// - `.yaml`, `.yml`: YAML configuration format
    /// - `.toml`: TOML configuration format
    #[pyo3(name = "add_file_source")]
    fn add_file_source_impl(&mut self, path: String) {
        self.add_file_source(path);
    }

    /// Adds environment variables as a configuration source from Python
    ///
    /// Environment variables are prefixed with `Ri_` and double underscores
    /// are converted to dots (`.`) in the configuration key hierarchy.
    /// Example: `Ri_DATABASE__HOST` becomes `database.host`
    #[pyo3(name = "add_environment_source")]
    fn add_environment_source_impl(&mut self) {
        self.add_environment_source();
    }

    /// Gets a configuration value as string from Python
    ///
    /// This method retrieves a configuration value by key, returning it as a string.
    /// If the key does not exist, returns `None`.
    ///
    /// ## Parameters
    ///
    /// - `key`: Configuration key string (dot-notation supported, e.g., "server.port")
    ///
    /// ## Returns
    ///
    /// Optional string containing the configuration value if found, `None` otherwise
    ///
    /// ## Example
    ///
    /// ```python
    /// manager = RiConfigManager.new_default()
    /// value = manager.get("server.port")
    /// if value:
    ///     print(f"Server port: {value}")
    /// ```
    #[pyo3(name = "get")]
    fn get_config_impl(&self, key: String) -> Option<String> {
        self.config().get(&key).cloned()
    }
}

#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Clone, Debug)]
pub struct RiConfigValidator {
    required_keys: Vec<String>,
    port_keys: Vec<String>,
    timeout_keys: Vec<String>,
    secret_keys: Vec<String>,
    url_keys: Vec<String>,
    positive_int_keys: Vec<String>,
}

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

impl RiConfigValidator {
    pub fn new() -> Self {
        RiConfigValidator {
            required_keys: Vec::new(),
            port_keys: vec!["server.port".to_string(), "cache.redis.port".to_string(), "database.port".to_string()],
            timeout_keys: vec!["server.timeout".to_string(), "cache.ttl".to_string(), "session.timeout".to_string()],
            secret_keys: vec!["auth.jwt.secret".to_string(), "auth.password.salt".to_string(), "encryption.key".to_string()],
            url_keys: vec!["database.url".to_string(), "cache.redis.url".to_string(), "mq.url".to_string()],
            positive_int_keys: vec!["pool.size".to_string(), "worker.count".to_string(), "retry.max".to_string()],
        }
    }

    pub fn add_required(&mut self, key: String) -> &mut Self {
        self.required_keys.push(key);
        self
    }

    pub fn add_port_check(&mut self, key: String) -> &mut Self {
        self.port_keys.push(key);
        self
    }

    pub fn add_timeout_check(&mut self, key: String) -> &mut Self {
        self.timeout_keys.push(key);
        self
    }

    pub fn add_secret_check(&mut self, key: String) -> &mut Self {
        self.secret_keys.push(key);
        self
    }

    pub fn add_url_check(&mut self, key: String) -> &mut Self {
        self.url_keys.push(key);
        self
    }

    pub fn add_positive_int_check(&mut self, key: String) -> &mut Self {
        self.positive_int_keys.push(key);
        self
    }

    pub fn validate_config(&self, config: &RiConfig) -> Result<(), crate::core::RiError> {
        for key in &self.required_keys {
            if !config.has_key(key) {
                return Err(crate::core::RiError::Config(format!(
                    "Missing required configuration key: {}", key
                )));
            }
        }

        for key in &self.port_keys {
            if let Some(port) = config.get_port(key) {
                if port == 0 {
                    return Err(crate::core::RiError::Config(format!(
                        "Invalid port number for {}: must be between 1 and 65535", key
                    )));
                }
            }
        }

        for key in &self.timeout_keys {
            if let Some(timeout) = config.get_timeout_secs(key) {
                if timeout == 0 {
                    return Err(crate::core::RiError::Config(format!(
                        "Invalid timeout for {}: must be between 1 and 86400 seconds", key
                    )));
                }
            }
        }

        for key in &self.secret_keys {
            if let Some(secret) = config.get_str(key) {
                if secret.len() < 8 {
                    return Err(crate::core::RiError::Config(format!(
                        "Secret key {} is too short: minimum length is 8 characters", key
                    )));
                }
                if secret == "secret" || secret == "password" || secret == "123456" {
                    return Err(crate::core::RiError::Config(format!(
                        "Insecure secret key detected for {}: using default or weak value", key
                    )));
                }
            }
        }

        for key in &self.url_keys {
            if let Some(url) = config.get_str(key) {
                if !url.starts_with("http://") && !url.starts_with("https://")
                    && !url.starts_with("redis://") && !url.starts_with("postgresql://")
                    && !url.starts_with("mysql://") && !url.starts_with("amqp://")
                    && !url.starts_with("kafka://") && !url.starts_with("sqlite://")
                {
                    return Err(crate::core::RiError::Config(format!(
                        "Invalid URL format for {}: {}", key, url
                    )));
                }
            }
        }

        for key in &self.positive_int_keys {
            if let Some(value) = config.get_u32(key) {
                if value == 0 {
                    return Err(crate::core::RiError::Config(format!(
                        "Invalid value for {}: must be a positive integer", key
                    )));
                }
            }
        }

        Ok(())
    }

    pub fn validate_with_requirements(
        &self,
        config: &RiConfig,
        requirements: &[String],
    ) -> Result<(), crate::core::RiError> {
        for key in requirements {
            if !config.has_key(key) {
                return Err(crate::core::RiError::Config(format!(
                    "Missing required configuration key: {}", key
                )));
            }
        }
        self.validate_config(config)
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiConfigValidator {
    #[new]
    fn py_new() -> Self {
        Self::new()
    }

    #[pyo3(name = "require")]
    fn py_add_required(&mut self, key: String) {
        self.required_keys.push(key);
    }

    #[pyo3(name = "require_port")]
    fn py_add_port_check(&mut self, key: String) {
        self.port_keys.push(key);
    }

    #[pyo3(name = "require_timeout")]
    fn py_add_timeout_check(&mut self, key: String) {
        self.timeout_keys.push(key);
    }

    #[pyo3(name = "require_secret")]
    fn py_add_secret_check(&mut self, key: String) {
        self.secret_keys.push(key);
    }

    #[pyo3(name = "require_url")]
    fn py_add_url_check(&mut self, key: String) {
        self.url_keys.push(key);
    }

    #[pyo3(name = "require_positive_int")]
    fn py_add_positive_int_check(&mut self, key: String) {
        self.positive_int_keys.push(key);
    }

    #[pyo3(name = "validate")]
    fn py_validate(&self, config: &RiConfig) -> bool {
        self.validate_config(config).is_ok()
    }
}