teamy-figue 2.0.2

Type-safe CLI arguments, config files, and environment variables powered by Facet reflection
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
//! Builder API for layered configuration.
//!
//! This module provides the [`builder`] function and [`ConfigBuilder`] type for
//! constructing layered configuration parsers. Use this when you need to combine
//! multiple configuration sources (CLI, environment variables, config files).
//!
//! # Overview
//!
//! The builder pattern allows you to:
//! - Configure CLI argument parsing
//! - Set up environment variable parsing with custom prefixes
//! - Load configuration files in various formats
//! - Customize help text and version information
//!
//! # Example
//!
//! ```rust
//! use facet::Facet;
//! use figue::{self as args, builder, Driver};
//!
//! #[derive(Facet, Debug)]
//! struct Args {
//!     #[facet(args::config, args::env_prefix = "MYAPP")]
//!     config: Config,
//! }
//!
//! #[derive(Facet, Debug)]
//! struct Config {
//!     #[facet(default = 8080)]
//!     port: u16,
//!     #[facet(default = "localhost")]
//!     host: String,
//! }
//!
//! // Build the configuration
//! let config = builder::<Args>()
//!     .unwrap()
//!     .cli(|cli| cli.args(["--config.port", "3000"]))
//!     .help(|h| h.program_name("myapp").version("1.0.0"))
//!     .build();
//!
//! // Run the driver to get the parsed value
//! let output = Driver::new(config).run().into_result().unwrap();
//! assert_eq!(output.value.config.port, 3000);
//! ```
//!
//! # Layer Priority
//!
//! When the same field is set in multiple sources, the priority order is:
//! 1. CLI arguments (highest)
//! 2. Environment variables
//! 3. Config files
//! 4. Code defaults (lowest)
#![allow(private_interfaces)]

use std::marker::PhantomData;
use std::string::String;
use std::sync::Arc;

use camino::Utf8PathBuf;
use facet::Facet;
use facet_reflect::ReflectError;

use crate::{
    config_format::{ConfigFormat, ConfigFormatError},
    help::HelpConfig,
    layers::{
        cli::{CliConfig, CliConfigBuilder},
        env::{EnvConfig, EnvConfigBuilder},
        file::FileConfig,
    },
    schema::{Schema, error::SchemaError},
};

/// Start configuring an args/config parser for a given type.
///
/// This is the main entry point for building layered configuration. The type `T`
/// must implement [`Facet`] and be properly annotated with figue attributes.
///
/// # Example
///
/// ```rust
/// use facet::Facet;
/// use figue::{self as args, builder, Driver};
///
/// #[derive(Facet)]
/// struct Args {
///     #[facet(args::named, default)]
///     verbose: bool,
///     #[facet(args::positional)]
///     file: String,
/// }
///
/// let config = builder::<Args>()
///     .expect("schema should be valid")
///     .cli(|cli| cli.args(["--verbose", "input.txt"]))
///     .build();
///
/// let args: Args = Driver::new(config).run().unwrap();
/// assert!(args.verbose);
/// ```
///
/// # Errors
///
/// # Errors
///
/// Returns an error if:
/// - The type is not a struct (enums cannot be root types)
/// - Fields are missing required annotations (`args::positional`, `args::named`, etc.)
/// - Schema validation fails
pub fn builder<T>() -> Result<ConfigBuilder<T>, BuilderError>
where
    T: Facet<'static>,
{
    let schema = Schema::from_shape(T::SHAPE)?;
    Ok(ConfigBuilder {
        _phantom: PhantomData,
        schema,
        cli_config: None,
        help_config: None,
        env_config: None,
        file_config: None,
    })
}

/// Builder for layered configuration parsing.
///
/// Use the fluent API to configure each layer:
/// - [`.cli()`](Self::cli) - Configure CLI argument parsing
/// - [`.env()`](Self::env) - Configure environment variable parsing
/// - [`.file()`](Self::file) - Configure config file loading
/// - [`.help()`](Self::help) - Configure help text generation
/// - [`.build()`](Self::build) - Finalize and create the config
///
/// # Example
///
/// ```rust
/// use facet::Facet;
/// use figue::{self as args, builder, Driver};
///
/// #[derive(Facet)]
/// struct Args {
///     #[facet(args::config, args::env_prefix = "APP")]
///     config: AppConfig,
/// }
///
/// #[derive(Facet)]
/// struct AppConfig {
///     #[facet(default = 8080)]
///     port: u16,
/// }
///
/// let config = builder::<Args>()
///     .unwrap()
///     .cli(|cli| cli.args(["--config.port", "9000"]))  // CLI takes priority
///     .help(|h| h.program_name("myapp"))
///     .build();
///
/// let output = Driver::new(config).run().into_result().unwrap();
/// assert_eq!(output.value.config.port, 9000);
/// ```
pub struct ConfigBuilder<T> {
    _phantom: PhantomData<T>,
    /// Parsed schema for the target type.
    schema: Schema,
    /// CLI parsing settings, if the user configured that layer.
    cli_config: Option<CliConfig>,
    /// Help text settings, if provided.
    help_config: Option<HelpConfig>,
    /// Environment parsing settings, if provided.
    env_config: Option<EnvConfig>,
    /// File parsing settings for the file layer.
    file_config: Option<FileConfig>,
}

