clapfig 0.21.4

Rich, layered configuration for Rust CLI apps
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
//! End-to-end tests for `#[derive(clapfig::Schema)]`.
//!
//! These exercise the static-path schema-metadata symmetry contract from
//! `docs/proposals/schema-metadata-symmetry.md`:
//!
//! - JSON Schema `"type"` is emitted for every leaf, including those
//!   without defaults (gap #1).
//! - JSON Schema `"enum"` is emitted for allowed-constrained leaves
//!   (gap #2).
//! - `config gen` template emits `# Allowed: ...` for allowed-constrained
//!   leaves (gap #3) and `#key = <placeholder>` for required leaves
//!   without a default (gap #4).
//!
//! Plus end-to-end load behavior parallels the confique-driven path:
//! defaults, env vars, CLI overrides, strict-mode validation, typed
//! post_validate.

#![cfg(feature = "derive")]

use clapfig::{Clapfig, ConfigAction, ConfigResult, Schema, SearchPath};
use serde::{Deserialize, Serialize};
use tempfile::TempDir;

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq)]
struct AppConfig {
    /// Listen host.
    #[clapfig(default = "localhost")]
    host: String,

    /// Listen port.
    #[clapfig(default = 8080)]
    port: u16,

    /// Enable debug mode.
    #[clapfig(default = false)]
    debug: bool,

    /// Database settings.
    database: DbConfig,
}

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq)]
struct DbConfig {
    /// Database URL.
    url: Option<String>,

    /// Connection pool size.
    #[clapfig(default = 5)]
    pool_size: u32,
}

#[test]
fn schema_static_carries_expected_field_names() {
    let s = AppConfig::schema_static();
    assert_eq!(s.name, "AppConfig");
    let names: Vec<&str> = s.fields.iter().map(|f| f.name).collect();
    assert_eq!(names, vec!["host", "port", "debug", "database"]);
}

#[test]
fn schema_runtime_view_matches_static_view() {
    let r = AppConfig::schema();
    assert_eq!(r.name, "AppConfig");
    assert_eq!(r.fields.len(), 4);
}

#[test]
fn load_returns_typed_struct_with_defaults() {
    let dir = TempDir::new().unwrap();
    let cfg: AppConfig = Clapfig::schema_builder::<AppConfig>()
        .app_name("myapp")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.host, "localhost");
    assert_eq!(cfg.port, 8080);
    assert!(!cfg.debug);
    assert_eq!(cfg.database.pool_size, 5);
    assert_eq!(cfg.database.url, None);
}

#[test]
fn load_file_overrides_defaults() {
    let dir = TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("myapp.toml"),
        "host = \"prod.local\"\nport = 9090\n[database]\nurl = \"pg://prod\"\n",
    )
    .unwrap();

    let cfg: AppConfig = Clapfig::schema_builder::<AppConfig>()
        .app_name("myapp")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.host, "prod.local");
    assert_eq!(cfg.port, 9090);
    assert_eq!(cfg.database.url.as_deref(), Some("pg://prod"));
}

#[test]
fn strict_rejects_unknown_top_level_key() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("myapp.toml"), "typo_key = 1\n").unwrap();

    let result: Result<AppConfig, _> = Clapfig::schema_builder::<AppConfig>()
        .app_name("myapp")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load();
    assert!(result.is_err());
}

#[test]
fn cli_override_wins() {
    let dir = TempDir::new().unwrap();
    let cfg: AppConfig = Clapfig::schema_builder::<AppConfig>()
        .app_name("myapp")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .cli_override("port", Some(11111i64))
        .load()
        .unwrap();
    assert_eq!(cfg.port, 11111);
}

#[test]
fn typed_post_validate_sees_merged_c() {
    let dir = TempDir::new().unwrap();
    let result: Result<AppConfig, _> = Clapfig::schema_builder::<AppConfig>()
        .app_name("myapp")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .post_validate(|c: &AppConfig| {
            if c.port < 10000 {
                Err(format!("port {} too low", c.port))
            } else {
                Ok(())
            }
        })
        .load();
    let err = result.unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("8080") && msg.contains("too low"));
}

