figue 4.0.3

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
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
use std::{collections::HashMap, hash::RandomState};

use crate::{
    Attr,
    schema::{
        ArgKind, ArgLevelSchema, ArgSchema, ConfigEnumSchema, ConfigEnumVariantSchema,
        ConfigFieldGroupSchema, ConfigFieldSchema, ConfigStructSchema, ConfigValueSchema,
        ConfigVecSchema, Docs, LeafKind, LeafSchema, ScalarType, Schema, SpecialFields, Subcommand,
        ValueSchema,
        error::{SchemaError, SchemaErrorContext},
    },
};
use facet::{
    Def, EnumType, Facet, Field, ScalarType as FacetScalarType, Shape, StructKind, Type, UserType,
    Variant,
};
use heck::ToKebabCase;
use indexmap::IndexMap;

impl Schema {
    /// Parse a schema from a given shape
    pub(crate) fn from_shape(shape: &'static Shape) -> Result<Self, SchemaError> {
        let struct_type = match &shape.ty {
            Type::User(UserType::Struct(s)) => *s,
            _ => {
                return Err(SchemaError::new(
                    SchemaErrorContext::root(shape),
                    "top-level shape must be a struct",
                ));
            }
        };

        let ctx_root = SchemaErrorContext::root(shape);
        let config_fields = discover_config_fields(struct_type.fields, &ctx_root, false)?;

        let (args, special) = arg_level_from_fields_with_special(struct_type.fields, &ctx_root)?;

        let mut configs = Vec::new();
        for (field, field_ctx) in config_fields {
            let shape = field.shape();
            let optional_root = matches!(shape.def, Def::Option(_));
            let config_shape = match shape.def {
                Def::Option(opt) => opt.t,
                _ => shape,
            };
            // Extract env_prefix from the config field's attributes
            let env_prefix = extract_env_prefix(field);
            configs.push(config_struct_schema_from_shape(
                config_shape,
                &field_ctx,
                docs_from_lines(field.doc),
                Some(field.effective_name().to_string()),
                env_prefix,
                optional_root,
                field.is_flattened(),
            )?);
        }
        // Extract docs from the top-level shape
        let docs = docs_from_lines(shape.doc);

        Ok(Schema {
            docs,
            args,
            configs,
            special,
        })
    }
}

fn has_any_args_attr(field: &Field) -> bool {
    field.has_attr(Some("args"), "positional")
        || field.has_attr(Some("args"), "named")
        || field.has_attr(Some("args"), "subcommand")
        || field.has_attr(Some("args"), "config")
        || field.has_attr(Some("args"), "short")
        || field.has_attr(Some("args"), "counted")
        || field.has_attr(Some("args"), "env_prefix")
        || field.is_flattened()
}

/// Extract the env_prefix value from a field's `#[facet(args::env_prefix = "...")]` attribute.
fn extract_env_prefix(field: &Field) -> Option<String> {
    let attr = field.get_attr(Some("args"), "env_prefix")?;
    let parsed = attr.get_as::<crate::Attr>()?;

    if let crate::Attr::EnvPrefix(prefix_opt) = parsed {
        prefix_opt.map(|s| s.to_string())
    } else {
        None
    }
}

fn discover_config_fields(
    fields: &'static [Field],
    ctx: &SchemaErrorContext,
    inside_subcommand: bool,
) -> Result<Vec<(&'static Field, SchemaErrorContext)>, SchemaError> {
    let mut config_fields = Vec::new();

    for field in fields {
        let field_ctx = ctx.with_field(field.name);

        if is_config_field(field) {
            if inside_subcommand {
                return Err(SchemaError::new(
                    field_ctx,
                    "#[facet(args::config)] inside a subcommand variant is not supported",
                )
                .with_primary_label("place this config field on the outermost args struct"));
            }

            config_fields.push((field, field_ctx));
            continue;
        }

        if field.has_attr(Some("args"), "env_prefix") {
            return Err(SchemaError::new(
                field_ctx,
                format!(
                    "field `{}` uses args::env_prefix without args::config",
                    field.name
                ),
            ));
        }

        if field.is_flattened() {
            let inner_shape = field.shape();
            let Type::User(UserType::Struct(struct_type)) = inner_shape.ty else {
                return Err(SchemaError::new(
                    field_ctx,
                    format!("flattened field `{}` must be a struct", field.name),
                ));
            };

            config_fields.extend(discover_config_fields(
                struct_type.fields,
                &field_ctx,
                inside_subcommand,
            )?);
        }

        if field.has_attr(Some("args"), "subcommand") {
            let field_shape = field.shape();
            let (enum_shape, enum_type) = match field_shape.def {
                Def::Option(opt) => match opt.t.ty {
                    Type::User(UserType::Enum(enum_type)) => (opt.t, enum_type),
                    _ => continue,
                },
                _ => match field_shape.ty {
                    Type::User(UserType::Enum(enum_type)) => (field_shape, enum_type),
                    _ => continue,
                },
            };

            for variant in enum_type.variants {
                let variant_ctx =
                    SchemaErrorContext::root(enum_shape).with_variant(variant_cli_name(variant));
                let variant_fields = variant_fields_for_schema(variant);
                discover_config_fields(variant_fields, &variant_ctx, true)?;
            }
        }
    }

    Ok(config_fields)
}

