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
//! # SuperConfig
//!
//! **Advanced Configuration Management System** - Built on Figment's proven foundation while retaining 100% compatibility, SuperConfig provides advanced features including hierarchical cascading, intelligent array merging, pattern-based discovery, resilient loading with warnings, and advanced environment variable processing.
//!
//! SuperConfig is designed for modern applications that demand sophisticated configuration patterns, high performance, and bulletproof reliability.
//!
//! ## 🚀 Advanced Configuration Features
//!
//! SuperConfig goes far beyond basic configuration loading with advanced capabilities:
//!
//! - **🔄 Resilient Loading**: Continues loading even when some configs fail, collecting warnings instead of crashing
//! - **🌳 Hierarchical Discovery**: Git-style config inheritance across system → user → project → local levels
//! - **🔀 Intelligent Array Merging**: Advanced composition with `_add`/`_remove` patterns across all sources
//! - **🎯 Pattern-Based Discovery**: Powerful glob patterns for flexible multi-source configuration loading
//! - **🧠 Smart Format Detection**: Content-based parsing with intelligent caching and fallback strategies
//! - **⚡ Enhanced Environment Variables**: JSON parsing, automatic nesting, and smart type detection
//! - **🔍 Advanced Debugging**: Built-in introspection, source tracking, validation, and warning collection
//! - **🗣️ Verbosity System**: CLI-style debugging with multiple verbosity levels for troubleshooting configuration issues
//! - **🚀 Production Optimizations**: Lazy loading, modification time caching, and optimized data structures
//!
//! ## 🎯 SuperConfig All-in-One Solution
//!
//! SuperConfig provides everything you need in a single, powerful interface:
//!
//! ### 🔧 Advanced Configuration Providers
//! - **Universal Provider** - Smart format detection with intelligent caching and content analysis
//! - **Nested Environment Variables** - JSON parsing, automatic nesting, and smart type detection
//! - **Empty Value Filtering** - Automatic filtering while preserving meaningful falsy values
//! - **Wildcard Pattern Discovery** - Unified glob-based configuration discovery with advanced sorting
//!
//! ### 🛠️ Built-in Configuration Methods
//! - **Fluent Builder API** - `.with_file()`, `.with_env()`, `.with_hierarchical_config()`, `.with_defaults()`
//! - **Array Merging** - Intelligent composition with `_add`/`_remove` patterns across all sources
//! - **Access & Export** - `.as_json()`, `.as_yaml()`, `.get_string()`, `.has_key()`, `.debug_config()`
//! - **Warning System** - Resilient loading with comprehensive error collection and reporting
//!
//! ### 💯 100% Figment Compatibility
//! - All Figment methods and functionalities work out of the box with SuperConfig
//! - Drop-in replacement for existing Figment code
//! - Gradual migration path for existing projects
//!
//! ## 🎯 Quick Start
//!
//! SuperConfig provides a clean, powerful API for all your configuration needs:
//!
//! ```rust,no_run
//! use superconfig::SuperConfig;
//!
//! // Simple configuration loading
//! let config = SuperConfig::new()
//! .with_file("config.toml") // Smart format detection
//! .with_env("APP_") // Enhanced environment variables
//! .with_hierarchical_config("myapp"); // Git-style discovery
//! ```
//!
//! ## 🌟 Real-World Examples
//!
//! ### Web Application Configuration
//! ```rust,no_run
//! use superconfig::SuperConfig;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Deserialize, Serialize, Default)]
//! struct WebConfig {
//! server: ServerConfig,
//! database: DatabaseConfig,
//! features: Vec<String>,
//! }
//!
//! #[derive(Deserialize, Serialize, Default)]
//! struct ServerConfig {
//! host: String,
//! port: u16,
//! }
//!
//! #[derive(Deserialize, Serialize, Default)]
//! struct DatabaseConfig {
//! url: String,
//! timeout: u32,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Load configuration with intelligent fallbacks and validation
//! let super_config = SuperConfig::new()
//! .with_defaults(WebConfig::default())
//! .with_file("config.toml") // Base configuration
//! .with_file("config.local.toml") // Local overrides
//! .with_env("WEBAPP_") // Environment variables
//! .with_cli_opt(Some(std::env::args().collect::<Vec<_>>())); // CLI arguments
//!
//! let config: WebConfig = super_config.extract()?;
//!
//! // Check for configuration warnings
//! if super_config.has_warnings() {
//! super_config.print_warnings();
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Microservice with Dynamic Discovery
//! ```rust,no_run
//! use superconfig::{SuperConfig, Wildcard};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Load configuration from multiple sources with pattern matching
//! let config = SuperConfig::new()
//! .merge(Wildcard::hierarchical("config", "myservice")) // Git-style discovery
//! .merge(Wildcard::new("./config/features/*.toml")) // Feature configs
//! .merge(Wildcard::new("/etc/myservice/**/*.yaml")) // System configs
//! .with_env("SERVICE_"); // Environment
//!
//! // Export for debugging
//! println!("Final config: {}", config.as_yaml()?);
//! println!("Sources: {:#?}", config.debug_sources());
//! # Ok(())
//! # }
//! ```
//!
//! ### Production Configuration with Array Merging
//! ```rust,no_run
//! // config/base.toml
//! // features = ["auth", "logging"]
//! // allowed_ips = ["127.0.0.1"]
//!
//! // config/production.toml
//! // features_add = ["metrics", "tracing"]
//! // features_remove = ["logging"]
//! // allowed_ips_add = ["10.0.0.0/8", "192.168.0.0/16"]
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # use superconfig::SuperConfig;
//! let config = SuperConfig::new()
//! .with_file("config/base.toml")
//! .with_file("config/production.toml");
//! # Ok(())
//! # }
//!
//! // Result: features = ["auth", "metrics", "tracing"]
//! // Result: allowed_ips = ["127.0.0.1", "10.0.0.0/8", "192.168.0.0/16"]
//! ```
//!
//! ## ⚡ Performance Characteristics
//!
//! SuperConfig implements several optimization strategies:
//!
//! - **Lazy Loading**: Files only read when needed, cached by modification time
//! - **Smart Detection**: Content-based format detection with fallback chains
//! - **Conditional Processing**: Array merging only when `_add`/`_remove` patterns detected
//! - **Efficient Caching**: Parsed environment variables and file contents cached
//! - **Memory Efficient**: Optimized data structures for large configurations
//!
//! ## 🔗 100% Figment Compatibility
//!
//! **Bonus Feature**: SuperConfig is fully compatible with existing Figment code:
//! - All Figment methods work seamlessly
//! - Existing Figment configurations can be enhanced without changes
//! - SuperConfig can be converted to/from regular Figment instances
//! - No breaking changes to your existing Figment workflow
//!
//! ## Usage Approaches
//!
//! Choose the approach that best fits your project:
//!
//! ### Primary: SuperConfig Platform (Recommended)
//!
//! **The recommended way** - Experience SuperConfig's full power with clean, intuitive APIs:
//!
//! ```rust,no_run
//! use superconfig::SuperConfig; // Only import you need
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, Deserialize, Serialize, Default)]
//! struct AppConfig {
//! name: String,
//! port: u16,
//! features: Vec<String>,
//! }
//!
//! # fn main() -> Result<(), figment::Error> {
//! let cli_args = AppConfig {
//! name: "myapp".to_string(),
//! port: 3000,
//! ..Default::default()
//! };
//!
//! let config: AppConfig = SuperConfig::new()
//! .with_defaults(AppConfig::default()) // Set smart defaults
//! .with_hierarchical_config("myapp") // System → user → project cascade
//! .with_file("config") // Auto-detects .toml/.json/.yaml
//! .with_env("APP_") // JSON parsing + nesting
//! .with_cli_opt(Some(cli_args)) // Filtered CLI overrides
//! .extract()?; // Direct extraction
//!
//! Ok(())
//! # }
//! ```
//!
//! ### Alternative: Figment Compatibility Mode
//!
//! **For existing Figment users** - SuperConfig provides all Figment functionality while adding enhanced features:
//!
//! ```rust,no_run
//! use superconfig::{SuperConfig, Universal, Nested};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct Config { name: String, features: Vec<String> }
//!
//! let cli_args = Config {
//! name: "myapp".to_string(),
//! features: vec!["auth".to_string()]
//! };
//!
//! let config = SuperConfig::new() // SuperConfig with Figment compatibility
//! .merge(Universal::file("config")) // Enhanced provider
//! .merge(Nested::prefixed("APP_")) // Enhanced provider
//! .with_cli_opt(Some(cli_args)); // SuperConfig method
//!
//! // All Figment methods work seamlessly
//! let result = config.extract::<Config>()?;
//! let json_output = config.as_json()?; // SuperConfig extension
//! let has_redis = config.has_key("redis.enabled")?; // SuperConfig extension
//! # Ok::<(), figment::Error>(())
//! ```
//!
//! ## 🔍 Configuration Debugging
//!
//! SuperConfig provides rich debugging capabilities for development and troubleshooting:
//!
//! ```rust,no_run
//! use superconfig::SuperConfig;
//!
//! # fn main() -> Result<(), figment::Error> {
//! let config = SuperConfig::new()
//! .with_hierarchical_config("myapp")
//! .with_env("APP_");
//!
//! // Export in different formats
//! let json_config = config.as_json()?;
//! let yaml_config = config.as_yaml()?;
//! let toml_config = config.as_toml()?;
//!
//! // Value extraction and validation
//! let db_host = config.get_string("database.host")?;
//! let features = config.get_array::<String>("features")?;
//! let has_redis = config.has_key("redis.enabled")?;
//! let all_keys = config.keys()?;
//!
//! // Full debug output with source tracking
//! let debug_output = config.debug_config()?;
//! println!("{}", debug_output);
//!
//! // Source metadata for troubleshooting
//! let sources = config.debug_sources();
//! for source in sources {
//! println!("Provider: {:?}", source);
//! }
//! # Ok(())
//! # }
//! ```
use crate;
use Figment;
use RefCell;
use Deref;
// Re-export figment for compatibility
pub use figment;
// Re-export enhanced providers for existing Figment users
pub use ;
// Re-export verbosity types for clients
pub use VerbosityLevel;
/// SuperConfig is a universal configuration management platform that combines
/// advanced features with 100% Figment compatibility.
///
/// Built on Figment's solid foundation, SuperConfig adds production-ready capabilities
/// including hierarchical configuration cascades, advanced array merging, intelligent
/// format detection, verbosity debugging, and performance optimizations - while maintaining
/// seamless compatibility with existing Figment code.
///
/// ## Core Features
///
/// - **Hierarchical Configuration**: Git-like config inheritance across system → user → project levels
/// - **Advanced Array Merging**: Compose configurations with `_add`/`_remove` patterns
/// - **Intelligent Format Detection**: Content-based parsing with caching and fallback strategies
/// - **Verbosity System**: CLI-style debugging with `-v`, `-vv`, `-vvv` levels for troubleshooting
/// - **Performance Optimized**: Lazy loading, caching, and optimized data structures
///
/// ## Quick Start Example
///
/// ```rust,no_run
/// use superconfig::{SuperConfig, VerbosityLevel};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize, Default)]
/// struct AppConfig {
/// database_url: String,
/// log_level: String,
/// port: u16,
/// }
///
/// // Basic configuration loading
/// let config: AppConfig = SuperConfig::new()
/// .with_defaults(AppConfig::default())
/// .with_file("config.toml")
/// .with_env("APP_")
/// .extract()?;
///
/// # Ok::<(), figment::Error>(())
/// ```
///
/// ## Verbosity for Debugging
///
/// Enable verbosity to debug configuration loading issues:
///
/// ```rust,no_run
/// use superconfig::{SuperConfig, VerbosityLevel};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize, Default)]
/// struct Config {
/// host: String,
/// port: u16,
/// }
///
/// // Enable debug verbosity (equivalent to -vv in CLI)
/// let config: Config = SuperConfig::new()
/// .with_verbosity(VerbosityLevel::Debug) // Shows detailed loading steps
/// .with_hierarchical_config("myapp")
/// .with_env("APP_")
/// .extract()?;
///
/// # Ok::<(), figment::Error>(())
/// ```
///
/// ## CLI Integration Example
///
/// Integrate verbosity with CLI argument parsing:
///
/// ```rust,no_run
/// use superconfig::{SuperConfig, VerbosityLevel};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize, Default)]
/// struct Config {
/// host: String,
/// port: u16,
/// }
///
/// // Parse CLI verbosity (normally from clap, structopt, etc.)
/// fn parse_verbosity() -> u8 {
/// std::env::args()
/// .skip(1)
/// .filter(|arg| arg.starts_with("-v"))
/// .map(|arg| arg.matches('v').count() as u8)
/// .max()
/// .unwrap_or(0)
/// }
///
/// let verbosity = VerbosityLevel::from_cli_args(parse_verbosity());
///
/// let config: Config = SuperConfig::new()
/// .with_verbosity(verbosity) // Respects -v, -vv, -vvv from command line
/// .with_defaults(Config::default())
/// .with_hierarchical_config("myapp")
/// .with_env("APP_")
/// .extract()?;
///
/// # Ok::<(), figment::Error>(())
/// ```
///
/// ## Advanced Features
///
/// ### Array Merging
/// ```rust,no_run
/// // config/base.toml
/// // features = ["auth", "logging"]
///
/// // config/production.toml
/// // features_add = ["metrics", "tracing"]
/// // features_remove = ["logging"]
///
/// // Result: features = ["auth", "metrics", "tracing"]
/// # use superconfig::SuperConfig;
/// let config = SuperConfig::new()
/// .with_file("config/base.toml")
/// .with_file("config/production.toml");
/// ```
///
/// ### Debug Message Collection
/// ```rust,no_run
/// use superconfig::{SuperConfig, VerbosityLevel};
///
/// let config = SuperConfig::new()
/// .with_verbosity(VerbosityLevel::Debug)
/// .with_file("config.toml");
///
/// // Access debug messages programmatically
/// let debug_messages = config.debug_messages();
/// for msg in debug_messages {
/// println!("{}: {}", msg.provider, msg.message);
/// }
/// ```
///
/// ## Universal Platform Vision
///
/// SuperConfig is designed to become the universal configuration standard across popular
/// languages through WebAssembly bindings, REST APIs, and protocol standardization.
/// Deref to Figment provides 100% compatibility - all Figment methods work seamlessly
// Fluent methods are now implemented directly in fluent.rs