/// Fully built configuration (schema + sources) for the driver.
pub struct Config<T> {
    /// Parsed schema for the target type.
    pub schema: Schema,
    /// CLI parsing settings, if the user configured that layer.
    pub cli_config: Option<CliConfig>,
    /// Help text settings, if provided.
    pub help_config: Option<HelpConfig>,
    /// Environment parsing settings, if provided.
    pub env_config: Option<EnvConfig>,
    /// File parsing settings for the file layer.
    pub file_config: Option<FileConfig>,
    /// Type marker.
    _phantom: PhantomData<T>,
}

impl<T> ConfigBuilder<T> {
    /// Configure CLI argument parsing.
    ///
    /// Use this to specify where CLI arguments come from and how they're parsed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::named)]
    ///     verbose: bool,
    /// }
    ///
    /// // Parse specific arguments (useful for testing)
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .cli(|cli| cli.args(["--verbose"]))
    ///     .build();
    ///
    /// let args: Args = Driver::new(config).run().unwrap();
    /// assert!(args.verbose);
    /// ```
    ///
    /// For production use, parse from `std::env::args()`:
    ///
    /// ```rust,no_run
    /// # use facet::Facet;
    /// # use figue::{self as args, builder, Driver};
    /// # #[derive(Facet)]
    /// # struct Args { #[facet(args::named)] verbose: bool }
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .cli(|cli| cli.args(std::env::args().skip(1)))
    ///     .build();
    /// ```
    pub fn cli<F>(mut self, f: F) -> Self
    where
        F: FnOnce(CliConfigBuilder) -> CliConfigBuilder,
    {
        self.cli_config = Some(f(CliConfigBuilder::new()).build());
        self
    }

    /// Configure help text generation.
    ///
    /// Use this to set the program name, version, and additional description
    /// shown in help output and version output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver, DriverError};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::named, args::help, default)]
    ///     help: bool,
    /// }
    ///
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .cli(|cli| cli.args(["--help"]))
    ///     .help(|h| h
    ///         .program_name("myapp")
    ///         .version("1.2.3")
    ///         .description("A helpful description"))
    ///     .build();
    ///
    /// let result = Driver::new(config).run().into_result();
    /// match result {
    ///     Err(DriverError::Help { text }) => {
    ///         assert!(text.contains("myapp"));
    ///     }
    ///     _ => panic!("expected help"),
    /// }
    /// ```
    pub fn help<F>(mut self, f: F) -> Self
    where
        F: FnOnce(HelpConfigBuilder) -> HelpConfigBuilder,
    {
        self.help_config = Some(f(HelpConfigBuilder::new()).build());
        self
    }