/// Extract all env_alias values from a field's `#[facet(args::env_alias = "...")]` attributes.
/// Multiple aliases can be specified by using the attribute multiple times:
/// `#[facet(args::env_alias = "A", args::env_alias = "B")]`
fn extract_env_aliases(field: &Field) -> Vec<String> {
    let mut aliases = Vec::new();
    // Iterate through all attributes to find all env_alias entries
    for field_attr in field.attributes {
        if field_attr.ns == Some("args") && field_attr.key == "env_alias" {
            // The attribute data is stored as &str directly
            if let Some(s) = field_attr.get_as::<&str>() {
                aliases.push(s.to_string());
            }
        }
    }
    aliases
}

/// Check if a field has `#[facet(args::env_subst)]` attribute.
fn has_env_subst(field: &Field) -> bool {
    field.has_attr(Some("args"), "env_subst")
}

/// Check if a shape (struct) has `#[facet(args::env_subst_all)]` attribute.
fn has_env_subst_all(shape: &'static Shape) -> bool {
    shape
        .attributes
        .iter()
        .any(|attr| attr.ns == Some("args") && attr.key == "env_subst_all")
}

/// Extract a custom type label from `#[facet(args::label = "...")]`.
fn extract_label(field: &Field) -> Option<String> {
    // Prefer typed parsing via Attr
    if let Some(attr) = field.get_attr(Some("args"), "label") {
        if let Some(parsed) = attr.get_as::<Attr>()
            && let Attr::Label(s) = parsed
        {
            return Some(s.to_string());
        }
        // Fallback: direct &str if typed form isn't available
        if let Some(s) = attr.get_as::<&str>() {
            return Some(s.to_string());
        }
    }
    None
}

/// Extract the default value from a field's `#[facet(default)]` or `#[facet(default = ...)]` attribute,
/// serialized to ConfigValue.
///
/// Returns None if the field has no default, or if the default cannot be serialized.
fn extract_field_default(field: &Field) -> Option<crate::config_value::ConfigValue> {
    let default_source = field.default.as_ref()?;
    let shape = field.shape();

    match crate::config_value_parser::serialize_default_to_config_value(default_source, shape) {
        Ok(config_value) => {
            // Don't return null for types that shouldn't be null - that indicates
            // the serialization couldn't represent the default value properly
            if matches!(config_value, crate::config_value::ConfigValue::Null(_)) {
                if let Some(value) = from_trait_vec_default(default_source, shape) {
                    return Some(value);
                }
                tracing::debug!(
                    field = field.name,
                    "extract_field_default: serialized to null, skipping"
                );
                None
            } else {
                tracing::debug!(
                    field = field.name,
                    ?config_value,
                    "extract_field_default: successfully extracted default"
                );
                Some(config_value)
            }
        }
        Err(e) => {
            if let Some(value) = from_trait_vec_default(default_source, shape) {
                return Some(value);
            }
            tracing::debug!(
                field = field.name,
                error = %e,
                "extract_field_default: failed to serialize default"
            );
            None
        }
    }
}

fn from_trait_vec_default(
    default_source: &facet_core::DefaultSource,
    shape: &'static Shape,
) -> Option<crate::config_value::ConfigValue> {
    if !matches!(default_source, facet_core::DefaultSource::FromTrait)
        || !matches!(shape.def, Def::List(_))
    {
        return None;
    }

    Some(crate::config_value::ConfigValue::Array(
        crate::config_value::Sourced {
            value: Vec::new(),
            span: None,
            provenance: Some(crate::provenance::Provenance::Default),
        },
    ))
}

fn docs_from_lines(lines: &'static [&'static str]) -> Docs {
    if lines.is_empty() {
        return Docs::default();
    }

    let summary = lines
        .first()
        .map(|line| line.trim().to_string())
        .filter(|s| !s.is_empty());

    let details = if lines.len() > 1 {
        let mut buf = String::new();
        for line in &lines[1..] {
            if !buf.is_empty() {
                buf.push('\n');
            }
            buf.push_str(line.trim());
        }
        if buf.is_empty() { None } else { Some(buf) }
    } else {
        None
    };

    Docs { summary, details }
}

