confers 0.2.2

A modern, type-safe configuration management library with validation, diff, and hot-reload support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

#[cfg(feature = "audit")]
use crate::audit::AuditConfig as AuditConfigComplex;
use crate::audit::Sanitize;
#[cfg(feature = "encryption")]
use crate::encryption::ConfigEncryption;
use crate::error::ConfigError;
use crate::providers::cli_provider::CliConfigProvider;
use crate::providers::environment_provider::EnvironmentProvider;
use crate::providers::file_provider::FileConfigProvider;
use crate::providers::provider::ProviderManager;
use crate::providers::SerializedProvider;
#[cfg(all(feature = "remote", feature = "encryption"))]
use crate::security::secure_string::{SecureString, SensitivityLevel};
use figment::providers::{Format, Json, Serialized, Toml, Yaml};
#[cfg(feature = "encryption")]
use figment::value::Tag;
use figment::value::Value;
use figment::Figment;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[allow(unused_imports)]
use std::sync::Arc;
#[cfg(feature = "validation")]
use validator::Validate;

#[cfg(any(feature = "encryption", feature = "remote"))]
// use crate::security; // Uncomment when needed
/// A type alias for the sanitizer function
type SanitizerFn<T> = std::sync::Arc<dyn Fn(T) -> Result<T, ConfigError> + Send + Sync>;

/// Trait for optionally validating configuration
pub trait OptionalValidate {
    fn optional_validate(&self) -> Result<(), crate::error::ConfigError> {
        Ok(())
    }
}

#[cfg(feature = "validation")]
/// Implement OptionalValidate for types that implement Validate
impl<T: Validate> OptionalValidate for T {
    fn optional_validate(&self) -> Result<(), crate::error::ConfigError> {
        self.validate()
            .map_err(|e| crate::error::ConfigError::ValidationError(format!("{:?}", e)))
    }
}

#[cfg(feature = "remote")]
use crate::providers::consul_provider::ConsulConfigProvider;

#[cfg(feature = "remote")]
use crate::providers::etcd_provider::EtcdConfigProvider;

#[cfg(feature = "remote")]
use crate::providers::http_provider::HttpConfigProvider;

#[cfg(feature = "monitoring")]
use std::sync::OnceLock;

/// Get current memory usage in MB using sysinfo crate
/// Cross-platform support: Linux, macOS, Windows
/// Uses caching to avoid repeated system calls
#[allow(dead_code)]
#[cfg(feature = "monitoring")]
fn get_memory_usage_mb() -> Option<f64> {
    static LAST_MEMORY: OnceLock<(f64, std::time::Instant)> = OnceLock::new();
    let now = std::time::Instant::now();

    // Use cache duration from constants (1 second) to balance performance and accuracy
    if let Some((memory, time)) = LAST_MEMORY.get() {
        if now.duration_since(*time)
            < std::time::Duration::from_millis(crate::constants::time::MEMORY_CACHE_DURATION_MS)
        {
            return Some(*memory);
        }
    }

    use std::process;
    use sysinfo::{Pid, ProcessRefreshKind, RefreshKind, System};

    let sys = System::new_with_specifics(
        RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
    );

    let current_pid = Pid::from_u32(process::id());
    let memory = sys
        .process(current_pid)
        .map(|process| process.memory() as f64 / 1024.0 / 1024.0);

    if let Some(mem_value) = memory {
        let _ = LAST_MEMORY.set((mem_value, now));
    }

    memory
}

/// Get current memory usage with cache (deprecated)
///
/// # Deprecated
///
/// This method is deprecated because OnceLock cannot clear the cache.
/// Please use `get_memory_usage_mb()` directly, which automatically refreshes
/// the cache after 1 second (see `crate::constants::time::MEMORY_CACHE_DURATION_MS`).
///
/// The cache cannot be force-refreshed due to OnceLock limitations.
/// For more accurate memory checks, the system relies on a reasonable cache
/// duration that balances performance and accuracy.
#[deprecated(since = "0.3.0", note = "Use get_memory_usage_mb() instead")]
#[allow(dead_code)]
#[cfg(feature = "monitoring")]
pub fn force_refresh_memory() -> Option<f64> {
    // Note: OnceLock cannot be cleared, so this function cannot force a refresh.
    // It returns the cached value (or fresh if cache expired).
    get_memory_usage_mb()
}

#[allow(dead_code)]
#[cfg(not(feature = "monitoring"))]
fn get_memory_usage_mb() -> Option<f64> {
    None
}

#[cfg(feature = "audit")]
use crate::audit::AuditLogger;

/// Configuration loader that supports multiple sources and formats
#[derive(Clone)]
pub struct ConfigLoader<T> {
    /// Default configuration values
    defaults: Option<T>,
    /// Explicit configuration files to load
    explicit_files: Vec<PathBuf>,
    /// Application name for standard config file locations
    app_name: Option<String>,
    /// Environment prefix for environment variables
    env_prefix: Option<String>,
    /// Whether to use environment variables
    use_env: bool,
    /// Whether to use strict mode (fail on any error)
    strict: bool,
    /// Whether to enable file watching
    watch: bool,
    /// Format detection mode (ByContent, ByExtension)
    format_detection: Option<String>,
    /// Custom sanitizer function
    #[cfg(any(feature = "encryption", feature = "remote"))]
    sanitizer: Option<SanitizerFn<T>>,
    /// CLI configuration provider
    cli_provider: Option<CliConfigProvider>,
    /// Remote configuration settings
    #[cfg(feature = "remote")]
    remote_config: RemoteConfig,
    /// Etcd configuration provider
    #[cfg(feature = "remote")]
    etcd_provider: Option<EtcdConfigProvider>,
    /// Consul configuration provider
    #[cfg(feature = "remote")]
    consul_provider: Option<ConsulConfigProvider>,
    /// Audit configuration
    #[cfg(feature = "audit")]
    audit: AuditConfig,
    /// Maximum memory limit in MB (0 = no limit)
    memory_limit_mb: usize,
    /// Maximum configuration file size in MB (0 = no limit)
    max_config_size_mb: usize,
}

/// Remote configuration settings
#[cfg(feature = "remote")]
#[derive(Clone, Debug)]
pub struct RemoteConfig {
    enabled: bool,
    url: Option<String>,
    #[cfg(feature = "encryption")]
    token: Option<Arc<SecureString>>,
    #[cfg(not(feature = "encryption"))]
    token: Option<String>,
    username: Option<String>,
    #[cfg(feature = "encryption")]
    password: Option<Arc<SecureString>>,
    #[cfg(not(feature = "encryption"))]
    password: Option<String>,
    ca_cert: Option<PathBuf>,
    client_cert: Option<PathBuf>,
    client_key: Option<PathBuf>,
    timeout: Option<String>,
    fallback: bool,
}

#[cfg(feature = "remote")]
impl RemoteConfig {
    pub fn new() -> Self {
        Self::default()
    }

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

    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    #[cfg(feature = "encryption")]
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(Arc::new(SecureString::new(
            token.into(),
            SensitivityLevel::High,
        )));
        self
    }

    #[cfg(not(feature = "encryption"))]
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    pub fn with_username(mut self, username: impl Into<String>) -> Self {
        self.username = Some(username.into());
        self
    }

    #[cfg(feature = "encryption")]
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(Arc::new(SecureString::new(
            password.into(),
            SensitivityLevel::Critical,
        )));
        self
    }

    #[cfg(not(feature = "encryption"))]
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    pub fn with_timeout(mut self, timeout: impl Into<String>) -> Self {
        self.timeout = Some(timeout.into());
        self
    }

    pub fn with_fallback(mut self, fallback: bool) -> Self {
        self.fallback = fallback;
        self
    }

    pub fn url(&self) -> Option<&str> {
        self.url.as_deref()
    }

    pub fn username(&self) -> Option<&str> {
        self.username.as_deref()
    }
}

#[cfg(feature = "remote")]
impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            url: None,
            token: None,
            username: None,
            password: None,
            ca_cert: None,
            client_cert: None,
            client_key: None,
            timeout: None,
            fallback: true,
        }
    }
}

/// Simple audit configuration for ConfigLoader
#[cfg(feature = "audit")]
#[derive(Clone, Debug, Default)]
pub struct AuditConfig {
    pub enabled: bool,
    pub file_path: Option<String>,
}