// -- Gap #1: JSON Schema "type" emitted for fields without defaults ---------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct RequiredFieldsConfig {
    /// Required name (no default).
    name: String,

    /// Required port (no default).
    port: u32,
}

#[test]
fn json_schema_emits_type_for_required_fields_without_defaults() {
    let result = Clapfig::schema_builder::<RequiredFieldsConfig>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Schema { output: None })
        .unwrap();
    let s = match result {
        ConfigResult::Schema(s) => s,
        other => panic!("expected Schema, got {other:?}"),
    };
    let v: serde_json::Value = serde_json::from_str(&s).unwrap();
    let props = &v["properties"];
    assert_eq!(
        props["name"]["type"], "string",
        "gap #1: required leaf without default must still get a JSON Schema `type`. Got: {props}"
    );
    assert_eq!(props["port"]["type"], "integer", "gap #1 (port)");
}

// -- Gap #2 + #3: enum metadata via `#[clapfig(allowed = [...])]` -----------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct EnumConfig {
    /// Log severity.
    #[clapfig(allowed = ["debug", "info", "warn", "error"], default = "info")]
    level: String,
}

#[test]
fn json_schema_emits_enum_for_allowed_constrained_leaf() {
    let result = Clapfig::schema_builder::<EnumConfig>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Schema { output: None })
        .unwrap();
    let s = match result {
        ConfigResult::Schema(s) => s,
        other => panic!("expected Schema, got {other:?}"),
    };
    let v: serde_json::Value = serde_json::from_str(&s).unwrap();
    let enum_array = v["properties"]["level"]["enum"]
        .as_array()
        .expect("gap #2: allowed-constrained leaf must emit JSON Schema enum");
    let names: Vec<&str> = enum_array.iter().map(|x| x.as_str().unwrap()).collect();
    assert_eq!(names, vec!["debug", "info", "warn", "error"]);
}

#[test]
fn template_emits_allowed_line_for_enum_leaf() {
    let result = Clapfig::schema_builder::<EnumConfig>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Gen { output: None })
        .unwrap();
    let t = match result {
        ConfigResult::Template(t) => t,
        other => panic!("expected Template, got {other:?}"),
    };
    assert!(
        t.contains("# Allowed: \"debug\" | \"info\" | \"warn\" | \"error\""),
        "gap #3: template must emit `# Allowed:` line. Got:\n{t}"
    );
}

#[test]
fn enum_constraint_rejects_out_of_set_value_at_load() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("test.toml"), "level = \"garbage\"\n").unwrap();
    let result: Result<EnumConfig, _> = Clapfig::schema_builder::<EnumConfig>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load();
    assert!(result.is_err());
}

// -- Gap #4: template emits placeholder for required leaves without default -

#[test]
fn template_emits_placeholder_for_required_leaf_without_default() {
    let result = Clapfig::schema_builder::<RequiredFieldsConfig>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Gen { output: None })
        .unwrap();
    let t = match result {
        ConfigResult::Template(t) => t,
        other => panic!("expected Template, got {other:?}"),
    };
    // The runtime-path emitter writes `#key = <placeholder>` for required
    // leaves without a default — `#name = ""` for a String, `#port = 0` for
    // an integer. The confique-driven static path doesn't (gap #4).
    assert!(
        t.contains("#name = \"\""),
        "gap #4: required String leaf must get `#name = \"\"` placeholder. Got:\n{t}"
    );
    assert!(
        t.contains("#port = 0"),
        "gap #4: required integer leaf must get `#port = 0` placeholder. Got:\n{t}"
    );
}

// -- Doc comments propagate to JSON Schema description ---------------------

#[test]
fn doc_comments_become_descriptions() {
    let result = Clapfig::schema_builder::<AppConfig>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Schema { output: None })
        .unwrap();
    let s = match result {
        ConfigResult::Schema(s) => s,
        other => panic!("expected Schema, got {other:?}"),
    };
    let v: serde_json::Value = serde_json::from_str(&s).unwrap();
    let host_desc = v["properties"]["host"]["description"].as_str().unwrap();
    assert!(host_desc.contains("Listen host"));
}

// -- `#[clapfig(env = ...)]` populates the env hint -------------------------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct EnvConfig {
    #[clapfig(env = "X_PORT", default = 1)]
    port: u32,
}