fn scalar_kind_from_shape(shape: &'static Shape) -> Option<ScalarType> {
    match shape.scalar_type()? {
        FacetScalarType::Bool => Some(ScalarType::Bool),
        FacetScalarType::Str
        | FacetScalarType::String
        | FacetScalarType::CowStr
        | FacetScalarType::Char => Some(ScalarType::String),
        FacetScalarType::F32 | FacetScalarType::F64 => Some(ScalarType::Float),
        FacetScalarType::U8
        | FacetScalarType::U16
        | FacetScalarType::U32
        | FacetScalarType::U64
        | FacetScalarType::U128
        | FacetScalarType::USize
        | FacetScalarType::I8
        | FacetScalarType::I16
        | FacetScalarType::I32
        | FacetScalarType::I64
        | FacetScalarType::I128
        | FacetScalarType::ISize => Some(ScalarType::Integer),
        _ => None,
    }
}

fn enum_variants(enum_type: EnumType) -> Vec<String> {
    enum_type.variants.iter().map(variant_cli_name).collect()
}

fn variant_cli_name(variant: &Variant) -> String {
    variant.effective_name().to_kebab_case()
}

fn leaf_schema_from_shape(
    shape: &'static Shape,
    _ctx: &SchemaErrorContext,
) -> Result<LeafSchema, SchemaError> {
    if let Some(scalar) = scalar_kind_from_shape(shape) {
        return Ok(LeafSchema {
            kind: LeafKind::Scalar(scalar),
            shape,
        });
    }

    match &shape.ty {
        Type::User(UserType::Enum(enum_type)) => Ok(LeafSchema {
            kind: LeafKind::Enum {
                variants: enum_variants(*enum_type),
            },
            shape,
        }),
        // Fallback: treat as Other and let deserialization handle it
        _ => Ok(LeafSchema {
            kind: LeafKind::Scalar(ScalarType::Other),
            shape,
        }),
    }
}

fn value_schema_from_shape(
    shape: &'static Shape,
    ctx: &SchemaErrorContext,
) -> Result<ValueSchema, SchemaError> {
    match shape.def {
        Def::Option(opt) => Ok(ValueSchema::Option {
            value: Box::new(value_schema_from_shape(opt.t, ctx)?),
            shape,
        }),
        Def::List(list) => Ok(ValueSchema::Vec {
            element: Box::new(value_schema_from_shape(list.t, ctx)?),
            shape,
        }),
        _ => match &shape.ty {
            Type::User(UserType::Struct(_)) => Ok(ValueSchema::Struct {
                fields: config_struct_schema_from_shape(
                    shape,
                    ctx,
                    Docs::default(),
                    None,
                    None,
                    false,
                    false,
                )?,
                shape,
            }),
            _ => Ok(ValueSchema::Leaf(leaf_schema_from_shape(shape, ctx)?)),
        },
    }
}

fn config_value_schema_from_shape(
    shape: &'static Shape,
    ctx: &SchemaErrorContext,
) -> Result<ConfigValueSchema, SchemaError> {
    match shape.def {
        Def::Option(opt) => Ok(ConfigValueSchema::Option {
            value: Box::new(config_value_schema_from_shape(opt.t, ctx)?),
            shape,
        }),
        Def::List(list) => Ok(ConfigValueSchema::Vec(ConfigVecSchema {
            element: Box::new(config_value_schema_from_shape(list.t, ctx)?),
            shape,
        })),
        _ => match &shape.ty {
            Type::User(UserType::Struct(_)) => {
                Ok(ConfigValueSchema::Struct(config_struct_schema_from_shape(
                    shape,
                    ctx,
                    Docs::default(),
                    None,
                    None,
                    false,
                    false,
                )?))
            }
            Type::User(UserType::Enum(enum_type)) => Ok(ConfigValueSchema::Enum(
                config_enum_schema_from_shape(shape, *enum_type, ctx)?,
            )),
            _ => Ok(ConfigValueSchema::Leaf(leaf_schema_from_shape(shape, ctx)?)),
        },
    }
}

fn value_schema_from_config_value_schema(value: &ConfigValueSchema) -> ValueSchema {
    match value {
        ConfigValueSchema::Leaf(leaf) => ValueSchema::Leaf(leaf.clone()),
        ConfigValueSchema::Option { value, shape } => ValueSchema::Option {
            value: Box::new(value_schema_from_config_value_schema(value)),
            shape,
        },
        ConfigValueSchema::Vec(vec_schema) => ValueSchema::Vec {
            element: Box::new(value_schema_from_config_value_schema(vec_schema.element())),
            shape: vec_schema.shape(),
        },
        ConfigValueSchema::Struct(struct_schema) => ValueSchema::Struct {
            fields: struct_schema.clone(),
            shape: struct_schema.shape(),
        },
        ConfigValueSchema::Enum(enum_schema) => ValueSchema::Leaf(LeafSchema {
            kind: LeafKind::Enum {
                variants: enum_schema
                    .variants()
                    .keys()
                    .map(|name| name.to_kebab_case())
                    .collect(),
            },
            shape: enum_schema.shape(),
        }),
    }
}

fn value_schema_is_multiple(value: &ValueSchema) -> bool {
    match value {
        ValueSchema::Option { value, .. } => value_schema_is_multiple(value),
        ValueSchema::Vec { .. } => true,
        _ => false,
    }
}