    /// Configure environment variable parsing.
    ///
    /// Environment variables are parsed according to the schema's `args::env_prefix`
    /// attribute. For example, with prefix "MYAPP" and a field `port`, the env var
    /// `MYAPP__PORT` will be read.
    ///
    /// # Example
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver, MockEnv};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::config, args::env_prefix = "APP")]
    ///     config: Config,
    /// }
    ///
    /// #[derive(Facet)]
    /// struct Config {
    ///     #[facet(default = 8080)]
    ///     port: u16,
    /// }
    ///
    /// // Use MockEnv for testing (to avoid modifying real environment)
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .env(|env| env.source(MockEnv::from_pairs([
    ///         ("APP__PORT", "9000"),
    ///     ])))
    ///     .build();
    ///
    /// let output = Driver::new(config).run().into_result().unwrap();
    /// assert_eq!(output.value.config.port, 9000);
    /// ```
    pub fn env<F>(mut self, f: F) -> Self
    where
        F: FnOnce(EnvConfigBuilder) -> EnvConfigBuilder,
    {
        self.env_config = Some(f(EnvConfigBuilder::new()).build());
        self
    }

    /// Configure config file parsing.
    ///
    /// Load configuration from JSON, or other formats via the format registry.
    ///
    /// # Example
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::config)]
    ///     config: Config,
    /// }
    ///
    /// #[derive(Facet)]
    /// struct Config {
    ///     #[facet(default = 8080)]
    ///     port: u16,
    /// }
    ///
    /// // Use inline content for testing (avoids file I/O)
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .file(|f| f.content(r#"{"port": 9000}"#, "config.json"))
    ///     .build();
    ///
    /// let output = Driver::new(config).run().into_result().unwrap();
    /// assert_eq!(output.value.config.port, 9000);
    /// ```
    pub fn file<F>(mut self, f: F) -> Self
    where
        F: FnOnce(FileConfigBuilder) -> FileConfigBuilder,
    {
        self.file_config = Some(f(FileConfigBuilder::new()).build());
        self
    }

    /// Finalize the builder and return a [`Config`] for use with [`Driver`](crate::Driver).
    ///
    /// After calling this, create a `Driver` and call `run()`:
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::positional)]
    ///     file: String,
    /// }
    ///
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .cli(|cli| cli.args(["input.txt"]))
    ///     .build();
    ///
    /// let output = Driver::new(config).run().into_result().unwrap();
    /// assert_eq!(output.value.file, "input.txt");
    /// ```
    pub fn build(self) -> Config<T> {
        Config {
            schema: self.schema,
            cli_config: self.cli_config,
            help_config: self.help_config,
            env_config: self.env_config,
            file_config: self.file_config,
            _phantom: PhantomData,
        }
    }
}

// ============================================================================
// Help Configuration
// ============================================================================

/// Builder for help text configuration.
///
/// Configure how help and version information is displayed.
///
/// # Example
///
/// ```rust
/// use facet::Facet;
/// use figue::{self as args, builder, Driver, DriverError};
///
/// #[derive(Facet)]
/// struct Args {
///     #[facet(args::named, args::version, default)]
///     version: bool,
/// }
///
/// let config = builder::<Args>()
///     .unwrap()
///     .cli(|cli| cli.args(["--version"]))
///     .help(|h| h.program_name("myapp").version("1.0.0"))
///     .build();
///
/// let result = Driver::new(config).run().into_result();
/// match result {
///     Err(DriverError::Version { text }) => {
///         assert!(text.contains("myapp 1.0.0"));
///     }
///     _ => panic!("expected version"),
/// }
/// ```
#[derive(Debug, Default)]
pub struct HelpConfigBuilder {
    config: HelpConfig,
}

impl HelpConfigBuilder {
    /// Create a new help config builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the program name shown in help and version output.
    ///
    /// If not set, defaults to the executable name from `std::env::args()`.
    pub fn program_name(mut self, name: impl Into<String>) -> Self {
        self.config.program_name = Some(name.into());
        self
    }

    /// Set the program version shown by `--version`.
    ///
    /// Use `env!("CARGO_PKG_VERSION")` to capture your crate's version:
    ///
    /// ```rust,no_run
    /// # use figue::builder;
    /// # use facet::Facet;
    /// # #[derive(Facet)] struct Args { #[facet(figue::positional)] f: String }
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .help(|h| h.version(env!("CARGO_PKG_VERSION")))
    ///     .build();
    /// ```
    ///
    /// If not set, `--version` will display "unknown".
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.config.version = Some(version.into());
        self
    }

    /// Set an additional description shown after the auto-generated help.
    ///
    /// This appears below the program name and doc comment, useful for
    /// additional context or examples.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.config.description = Some(description.into());
        self
    }

    /// Set the text wrapping width for help output.
    ///
    /// Set to 0 to disable wrapping. Default is 80 columns.
    pub fn width(mut self, width: usize) -> Self {
        self.config.width = width;
        self
    }

    /// Enable or disable implementation source file hints in help output.
    ///
    /// When enabled, help text includes an `Implementation:` section that points
    /// to the source file reported by Facet shape metadata (`Shape::source_file`).
    /// This is useful for CLIs that want to guide contributors to command handlers.
    pub fn include_implementation_source_file(mut self, include: bool) -> Self {
        self.config.include_implementation_source_file = include;
        self
    }

    /// Add an implementation URL line in help output.
    ///
    /// The callback receives the implementation source file path from Facet shape
    /// metadata (for example, `src\\cli\\mod.rs`) and returns a URL string.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use figue::builder;
    /// # use facet::Facet;
    /// # #[derive(Facet)] struct Args { #[facet(figue::named)] verbose: bool }
    /// let _config = builder::<Args>()
    ///     .unwrap()
    ///     .help(|h| h.include_implementation_url(|path| {
    ///         format!("https://example.com/src/{}", path.replace('\\', "/"))
    ///     }))
    ///     .build();
    /// ```
    pub fn include_implementation_url<F>(mut self, render_url: F) -> Self
    where
        F: Fn(&str) -> String + Send + Sync + 'static,
    {
        self.config.implementation_url = Some(Arc::new(render_url));
        self
    }

    /// Add a GitHub implementation URL line in help output.
    ///
    /// This is a convenience wrapper over [`Self::include_implementation_url`].
    /// It creates URLs like:
    /// `https://github.com/<owner/repo>/blob/<revision>/<path>`
    pub fn include_implementation_git_url(
        self,
        owner_repo: impl Into<String>,
        revision: impl Into<String>,
    ) -> Self {
        let owner_repo = owner_repo.into();
        let revision = revision.into();
        self.include_implementation_url(move |source_file| {
            let normalized = source_file.replace('\\', "/");
            format!("https://github.com/{owner_repo}/blob/{revision}/{normalized}")
        })
    }

    /// Build the help configuration.
    fn build(self) -> HelpConfig {
        self.config
    }
}