#[test]
fn explicit_env_attribute_is_carried_into_static_schema() {
    let s = EnvConfig::schema_static();
    let leaf = match &s.fields[0].field {
        clapfig::static_schema::FieldStatic::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    assert_eq!(leaf.env, Some("X_PORT"));
}

// -- `#[clapfig(value)]` opt-in to LeafType::Value --------------------------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct ValueConfig {
    /// Free-form rule shape.
    #[clapfig(value)]
    rule: toml::Value,
}

#[test]
fn value_attribute_yields_value_leaf_in_static_schema() {
    let s = ValueConfig::schema_static();
    let leaf = match &s.fields[0].field {
        clapfig::static_schema::FieldStatic::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    assert!(matches!(
        leaf.ty,
        clapfig::static_schema::LeafTypeStatic::Value
    ));
}

#[test]
fn value_leaf_accepts_any_shape_at_load() {
    let dir = TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("test.toml"),
        "rule = [\"warn\", { max = 80 }]\n",
    )
    .unwrap();
    let cfg: ValueConfig = Clapfig::schema_builder::<ValueConfig>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert!(cfg.rule.as_array().is_some());
}

// -- `#[clapfig(rename = "...")]` overrides schema field name ---------------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct RenameConfig {
    #[clapfig(rename = "Host", default = "x")]
    #[serde(rename = "Host")]
    host: String,
}

#[test]
fn rename_attribute_changes_schema_field_name() {
    let s = RenameConfig::schema_static();
    assert_eq!(s.fields[0].name, "Host");
}

// -- Struct-level attrs: name override and per-node strict -----------------

#[derive(Schema, Serialize, Deserialize, Debug)]
#[clapfig(name = "RenamedRoot")]
struct NamedRootConfig {
    #[clapfig(default = 1)]
    x: i64,
}

#[test]
fn struct_name_attribute_overrides_schema_name() {
    let s = NamedRootConfig::schema_static();
    assert_eq!(s.name, "RenamedRoot");
}

#[derive(Schema, Serialize, Deserialize, Debug)]
#[clapfig(strict = false)]
struct LenientConfig {
    #[clapfig(default = 1)]
    x: i64,
}

#[test]
fn struct_strict_attribute_cascades_to_unknown_keys() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("t.toml"), "x = 2\nrogue = 99\n").unwrap();
    let cfg: LenientConfig = Clapfig::schema_builder::<LenientConfig>()
        .app_name("t")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.x, 2);
}

// -- Vec<scalar> support ----------------------------------------------------

#[derive(Schema, Serialize, Deserialize, Debug)]
struct VecConfig {
    #[clapfig(default = ["a", "b"])]
    tags: Vec<String>,
}

#[test]
fn vec_of_string_field_emits_array_leaf_type() {
    let s = VecConfig::schema_static();
    let leaf = match &s.fields[0].field {
        clapfig::static_schema::FieldStatic::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    match &leaf.ty {
        clapfig::static_schema::LeafTypeStatic::Array(inner) => {
            assert!(matches!(
                inner,
                clapfig::static_schema::LeafTypeStatic::String
            ));
        }
        other => panic!("expected Array, got {other:?}"),
    }
}

#[test]
fn vec_default_loads_via_runtime_pipeline() {
    let dir = TempDir::new().unwrap();
    let cfg: VecConfig = Clapfig::schema_builder::<VecConfig>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.tags, vec!["a".to_string(), "b".to_string()]);
}

// -- Unit-only enum support (issue #54 item 1) -----------------------------

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[clapfig(rename_all = "lowercase")]
#[serde(rename_all = "lowercase")]
enum PdfPageSize {
    A4,
    Letter,
    Legal,
}

#[derive(Schema, Serialize, Deserialize, Debug)]
struct PdfDoc {
    /// Page size for the rendered document.
    page_size: PdfPageSize,
}

#[test]
fn unit_enum_schema_carries_variant_names_post_rename() {
    let s = PdfPageSize::schema_static();
    assert_eq!(s.enum_variants, &["a4", "letter", "legal"]);
    assert!(s.fields.is_empty());
}