fn config_enum_schema_from_shape(
    shape: &'static Shape,
    enum_type: facet::EnumType,
    ctx: &SchemaErrorContext,
) -> Result<ConfigEnumSchema, SchemaError> {
    let mut variants: IndexMap<String, ConfigEnumVariantSchema, RandomState> = IndexMap::default();

    for variant in enum_type.variants {
        let variant_ctx = ctx.with_variant(variant.name.to_string());
        let docs = docs_from_lines(variant.doc);

        let mut fields: IndexMap<String, ConfigFieldSchema, RandomState> = IndexMap::default();

        // Handle struct variants
        for field in variant.data.fields {
            let field_ctx = variant_ctx.with_field(field.name);
            let field_docs = docs_from_lines(field.doc);
            let sensitive = field.flags.contains(facet_core::FieldFlags::SENSITIVE);
            let env_aliases = extract_env_aliases(field);
            let env_subst = has_env_subst(field);
            let value = config_value_schema_from_shape(field.shape(), &field_ctx)?;
            let default = extract_field_default(field);

            fields.insert(
                field.effective_name().to_string(),
                ConfigFieldSchema {
                    docs: field_docs,
                    sensitive,
                    env_aliases,
                    env_subst,
                    value,
                    default,
                },
            );
        }

        variants.insert(
            variant.effective_name().to_string(),
            ConfigEnumVariantSchema { docs, fields },
        );
    }

    Ok(ConfigEnumSchema { shape, variants })
}

fn config_struct_schema_from_shape(
    shape: &'static Shape,
    ctx: &SchemaErrorContext,
    docs: Docs,
    field_name: Option<String>,
    env_prefix: Option<String>,
    optional_root: bool,
    flattened_root: bool,
) -> Result<ConfigStructSchema, SchemaError> {
    config_struct_schema_from_shape_inner(
        shape,
        ctx,
        docs,
        ConfigStructBuildOptions {
            field_name,
            env_prefix,
            optional_root,
            flattened_root,
            path_prefix: Vec::new(),
            parent_env_subst_all: false,
        },
    )
}

struct ConfigStructBuildOptions {
    field_name: Option<String>,
    env_prefix: Option<String>,
    optional_root: bool,
    flattened_root: bool,
    path_prefix: Vec<String>,
    parent_env_subst_all: bool,
}

fn config_struct_schema_from_shape_inner(
    shape: &'static Shape,
    ctx: &SchemaErrorContext,
    docs: Docs,
    options: ConfigStructBuildOptions,
) -> Result<ConfigStructSchema, SchemaError> {
    let ConfigStructBuildOptions {
        field_name,
        env_prefix,
        optional_root,
        flattened_root,
        path_prefix,
        parent_env_subst_all,
    } = options;

    let struct_type = match &shape.ty {
        Type::User(UserType::Struct(s)) => *s,
        _ => {
            return Err(SchemaError::new(
                ctx.clone(),
                "config field must be a struct",
            ));
        }
    };

    // Check if this struct has env_subst_all - applies to direct children only
    let this_env_subst_all = has_env_subst_all(shape);
    // For direct children, env_subst is enabled if either:
    // - The parent passed down env_subst_all (for flattened fields)
    // - This struct has env_subst_all
    let apply_env_subst_to_children = parent_env_subst_all || this_env_subst_all;

    let mut fields_map: IndexMap<String, ConfigFieldSchema, RandomState> = IndexMap::default();
    let mut field_groups = Vec::new();

    for field in struct_type.fields {
        let field_ctx = ctx.with_field(field.name);

        // Handle flattened fields - recurse into the inner struct and merge fields
        if field.is_flattened() {
            let inner_shape = field.shape();
            let _inner_struct = match &inner_shape.ty {
                Type::User(UserType::Struct(s)) => *s,
                _ => {
                    return Err(SchemaError::new(
                        field_ctx,
                        format!("flattened config field `{}` must be a struct", field.name),
                    ));
                }
            };

            // Build the new path prefix including this field's effective name
            let mut new_prefix = path_prefix.clone();
            new_prefix.push(field.effective_name().to_string());

            // Recursively process the inner struct's fields
            // Nested flattened structs don't have their own env_prefix
            // Pass down env_subst_all so flattened fields inherit it (they become direct children)
            let inner = config_struct_schema_from_shape_inner(
                inner_shape,
                &field_ctx,
                Docs::default(),
                ConfigStructBuildOptions {
                    field_name: None,
                    env_prefix: None,
                    optional_root: false,
                    flattened_root: false,
                    path_prefix: new_prefix,
                    parent_env_subst_all: apply_env_subst_to_children,
                },
            )?;

            field_groups.push(ConfigFieldGroupSchema {
                name: field.effective_name().to_string(),
                docs: docs_from_lines(field.doc),
                fields: inner.fields.clone(),
                field_groups: inner.field_groups.clone(),
            });

            // Merge the inner fields into our fields (checking for conflicts)
            for (name, field_schema) in inner.fields {
                if fields_map.contains_key(&name) {
                    return Err(SchemaError::new(
                        field_ctx.clone(),
                        format!(
                            "duplicate config field `{}` (from flattened field `{}`)",
                            name, field.name
                        ),
                    ));
                }
                fields_map.insert(name, field_schema);
            }

            continue;
        }

        // Non-flattened field
        let docs = docs_from_lines(field.doc);
        let sensitive = field.flags.contains(facet_core::FieldFlags::SENSITIVE);
        let env_aliases = extract_env_aliases(field);
        let value = config_value_schema_from_shape(field.shape(), &field_ctx)?;
        let default = extract_field_default(field);

        // env_subst is enabled if:
        // - The field has #[facet(args::env_subst)] directly, OR
        // - The parent struct has env_subst_all (applies to direct children)
        let env_subst = has_env_subst(field) || apply_env_subst_to_children;

        // Use the effective (serialized) name as the key
        let effective_name = field.effective_name().to_string();

        fields_map.insert(
            effective_name,
            ConfigFieldSchema {
                docs,
                sensitive,
                env_aliases,
                env_subst,
                value,
                default,
            },
        );
    }

    // Check for conflicting env aliases across all fields
    check_env_alias_conflicts(&fields_map, ctx)?;

    Ok(ConfigStructSchema {
        docs,
        field_name,
        env_prefix,
        optional_root,
        flattened_root,
        shape,
        fields: fields_map,
        field_groups,
    })
}