// ============================================================================
// File Configuration Builder
// ============================================================================

/// Builder for config file parsing configuration.
///
/// Configure how configuration files are loaded and parsed.
///
/// # Example
///
/// ```rust
/// use facet::Facet;
/// use figue::{self as args, builder, Driver};
///
/// #[derive(Facet)]
/// struct Args {
///     #[facet(args::config)]
///     config: Config,
/// }
///
/// #[derive(Facet)]
/// struct Config {
///     #[facet(default = "localhost")]
///     host: String,
///     #[facet(default = 8080)]
///     port: u16,
/// }
///
/// // Load from inline JSON (useful for testing)
/// let config = builder::<Args>()
///     .unwrap()
///     .file(|f| f.content(r#"{"host": "0.0.0.0", "port": 3000}"#, "config.json"))
///     .build();
///
/// let output = Driver::new(config).run().into_result().unwrap();
/// assert_eq!(output.value.config.host, "0.0.0.0");
/// assert_eq!(output.value.config.port, 3000);
/// ```
#[derive(Default)]
pub struct FileConfigBuilder {
    config: FileConfig,
}

impl FileConfigBuilder {
    /// Create a new file config builder.
    pub fn new() -> Self {
        Self {
            config: FileConfig::default(),
        }
    }

    /// Set default paths to check for config files.
    ///
    /// These are checked in order; the first existing file is used.
    /// Common patterns include `./config.json`, `~/.config/app/config.json`, etc.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use figue::builder;
    /// # use facet::Facet;
    /// # #[derive(Facet)] struct Args { #[facet(figue::config)] config: Config }
    /// # #[derive(Facet)] struct Config { #[facet(default = 0)] port: u16 }
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .file(|f| f.default_paths([
    ///         "./config.json",
    ///         "~/.config/myapp/config.json",
    ///         "/etc/myapp/config.json",
    ///     ]))
    ///     .build();
    /// ```
    pub fn default_paths<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<Utf8PathBuf>,
    {
        self.config.default_paths = paths.into_iter().map(|p| p.into()).collect();
        self
    }

    /// Register an additional config file format.
    ///
    /// By default, JSON is supported. Use this to add TOML, YAML, or custom formats.
    /// See [`ConfigFormat`] for implementing custom formats.
    pub fn format<F: ConfigFormat + 'static>(mut self, format: F) -> Self {
        self.config.registry.register(format);
        self
    }

    /// Enable strict mode - error on unknown keys in config file.
    ///
    /// By default, unknown keys are ignored. In strict mode, any key in the
    /// config file that doesn't match a schema field causes an error.
    pub fn strict(mut self) -> Self {
        self.config.strict = true;
        self
    }

    /// Set inline content for testing (avoids disk I/O).
    ///
    /// The filename is used for format detection (e.g., "config.toml" or "settings.json").
    /// This is useful for unit tests that don't want to create actual files.
    ///
    /// # Example
    ///
    /// ```rust
    /// use facet::Facet;
    /// use figue::{self as args, builder, Driver};
    ///
    /// #[derive(Facet)]
    /// struct Args {
    ///     #[facet(args::config)]
    ///     config: Config,
    /// }
    ///
    /// #[derive(Facet)]
    /// struct Config {
    ///     #[facet(default = 8080)]
    ///     port: u16,
    /// }
    ///
    /// let config = builder::<Args>()
    ///     .unwrap()
    ///     .file(|f| f.content(r#"{"port": 9000}"#, "test.json"))
    ///     .build();
    ///
    /// let output = Driver::new(config).run().into_result().unwrap();
    /// assert_eq!(output.value.config.port, 9000);
    /// ```
    pub fn content(mut self, content: impl Into<String>, filename: impl Into<String>) -> Self {
        self.config.inline_content = Some((content.into(), filename.into()));
        self
    }

    /// Build the file configuration.
    fn build(self) -> FileConfig {
        self.config
    }
}

// ============================================================================
// Errors
// ============================================================================

/// Errors that can occur when building configuration.
///
/// These errors happen during the setup phase, before actual parsing begins.
/// They typically indicate problems with the schema definition or file loading.
#[derive(Facet)]
#[repr(u8)]
pub enum BuilderError {
    /// Schema validation failed.
    ///
    /// The type definition has errors, such as missing required attributes
    /// or invalid combinations of attributes.
    SchemaError(#[facet(opaque)] SchemaError),

    /// Memory allocation failed when preparing the destination type.
    Alloc(#[facet(opaque)] ReflectError),

    /// Config file was not found at the specified path.
    FileNotFound {
        /// The path that was checked.
        path: Utf8PathBuf,
    },

    /// Failed to read the config file.
    FileRead(Utf8PathBuf, String),

    /// Failed to parse the config file content.
    FileParse(Utf8PathBuf, ConfigFormatError),

    /// CLI argument parsing failed.
    CliParse(String),

    /// An unknown key was found in configuration.
    ///
    /// Only reported in strict mode.
    UnknownKey {
        /// The unknown key.
        key: String,
        /// Where the key came from (e.g., "config file", "environment").
        source: &'static str,
        /// A suggested correction if the key appears to be a typo.
        suggestion: Option<String>,
    },

    /// A required field was not provided.
    MissingRequired(String),
}

impl std::fmt::Display for BuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuilderError::SchemaError(e) => write!(f, "{e}"),
            BuilderError::Alloc(e) => write!(f, "allocation failed: {e}"),
            BuilderError::FileNotFound { path } => {
                write!(f, "config file not found: {path}")
            }
            BuilderError::FileRead(path, msg) => {
                write!(f, "error reading {path}: {msg}")
            }
            BuilderError::FileParse(path, e) => {
                write!(f, "error parsing {path}: {e}")
            }
            BuilderError::CliParse(msg) => write!(f, "{msg}"),
            BuilderError::UnknownKey {
                key,
                source,
                suggestion,
            } => {
                write!(f, "unknown configuration key '{key}' from {source}")?;
                if let Some(suggestion) = suggestion {
                    write!(f, " (did you mean '{suggestion}'?)")?;
                }
                Ok(())
            }
            BuilderError::MissingRequired(field) => {
                write!(f, "missing required configuration: {field}")
            }
        }
    }
}

impl std::fmt::Debug for BuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl std::error::Error for BuilderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BuilderError::SchemaError(e) => Some(e),
            BuilderError::Alloc(e) => Some(e),
            BuilderError::FileParse(_, e) => Some(e),
            _ => None,
        }
    }
}