#[test]
fn unit_enum_field_flattens_to_runtime_leaf_enum() {
    let s = PdfDoc::schema();
    let leaf = match &s.fields[0].field {
        clapfig::runtime::Field::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    match &leaf.ty {
        clapfig::runtime::LeafType::Enum { values } => {
            assert_eq!(values.len(), 3);
            assert_eq!(values[0], toml::Value::String("a4".into()));
            assert_eq!(values[1], toml::Value::String("letter".into()));
            assert_eq!(values[2], toml::Value::String("legal".into()));
        }
        other => panic!("expected Enum, got {other:?}"),
    }
}

#[test]
fn unit_enum_template_emits_allowed_hint() {
    let result = Clapfig::schema_builder::<PdfDoc>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Gen { output: None })
        .unwrap();
    let t = match result {
        ConfigResult::Template(t) => t,
        other => panic!("expected Template, got {other:?}"),
    };
    assert!(
        t.contains("# Allowed: \"a4\" | \"letter\" | \"legal\""),
        "unit enum must surface allowed hint in template. Got:\n{t}"
    );
}

#[test]
fn unit_enum_load_accepts_known_variant() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("test.toml"), "page_size = \"letter\"\n").unwrap();
    let cfg: PdfDoc = Clapfig::schema_builder::<PdfDoc>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.page_size, PdfPageSize::Letter);
}

#[test]
fn unit_enum_load_rejects_unknown_variant() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("test.toml"), "page_size = \"a3\"\n").unwrap();
    let result: Result<PdfDoc, _> = Clapfig::schema_builder::<PdfDoc>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load();
    assert!(result.is_err());
}

#[test]
fn unit_enum_json_schema_carries_enum_array() {
    let result = Clapfig::schema_builder::<PdfDoc>()
        .app_name("test")
        .no_env()
        .handle(&ConfigAction::Schema { output: None })
        .unwrap();
    let s = match result {
        ConfigResult::Schema(s) => s,
        other => panic!("expected Schema, got {other:?}"),
    };
    let v: serde_json::Value = serde_json::from_str(&s).unwrap();
    let arr = v["properties"]["page_size"]["enum"]
        .as_array()
        .expect("unit enum field must emit JSON Schema enum array");
    let names: Vec<&str> = arr.iter().map(|x| x.as_str().unwrap()).collect();
    assert_eq!(names, vec!["a4", "letter", "legal"]);
}

// Enum without rename_all keeps variant names verbatim.
#[derive(Schema, Serialize, Deserialize, Debug, PartialEq, Eq)]
enum Mode {
    Fast,
    Slow,
}

#[test]
fn unit_enum_without_rename_all_keeps_pascal_names() {
    let s = Mode::schema_static();
    assert_eq!(s.enum_variants, &["Fast", "Slow"]);
}

// Per-variant `#[clapfig(rename = "...")]` overrides the rename_all rule.
#[derive(Schema, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[clapfig(rename_all = "snake_case")]
enum Mixed {
    AlphaBeta,
    #[clapfig(rename = "GAMMA")]
    Gamma,
}

#[test]
fn unit_enum_variant_rename_overrides_rename_all() {
    let s = Mixed::schema_static();
    assert_eq!(s.enum_variants, &["alpha_beta", "GAMMA"]);
}

// Acronym runs in variant names render the serde way: consecutive
// uppercase letters stay together; the new-word boundary is the *next*
// uppercase letter that's followed by a lowercase letter.
#[derive(Schema, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[clapfig(rename_all = "snake_case")]
#[serde(rename_all = "snake_case")]
enum AcronymVariants {
    MyHTTPApi,
    IOError,
    HTTPServer,
    MyVariant,
}

#[test]
fn rename_all_snake_case_groups_acronym_runs() {
    let s = AcronymVariants::schema_static();
    assert_eq!(
        s.enum_variants,
        &["my_http_api", "io_error", "http_server", "my_variant"]
    );
}

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[clapfig(rename_all = "camelCase")]
enum CamelAcronyms {
    MyHTTPApi,
    IOError,
}

#[test]
fn rename_all_camel_case_groups_acronym_runs() {
    let s = CamelAcronyms::schema_static();
    assert_eq!(s.enum_variants, &["myHttpApi", "ioError"]);
}