/// Check that no two fields share the same env alias.
fn check_env_alias_conflicts(
    fields: &IndexMap<String, ConfigFieldSchema, RandomState>,
    ctx: &SchemaErrorContext,
) -> Result<(), SchemaError> {
    use std::collections::HashMap;

    // Map from alias to the field name that uses it
    let mut alias_to_field: HashMap<&str, &str> = HashMap::new();

    for (field_name, field_schema) in fields.iter() {
        for alias in field_schema.env_aliases() {
            if let Some(existing_field) = alias_to_field.get(alias.as_str()) {
                return Err(SchemaError::new(
                    ctx.clone(),
                    format!(
                        "env alias `{}` is used by both `{}` and `{}`",
                        alias, existing_field, field_name
                    ),
                ));
            }
            alias_to_field.insert(alias.as_str(), field_name.as_str());
        }
    }

    Ok(())
}

fn short_from_field(field: &Field) -> Option<char> {
    field
        .get_attr(Some("args"), "short")
        .and_then(|attr| attr.get_as::<Attr>())
        .and_then(|attr| {
            if let Attr::Short(c) = attr {
                c.or_else(|| field.effective_name().chars().next())
            } else {
                None
            }
        })
}

fn short_from_variant(variant: &Variant) -> Option<char> {
    variant
        .get_attr(Some("args"), "short")
        .and_then(|attr| attr.get_as::<Attr>())
        .and_then(|attr| {
            if let Attr::Short(c) = attr {
                c.or_else(|| variant.effective_name().chars().next())
            } else {
                None
            }
        })
}

fn variant_fields_for_schema(variant: &Variant) -> &'static [Field] {
    let fields = variant.data.fields;
    if is_flattened_tuple_variant(variant) {
        let inner_shape = fields[0].shape();
        if let Type::User(UserType::Struct(struct_type)) = inner_shape.ty {
            return struct_type.fields;
        }
    }
    fields
}

/// Check if this variant is a tuple variant with a single struct field that gets flattened.
/// E.g., `Bench(BenchArgs)` where `BenchArgs` is a struct.
fn is_flattened_tuple_variant(variant: &Variant) -> bool {
    let fields = variant.data.fields;
    if variant.data.kind == StructKind::TupleStruct && fields.len() == 1 {
        let inner_shape = fields[0].shape();
        matches!(inner_shape.ty, Type::User(UserType::Struct(_)))
    } else {
        false
    }
}

fn arg_level_from_fields(
    fields: &'static [Field],
    ctx: &SchemaErrorContext,
) -> Result<ArgLevelSchema, SchemaError> {
    let (args, _special) = arg_level_from_fields_with_prefix(fields, ctx, Vec::new())?;
    Ok(args)
}

fn arg_level_from_fields_with_special(
    fields: &'static [Field],
    ctx: &SchemaErrorContext,
) -> Result<(ArgLevelSchema, SpecialFields), SchemaError> {
    arg_level_from_fields_with_prefix(fields, ctx, Vec::new())
}