impl<T> Default for ConfigLoader<T> {
    fn default() -> Self {
        Self {
            defaults: None,
            explicit_files: Vec::new(),
            app_name: None,
            env_prefix: None,
            use_env: true,
            strict: false,
            watch: false,
            format_detection: None,
            #[cfg(any(feature = "encryption", feature = "remote"))]
            sanitizer: None,
            cli_provider: None,
            #[cfg(feature = "remote")]
            remote_config: RemoteConfig::default(),
            #[cfg(feature = "remote")]
            etcd_provider: None,
            #[cfg(feature = "remote")]
            consul_provider: None,
            #[cfg(feature = "audit")]
            audit: AuditConfig::default(),
            memory_limit_mb: 512, // Increased to reasonable default for production
            max_config_size_mb: crate::constants::config::MAX_CONFIG_SIZE_MB,
        }
    }
}

impl<T: OptionalValidate> ConfigLoader<T> {
    /// Create a new configuration loader
    pub fn new() -> Self {
        Self::default()
    }

    /// Set default configuration values
    pub fn with_defaults(mut self, defaults: T) -> Self {
        self.defaults = Some(defaults);
        self
    }

    /// Add an explicit configuration file
    pub fn with_file(mut self, path: impl AsRef<Path>) -> Self {
        self.explicit_files.push(path.as_ref().to_path_buf());
        self
    }

    /// Add multiple explicit configuration files
    pub fn with_files(mut self, paths: Vec<impl AsRef<Path>>) -> Self {
        self.explicit_files
            .extend(paths.iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    /// Set the application name for standard config file locations
    pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
        self.app_name = Some(name.into());
        self
    }

    /// Set the environment prefix for environment variables
    pub fn with_env_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.env_prefix = Some(prefix.into());
        self
    }

    /// Enable or disable environment variables
    pub fn with_env(mut self, enabled: bool) -> Self {
        self.use_env = enabled;
        self
    }

    /// Enable or disable strict mode
    pub fn with_strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Enable or disable file watching
    pub fn with_watch(mut self, watch: bool) -> Self {
        self.watch = watch;
        self
    }

    /// Set format detection mode
    pub fn with_format_detection(mut self, mode: impl Into<String>) -> Self {
        self.format_detection = Some(mode.into());
        self
    }

    /// Set custom sanitizer function
    #[cfg(any(feature = "encryption", feature = "remote"))]
    pub fn with_sanitizer(
        mut self,
        sanitizer: impl Fn(T) -> Result<T, ConfigError> + Send + Sync + 'static,
    ) -> Self {
        self.sanitizer = Some(std::sync::Arc::new(sanitizer));
        self
    }

    /// Set CLI configuration provider
    pub fn with_cli_provider(mut self, provider: CliConfigProvider) -> Self {
        self.cli_provider = Some(provider);
        self
    }