impl From<SchemaError> for BuilderError {
    fn from(e: SchemaError) -> Self {
        BuilderError::SchemaError(e)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate as args;
    use facet::Facet;

    #[derive(Facet)]
    struct TestConfig {
        #[facet(args::config)]
        config: TestConfigLayer,
    }

    #[derive(Facet)]
    struct TestConfigLayer {
        #[facet(args::named)]
        port: u16,
        #[facet(args::named)]
        host: String,
    }

    #[test]
    fn test_cli_config_builder() {
        let config = CliConfigBuilder::new()
            .args(["--port", "8080"])
            .strict()
            .build();

        assert_eq!(config.resolve_args(), vec!["--port", "8080"]);
        assert!(config.strict());
    }

    #[test]
    fn test_env_config_builder() {
        let config = EnvConfigBuilder::new().prefix("MYAPP").strict().build();

        assert_eq!(config.prefix, "MYAPP");
        assert!(config.strict);
    }

    #[test]
    fn test_file_config_builder() {
        let config = FileConfigBuilder::new()
            .default_paths(["./config.json", "~/.config/app.json"])
            .strict()
            .build();

        // explicit_path is set by the driver when CLI provides --config <path>
        assert_eq!(config.explicit_path, None);
        assert_eq!(config.default_paths.len(), 2);
        assert!(config.strict);
    }
}