fn arg_level_from_fields_with_prefix(
    fields: &'static [Field],
    ctx: &SchemaErrorContext,
    path_prefix: Vec<String>,
) -> Result<(ArgLevelSchema, SpecialFields), SchemaError> {
    let mut args: IndexMap<String, ArgSchema, RandomState> = IndexMap::default();
    let mut subcommands: IndexMap<String, Subcommand, RandomState> = IndexMap::default();
    let mut subcommand_field_name: Option<String> = None;
    let mut subcommand_optional: bool = false;
    let mut special = SpecialFields::default();

    let mut seen_long: HashMap<String, SchemaErrorContext> = HashMap::new();
    let mut seen_short: HashMap<char, SchemaErrorContext> = HashMap::new();
    let mut seen_subcommands: HashMap<String, SchemaErrorContext> = HashMap::new();
    let mut seen_subcommand_short: HashMap<char, SchemaErrorContext> = HashMap::new();

    let mut first_subcommand_field: Option<SchemaErrorContext> = None;

    for field in fields {
        let field_ctx = ctx.with_field(field.name);

        if is_config_field(field) {
            if field.is_flattened() {
                let shape = field.shape();
                let optional_root = matches!(shape.def, Def::Option(_));
                let config_shape = match shape.def {
                    Def::Option(opt) => opt.t,
                    _ => shape,
                };
                let config_field_name = field.effective_name().to_string();
                let config_schema = config_struct_schema_from_shape(
                    config_shape,
                    &field_ctx,
                    docs_from_lines(field.doc),
                    Some(config_field_name.clone()),
                    extract_env_prefix(field),
                    optional_root,
                    true,
                )?;

                for (name, config_field_schema) in config_schema.fields() {
                    let long = name.to_kebab_case();
                    if let Some(existing_ctx) = seen_long.get(&long) {
                        return Err(SchemaError::new(
                            existing_ctx.clone(),
                            format!("duplicate flag `--{long}` (from flattened config root)"),
                        )
                        .with_primary_label(format!("`--{long}` first defined here"))
                        .with_label(field_ctx.clone(), "flattened config root defined here"));
                    }
                    if args.contains_key(name) {
                        return Err(SchemaError::new(
                            field_ctx.clone(),
                            format!("duplicate argument `{name}` (from flattened config root)"),
                        )
                        .with_primary_label("flattened config root defined here"));
                    }
                    seen_long.insert(long, field_ctx.clone());

                    let value = value_schema_from_config_value_schema(config_field_schema.value());
                    let arg = ArgSchema {
                        name: name.clone(),
                        insertion_path: vec![config_field_name.clone(), name.clone()],
                        docs: config_field_schema.docs().clone(),
                        kind: ArgKind::Named {
                            short: None,
                            counted: false,
                        },
                        multiple: value_schema_is_multiple(&value),
                        value,
                        label: None,
                        required: false,
                        default: None,
                    };

                    args.insert(name.clone(), arg);
                }
            }
            continue;
        }

        // Handle flattened fields - recurse into the inner struct
        if field.is_flattened() {
            let inner_shape = field.shape();
            let struct_type = match &inner_shape.ty {
                Type::User(UserType::Struct(s)) => *s,
                _ => {
                    return Err(SchemaError::new(
                        field_ctx,
                        format!("flattened field `{}` must be a struct", field.name),
                    ));
                }
            };

            // For flatten, fields appear at the CURRENT level in ConfigValue,
            // so we pass the same path_prefix (don't add the field name)
            let (inner, inner_special) = arg_level_from_fields_with_prefix(
                struct_type.fields,
                &field_ctx,
                path_prefix.clone(),
            )?;

            // Merge special fields from the inner struct
            if inner_special.help.is_some() {
                special.help = inner_special.help;
            }
            if inner_special.html_help.is_some() {
                special.html_help = inner_special.html_help;
            }
            if inner_special.version.is_some() {
                special.version = inner_special.version;
            }
            if inner_special.completions.is_some() {
                special.completions = inner_special.completions;
            }
            if inner_special.export_jsonschemas.is_some() {
                special.export_jsonschemas = inner_special.export_jsonschemas;
            }

            // Merge the inner args into our args (checking for conflicts)
            for (name, arg) in inner.args {
                if let Some(existing_ctx) = seen_long.get(&name) {
                    return Err(SchemaError::new(
                        existing_ctx.clone(),
                        format!("duplicate flag `--{}` (from flattened field)", name),
                    )
                    .with_primary_label("first defined here")
                    .with_label(field_ctx.clone(), "flattened here"));
                }
                seen_long.insert(name.clone(), field_ctx.clone());

                if let ArgKind::Named { short: Some(c), .. } = &arg.kind {
                    if let Some(existing_ctx) = seen_short.get(c) {
                        return Err(SchemaError::new(
                            existing_ctx.clone(),
                            format!("duplicate flag `-{}` (from flattened field)", c),
                        )
                        .with_primary_label("first defined here")
                        .with_label(field_ctx.clone(), "flattened here"));
                    }
                    seen_short.insert(*c, field_ctx.clone());
                }

                args.insert(name, arg);
            }

            // Merge subcommands too
            for (name, sub) in inner.subcommands {
                if let Some(existing_ctx) = seen_subcommands.get(&name) {
                    return Err(SchemaError::new(
                        existing_ctx.clone(),
                        format!("duplicate subcommand `{}` (from flattened field)", name),
                    )
                    .with_primary_label("first defined here")
                    .with_label(field_ctx.clone(), "flattened here"));
                }
                seen_subcommands.insert(name.clone(), field_ctx.clone());
                subcommands.insert(name, sub);
            }

            // If the inner level had a subcommand field, propagate it
            if inner.subcommand_field_name.is_some() {
                if first_subcommand_field.is_some() {
                    return Err(SchemaError::new(
                        field_ctx,
                        "multiple subcommand fields via flatten",
                    ));
                }
                first_subcommand_field = Some(field_ctx.clone());
                subcommand_field_name = inner.subcommand_field_name;
                subcommand_optional = inner.subcommand_optional;
            }

            continue;
        }

        if !has_any_args_attr(field) {
            return Err(SchemaError::new(
                field_ctx,
                format!(
                    "field `{}` is missing a #[facet(args::...)] annotation",
                    field.name
                ),
            ));
        }

        if field.has_attr(Some("args"), "env_prefix") && !field.has_attr(Some("args"), "config") {
            return Err(SchemaError::new(
                field_ctx,
                format!(
                    "field `{}` uses args::env_prefix without args::config",
                    field.name
                ),
            ));
        }

        let is_positional = field.has_attr(Some("args"), "positional");
        let is_subcommand = field.has_attr(Some("args"), "subcommand");

        if field.has_attr(Some("args"), "short") && is_positional {
            return Err(SchemaError::new(
                field_ctx,
                "#[facet(args::positional)] is not compatible with #[facet(args::short)]",
            )
            .with_primary_label("has both attributes"));
        }

        if is_counted_field(field) && !is_supported_counted_type(field.shape()) {
            return Err(SchemaError::new(
                field_ctx,
                format!(
                    "field `{}` marked as counted must be an integer",
                    field.name
                ),
            ));
        }

        if is_subcommand {
            if let Some(first_ctx) = &first_subcommand_field {
                return Err(SchemaError::new(
                    first_ctx.clone(),
                    "only one field may be marked with #[facet(args::subcommand)] at this level",
                )
                .with_primary_label("first marked here")
                .with_label(field_ctx, "also marked here"));
            }
            first_subcommand_field = Some(field_ctx.clone());
            subcommand_field_name = Some(field.name.to_string());

            let field_shape = field.shape();
            let (enum_shape, enum_type, is_optional) = match field_shape.def {
                Def::Option(opt) => match opt.t.ty {
                    Type::User(UserType::Enum(enum_type)) => (opt.t, enum_type, true),
                    _ => {
                        return Err(SchemaError::new(
                            field_ctx,
                            format!(
                                "field `{}` marked as subcommand must be an enum",
                                field.name
                            ),
                        ));
                    }
                },
                _ => match field_shape.ty {
                    Type::User(UserType::Enum(enum_type)) => (field_shape, enum_type, false),
                    _ => {
                        return Err(SchemaError::new(
                            field_ctx,
                            format!(
                                "field `{}` marked as subcommand must be an enum",
                                field.name
                            ),
                        ));
                    }
                },
            };
            subcommand_optional = is_optional;

            for variant in enum_type.variants {
                let cli_name = variant_cli_name(variant);
                // effective_name respects #[facet(rename = "...")], used for deserialization
                let effective_name = variant.effective_name().to_string();
                let docs = docs_from_lines(variant.doc);
                let short = short_from_variant(variant);
                let variant_fields = variant_fields_for_schema(variant);
                let variant_ctx =
                    SchemaErrorContext::root(enum_shape).with_variant(cli_name.clone());
                let args_schema = arg_level_from_fields(variant_fields, &variant_ctx)?;
                let is_flattened_tuple = is_flattened_tuple_variant(variant);

                if let Some(short) = short {
                    if let Some(existing_ctx) = seen_subcommand_short.get(&short) {
                        return Err(SchemaError::new(
                            existing_ctx.clone(),
                            format!("duplicate subcommand short alias `{short}`"),
                        )
                        .with_primary_label(format!("`{short}` first defined here"))
                        .with_label(variant_ctx.clone(), "defined again here"));
                    }
                    if let Some(existing_ctx) = seen_subcommands.get(&short.to_string()) {
                        return Err(SchemaError::new(
                            existing_ctx.clone(),
                            format!(
                                "subcommand short alias `{short}` conflicts with existing subcommand name"
                            ),
                        )
                        .with_primary_label("conflicting name defined here")
                        .with_label(variant_ctx.clone(), "conflicting short alias defined here"));
                    }
                    seen_subcommand_short.insert(short, variant_ctx.clone());
                }

                let sub = Subcommand {
                    name: cli_name.clone(),
                    effective_name: effective_name.clone(),
                    docs,
                    short,
                    args: args_schema,
                    is_flattened_tuple,
                    shape: enum_shape,
                };

                if let Some(existing_ctx) = seen_subcommands.get(&cli_name) {
                    return Err(SchemaError::new(
                        existing_ctx.clone(),
                        format!("duplicate subcommand name `{cli_name}`"),
                    )
                    .with_primary_label("first defined here")
                    .with_label(variant_ctx, "defined again here"));
                }
                seen_subcommands.insert(cli_name.clone(), variant_ctx.clone());
                subcommands.insert(effective_name, sub);
            }

            continue;
        }

        let short = if field.has_attr(Some("args"), "short") {
            short_from_field(field)
        } else {
            None
        };
        let counted = field.has_attr(Some("args"), "counted");

        let kind = if is_positional {
            ArgKind::Positional
        } else {
            ArgKind::Named { short, counted }
        };

        let value = value_schema_from_shape(field.shape(), &field_ctx)?;

        // Struct types in args must be flattened - CLI can't represent nested structs
        // without dotted path syntax (which is only for args::config fields)
        if matches!(value, ValueSchema::Struct { .. }) {
            return Err(SchemaError::new(
                field_ctx.clone(),
                "struct fields in args must use #[facet(flatten)]",
            )
            .with_primary_label("this field is a struct type")
            .with_label(
                field_ctx.clone(),
                "add #[facet(flatten)] to include its fields at this level",
            ));
        }

        #[allow(clippy::nonminimal_bool)]
        let required = {
            let shape = field.shape();
            !matches!(shape.def, Def::Option(_))
                && !field.has_default()
                && !shape.is_shape(bool::SHAPE)
                && !(counted && is_supported_counted_type(shape))
        };
        let multiple = counted || matches!(field.shape().def, Def::List(_));

        if !is_positional {
            let long = field.effective_name().to_kebab_case();
            if let Some(existing_ctx) = seen_long.get(&long) {
                return Err(SchemaError::new(
                    existing_ctx.clone(),
                    format!("duplicate flag `--{long}`"),
                )
                .with_primary_label(format!("`--{long}` first defined here"))
                .with_label(field_ctx.clone(), "defined again here"));
            }
            seen_long.insert(long.clone(), field_ctx.clone());

            if let Some(c) = short {
                if let Some(existing_ctx) = seen_short.get(&c) {
                    return Err(SchemaError::new(
                        existing_ctx.clone(),
                        format!("duplicate flag `-{c}`"),
                    )
                    .with_primary_label(format!("`-{c}` first defined here"))
                    .with_label(field_ctx.clone(), "defined again here"));
                }
                seen_short.insert(c, field_ctx.clone());
            }
        }

        let docs = docs_from_lines(field.doc);
        let effective_name = field.effective_name().to_string();
        let default = extract_field_default(field);

        // Build the full path for this field (for special field detection)
        // The path uses the EFFECTIVE name (what appears in ConfigValue)
        let mut field_path = path_prefix.clone();
        field_path.push(effective_name.clone());

        // Detect special fields by ATTRIBUTE, except for built-in html_help,
        // which is recognized by its field name to keep FigueBuiltins usable
        // without introducing another public attribute.
        if field.has_attr(Some("args"), "help") {
            special.help = Some(field_path.clone());
        }
        if field.has_attr(Some("args"), "html_help") || field.name == "html_help" {
            special.html_help = Some(field_path.clone());
        }
        if field.has_attr(Some("args"), "version") {
            special.version = Some(field_path.clone());
        }
        if field.has_attr(Some("args"), "completions") {
            special.completions = Some(field_path.clone());
        }
        if field.has_attr(Some("args"), "export_jsonschemas") {
            special.export_jsonschemas = Some(field_path.clone());
        }

        let arg = ArgSchema {
            name: effective_name.clone(),
            insertion_path: vec![effective_name.clone()],
            docs,
            kind,
            value,
            label: extract_label(field),
            required,
            multiple,
            default,
        };

        if args.contains_key(&effective_name) {
            return Err(SchemaError::new(
                field_ctx.clone(),
                format!("duplicate argument `{effective_name}`"),
            )
            .with_primary_label("defined again here"));
        }

        args.insert(effective_name, arg);
    }

    Ok((
        ArgLevelSchema {
            args,
            subcommands,
            subcommand_field_name,
            subcommand_optional,
        },
        special,
    ))
}

/// Check if a field is marked with `args::counted`.
fn is_counted_field(field: &facet_core::Field) -> bool {
    field.has_attr(Some("args"), "counted")
}

/// Check if a shape is a supported type for counted fields (integer types).
const fn is_supported_counted_type(shape: &'static facet_core::Shape) -> bool {
    use facet_core::{NumericType, PrimitiveType, Type};
    matches!(
        shape.ty,
        Type::Primitive(PrimitiveType::Numeric(NumericType::Integer { .. }))
    )
}

/// Check if a field is marked with `args::config`.
fn is_config_field(field: &facet_core::Field) -> bool {
    field.has_attr(Some("args"), "config")
}