// -- BTreeMap<String, NestedStruct> → Field::MapOf (issue #54 item 2) ------

use std::collections::BTreeMap;

#[derive(Schema, Serialize, Deserialize, Debug)]
struct Plugin {
    /// Whether this plugin is enabled.
    #[clapfig(default = false)]
    enabled: bool,

    /// Severity threshold for emitted diagnostics.
    severity: String,
}

#[derive(Schema, Serialize, Deserialize, Debug)]
struct PluginHost {
    /// Map of installed plugins, keyed by plugin name.
    plugins: BTreeMap<String, Plugin>,
}

#[test]
fn map_of_nested_struct_emits_map_of_field() {
    let s = PluginHost::schema_static();
    let plugins = &s.fields[0];
    assert!(matches!(
        plugins.field,
        clapfig::static_schema::FieldStatic::MapOf(_)
    ));
}

#[test]
fn map_of_nested_struct_loads_user_keyed_entries() {
    let dir = TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("test.toml"),
        "[plugins.audit]\nseverity = \"warn\"\n[plugins.fmt]\nenabled = true\nseverity = \"error\"\n",
    )
    .unwrap();
    let cfg: PluginHost = Clapfig::schema_builder::<PluginHost>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.plugins.len(), 2);
    assert!(!cfg.plugins["audit"].enabled);
    assert_eq!(cfg.plugins["audit"].severity, "warn");
    assert!(cfg.plugins["fmt"].enabled);
}

#[test]
fn map_of_nested_struct_rejects_unknown_key_in_entry() {
    let dir = TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("test.toml"),
        "[plugins.audit]\nseverity = \"warn\"\nrogue = 1\n",
    )
    .unwrap();
    let result: Result<PluginHost, _> = Clapfig::schema_builder::<PluginHost>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .strict(true)
        .load();
    let err = result.unwrap_err();
    let keys = err.unknown_keys().expect("expected UnknownKeys");
    assert_eq!(keys.len(), 1);
    assert_eq!(keys[0].key, "plugins.audit.rogue");
}

// -- Macro-emitted field path enumeration (issue #54 item 7) ---------------

#[test]
fn field_paths_lists_leaves_and_sections_in_source_order() {
    let paths = AppConfig::field_paths();
    // Source order: host, port, debug, database (section, then its leaves).
    assert_eq!(
        paths,
        vec![
            "host".to_string(),
            "port".into(),
            "debug".into(),
            "database".into(),
            "database.url".into(),
            "database.pool_size".into(),
        ]
    );
}

#[test]
fn field_paths_treats_unit_enum_field_as_a_single_leaf_path() {
    // Enum-kind nested schemas flatten to a leaf at the runtime layer; the
    // variant names are metadata on the leaf, not separate paths, so they
    // must not appear in the path inventory.
    let paths = PdfDoc::field_paths();
    assert_eq!(paths, vec!["page_size".to_string()]);
}

// -- Leaf attrs on enum-typed fields (case 3 follow-up) --------------------
//
// Previously, `#[clapfig(default = "lexed")] page_size: PdfPageSize` errored
// at derive time: leaf attrs on nested-struct fields were blanket-rejected
// because the macro can't syntactically distinguish a struct from a
// unit-only enum. Users had to fall back to `#[clapfig(value, default = ...)]`,
// which dropped the `LeafType::Enum` metadata.
//
// Now the macro emits `LeafTypeStatic::EnumRef(<T as Schema>::STATIC)` for
// these cases. The converter checks `is_enum()` at first `schema()` call:
// enum-kind produces `LeafType::Enum` with the supplied default / env /
// optional; struct-kind panics with a clear authoring-error message.

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq)]
struct DocWithDefaultEnum {
    /// Default page size if the user omits the key.
    #[clapfig(default = "letter")]
    page_size: PdfPageSize,
}