    /// Configure remote configuration
    #[cfg(feature = "remote")]
    pub fn with_remote_config(mut self, url: impl Into<String>) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.url = Some(url.into());
        self
    }

    /// Alias for with_remote_config - enable remote configuration with URL
    #[cfg(feature = "remote")]
    pub fn remote(self, url: impl Into<String>) -> Self {
        self.with_remote_config(url)
    }

    /// Alias for with_remote_config - enable remote configuration with URL
    #[cfg(feature = "remote")]
    pub fn with_remote(self, url: impl Into<String>) -> Self {
        self.with_remote_config(url)
    }

    /// Configure remote configuration with authentication
    #[cfg(all(feature = "remote", feature = "encryption"))]
    pub fn with_remote_auth(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.username = Some(username.into());
        self.remote_config.password = Some(Arc::new(SecureString::new(
            password.into(),
            SensitivityLevel::Critical,
        )));
        self
    }

    /// Configure remote configuration with authentication (non-encrypted)
    #[cfg(feature = "remote")]
    #[cfg(not(feature = "encryption"))]
    pub fn with_remote_auth(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.username = Some(username.into());
        self.remote_config.password = Some(password.into());
        self
    }

    /// Configure remote configuration with bearer token
    #[cfg(all(feature = "remote", feature = "encryption"))]
    pub fn with_remote_token(mut self, token: impl Into<String>) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.token = Some(Arc::new(SecureString::new(
            token.into(),
            SensitivityLevel::High,
        )));
        self
    }

    /// Configure remote configuration with bearer token (non-encrypted)
    #[cfg(feature = "remote")]
    #[cfg(not(feature = "encryption"))]
    pub fn with_remote_token(mut self, token: impl Into<String>) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.token = Some(token.into());
        self
    }

    /// Configure remote configuration with TLS
    #[cfg(feature = "remote")]
    pub fn with_remote_tls(
        mut self,
        ca_cert: impl AsRef<Path>,
        client_cert: Option<impl AsRef<Path>>,
        client_key: Option<impl AsRef<Path>>,
    ) -> Self {
        self.remote_config.enabled = true;
        self.remote_config.ca_cert = Some(ca_cert.as_ref().to_path_buf());
        self.remote_config.client_cert = client_cert.map(|p| p.as_ref().to_path_buf());
        self.remote_config.client_key = client_key.map(|p| p.as_ref().to_path_buf());
        self
    }

    /// Set etcd configuration provider
    #[cfg(feature = "remote")]
    pub fn with_etcd(mut self, provider: EtcdConfigProvider) -> Self {
        self.etcd_provider = Some(provider);
        self
    }

    /// Set consul configuration provider
    #[cfg(feature = "remote")]
    pub fn with_consul(mut self, provider: ConsulConfigProvider) -> Self {
        self.consul_provider = Some(provider);
        self
    }

    /// Configure audit logging
    #[cfg(feature = "audit")]
    pub fn with_audit(mut self, enabled: bool) -> Self {
        self.audit.enabled = enabled;
        self
    }

    /// Configure audit file path
    #[cfg(feature = "audit")]
    pub fn with_audit_file(mut self, path: impl Into<String>) -> Self {
        self.audit.enabled = true;
        self.audit.file_path = Some(path.into());
        self
    }

    /// Set remote configuration timeout
    #[cfg(feature = "remote")]
    pub fn with_remote_timeout(mut self, timeout: impl Into<String>) -> Self {
        self.remote_config.timeout = Some(timeout.into());
        self
    }

    /// Set memory limit in MB
    pub fn with_memory_limit(mut self, limit_mb: usize) -> Self {
        if limit_mb > 0 && limit_mb < 100 {
            #[cfg(feature = "tracing")]
            tracing::warn!(
                "Memory limit of {}MB may be too low for production. Recommended minimum: 100MB",
                limit_mb
            );
        }
        self.memory_limit_mb = limit_mb;
        self
    }

    /// Set maximum configuration file size in MB
    ///
    /// This prevents loading extremely large configuration files that could
    /// cause memory issues or DoS attacks. Set to 0 to disable the limit.
    ///
    /// # Arguments
    ///
    /// * `size_mb` - Maximum file size in megabytes (default: 10MB)
    ///
    /// # Example
    ///
    /// ```rust
    /// # use confers::ConfigLoader;
    /// # use serde::{Deserialize, Serialize};
    /// # #[derive(Debug, Clone, Serialize, Deserialize)]
    /// # struct Config {}
    /// # impl confers::OptionalValidate for Config {
    /// #     fn optional_validate(&self) -> Result<(), confers::ConfigError> {
    /// #         Ok(())
    /// #     }
    /// # }
    /// let loader = ConfigLoader::<Config>::new()
    ///     .with_max_config_size(5); // Limit to 5MB
    /// ```
    pub fn with_max_config_size(mut self, size_mb: usize) -> Self {
        self.max_config_size_mb = size_mb;
        self
    }

    /// Set remote configuration fallback
    #[cfg(feature = "remote")]
    pub fn with_remote_fallback(mut self, fallback: bool) -> Self {
        self.remote_config.fallback = fallback;
        self
    }

    /// Set remote username
    #[cfg(feature = "remote")]
    pub fn with_remote_username(mut self, username: impl Into<String>) -> Self {
        self.remote_config.username = Some(username.into());
        self
    }

    /// Alias for with_remote_username
    #[cfg(feature = "remote")]
    pub fn remote_username(self, username: impl Into<String>) -> Self {
        self.with_remote_username(username)
    }

    /// Set remote password
    #[cfg(all(feature = "remote", feature = "encryption"))]
    pub fn with_remote_password(mut self, password: impl Into<String>) -> Self {
        self.remote_config.password = Some(Arc::new(SecureString::new(
            password.into(),
            SensitivityLevel::Critical,
        )));
        self
    }

    /// Set remote password (non-encrypted)
    #[cfg(feature = "remote")]
    #[cfg(not(feature = "encryption"))]
    pub fn with_remote_password(mut self, password: impl Into<String>) -> Self {
        self.remote_config.password = Some(password.into());
        self
    }

    /// Alias for with_remote_password
    #[cfg(feature = "remote")]
    pub fn remote_password(self, password: impl Into<String>) -> Self {
        self.with_remote_password(password)
    }

    /// Configure audit logging
    #[cfg(feature = "audit")]
    pub fn with_audit_log(mut self, enabled: bool) -> Self {
        self.audit.enabled = enabled;
        self
    }

    /// Configure audit file path
    #[cfg(feature = "audit")]
    pub fn with_audit_log_path(mut self, path: impl Into<String>) -> Self {
        self.audit.enabled = true;
        self.audit.file_path = Some(path.into());
        self
    }

    /// Configure remote CA cert
    #[cfg(feature = "remote")]
    pub fn with_remote_ca_cert(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.remote_config.ca_cert = Some(path.into());
        self
    }

    /// Configure remote client cert
    #[cfg(feature = "remote")]
    pub fn with_remote_client_cert(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.remote_config.client_cert = Some(path.into());
        self
    }

    /// Configure remote client key
    #[cfg(feature = "remote")]
    pub fn with_remote_client_key(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.remote_config.client_key = Some(path.into());
        self
    }

    /// Detect file format by content with improved heuristics
    pub fn detect_format(path: &Path) -> Option<String> {
        use crate::utils::file_format::{detect_format_by_content, detect_format_by_extension};

        // Try content detection first
        if let Some(format) = detect_format_by_content(path) {
            return Some(format.to_string());
        }

        // Fall back to extension detection
        detect_format_by_extension(path).map(|f| f.to_string())
    }

    /// Detect file format by extension
    pub fn detect_format_by_extension(path: &Path) -> Option<String> {
        use crate::utils::file_format::detect_format_by_extension;
        detect_format_by_extension(path).map(|f| f.to_string())
    }

    /// Setup base provider with default configuration
    ///
    /// This helper method initializes the ProviderManager and adds the base figment
    /// as a SerializedProvider, which includes default configuration values.
    #[allow(dead_code)]
    fn setup_base_provider(&self, figment: &Figment) -> ProviderManager {
        let mut manager = ProviderManager::new();
        manager.add_provider(SerializedProvider::new(figment.clone(), "base_config"));
        manager
    }

    /// Setup file provider for loading explicit configuration files
    ///
    /// This helper method adds a FileConfigProvider to the manager if explicit files
    /// are configured. Files are loaded with priority 40 (lower than environment variables).
    #[allow(dead_code)]
    fn setup_file_provider(&self, manager: &mut ProviderManager) -> Result<(), ConfigError> {
        if !self.explicit_files.is_empty() {
            // Check file sizes before loading
            if self.max_config_size_mb > 0 {
                for path in &self.explicit_files {
                    if path.exists() {
                        let metadata = std::fs::metadata(path)
                            .map_err(|e| ConfigError::IoError(e.to_string()))?;

                        let file_size = metadata.len();
                        let max_size_bytes = self.max_config_size_mb * 1024 * 1024;

                        if file_size > max_size_bytes as u64 {
                            return Err(ConfigError::ConfigTooLarge {
                                path: path.clone(),
                                size_mb: (file_size / (1024 * 1024)) as usize,
                                limit_mb: self.max_config_size_mb,
                            });
                        }
                    }
                }
            }

            let mut file_provider = FileConfigProvider::new(self.explicit_files.clone())
                .with_name("explicit_files")
                .with_priority(40); // Lower priority than environment (loaded first, overridden)

            if let Some(format_mode) = &self.format_detection {
                file_provider = file_provider.with_format_detection(format_mode.clone());
            }

            manager.add_provider(file_provider);
        }
        Ok(())
    }

    /// Setup environment variable provider
    ///
    /// This helper method adds an EnvironmentProvider to the manager if environment
    /// loading is enabled. Environment variables have priority 50 (higher than files).
    #[allow(dead_code)]
    fn setup_env_provider<C: crate::ConfigMap>(&self, manager: &mut ProviderManager) {
        if self.use_env {
            let env_prefix = self.env_prefix.as_deref().unwrap_or("");
            let mut env_provider = EnvironmentProvider::new(env_prefix).with_priority(50);

            // Add custom environment variable mappings from ConfigMap trait
            let custom_mappings = C::env_mapping();
            if !custom_mappings.is_empty() {
                env_provider = env_provider.with_custom_mappings(custom_mappings);
            }

            manager.add_provider(env_provider);
        }
    }

    /// Setup remote configuration providers (HTTP, etcd, Consul)
    ///
    /// This helper method adds remote configuration providers to the manager if they
    /// are configured. All remote providers have priority 50.
    #[cfg(feature = "remote")]
    #[allow(dead_code)]
    fn setup_remote_providers(&self, manager: &mut ProviderManager) {
        // Load HTTP remote config if enabled
        if self.remote_config.enabled {
            if let Some(url) = &self.remote_config.url {
                let mut http_provider = HttpConfigProvider::new(url.clone()).with_priority(50);

                #[cfg(feature = "encryption")]
                if let Some(token) = &self.remote_config.token {
                    http_provider = http_provider.with_bearer_token_secure(Arc::clone(token));
                }

                #[cfg(feature = "encryption")]
                if let (Some(username), Some(password)) =
                    (&self.remote_config.username, &self.remote_config.password)
                {
                    http_provider =
                        http_provider.with_auth_secure(username.clone(), Arc::clone(password));
                }

                if let Some(ca_cert) = &self.remote_config.ca_cert {
                    http_provider = http_provider.with_tls(
                        ca_cert.clone(),
                        self.remote_config.client_cert.clone(),
                        self.remote_config.client_key.clone(),
                    );
                }

                manager.add_provider(http_provider);
            }
        }

        // Load etcd config if provided
        if let Some(etcd_provider) = &self.etcd_provider {
            let mut provider = etcd_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    Some(ca_cert.to_string_lossy().into_owned()),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider =
                    provider.with_tls(Some(ca_cert.to_string_lossy().into_owned()), None, None);
            }

            // Also apply auth if provided in remote_config
            #[cfg(feature = "encryption")]
            if let (Some(username), Some(password)) =
                (&self.remote_config.username, &self.remote_config.password)
            {
                provider = provider.with_auth_secure(username.clone(), Arc::clone(password));
            }

            manager.add_provider(provider);
        }

        // Load consul config if provided
        if let Some(consul_provider) = &self.consul_provider {
            let mut provider = consul_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    None::<PathBuf>,
                    None::<PathBuf>,
                );
            }

            // Also apply token if provided in remote_config
            #[cfg(feature = "encryption")]
            if let Some(token) = &self.remote_config.token {
                provider = provider.with_token_secure(Arc::clone(token));
            }

            manager.add_provider(provider);
        }
    }

    /// Apply decryption to configuration if encryption is enabled
    /// Apply memory limit check before configuration extraction
    ///
    /// This helper method checks if the current memory usage exceeds the configured
    /// limit and returns an error if it does.
    #[allow(dead_code)]
    #[cfg(feature = "monitoring")]
    fn apply_memory_check(&self) -> Result<(), ConfigError> {
        if self.memory_limit_mb > 0 {
            let current_mb = get_memory_usage_mb().ok_or_else(|| {
                ConfigError::RuntimeError("Failed to get memory usage".to_string())
            })?;

            if current_mb as usize > self.memory_limit_mb {
                return Err(ConfigError::MemoryLimitExceeded {
                    limit: self.memory_limit_mb,
                    current: current_mb as usize,
                });
            }
        }
        Ok(())
    }

    /// Finalize configuration by applying template expansion, sanitization, and validation
    ///
    /// This helper method applies post-processing steps to the extracted configuration:
    /// 1. Template expansion
    /// 2. Sanitization (if configured)
    /// 3. Validation
    #[allow(dead_code)]
    fn finalize_config(&self, mut config: T) -> Result<T, ConfigError>
    where
        T: Serialize + for<'de> Deserialize<'de> + Clone,
    {
        // Apply template expansion
        self.apply_template_expansion(&mut config)?;

        // Apply sanitization if available
        #[cfg(any(feature = "encryption", feature = "remote"))]
        if let Some(sanitizer) = &self.sanitizer {
            config = sanitizer(config)?;
        }

        // Validate configuration - return error if validation fails
        if let Err(ref validation_errors) = config.optional_validate() {
            return Err(ConfigError::ValidationError(validation_errors.to_string()));
        }

        Ok(config)
    }

    /// Helper method to load configuration with a given figment (non-audit version)
    #[allow(clippy::type_complexity)]
    #[allow(dead_code)]
    #[cfg(feature = "audit")]
    async fn load_with_figment(
        &self,
        mut figment: Figment,
        _run_env: Option<String>,
        _app_name: Option<&str>,
        mut audit_info: Option<(
            Vec<(String, String, Option<String>, Option<std::time::Duration>)>,
            std::time::Instant,
        )>,
    ) -> Result<T, ConfigError>
    where
        T: for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + OptionalValidate
            + crate::ConfigMap,
    {
        let _load_start = std::time::Instant::now();
        let mut config_sources_status = Vec::new();
        if let Some((ref mut status, _)) = audit_info {
            config_sources_status = status.clone();
        }

        // Initialize ProviderManager
        let mut manager = ProviderManager::new();

        // 1. Add base figment as SerializedProvider (includes defaults)
        manager.add_provider(SerializedProvider::new(figment.clone(), "base_config"));

        // 2. Load explicit files using FileConfigProvider
        let mut _explicit_files_loaded = 0;
        let file_start = std::time::Instant::now();

        if !self.explicit_files.is_empty() {
            // Check file sizes before loading
            if self.max_config_size_mb > 0 {
                for path in &self.explicit_files {
                    if path.exists() {
                        let metadata = std::fs::metadata(path)
                            .map_err(|e| ConfigError::IoError(e.to_string()))?;

                        let file_size = metadata.len();
                        let max_size_bytes = self.max_config_size_mb * 1024 * 1024;

                        if file_size > max_size_bytes as u64 {
                            return Err(ConfigError::ConfigTooLarge {
                                path: path.clone(),
                                size_mb: (file_size / (1024 * 1024)) as usize,
                                limit_mb: self.max_config_size_mb,
                            });
                        }
                    }
                }
            }

            let mut file_provider = FileConfigProvider::new(self.explicit_files.clone())
                .with_name("explicit_files")
                .with_priority(40); // Lower priority than environment (loaded first, overridden)

            if let Some(format_mode) = &self.format_detection {
                file_provider = file_provider.with_format_detection(format_mode.clone());
            }

            manager.add_provider(file_provider);

            // We count loaded files for audit/status purposes
            // This is an approximation since FileConfigProvider handles loading internally
            for file in &self.explicit_files {
                if file.exists() && !is_editor_temp_file(file) {
                    _explicit_files_loaded += 1;
                    config_sources_status.push((
                        format!("explicit_file:{}", file.display()),
                        "Success".to_string(),
                        None,
                        Some(file_start.elapsed()),
                    ));
                }
            }
        }

        // 3. Load environment variables
        if self.use_env {
            let env_prefix = self.env_prefix.as_deref().unwrap_or("");
            let mut env_provider = EnvironmentProvider::new(env_prefix).with_priority(50); // Loaded after files (priority 40), so it can override file values

            // Add custom environment variable mappings from ConfigMap trait
            let custom_mappings = T::env_mapping();
            if !custom_mappings.is_empty() {
                env_provider = env_provider.with_custom_mappings(custom_mappings);
            }

            manager.add_provider(env_provider);
        }

        // 4. Load CLI arguments
        if let Some(cli_provider) = self.cli_provider.clone() {
            manager.add_provider(cli_provider);
        }

        // 5. Load remote config if enabled
        #[cfg(feature = "remote")]
        if self.remote_config.enabled {
            if let Some(url) = &self.remote_config.url {
                let mut http_provider = HttpConfigProvider::new(url.clone()).with_priority(50);

                #[cfg(feature = "encryption")]
                if let Some(token) = &self.remote_config.token {
                    http_provider = http_provider.with_bearer_token_secure(Arc::clone(token));
                }

                #[cfg(feature = "encryption")]
                if let (Some(username), Some(password)) =
                    (&self.remote_config.username, &self.remote_config.password)
                {
                    http_provider =
                        http_provider.with_auth_secure(username.clone(), Arc::clone(password));
                }

                if let Some(ca_cert) = &self.remote_config.ca_cert {
                    http_provider = http_provider.with_tls(
                        ca_cert.clone(),
                        self.remote_config.client_cert.clone(),
                        self.remote_config.client_key.clone(),
                    );
                }

                manager.add_provider(http_provider);
            }
        }

        // 6. Load etcd config if provided
        #[cfg(feature = "remote")]
        if let Some(etcd_provider) = &self.etcd_provider {
            let mut provider = etcd_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    Some(ca_cert.to_string_lossy().into_owned()),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider =
                    provider.with_tls(Some(ca_cert.to_string_lossy().into_owned()), None, None);
            }

            // Also apply auth if provided in remote_config
            #[cfg(feature = "encryption")]
            if let (Some(username), Some(password)) =
                (&self.remote_config.username, &self.remote_config.password)
            {
                provider = provider.with_auth_secure(username.clone(), Arc::clone(password));
            }

            manager.add_provider(provider);
        }

        // 7. Load consul config if provided
        #[cfg(feature = "remote")]
        if let Some(consul_provider) = &self.consul_provider {
            let mut provider = consul_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    None::<PathBuf>,
                    None::<PathBuf>,
                );
            }

            // Also apply token if provided in remote_config
            #[cfg(feature = "encryption")]
            if let Some(token) = &self.remote_config.token {
                provider = provider.with_token_secure(Arc::clone(token));
            }

            manager.add_provider(provider);
        }

        // 8. Extract and validate configuration using ProviderManager
        figment = manager.load_all()?;

        // Merge with initial figment to preserve profiles/metadata if any
        // Note: load_all returns a new Figment merged from all providers

        #[cfg(feature = "encryption")]
        {
            figment = self.decrypt_figment(figment)?;
        }

        // Check memory limit before extraction
        #[cfg(feature = "monitoring")]
        if self.memory_limit_mb > 0 {
            let current_mb = get_memory_usage_mb().ok_or_else(|| {
                ConfigError::RuntimeError("Failed to get memory usage".to_string())
            })?;

            if current_mb as usize > self.memory_limit_mb {
                return Err(ConfigError::MemoryLimitExceeded {
                    limit: self.memory_limit_mb,
                    current: current_mb as usize,
                });
            }
        }

        let mut config: T = figment
            .extract()
            .map_err(|e| ConfigError::ParseError(e.to_string()))?;

        // Apply template expansion
        self.apply_template_expansion(&mut config)?;

        // Apply sanitization if available
        #[cfg(any(feature = "encryption", feature = "remote"))]
        if let Some(sanitizer) = &self.sanitizer {
            config = sanitizer(config)?;
        }

        // Validate configuration - return error if validation fails (strict mode)
        if let Err(ref validation_errors) = config.optional_validate() {
            return Err(ConfigError::ValidationError(validation_errors.to_string()));
        }

        Ok(config)
    }

    /// Helper method to load configuration with a given figment (non-audit version)
    #[allow(clippy::type_complexity)]
    #[cfg(not(feature = "audit"))]
    async fn load_with_figment(
        &self,
        mut figment: Figment,
        _run_env: Option<String>,
        _app_name: Option<&str>,
        _audit_info: Option<(
            Vec<(String, String, Option<String>, Option<std::time::Duration>)>,
            std::time::Instant,
        )>,
    ) -> Result<T, ConfigError>
    where
        T: for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        // Initialize ProviderManager
        let mut manager = ProviderManager::new();

        // 1. Add base figment as SerializedProvider (includes defaults)
        manager.add_provider(SerializedProvider::new(figment.clone(), "base_config"));

        // 2. Load explicit files using FileConfigProvider
        if !self.explicit_files.is_empty() {
            let mut file_provider = FileConfigProvider::new(self.explicit_files.clone())
                .with_name("explicit_files")
                .with_priority(40); // Loaded before environment (priority 50), so environment can override

            if let Some(format_mode) = &self.format_detection {
                file_provider = file_provider.with_format_detection(format_mode.clone());
            }

            manager.add_provider(file_provider);
        }

        // 3. Load environment variables
        if self.use_env {
            let env_prefix = self.env_prefix.as_deref().unwrap_or("");
            let mut env_provider = EnvironmentProvider::new(env_prefix).with_priority(50); // Higher priority than files (loaded later, overrides file values)

            // Add custom environment variable mappings from ConfigMap trait
            let custom_mappings = T::env_mapping();
            if !custom_mappings.is_empty() {
                env_provider = env_provider.with_custom_mappings(custom_mappings);
            }

            manager.add_provider(env_provider);
        }

        // 4. Load CLI arguments
        if let Some(cli_provider) = self.cli_provider.clone() {
            manager.add_provider(cli_provider);
        }

        // 5. Load remote config if enabled
        #[cfg(feature = "remote")]
        if self.remote_config.enabled {
            if let Some(url) = &self.remote_config.url {
                let mut http_provider = HttpConfigProvider::new(url.clone()).with_priority(50);

                #[cfg(feature = "encryption")]
                if let Some(token) = &self.remote_config.token {
                    http_provider = http_provider.with_bearer_token_secure(Arc::clone(token));
                }

                #[cfg(feature = "encryption")]
                if let (Some(username), Some(password)) =
                    (&self.remote_config.username, &self.remote_config.password)
                {
                    http_provider =
                        http_provider.with_auth_secure(username.clone(), Arc::clone(password));
                }

                if let Some(ca_cert) = &self.remote_config.ca_cert {
                    http_provider = http_provider.with_tls(
                        ca_cert.clone(),
                        self.remote_config.client_cert.clone(),
                        self.remote_config.client_key.clone(),
                    );
                }

                manager.add_provider(http_provider);
            }
        }

        // 6. Load etcd config if provided
        #[cfg(feature = "remote")]
        if let Some(etcd_provider) = &self.etcd_provider {
            let mut provider = etcd_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    Some(ca_cert.to_string_lossy().into_owned()),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider =
                    provider.with_tls(Some(ca_cert.to_string_lossy().into_owned()), None, None);
            }

            // Also apply auth if provided in remote_config
            #[cfg(feature = "encryption")]
            if let (Some(username), Some(password)) =
                (&self.remote_config.username, &self.remote_config.password)
            {
                provider = provider.with_auth_secure(username.clone(), Arc::clone(password));
            }

            manager.add_provider(provider);
        }

        // 7. Load consul config if provided
        #[cfg(feature = "remote")]
        if let Some(consul_provider) = &self.consul_provider {
            let mut provider = consul_provider.clone();
            if let (Some(ca_cert), Some(client_cert), Some(client_key)) = (
                self.remote_config.ca_cert.as_ref(),
                self.remote_config.client_cert.as_ref(),
                self.remote_config.client_key.as_ref(),
            ) {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    Some(client_cert.to_string_lossy().into_owned()),
                    Some(client_key.to_string_lossy().into_owned()),
                );
            } else if let Some(ca_cert) = self.remote_config.ca_cert.as_ref() {
                provider = provider.with_tls(
                    ca_cert.to_string_lossy().into_owned(),
                    None::<PathBuf>,
                    None::<PathBuf>,
                );
            }

            // Also apply token if provided in remote_config
            #[cfg(feature = "encryption")]
            if let Some(token) = &self.remote_config.token {
                provider = provider.with_token_secure(Arc::clone(token));
            }

            manager.add_provider(provider);
        }

        // 8. Extract and validate configuration using ProviderManager
        figment = manager.load_all()?;

        // Merge with initial figment to preserve profiles/metadata if any
        // Note: load_all returns a new Figment merged from all providers

        #[cfg(feature = "encryption")]
        {
            figment = self.decrypt_figment(figment)?;
        }

        // Check memory limit before extraction
        #[cfg(feature = "monitoring")]
        if self.memory_limit_mb > 0 {
            let current_mb = get_memory_usage_mb().ok_or_else(|| {
                ConfigError::RuntimeError("Failed to get memory usage".to_string())
            })?;

            if current_mb as usize > self.memory_limit_mb {
                return Err(ConfigError::MemoryLimitExceeded {
                    limit: self.memory_limit_mb,
                    current: current_mb as usize,
                });
            }
        }

        let mut config: T = figment
            .extract()
            .map_err(|e| ConfigError::ParseError(e.to_string()))?;

        // Apply template expansion
        self.apply_template_expansion(&mut config)?;

        // Apply sanitization if available
        #[cfg(any(feature = "encryption", feature = "remote"))]
        if let Some(sanitizer) = &self.sanitizer {
            config = sanitizer(config)?;
        }

        // Validate configuration - return error if validation fails
        if let Err(ref validation_errors) = config.optional_validate() {
            return Err(ConfigError::ValidationError(validation_errors.to_string()));
        }

        Ok(config)
    }

    /// Load configuration asynchronously with audit support
    #[cfg(all(feature = "audit", feature = "validation"))]
    pub async fn load(&self) -> Result<T, ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + OptionalValidate
            + crate::ConfigMap,
    {
        let mut figment = Figment::new();

        // 1. Load defaults if provided
        if let Some(ref defaults) = self.defaults {
            figment = figment.merge(Serialized::from(defaults, "default"));
        }

        // 2. Load standard config files
        let mut _standard_files_loaded = 0;
        let mut search_paths = vec![std::path::PathBuf::from(".")];

        if let Some(config_dir) = dirs::config_dir() {
            if let Some(app_name) = &self.app_name {
                search_paths.push(config_dir.join(app_name));
            }
            search_paths.push(config_dir);
        }

        if let Some(home) = dirs::home_dir() {
            search_paths.push(home);
        }

        #[cfg(unix)]
        if let Some(app_name) = &self.app_name {
            search_paths.push(std::path::PathBuf::from(format!("/etc/{}", app_name)));
        }

        let run_env = std::env::var("RUN_ENV").ok();
        let app_name = self.app_name.as_deref().unwrap_or("app");

        let mut config_sources_status = Vec::new();
        let mut format_distribution = std::collections::HashMap::new();

        for path in &search_paths {
            let base_path = if let Some(app_name) = &self.app_name {
                path.join(app_name)
            } else {
                path.clone()
            };
            let formats = ["toml", "json", "yaml", "yml"];

            // Find all existing config files in priority order
            let mut existing_files = Vec::new();
            for format in &formats {
                let file_path = base_path.join(format!("config.{}", format));
                if file_path.exists() {
                    existing_files.push(file_path);
                }
            }

            // Load files in reverse order (highest priority first)
            for file_path in existing_files.iter().rev() {
                let path_str = file_path.to_string_lossy();
                let format = ConfigLoader::<T>::detect_format(file_path);

                if let Some(fmt) = format {
                    match fmt.as_str() {
                        "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                        "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                        "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                        _ => {}
                    }
                    _standard_files_loaded += 1;

                    // Track format distribution
                    *format_distribution.entry(fmt.clone()).or_insert(0) += 1;
                }
            }

            // Load environment-specific config files
            if let Some(ref env) = run_env {
                let mut existing_env_files = Vec::new();
                for format in &formats {
                    let env_file_path = path.join(format!("{}.{}.{}", app_name, env, format));
                    if env_file_path.exists() {
                        existing_env_files.push(env_file_path);
                    }
                }

                for env_file_path in existing_env_files.iter().rev() {
                    let path_str = env_file_path.to_string_lossy();
                    let format = ConfigLoader::<T>::detect_format(env_file_path);

                    if let Some(fmt) = format {
                        match fmt.as_str() {
                            "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                            "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                            "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                            _ => {}
                        }
                        _standard_files_loaded += 1;

                        // Track format distribution for env files
                        *format_distribution.entry(fmt.clone()).or_insert(0) += 1;
                    }
                }
            }
        }

        if _standard_files_loaded == 0 {
            config_sources_status.push((
                "standard_files".to_string(),
                "Skipped".to_string(),
                None,
                None,
            ));
        }

        let audit_info = Some((
            config_sources_status,
            std::time::Instant::now(),
            format_distribution,
        ));
        self.load_with_figment_audit(figment, run_env, app_name, audit_info)
            .await
    }

    /// Load configuration asynchronously with audit support (no validation)
    #[cfg(all(feature = "audit", not(feature = "validation")))]
    pub async fn load(&self) -> Result<T, ConfigError>
    where
        T: Sanitize + for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        let mut figment = Figment::new();

        // 1. Load defaults if provided
        if let Some(ref defaults) = self.defaults {
            figment = figment.merge(Serialized::from(defaults, "default"));
        }

        // 2. Load standard config files
        let mut _standard_files_loaded = 0;
        let mut search_paths = vec![std::path::PathBuf::from(".")];

        if let Some(config_dir) = dirs::config_dir() {
            if let Some(app_name) = &self.app_name {
                search_paths.push(config_dir.join(app_name));
            }
            search_paths.push(config_dir);
        }

        if let Some(home) = dirs::home_dir() {
            search_paths.push(home);
        }

        #[cfg(unix)]
        if let Some(app_name) = &self.app_name {
            search_paths.push(std::path::PathBuf::from(format!("/etc/{}", app_name)));
        }

        let run_env = std::env::var("RUN_ENV").ok();
        let app_name = self.app_name.as_deref().unwrap_or("app");

        let mut config_sources_status = Vec::new();
        let mut format_distribution = std::collections::HashMap::new();

        for path in &search_paths {
            let base_path = if let Some(app_name) = &self.app_name {
                path.join(app_name)
            } else {
                path.clone()
            };
            let formats = ["toml", "json", "yaml", "yml"];

            // Find all existing config files in priority order
            let mut existing_files = Vec::new();
            for format in &formats {
                let file_path = base_path.join(format!("config.{}", format));
                if file_path.exists() {
                    existing_files.push(file_path);
                }
            }

            // Load files in reverse order (highest priority first)
            for file_path in existing_files.iter().rev() {
                let path_str = file_path.to_string_lossy();
                let format = ConfigLoader::<T>::detect_format(file_path);

                if let Some(fmt) = format {
                    match fmt.as_str() {
                        "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                        "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                        "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                        _ => {}
                    }
                    _standard_files_loaded += 1;

                    // Track format distribution
                    *format_distribution.entry(fmt.clone()).or_insert(0) += 1;
                }
            }

            // Load environment-specific config files
            if let Some(ref env) = run_env {
                let mut existing_env_files = Vec::new();
                for format in &formats {
                    let env_file_path = path.join(format!("{}.{}.{}", app_name, env, format));
                    if env_file_path.exists() {
                        existing_env_files.push(env_file_path);
                    }
                }

                for env_file_path in existing_env_files.iter().rev() {
                    let path_str = env_file_path.to_string_lossy();
                    let format = ConfigLoader::<T>::detect_format(env_file_path);

                    if let Some(fmt) = format {
                        match fmt.as_str() {
                            "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                            "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                            "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                            _ => {}
                        }
                        _standard_files_loaded += 1;

                        // Track format distribution for env files
                        *format_distribution.entry(fmt.clone()).or_insert(0) += 1;
                    }
                }
            }
        }

        if _standard_files_loaded == 0 {
            config_sources_status.push((
                "standard_files".to_string(),
                "Skipped".to_string(),
                None,
                None,
            ));
        }

        let audit_info = Some((
            config_sources_status,
            std::time::Instant::now(),
            format_distribution,
        ));
        self.load_with_figment_audit(figment, run_env, app_name, audit_info)
            .await
    }

    /// Load configuration synchronously
    #[cfg(feature = "validation")]
    pub fn load_sync(&self) -> Result<T, ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + Validate
            + crate::ConfigMap,
    {
        Self::syncify(async { self.load().await })
    }

    /// Load configuration synchronously (without validation)
    #[cfg(not(feature = "validation"))]
    pub fn load_sync(&self) -> Result<T, ConfigError>
    where
        T: Sanitize + for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        Self::syncify(async { self.load().await })
    }

    #[doc(hidden)]
    pub fn syncify<F, R>(f: F) -> Result<R, ConfigError>
    where
        F: std::future::Future<Output = Result<R, ConfigError>>,
    {
        if let Ok(_handle) = tokio::runtime::Handle::try_current() {
            tokio::task::block_in_place(|| {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| {
                        ConfigError::RuntimeError(format!("Failed to create runtime: {}", e))
                    })?;
                rt.block_on(f)
            })
        } else {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| {
                    ConfigError::RuntimeError(format!("Failed to create runtime: {}", e))
                })?;
            runtime.block_on(f)
        }
    }

    /// Load configuration synchronously with audit support
    #[cfg(all(feature = "audit", feature = "validation"))]
    pub fn load_sync_with_audit(&self) -> Result<T, ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + Validate
            + crate::ConfigMap,
    {
        Self::syncify(async { self.load().await })
    }

    /// Load configuration synchronously with audit support (without validation)
    #[cfg(all(feature = "audit", not(feature = "validation")))]
    pub fn load_sync_with_audit(&self) -> Result<T, ConfigError>
    where
        T: Sanitize + for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        Self::syncify(async { self.load().await })
    }

    /// Load configuration synchronously with watcher support
    #[cfg(all(feature = "watch", feature = "validation"))]
    pub fn load_sync_with_watcher(
        &self,
    ) -> Result<(T, Option<crate::watcher::ConfigWatcher>), ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + Validate
            + crate::ConfigMap,
    {
        Self::syncify(async { self.load_with_watcher().await })
    }

    /// Load configuration synchronously with watcher support (without validation)
    #[cfg(all(feature = "watch", not(feature = "validation")))]
    pub fn load_sync_with_watcher(
        &self,
    ) -> Result<(T, Option<crate::watcher::ConfigWatcher>), ConfigError>
    where
        T: Sanitize + for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        Self::syncify(async { self.load_with_watcher().await })
    }

    /// Helper method to load configuration with a given figment (audit version)
    #[cfg(feature = "audit")]
    #[allow(clippy::type_complexity)]
    async fn load_with_figment_audit(
        &self,
        mut figment: Figment,
        _run_env: Option<String>,
        _app_name: &str,
        mut audit_info: Option<(
            Vec<(String, String, Option<String>, Option<std::time::Duration>)>,
            std::time::Instant,
            std::collections::HashMap<String, u32>,
        )>,
    ) -> Result<T, ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + OptionalValidate
            + crate::ConfigMap,
    {
        let load_start = std::time::Instant::now();
        let mut config_sources_status = Vec::new();
        let mut format_distribution = std::collections::HashMap::new();
        if let Some((ref mut status, _, ref mut fmt_dist)) = audit_info {
            config_sources_status = status.clone();
            format_distribution = fmt_dist.clone();
        }

        // Initialize ProviderManager
        let mut manager = ProviderManager::new();

        // 1. Add base figment as SerializedProvider (includes defaults)
        manager.add_provider(SerializedProvider::new(figment.clone(), "base_config"));

        // 4. Load explicit files
        let mut _explicit_files_loaded = 0;
        let file_start = std::time::Instant::now();

        if !self.explicit_files.is_empty() {
            let mut file_provider = FileConfigProvider::new(self.explicit_files.clone())
                .with_name("explicit_files")
                .with_priority(40); // Higher priority than environment

            if let Some(format_mode) = &self.format_detection {
                file_provider = file_provider.with_format_detection(format_mode.clone());
            }

            // We count loaded files for audit/status purposes
            // This is an approximation since FileConfigProvider handles loading internally
            for file in &self.explicit_files {
                if file.exists() && !is_editor_temp_file(file) {
                    _explicit_files_loaded += 1;

                    // Detect format for explicit files to track distribution
                    let format = file_provider.detect_format(file);
                    if let Some(fmt) = format {
                        *format_distribution.entry(fmt.clone()).or_insert(0) += 1;
                    }

                    config_sources_status.push((
                        format!("explicit_file:{}", file.display()),
                        "Success".to_string(),
                        None,
                        Some(file_start.elapsed()),
                    ));
                }
            }

            manager.add_provider(file_provider);
        }

        // 5. Load standard config files if app_name is provided
        // This part is a bit tricky because we're already inside load() which handles standard files
        // But load_with_figment_audit is designed to replace the manual loading in load()
        // However, the current implementation of load() already loads standard files into figment
        // BEFORE calling this function. So we don't need to load them again here.
        // We just need to track them for audit purposes, which is passed in audit_info.

        // 6. Load environment variables if enabled
        if self.use_env {
            let env_prefix = self.env_prefix.as_deref().unwrap_or("");
            let mut env_provider = EnvironmentProvider::new(env_prefix)
                .with_custom_mappings(T::env_mapping())
                .with_priority(50);

            // Add custom environment variable mappings from ConfigMap trait
            let custom_mappings = T::env_mapping();
            if !custom_mappings.is_empty() {
                env_provider = env_provider.with_custom_mappings(custom_mappings);
            }

            manager.add_provider(env_provider);
        }

        // 7. Load CLI overrides if available
        if let Some(cli_provider) = self.cli_provider.clone() {
            manager.add_provider(cli_provider);
        }

        // 8. Load remote configuration if enabled
        #[cfg(feature = "remote")]
        if self.remote_config.enabled {
            if let Some(url) = &self.remote_config.url {
                let mut http_provider = HttpConfigProvider::new(url.clone()).with_priority(50);

                #[cfg(feature = "encryption")]
                if let Some(token) = &self.remote_config.token {
                    http_provider = http_provider.with_bearer_token_secure(Arc::clone(token));
                }

                #[cfg(feature = "encryption")]
                if let (Some(username), Some(password)) =
                    (&self.remote_config.username, &self.remote_config.password)
                {
                    http_provider =
                        http_provider.with_auth_secure(username.clone(), Arc::clone(password));
                }

                if let Some(ca_cert) = &self.remote_config.ca_cert {
                    http_provider = http_provider.with_tls(
                        ca_cert.clone(),
                        self.remote_config.client_cert.clone(),
                        self.remote_config.client_key.clone(),
                    );
                }

                manager.add_provider(http_provider);
            }
        }

        // 9. Extract and validate configuration using ProviderManager
        figment = manager.load_all()?;

        #[cfg(feature = "encryption")]
        {
            figment = self.decrypt_figment(figment)?;
        }

        // Check memory limit before extraction
        #[cfg(feature = "monitoring")]
        if self.memory_limit_mb > 0 {
            let current_mb = get_memory_usage_mb().ok_or_else(|| {
                ConfigError::RuntimeError("Failed to get memory usage".to_string())
            })?;

            if current_mb as usize > self.memory_limit_mb {
                return Err(ConfigError::MemoryLimitExceeded {
                    limit: self.memory_limit_mb,
                    current: current_mb as usize,
                });
            }
        }

        // Extract configuration
        let mut config: T = figment
            .extract()
            .map_err(|e| ConfigError::ParseError(e.to_string()))?;

        // Apply template expansion
        self.apply_template_expansion(&mut config)?;

        // Apply decryption
        #[cfg(feature = "encryption")]
        self.apply_decryption(&mut config)?;

        // Apply sanitization if available
        #[cfg(any(feature = "encryption", feature = "remote"))]
        if let Some(sanitizer) = &self.sanitizer {
            config = sanitizer(config)?;
        }

        // Apply audit sanitization
        let _sanitized = config.sanitize();

        // Validate configuration
        config.optional_validate()?;

        // 10. Audit logging
        let default_path = self
            .audit
            .file_path
            .as_deref()
            .unwrap_or("config_audit.log");
        let validation_error = None;
        let config_source = Some(format!(
            "Config loaded from {} explicit files",
            _explicit_files_loaded
        ));

        // Calculate load statistics - only explicit files in this function
        let total_files_loaded = _explicit_files_loaded;
        // Use the tracked format distribution instead of creating a new one
        let env_vars_count = std::env::vars().count() as u32;

        // Estimate memory usage (simplified)
        let memory_usage_mb = get_memory_usage_mb();

        let audit_config = AuditConfigComplex {
            validation_error,
            config_source,
            load_duration: Some(load_start.elapsed()),
            config_sources_status: Some(config_sources_status),
            files_attempted: Some(total_files_loaded),
            files_loaded: Some(total_files_loaded),
            format_distribution: Some(format_distribution),
            env_vars_count: Some(env_vars_count),
            memory_usage_mb,
        };

        if let Err(e) = AuditLogger::log_to_file_with_source(
            &config,
            std::path::Path::new(&default_path),
            audit_config,
        ) {
            eprintln!("Warning: Failed to write audit log: {}", e);
        }

        Ok(config)
    }

    /// Load configuration asynchronously without audit support
    #[cfg(all(not(feature = "audit"), feature = "validation"))]
    pub async fn load(&self) -> Result<T, ConfigError>
    where
        T: for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        let mut figment = Figment::new();

        // 1. Load defaults if provided
        if let Some(ref defaults) = self.defaults {
            figment = figment.merge(Serialized::from(defaults, "default"));
        }

        // 2. Load standard config files
        let mut _standard_files_loaded = 0;
        let mut search_paths = vec![std::path::PathBuf::from(".")];

        if let Some(config_dir) = dirs::config_dir() {
            if let Some(app_name) = &self.app_name {
                search_paths.push(config_dir.join(app_name));
            }
            search_paths.push(config_dir);
        }

        if let Some(home) = dirs::home_dir() {
            search_paths.push(home);
        }

        #[cfg(unix)]
        if let Some(app_name) = &self.app_name {
            search_paths.push(std::path::PathBuf::from(format!("/etc/{}", app_name)));
        }

        let run_env = std::env::var("RUN_ENV").ok();
        let app_name = self.app_name.as_deref().unwrap_or("app");

        for path in &search_paths {
            let base_path = if let Some(app_name) = &self.app_name {
                path.join(app_name)
            } else {
                path.clone()
            };
            let formats = ["toml", "json", "yaml", "yml"];

            // Find all existing config files in priority order
            let mut existing_files = Vec::new();
            for format in &formats {
                let file_path = base_path.join(format!("config.{}", format));
                if file_path.exists() {
                    existing_files.push(file_path);
                }
            }

            // Load files in reverse order (highest priority first)
            for file_path in existing_files.iter().rev() {
                let path_str = file_path.to_string_lossy();
                let format = ConfigLoader::<T>::detect_format(file_path);

                if let Some(fmt) = format {
                    match fmt.as_str() {
                        "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                        "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                        "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                        _ => {}
                    }
                    _standard_files_loaded += 1;
                }
            }

            // Load environment-specific config files
            if let Some(ref env) = run_env {
                let mut existing_env_files = Vec::new();
                for format in &formats {
                    let env_file_path = path.join(format!("{}.{}.{}", app_name, env, format));
                    if env_file_path.exists() {
                        existing_env_files.push(env_file_path);
                    }
                }

                for env_file_path in existing_env_files.iter().rev() {
                    let path_str = env_file_path.to_string_lossy();
                    let format = ConfigLoader::<T>::detect_format(env_file_path);

                    if let Some(fmt) = format {
                        match fmt.as_str() {
                            "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                            "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                            "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                            _ => {}
                        }
                        _standard_files_loaded += 1;
                    }
                }
            }
        }

        self.load_with_figment(figment, run_env, Some(app_name), None)
            .await
    }

    /// Load configuration asynchronously without audit support (no validation)
    #[cfg(all(not(feature = "audit"), not(feature = "validation")))]
    pub async fn load(&self) -> Result<T, ConfigError>
    where
        T: for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        let mut figment = Figment::new();

        // 1. Load defaults if provided
        if let Some(ref defaults) = self.defaults {
            figment = figment.merge(Serialized::from(defaults, "default"));
        }

        // 2. Load standard config files
        let mut _standard_files_loaded = 0;
        let mut search_paths = vec![std::path::PathBuf::from(".")];

        if let Some(config_dir) = dirs::config_dir() {
            if let Some(app_name) = &self.app_name {
                search_paths.push(config_dir.join(app_name));
            }
            search_paths.push(config_dir);
        }

        if let Some(home) = dirs::home_dir() {
            search_paths.push(home);
        }

        #[cfg(unix)]
        if let Some(app_name) = &self.app_name {
            search_paths.push(std::path::PathBuf::from(format!("/etc/{}", app_name)));
        }

        let run_env = std::env::var("RUN_ENV").ok();
        let app_name = self.app_name.as_deref().unwrap_or("app");

        for path in &search_paths {
            let base_path = if let Some(app_name) = &self.app_name {
                path.join(app_name)
            } else {
                path.clone()
            };
            let formats = ["toml", "json", "yaml", "yml"];

            // Find all existing config files in priority order
            let mut existing_files = Vec::new();
            for format in &formats {
                let file_path = base_path.join(format!("config.{}", format));
                if file_path.exists() {
                    existing_files.push(file_path);
                }
            }

            // Load files in reverse order (highest priority first)
            for file_path in existing_files.iter().rev() {
                let path_str = file_path.to_string_lossy();
                let format = ConfigLoader::<T>::detect_format(file_path);

                if let Some(fmt) = format {
                    match fmt.as_str() {
                        "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                        "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                        "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                        _ => {}
                    }
                    _standard_files_loaded += 1;
                }
            }

            // Load environment-specific config files
            if let Some(ref env) = run_env {
                let mut existing_env_files = Vec::new();
                for format in &formats {
                    let env_file_path = path.join(format!("{}.{}.{}", app_name, env, format));
                    if env_file_path.exists() {
                        existing_env_files.push(env_file_path);
                    }
                }

                for env_file_path in existing_env_files.iter().rev() {
                    let path_str = env_file_path.to_string_lossy();
                    let format = ConfigLoader::<T>::detect_format(env_file_path);

                    if let Some(fmt) = format {
                        match fmt.as_str() {
                            "toml" => figment = figment.merge(Toml::file(path_str.as_ref())),
                            "yaml" => figment = figment.merge(Yaml::file(path_str.as_ref())),
                            "json" => figment = figment.merge(Json::file(path_str.as_ref())),
                            _ => {}
                        }
                        _standard_files_loaded += 1;
                    }
                }
            }
        }

        self.load_with_figment(figment, run_env, Some(app_name), None)
            .await
    }

    /// Load configuration with file watching
    #[cfg(all(feature = "watch", feature = "validation"))]
    pub async fn load_with_watcher(
        &self,
    ) -> Result<(T, Option<crate::watcher::ConfigWatcher>), ConfigError>
    where
        T: Sanitize
            + for<'de> Deserialize<'de>
            + Serialize
            + Default
            + Clone
            + crate::ConfigMap
            + Validate,
    {
        let explicit_files = self.explicit_files.clone();
        let watch = self.watch;
        let config = self.load().await?;

        let watcher = if watch {
            Some(crate::watcher::ConfigWatcher::new(explicit_files))
        } else {
            None
        };

        Ok((config, watcher))
    }

    /// Load configuration with file watching (without validation)
    #[cfg(all(feature = "watch", not(feature = "validation")))]
    pub async fn load_with_watcher(
        &self,
    ) -> Result<(T, Option<crate::watcher::ConfigWatcher>), ConfigError>
    where
        T: Sanitize + for<'de> Deserialize<'de> + Serialize + Default + Clone + crate::ConfigMap,
    {
        let explicit_files = self.explicit_files.clone();
        let watch = self.watch;
        let config = self.load().await?;

        let watcher = if watch {
            Some(crate::watcher::ConfigWatcher::new(explicit_files))
        } else {
            None
        };

        Ok((config, watcher))
    }

    /// Expand template variables in a value recursively
    fn expand_templates_recursive(&self, value: &mut Value) -> bool {
        match value {
            Value::String(tag, s) => {
                if s.contains("${") {
                    let expanded = self.expand_templates(s).unwrap_or_else(|| s.clone());
                    *value = Value::String(*tag, expanded);
                    true
                } else {
                    false
                }
            }
            Value::Dict(_tag, dict) => {
                let mut changed = false;
                for v in dict.values_mut() {
                    if self.expand_templates_recursive(v) {
                        changed = true;
                    }
                }
                changed
            }
            Value::Array(_tag, array) => {
                let mut changed = false;
                for v in array.iter_mut() {
                    if self.expand_templates_recursive(v) {
                        changed = true;
                    }
                }
                changed
            }
            _ => false,
        }
    }

    /// Expand template variables in a string
    fn expand_templates(&self, s: &str) -> Option<String> {
        if !s.contains("${") {
            return Some(s.to_string());
        }

        let mut result = s.to_string();
        let mut start = 0;

        while let Some(var_start) = result[start..].find("${") {
            let var_start = start + var_start;
            if let Some(var_end) = result[var_start..].find('}') {
                let var_end = var_start + var_end;
                let var_name = &result[var_start + 2..var_end];

                // Try with env prefix first, then without prefix
                let env_value = if let Some(prefix) = &self.env_prefix {
                    let prefixed_name = format!("{}_{}", prefix, var_name);
                    std::env::var(&prefixed_name).or_else(|_| std::env::var(var_name))
                } else {
                    std::env::var(var_name)
                };

                if let Ok(env_value) = env_value {
                    // Security: Validate environment value before substitution
                    // Block potentially dangerous characters that could enable injection attacks
                    if Self::is_safe_env_value(&env_value) {
                        result.replace_range(var_start..=var_end, &env_value);
                        start = var_start + env_value.len();
                    } else {
                        #[cfg(feature = "tracing")]
                        tracing::warn!(
                            "Environment variable '{}' contains unsafe characters, skipping substitution",
                            var_name
                        );
                        start = var_end + 1;
                    }
                } else {
                    start = var_end + 1;
                }
            } else {
                break;
            }
        }

        Some(result)
    }

    /// Check if an environment variable value is safe to substitute
    /// Blocks characters that could enable injection attacks
    fn is_safe_env_value(value: &str) -> bool {
        // Check for dangerous shell characters and injection patterns
        let dangerous_patterns = [';', '|', '&', '$', '`', '\'', '"', '\\', '\n', '\r', '\0'];

        // Check for dangerous patterns
        if value.contains("&&") || value.contains("||") {
            return false;
        }
        if value.contains("${") || value.contains("$(") {
            return false;
        }

        // Check for dangerous characters
        !value.chars().any(|c| dangerous_patterns.contains(&c))
    }

    /// Decrypt encrypted values recursively
    #[cfg(feature = "encryption")]
    #[allow(clippy::only_used_in_recursion)]
    fn decrypt_value_recursive(&self, value: &mut Value, encryptor: &ConfigEncryption) -> bool {
        match value {
            Value::String(_tag, s) => {
                if s.starts_with("enc:AES256GCM:") {
                    if let Ok(decrypted) = encryptor.decrypt(s) {
                        *value = Value::String(*_tag, decrypted);
                        true
                    } else {
                        false
                    }
                } else if s.starts_with("ENC(") && s.ends_with(")") {
                    let encrypted = &s[4..s.len() - 1];
                    if let Ok(decrypted) = encryptor.decrypt(encrypted) {
                        *value = Value::String(*_tag, decrypted);
                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            Value::Dict(_tag, dict) => {
                let mut changed = false;
                for v in dict.values_mut() {
                    if self.decrypt_value_recursive(v, encryptor) {
                        changed = true;
                    }
                }
                changed
            }
            Value::Array(_tag, array) => {
                let mut changed = false;
                for v in array.iter_mut() {
                    if self.decrypt_value_recursive(v, encryptor) {
                        changed = true;
                    }
                }
                changed
            }
            _ => false,
        }
    }

    /// Apply template expansion and decryption to a configuration object
    fn apply_template_expansion<U>(&self, config: &mut U) -> Result<(), ConfigError>
    where
        U: Serialize + for<'de> Deserialize<'de> + Clone,
    {
        // Serialize the config to a Value
        let mut value = Value::serialize(config.clone())
            .map_err(|e| ConfigError::ParseError(format!("Failed to serialize config: {}", e)))?;

        // Try to decrypt values if encryption key is available
        #[cfg(feature = "encryption")]
        {
            if let Ok(encryptor) = ConfigEncryption::from_env() {
                self.decrypt_value_recursive(&mut value, &encryptor);
            }
        }

        // Expand templates recursively
        self.expand_templates_recursive(&mut value);

        // Deserialize back to the config type
        *config = value
            .deserialize()
            .map_err(|e| ConfigError::ParseError(format!("Failed to deserialize config: {}", e)))?;

        Ok(())
    }

    /// Apply decryption to configuration values
    #[cfg(feature = "encryption")]
    #[allow(dead_code)]
    fn apply_decryption<U>(&self, config: &mut U) -> Result<(), ConfigError>
    where
        U: Serialize + for<'de> Deserialize<'de> + Clone,
    {
        // Check if encryption key is available
        if let Ok(encryptor) = ConfigEncryption::from_env() {
            // Serialize the config to a Value
            let mut value = Value::serialize(config.clone()).map_err(|e| {
                ConfigError::ParseError(format!("Failed to serialize config: {}", e))
            })?;

            // Decrypt values recursively
            self.decrypt_value_recursive(&mut value, &encryptor);

            // Deserialize back to the config type
            match value.deserialize::<U>() {
                Ok(deserialized) => {
                    *config = deserialized;
                }
                Err(e) => {
                    return Err(ConfigError::ParseError(format!(
                        "Failed to deserialize config: {}",
                        e
                    )));
                }
            }
        }

        Ok(())
    }

    /// Decrypt encrypted values in a figment before extraction
    #[cfg(feature = "encryption")]
    fn decrypt_figment(&self, figment: Figment) -> Result<Figment, ConfigError> {
        // Try to get encryption key from environment
        if let Ok(encryptor) = ConfigEncryption::from_env() {
            // Extract the figment as a Value first
            // We use extract_inner to get the merged value without validation
            // If extraction fails, we fallback to an empty dict
            let mut value = match figment.extract_inner::<Value>("") {
                Ok(v) => v,
                Err(_) => Value::Dict(Tag::Default, std::collections::BTreeMap::new()),
            };

            // Apply decryption recursively
            self.decrypt_value_recursive(&mut value, &encryptor);

            // Create a new figment with the decrypted value
            // We merge the decrypted value ON TOP of the original figment
            // This ensures decrypted values take precedence
            let decrypted_figment = Figment::new()
                .merge(figment)
                .merge(Serialized::from(value, "decrypted"));

            return Ok(decrypted_figment);
        }

        Ok(figment)
    }
}

/// Check if a file is an editor temporary file
pub fn is_editor_temp_file(path: &Path) -> bool {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("");

    // 避免单字符匹配(如单独的"#"不应被视为临时文件)
    if file_name.len() <= 1 {
        return file_name.ends_with('~');
    }

    file_name.ends_with('~')
        || file_name.starts_with('.') && file_name.ends_with('.')
        || file_name.starts_with('#') && file_name.ends_with('#')
        || file_name.ends_with(".swp")
        || file_name.ends_with(".swo")
        || file_name.ends_with(".tmp")
}