#[test]
fn default_on_enum_typed_field_round_trips_through_schema() {
    let s = DocWithDefaultEnum::schema();
    let leaf = match &s.fields[0].field {
        clapfig::runtime::Field::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    match &leaf.ty {
        clapfig::runtime::LeafType::Enum { values } => {
            assert_eq!(values.len(), 3);
            assert_eq!(values[1], toml::Value::String("letter".into()));
        }
        other => panic!("expected Enum, got {other:?}"),
    }
    assert_eq!(leaf.default, Some(toml::Value::String("letter".into())));
    assert!(!leaf.optional);
}

#[test]
fn default_on_enum_typed_field_applies_when_no_layer_provides_value() {
    let dir = TempDir::new().unwrap();
    let cfg: DocWithDefaultEnum = Clapfig::schema_builder::<DocWithDefaultEnum>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.page_size, PdfPageSize::Letter);
}

#[test]
fn default_on_enum_typed_field_loses_to_user_supplied_value() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("test.toml"), "page_size = \"a4\"\n").unwrap();
    let cfg: DocWithDefaultEnum = Clapfig::schema_builder::<DocWithDefaultEnum>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.page_size, PdfPageSize::A4);
}

#[derive(Schema, Serialize, Deserialize, Debug, PartialEq)]
struct DocWithOptionalEnum {
    /// Optional page size — `None` means "let the renderer pick."
    page_size: Option<PdfPageSize>,
}

#[test]
fn option_of_unit_enum_emits_optional_leaf_enum() {
    let s = DocWithOptionalEnum::schema();
    let leaf = match &s.fields[0].field {
        clapfig::runtime::Field::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    assert!(matches!(leaf.ty, clapfig::runtime::LeafType::Enum { .. }));
    assert!(
        leaf.optional,
        "Option<UnitEnum> must produce an optional leaf"
    );
}

#[test]
fn option_of_unit_enum_load_accepts_absence() {
    let dir = TempDir::new().unwrap();
    let cfg: DocWithOptionalEnum = Clapfig::schema_builder::<DocWithOptionalEnum>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.page_size, None);
}

#[test]
fn option_of_unit_enum_load_accepts_known_variant() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("test.toml"), "page_size = \"a4\"\n").unwrap();
    let cfg: DocWithOptionalEnum = Clapfig::schema_builder::<DocWithOptionalEnum>()
        .app_name("test")
        .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
        .no_env()
        .load()
        .unwrap();
    assert_eq!(cfg.page_size, Some(PdfPageSize::A4));
}

#[test]
fn explicit_env_on_enum_typed_field_carries_through() {
    #[derive(Schema, Serialize, Deserialize, Debug)]
    struct EnvEnumDoc {
        #[clapfig(env = "PAGE_SIZE_OVERRIDE", default = "a4")]
        page_size: PdfPageSize,
    }
    let s = EnvEnumDoc::schema();
    let leaf = match &s.fields[0].field {
        clapfig::runtime::Field::Leaf(l) => l,
        other => panic!("expected Leaf, got {other:?}"),
    };
    assert_eq!(leaf.env.as_deref(), Some("PAGE_SIZE_OVERRIDE"));
}

// Struct-with-leaf-attrs: deferred error at first `schema()` call. We
// can't catch this at derive time because the macro can't tell struct
// from unit-enum syntactically. Same pattern as the malformed-datetime
// default literal — authoring error, surfaces on first test run.
#[derive(Schema, Serialize, Deserialize, Debug)]
struct InnerStruct {
    #[clapfig(default = 1)]
    x: i64,
}

#[derive(Schema, Serialize, Deserialize, Debug)]
struct WrongShapeDoc {
    #[clapfig(default = "nope")]
    inner: InnerStruct,
}

#[test]
#[should_panic(expected = "field `inner` references type `InnerStruct`")]
fn leaf_attrs_on_struct_typed_field_panic_at_first_schema_call() {
    let _ = WrongShapeDoc::schema();
}

// Sibling case: `Option<NestedStruct>` with no leaf attrs. The same
// `EnumRef` path catches it, and the deferred-panic message must
// surface the `Option`-wrapper remediation specifically — not just the
// "drop the attributes" one — so the user knows which fix to apply.
#[derive(Schema, Serialize, Deserialize, Debug)]
struct OptionalStructDoc {
    inner: Option<InnerStruct>,
}

#[test]
#[should_panic(expected = "Option<InnerStruct>")]
fn option_of_struct_typed_field_panic_mentions_option_wrapper() {
    let _ = OptionalStructDoc::schema();
}