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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
//! Collect missing required fields by walking a Schema and ConfigValue together.

use crate::config_value::ConfigValue;
use crate::schema::{
    ArgKind, ArgLevelSchema, ConfigFieldSchema, ConfigStructSchema, ConfigValueSchema, Schema,
    ValueSchema,
};
use heck::ToKebabCase;
use heck::ToShoutySnakeCase;
use owo_colors::Stream::Stdout;

/// Normalize a program name for display in error messages and help text.
///
/// This function:
/// 1. Extracts just the filename from a full path
/// 2. Strips Cargo test binary hash suffixes (e.g., "main-138217976bbdb088" -> "main")
///
/// This ensures stable, readable output in both tests and help messages.
pub fn normalize_program_name(path: &str) -> String {
    // Extract just the filename from the path
    let name = std::path::Path::new(path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(path);

    // For Windows test binaries, strip trailing .exe before hash detection.
    let stem = name
        .strip_suffix(".exe")
        .or_else(|| name.strip_suffix(".EXE"))
        .unwrap_or(name);

    // Check if the name ends with a dash followed by exactly 16 hex characters
    if let Some(dash_pos) = stem.rfind('-') {
        let suffix = &stem[dash_pos + 1..];
        if suffix.len() == 16 && suffix.chars().all(|c| c.is_ascii_hexdigit()) {
            return stem[..dash_pos].to_string();
        }
    }
    name.to_string()
}

/// The kind of field that is missing - determines how errors should be formatted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingFieldKind {
    /// A direct CLI argument (flag or positional) at the top level or in a subcommand
    CliArg,
    /// A field in a config struct (has layered sources: file, env, CLI overrides)
    ConfigField,
}

/// A available subcommand name and its doc summary.
#[derive(Debug, Clone)]
pub struct AvailableSubcommand {
    /// CLI name (kebab-case)
    pub name: String,
    /// Doc summary if available
    pub doc: Option<String>,
}

/// Information about a missing required field.
#[derive(Debug, Clone)]
pub struct MissingFieldInfo {
    /// Field name (e.g., "email" or "host")
    pub field_name: String,
    /// Full path (e.g., "config.server.host")
    pub field_path: String,
    /// Type name
    pub type_name: String,
    /// Documentation comment if available
    pub doc_comment: Option<String>,
    /// CLI flag to set this field (e.g., "--config.server-host" or "--settings.server-host")
    pub cli_flag: Option<String>,
    /// Environment variable to set this field (e.g., "APP__SERVER__HOST")
    pub env_var: Option<String>,
    /// Environment variable aliases (e.g., ["DATABASE_URL", "DB_URL"])
    pub env_aliases: Vec<String>,
    /// What kind of field this is - determines error formatting strategy
    pub kind: MissingFieldKind,
    /// If this field is a subcommand, the available subcommands.
    /// Non-empty only when the missing field is a subcommand field.
    pub available_subcommands: Vec<AvailableSubcommand>,
}

/// Information about a corrected command with missing arguments for display.
pub struct CorrectedCommandInfo {
    /// The corrected command text showing what should be typed
    pub corrected_source: String,
    /// Diagnostics with spans pointing to the corrected source
    pub diagnostics: Vec<crate::driver::Diagnostic>,
}

/// Build corrected command source and diagnostics for missing CLI arguments.
///
/// Returns the corrected command as a source and diagnostics that point to it.
pub fn build_corrected_command_diagnostics(
    missing: &[MissingFieldInfo],
    cli_args: Option<&str>,
) -> CorrectedCommandInfo {
    use crate::driver::{Diagnostic, Severity};
    use crate::span::Span;

    let cli_text = cli_args.unwrap_or("");

    // Handle the first missing field (most common case)
    // Multiple missing would need a different UI approach
    if let Some(field) = missing.first() {
        // Build the corrected command with the missing argument
        let missing_arg_text = if let Some(cli_flag) = &field.cli_flag {
            if cli_flag.starts_with('<') && cli_flag.ends_with('>') {
                // Positional argument like <name>
                cli_flag.clone()
            } else if cli_flag.starts_with("--") {
                // Named argument like --region
                let flag_name = cli_flag.trim_start_matches("--");
                format!("{} <{}>", cli_flag, flag_name)
            } else {
                cli_flag.clone()
            }
        } else {
            format!("<{}>", field.field_name)
        };

        let corrected_command = if cli_text.is_empty() {
            // Get program name
            let program_name = std::env::args()
                .next()
                .map(|path| normalize_program_name(&path))
                .unwrap_or_else(|| "program".to_string());
            format!("{} {}", program_name, missing_arg_text)
        } else {
            format!("{} {}", cli_text, missing_arg_text)
        };

        // Calculate the span of the missing argument in the corrected command
        let missing_arg_start = if cli_text.is_empty() {
            corrected_command.len() - missing_arg_text.len()
        } else {
            cli_text.len() + 1
        };

        // Use generic message for the error, field docs go in the label (rendered by Ariadne)
        let message = "missing required argument".to_string();

        // Use field documentation as the label message
        let label = field.doc_comment.clone();

        let diagnostic = Diagnostic {
            message,
            label,
            path: None,
            span: Some(Span::new(missing_arg_start, missing_arg_text.len())),
            severity: Severity::Error,
        };

        CorrectedCommandInfo {
            corrected_source: corrected_command,
            diagnostics: vec![diagnostic],
        }
    } else {
        // No missing fields - return empty
        CorrectedCommandInfo {
            corrected_source: cli_text.to_string(),
            diagnostics: vec![],
        }
    }
}

/// Collect missing required fields by walking the schema and checking against the ConfigValue.
/// A field is "missing" if it's not in the ConfigValue AND is not Option.
///
/// This walks the Schema (which already handles flattening), so no flattening logic is needed here.
pub fn collect_missing_fields(
    value: &ConfigValue,
    schema: &Schema,
    missing: &mut Vec<MissingFieldInfo>,
) {
    let obj_map = match value {
        ConfigValue::Object(sourced) => &sourced.value,
        _ => return,
    };

    // Check CLI args (top-level arguments like --verbose, --output, etc.)
    collect_missing_in_arg_level(obj_map, schema.args(), "", missing);

    // Check config section if present
    if let Some(config_schema) = schema.config() {
        let env_prefix = config_schema.env_prefix();

        // The config value is nested under the config field name
        if let Some(field_name) = config_schema.field_name() {
            if let Some(config_value) = obj_map.get(field_name) {
                collect_missing_in_config_struct(
                    config_value,
                    config_schema,
                    "",
                    env_prefix,
                    missing,
                );
            } else {
                // The entire config struct is missing - report it
                missing.push(MissingFieldInfo {
                    field_name: field_name.to_string(),
                    field_path: field_name.to_string(),
                    type_name: "Struct".to_string(),
                    doc_comment: None,
                    cli_flag: None,
                    env_var: None,
                    env_aliases: Vec::new(),
                    kind: MissingFieldKind::ConfigField,
                    available_subcommands: Vec::new(),
                });
            }
        } else {
            // Config has no field name (shouldn't happen normally), check at root level
            collect_missing_in_config_struct(value, config_schema, "", env_prefix, missing);
        }
    }
}

/// Walk an arg level schema and check for missing required args.
fn collect_missing_in_arg_level(
    obj_map: &crate::config_value::ObjectMap,
    arg_level: &ArgLevelSchema,
    path_prefix: &str,
    missing: &mut Vec<MissingFieldInfo>,
) {
    for (name, arg_schema) in arg_level.args() {
        let field_path = if path_prefix.is_empty() {
            name.to_string()
        } else {
            format!("{}.{}", path_prefix, name)
        };

        if obj_map.get(name.as_str()).is_none() && arg_schema.required() {
            let type_name = get_value_type_name(arg_schema.value());

            // CLI args use kebab-case and are either positional or flags
            let cli_flag = match arg_schema.kind() {
                ArgKind::Positional => Some(format!("<{}>", name.to_kebab_case())),
                ArgKind::Named { .. } => Some(format!("--{}", name.to_kebab_case())),
            };

            missing.push(MissingFieldInfo {
                field_name: name.to_string(),
                field_path,
                type_name,
                doc_comment: arg_schema.docs().summary().map(|s| s.to_string()),
                cli_flag,
                env_var: None, // CLI args don't have env vars
                env_aliases: Vec::new(),
                kind: MissingFieldKind::CliArg,
                available_subcommands: Vec::new(),
            });
        }
    }

    // Check subcommands if present and required
    if let Some(subcommand_field) = arg_level.subcommand_field_name() {
        if !arg_level.subcommand_optional() && obj_map.get(subcommand_field).is_none() {
            // Subcommand field itself is missing
            let field_path = if path_prefix.is_empty() {
                subcommand_field.to_string()
            } else {
                format!("{}.{}", path_prefix, subcommand_field)
            };

            let available_subcommands: Vec<AvailableSubcommand> = arg_level
                .subcommands()
                .iter()
                .map(|(_, sub)| AvailableSubcommand {
                    name: sub.cli_name().to_string(),
                    doc: sub.docs().summary().map(|s| s.to_string()),
                })
                .collect();

            missing.push(MissingFieldInfo {
                field_name: subcommand_field.to_string(),
                field_path,
                type_name: "Subcommand".to_string(),
                doc_comment: None,
                cli_flag: Some(format!("<{}>", subcommand_field.to_kebab_case())),
                env_var: None,
                env_aliases: Vec::new(),
                kind: MissingFieldKind::CliArg,
                available_subcommands,
            });
        } else if let Some(ConfigValue::Enum(sourced)) = obj_map.get(subcommand_field) {
            // Subcommand is present - recursively check its arguments
            let enum_value = &sourced.value;
            let variant_name = &enum_value.variant;

            // Find the matching subcommand schema
            if let Some(subcommand_schema) = arg_level
                .subcommands()
                .iter()
                .find(|(name, _)| name.as_str() == variant_name)
                .map(|(_, schema)| schema)
            {
                // Recursively check the subcommand's arguments
                let subcommand_path = if path_prefix.is_empty() {
                    format!("{}::{}", subcommand_field, variant_name)
                } else {
                    format!("{}.{}::{}", path_prefix, subcommand_field, variant_name)
                };

                collect_missing_in_arg_level(
                    &enum_value.fields,
                    subcommand_schema.args(),
                    &subcommand_path,
                    missing,
                );
            }
        }
    }
}

/// Get a human-readable type name from a ValueSchema.
fn get_value_type_name(schema: &ValueSchema) -> String {
    match schema {
        ValueSchema::Leaf(leaf) => leaf.shape.to_string(),
        ValueSchema::Option { value, .. } => format!("Option<{}>", get_value_type_name(value)),
        ValueSchema::Vec { element, .. } => format!("Vec<{}>", get_value_type_name(element)),
        ValueSchema::Struct { shape, .. } => shape.to_string(),
    }
}

/// Context for collecting missing config fields.
struct ConfigContext<'a> {
    /// The config field name (e.g., "config" or "settings")
    config_field_name: &'a str,
    /// Environment variable prefix if set
    env_prefix: Option<&'a str>,
}

/// Walk a config struct schema and its corresponding ConfigValue.
fn collect_missing_in_config_struct(
    value: &ConfigValue,
    struct_schema: &ConfigStructSchema,
    path_prefix: &str,
    env_prefix: Option<&str>,
    missing: &mut Vec<MissingFieldInfo>,
) {
    let obj_map = match value {
        ConfigValue::Object(sourced) => &sourced.value,
        _ => return, // Not an object, can't check struct fields
    };

    // Get the config field name from the struct schema
    let config_field_name = struct_schema.field_name().unwrap_or("config");
    let ctx = ConfigContext {
        config_field_name,
        env_prefix,
    };

    for (field_name, field_schema) in struct_schema.fields() {
        let field_path = if path_prefix.is_empty() {
            field_name.to_string()
        } else {
            format!("{}.{}", path_prefix, field_name)
        };

        if let Some(field_value) = obj_map.get(field_name.as_str()) {
            // Field exists - recurse into nested structs/vecs
            collect_missing_in_config_field(field_value, field_schema, &field_path, &ctx, missing);
        } else {
            // Field is missing - check if it's required
            check_missing_field(field_name, &field_path, field_schema, &ctx, missing);
        }
    }
}

/// Walk a config field schema and its corresponding ConfigValue.
fn collect_missing_in_config_field(
    value: &ConfigValue,
    field_schema: &ConfigFieldSchema,
    path_prefix: &str,
    ctx: &ConfigContext,
    missing: &mut Vec<MissingFieldInfo>,
) {
    collect_missing_in_config_value(value, field_schema.value(), path_prefix, ctx, missing);
}

/// Walk a config value schema and its corresponding ConfigValue.
fn collect_missing_in_config_value(
    value: &ConfigValue,
    value_schema: &ConfigValueSchema,
    path_prefix: &str,
    ctx: &ConfigContext,
    missing: &mut Vec<MissingFieldInfo>,
) {
    match value_schema {
        ConfigValueSchema::Struct(struct_schema) => {
            // For nested structs, we don't have a new env_prefix, pass the existing one
            collect_missing_in_config_struct_inner(value, struct_schema, path_prefix, ctx, missing);
        }
        ConfigValueSchema::Vec(vec_schema) => {
            // Recurse into array elements
            if let ConfigValue::Array(sourced) = value {
                for (i, item) in sourced.value.iter().enumerate() {
                    let item_path = format!("{}[{}]", path_prefix, i);
                    collect_missing_in_config_value(
                        item,
                        vec_schema.element(),
                        &item_path,
                        ctx,
                        missing,
                    );
                }
            }
        }
        ConfigValueSchema::Option { value: inner, .. } => {
            // Option fields are never required, but recurse to check nested structs
            collect_missing_in_config_value(value, inner, path_prefix, ctx, missing);
        }
        ConfigValueSchema::Enum(enum_schema) => {
            // For enums, check if the selected variant has missing fields
            if let ConfigValue::Enum(sourced) = value {
                let variant_name = &sourced.value.variant;
                if let Some(variant_schema) = enum_schema.get_variant(variant_name) {
                    for (field_name, field_schema) in variant_schema.fields() {
                        let field_path = format!("{}.{}", path_prefix, field_name);
                        if let Some(field_value) = sourced.value.fields.get(field_name.as_str()) {
                            collect_missing_in_config_value(
                                field_value,
                                field_schema.value(),
                                &field_path,
                                ctx,
                                missing,
                            );
                        } else {
                            let is_optional =
                                matches!(field_schema.value(), ConfigValueSchema::Option { .. });
                            if !is_optional {
                                missing.push(MissingFieldInfo {
                                    field_name: field_name.to_string(),
                                    field_path,
                                    type_name: type_name_from_config_value_schema(
                                        field_schema.value(),
                                    ),
                                    doc_comment: None,
                                    cli_flag: None,
                                    env_var: None,
                                    env_aliases: field_schema.env_aliases().to_vec(),
                                    kind: MissingFieldKind::ConfigField,
                                    available_subcommands: Vec::new(),
                                });
                            }
                        }
                    }
                }
            }
        }
        ConfigValueSchema::Leaf(_) => {
            // Leaf values have no nested fields to check
        }
    }
}

/// Inner function for nested structs (doesn't reset context).
fn collect_missing_in_config_struct_inner(
    value: &ConfigValue,
    struct_schema: &ConfigStructSchema,
    path_prefix: &str,
    ctx: &ConfigContext,
    missing: &mut Vec<MissingFieldInfo>,
) {
    let obj_map = match value {
        ConfigValue::Object(sourced) => &sourced.value,
        _ => return,
    };

    for (field_name, field_schema) in struct_schema.fields() {
        let field_path = if path_prefix.is_empty() {
            field_name.to_string()
        } else {
            format!("{}.{}", path_prefix, field_name)
        };

        if let Some(field_value) = obj_map.get(field_name.as_str()) {
            collect_missing_in_config_field(field_value, field_schema, &field_path, ctx, missing);
        } else {
            check_missing_field(field_name, &field_path, field_schema, ctx, missing);
        }
    }
}

/// Check if a missing field is required and add it to the missing list if so.
fn check_missing_field(
    field_name: &str,
    field_path: &str,
    field_schema: &ConfigFieldSchema,
    ctx: &ConfigContext,
    missing: &mut Vec<MissingFieldInfo>,
) {
    // A field is required if it's NOT wrapped in Option
    let is_optional = matches!(field_schema.value(), ConfigValueSchema::Option { .. });

    if !is_optional {
        let type_name = get_config_type_name(field_schema.value());

        // CLI flag: --config.field-path (kebab-case the path segments)
        let cli_path = field_path
            .split('.')
            .map(|s| s.to_kebab_case())
            .collect::<Vec<_>>()
            .join(".");
        let cli_flag = Some(format!("--{}.{}", ctx.config_field_name, cli_path));

        // Env var: PREFIX__FIELD__PATH (SCREAMING_SNAKE_CASE)
        let env_var = ctx.env_prefix.map(|prefix| {
            let env_path = field_path
                .split('.')
                .map(|s| s.to_shouty_snake_case())
                .collect::<Vec<_>>()
                .join("__");
            format!("{}__{}", prefix, env_path)
        });

        missing.push(MissingFieldInfo {
            field_name: field_name.to_string(),
            field_path: field_path.to_string(),
            type_name,
            doc_comment: None, // Schema doesn't currently expose docs on ConfigFieldSchema
            cli_flag,
            env_var,
            env_aliases: field_schema.env_aliases().to_vec(),
            kind: MissingFieldKind::ConfigField,
            available_subcommands: Vec::new(),
        });
    }
}

/// Get a human-readable type name from a ConfigValueSchema.
fn get_config_type_name(schema: &ConfigValueSchema) -> String {
    match schema {
        ConfigValueSchema::Struct(_) => "Struct".to_string(),
        ConfigValueSchema::Vec(v) => format!("Vec<{}>", get_config_type_name(v.element())),
        ConfigValueSchema::Option { value, .. } => {
            format!("Option<{}>", get_config_type_name(value))
        }
        ConfigValueSchema::Enum(e) => e.shape().to_string(),
        ConfigValueSchema::Leaf(leaf) => leaf.shape.to_string(),
    }
}

fn type_name_from_config_value_schema(schema: &ConfigValueSchema) -> String {
    get_config_type_name(schema)
}

/// Format a summary of missing fields for display after the config dump.
///
/// This produces a focused list of just the missing fields with their paths,
/// types, and documentation (if available), so users can quickly see what
/// needs to be provided without scrolling through the entire config dump.
///
/// For CLI-only missing fields (when all missing fields have cli_flag set),
/// prefer using `format_missing_cli_args_with_mockup` for a more user-friendly display.
pub fn format_missing_fields_summary(missing: &[MissingFieldInfo]) -> String {
    use owo_colors::OwoColorize;
    use std::fmt::Write;

    if missing.is_empty() {
        return String::new();
    }

    let mut output = String::new();

    for field in missing {
        // Field path and type
        write!(
            output,
            "  {} <{}>",
            field
                .field_path
                .if_supports_color(Stdout, |text| text.bold()),
            field
                .type_name
                .if_supports_color(Stdout, |text| text.cyan()),
        )
        .unwrap();

        // Show how to set the field
        let mut hints = Vec::new();
        if let Some(cli) = &field.cli_flag {
            hints.push(
                cli.if_supports_color(Stdout, |text| text.green())
                    .to_string(),
            );
        }
        if let Some(env) = &field.env_var {
            hints.push(
                format!("${}", env)
                    .if_supports_color(Stdout, |text| text.yellow())
                    .to_string(),
            );
        }
        // Show env aliases
        for alias in &field.env_aliases {
            hints.push(
                format!(
                    "${} {}",
                    alias,
                    "(alias)".if_supports_color(Stdout, |text| text.dimmed())
                )
                .if_supports_color(Stdout, |text| text.yellow())
                .to_string(),
            );
        }
        if !hints.is_empty() {
            write!(output, " ({})", hints.join(" or ")).unwrap();
        }

        // Add doc comment on a new line if available
        if let Some(doc) = &field.doc_comment {
            write!(
                output,
                "\n    {}",
                doc.if_supports_color(Stdout, |text| text.dimmed())
            )
            .unwrap();
        }

        output.push('\n');
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config_value::{ObjectMap, Sourced};
    use facet::Facet;
    use figue_attrs as args;

    // ========================================================================
    // Test helpers
    // ========================================================================

    fn cv_object(fields: impl IntoIterator<Item = (&'static str, ConfigValue)>) -> ConfigValue {
        let map: ObjectMap = fields
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect();
        ConfigValue::Object(Sourced::new(map))
    }

    fn cv_array(items: impl IntoIterator<Item = ConfigValue>) -> ConfigValue {
        ConfigValue::Array(Sourced::new(items.into_iter().collect()))
    }

    fn cv_string(s: &str) -> ConfigValue {
        ConfigValue::String(Sourced::new(s.to_string()))
    }

    fn cv_int(i: i64) -> ConfigValue {
        ConfigValue::Integer(Sourced::new(i))
    }

    fn cv_bool(b: bool) -> ConfigValue {
        ConfigValue::Bool(Sourced::new(b))
    }

    // ========================================================================
    // Basic test structs - use different field names to avoid hardcoding
    // ========================================================================

    #[derive(Facet)]
    struct SimpleFields {
        host: String,
        port: u16,
    }

    // Uses "config" as the field name
    #[derive(Facet)]
    struct ArgsWithConfig {
        #[facet(args::config)]
        config: SimpleFields,
    }

    // Uses "settings" as the field name to ensure we don't hardcode "config"
    #[derive(Facet)]
    struct ArgsWithSettings {
        #[facet(args::config)]
        settings: SimpleFields,
    }

    // ========================================================================
    // Tests: All fields present
    // ========================================================================

    #[test]
    fn test_all_fields_present_with_config() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([("host", cv_string("localhost")), ("port", cv_int(8080))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    #[test]
    fn test_all_fields_present_with_settings() {
        let schema = Schema::from_shape(ArgsWithSettings::SHAPE).unwrap();
        let value = cv_object([(
            "settings",
            cv_object([("host", cv_string("localhost")), ("port", cv_int(8080))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    #[test]
    fn test_empty_root_reports_config_missing() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let value = cv_object([]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field (config), got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "config");
    }

    #[test]
    fn test_empty_root_reports_settings_missing() {
        let schema = Schema::from_shape(ArgsWithSettings::SHAPE).unwrap();
        let value = cv_object([]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field (settings), got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "settings");
    }

    #[test]
    fn test_empty_config_reports_inner_fields() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            2,
            "Expected 2 missing fields, got: {:?}",
            missing
        );
        let names: Vec<_> = missing.iter().map(|m| m.field_name.as_str()).collect();
        assert!(names.contains(&"host"), "Should report 'host' as missing");
        assert!(names.contains(&"port"), "Should report 'port' as missing");
    }

    // ========================================================================
    // Tests: Single missing field
    // ========================================================================

    #[test]
    fn test_missing_required_field() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([("host", cv_string("localhost"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "port");
        assert_eq!(missing[0].field_path, "port");
    }

    #[test]
    fn test_missing_string_field_with_settings() {
        let schema = Schema::from_shape(ArgsWithSettings::SHAPE).unwrap();
        let value = cv_object([("settings", cv_object([("port", cv_int(8080))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "host");
        assert_eq!(missing[0].field_path, "host");
    }

    // ========================================================================
    // Tests: Optional fields
    // ========================================================================

    #[derive(Facet)]
    struct FieldsWithOptional {
        host: String,
        port: Option<u16>,
    }

    #[derive(Facet)]
    struct ArgsWithOptionalConfig {
        #[facet(args::config)]
        config: FieldsWithOptional,
    }

    #[test]
    fn test_optional_field_not_reported_missing() {
        let schema = Schema::from_shape(ArgsWithOptionalConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([("host", cv_string("localhost"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Optional fields should not be reported as missing: {:?}",
            missing
        );
    }

    #[derive(Facet)]
    struct AllOptionalFields {
        host: Option<String>,
        port: Option<u16>,
        debug: Option<bool>,
    }

    #[derive(Facet)]
    struct ArgsWithAllOptionalSettings {
        #[facet(args::config)]
        settings: AllOptionalFields,
    }

    #[test]
    fn test_all_optional_fields_empty_config() {
        let schema = Schema::from_shape(ArgsWithAllOptionalSettings::SHAPE).unwrap();
        let value = cv_object([("settings", cv_object([]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "All-optional config should have no missing fields: {:?}",
            missing
        );
    }

    // ========================================================================
    // Tests: Nested structs
    // ========================================================================

    #[derive(Facet)]
    struct NestedFields {
        server: SimpleFields,
    }

    #[derive(Facet)]
    struct ArgsWithNestedConfig {
        #[facet(args::config)]
        config: NestedFields,
    }

    #[derive(Facet)]
    struct ArgsWithNestedSettings {
        #[facet(args::config)]
        settings: NestedFields,
    }

    #[test]
    fn test_nested_missing_field() {
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([("server", cv_object([("port", cv_int(8080))]))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "host");
        assert_eq!(missing[0].field_path, "server.host");
    }

    #[test]
    fn test_nested_all_fields_present() {
        let schema = Schema::from_shape(ArgsWithNestedSettings::SHAPE).unwrap();
        let value = cv_object([(
            "settings",
            cv_object([(
                "server",
                cv_object([("host", cv_string("localhost")), ("port", cv_int(8080))]),
            )]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    #[test]
    fn test_nested_struct_entirely_missing() {
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field (the struct), got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "server");
        assert_eq!(missing[0].field_path, "server");
    }

    // ========================================================================
    // Tests: Deeply nested structs
    // ========================================================================

    #[derive(Facet)]
    struct Level2 {
        value: String,
    }

    #[derive(Facet)]
    struct Level1 {
        level2: Level2,
    }

    #[derive(Facet)]
    struct DeepFields {
        level1: Level1,
    }

    #[derive(Facet)]
    struct ArgsWithDeepConfig {
        #[facet(args::config)]
        config: DeepFields,
    }

    #[test]
    fn test_deeply_nested_missing_field() {
        let schema = Schema::from_shape(ArgsWithDeepConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([("level1", cv_object([("level2", cv_object([]))]))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "value");
        assert_eq!(missing[0].field_path, "level1.level2.value");
    }

    #[test]
    fn test_deeply_nested_all_present() {
        let schema = Schema::from_shape(ArgsWithDeepConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([(
                "level1",
                cv_object([("level2", cv_object([("value", cv_string("hello"))]))]),
            )]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    // ========================================================================
    // Tests: Flattened structs
    // ========================================================================

    #[derive(Facet)]
    struct CommonFields {
        timeout: u32,
    }

    #[derive(Facet)]
    struct FlattenedFields {
        host: String,
        #[facet(flatten)]
        common: CommonFields,
    }

    #[derive(Facet)]
    struct ArgsWithFlattenedConfig {
        #[facet(args::config)]
        config: FlattenedFields,
    }

    #[derive(Facet)]
    struct ArgsWithFlattenedSettings {
        #[facet(args::config)]
        settings: FlattenedFields,
    }

    #[test]
    fn test_flattened_all_fields_present() {
        let schema = Schema::from_shape(ArgsWithFlattenedConfig::SHAPE).unwrap();
        // Flattened fields appear at the same level
        let value = cv_object([(
            "config",
            cv_object([("host", cv_string("localhost")), ("timeout", cv_int(30))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    #[test]
    fn test_flattened_missing_inner_field() {
        let schema = Schema::from_shape(ArgsWithFlattenedSettings::SHAPE).unwrap();
        // Missing 'timeout' which comes from flattened CommonFields
        let value = cv_object([("settings", cv_object([("host", cv_string("localhost"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "timeout");
    }

    #[test]
    fn test_flattened_missing_outer_field() {
        let schema = Schema::from_shape(ArgsWithFlattenedConfig::SHAPE).unwrap();
        // Missing 'host', have 'timeout' from flattened struct
        let value = cv_object([("config", cv_object([("timeout", cv_int(30))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "host");
    }

    // ========================================================================
    // Tests: Vec fields
    // ========================================================================

    #[derive(Facet)]
    struct FieldsWithVec {
        name: String,
        items: Vec<String>,
    }

    #[derive(Facet)]
    struct ArgsWithVecConfig {
        #[facet(args::config)]
        config: FieldsWithVec,
    }

    #[test]
    fn test_vec_field_present_empty() {
        let schema = Schema::from_shape(ArgsWithVecConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([("name", cv_string("test")), ("items", cv_array([]))]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Empty vec should be valid: {:?}",
            missing
        );
    }

    #[test]
    fn test_vec_field_present_with_items() {
        let schema = Schema::from_shape(ArgsWithVecConfig::SHAPE).unwrap();
        let value = cv_object([(
            "config",
            cv_object([
                ("name", cv_string("test")),
                ("items", cv_array([cv_string("a"), cv_string("b")])),
            ]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Vec with items should be valid: {:?}",
            missing
        );
    }

    #[test]
    fn test_vec_field_missing() {
        let schema = Schema::from_shape(ArgsWithVecConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([("name", cv_string("test"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "items");
    }

    // ========================================================================
    // Tests: Vec of structs
    // ========================================================================

    #[derive(Facet)]
    struct FieldsWithVecOfStructs {
        servers: Vec<SimpleFields>,
    }

    #[derive(Facet)]
    struct ArgsWithVecOfStructsSettings {
        #[facet(args::config)]
        settings: FieldsWithVecOfStructs,
    }

    #[test]
    fn test_vec_of_structs_all_valid() {
        let schema = Schema::from_shape(ArgsWithVecOfStructsSettings::SHAPE).unwrap();
        let value = cv_object([(
            "settings",
            cv_object([(
                "servers",
                cv_array([
                    cv_object([("host", cv_string("a.com")), ("port", cv_int(80))]),
                    cv_object([("host", cv_string("b.com")), ("port", cv_int(443))]),
                ]),
            )]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Expected no missing fields, got: {:?}",
            missing
        );
    }

    #[test]
    fn test_vec_of_structs_missing_field_in_element() {
        let schema = Schema::from_shape(ArgsWithVecOfStructsSettings::SHAPE).unwrap();
        let value = cv_object([(
            "settings",
            cv_object([(
                "servers",
                cv_array([
                    cv_object([("host", cv_string("a.com")), ("port", cv_int(80))]),
                    cv_object([("host", cv_string("b.com"))]), // missing port
                ]),
            )]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "port");
        assert_eq!(missing[0].field_path, "servers[1].port");
    }

    #[test]
    fn test_vec_of_structs_missing_in_multiple_elements() {
        let schema = Schema::from_shape(ArgsWithVecOfStructsSettings::SHAPE).unwrap();
        let value = cv_object([(
            "settings",
            cv_object([(
                "servers",
                cv_array([
                    cv_object([("port", cv_int(80))]),         // missing host
                    cv_object([("host", cv_string("b.com"))]), // missing port
                ]),
            )]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            2,
            "Expected 2 missing fields, got: {:?}",
            missing
        );

        let paths: Vec<_> = missing.iter().map(|m| m.field_path.as_str()).collect();
        assert!(
            paths.contains(&"servers[0].host"),
            "Should report servers[0].host"
        );
        assert!(
            paths.contains(&"servers[1].port"),
            "Should report servers[1].port"
        );
    }

    // ========================================================================
    // Tests: Optional nested struct
    // ========================================================================

    #[derive(Facet)]
    struct FieldsWithOptionalNested {
        name: String,
        server: Option<SimpleFields>,
    }

    #[derive(Facet)]
    struct ArgsWithOptionalNestedConfig {
        #[facet(args::config)]
        config: FieldsWithOptionalNested,
    }

    #[test]
    fn test_optional_nested_struct_absent() {
        let schema = Schema::from_shape(ArgsWithOptionalNestedConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([("name", cv_string("test"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Optional nested struct should not be required: {:?}",
            missing
        );
    }

    #[test]
    fn test_optional_nested_struct_present_but_incomplete() {
        let schema = Schema::from_shape(ArgsWithOptionalNestedConfig::SHAPE).unwrap();
        // server is present but missing 'port'
        let value = cv_object([(
            "config",
            cv_object([
                ("name", cv_string("test")),
                ("server", cv_object([("host", cv_string("localhost"))])),
            ]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        // When the optional struct IS provided, its required fields must be present
        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "port");
        assert_eq!(missing[0].field_path, "server.port");
    }

    // ========================================================================
    // Tests: Mixed required and optional
    // ========================================================================

    #[derive(Facet)]
    struct MixedFields {
        required_str: String,
        optional_str: Option<String>,
        required_int: u32,
        optional_int: Option<u32>,
    }

    #[derive(Facet)]
    struct ArgsWithMixedSettings {
        #[facet(args::config)]
        settings: MixedFields,
    }

    #[test]
    fn test_mixed_only_required_missing() {
        let schema = Schema::from_shape(ArgsWithMixedSettings::SHAPE).unwrap();
        // Only optional fields provided
        let value = cv_object([(
            "settings",
            cv_object([
                ("optional_str", cv_string("opt")),
                ("optional_int", cv_int(42)),
            ]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            2,
            "Expected 2 missing required fields, got: {:?}",
            missing
        );
        let names: Vec<_> = missing.iter().map(|m| m.field_name.as_str()).collect();
        assert!(names.contains(&"required_str"));
        assert!(names.contains(&"required_int"));
    }

    #[test]
    fn test_mixed_all_required_present() {
        let schema = Schema::from_shape(ArgsWithMixedSettings::SHAPE).unwrap();
        // Only required fields provided (optional ones absent)
        let value = cv_object([(
            "settings",
            cv_object([
                ("required_str", cv_string("req")),
                ("required_int", cv_int(123)),
            ]),
        )]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "All required fields present, should have no missing: {:?}",
            missing
        );
    }

    // ========================================================================
    // Tests: No config section (CLI args only)
    // ========================================================================

    #[derive(Facet)]
    struct ArgsWithoutConfig {
        #[facet(args::named)]
        verbose: bool,
    }

    #[test]
    fn test_no_config_section() {
        let schema = Schema::from_shape(ArgsWithoutConfig::SHAPE).unwrap();
        let value = cv_object([("verbose", cv_bool(true))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "No config section means no missing config fields: {:?}",
            missing
        );
    }

    // ========================================================================
    // Tests: Required CLI args
    // ========================================================================

    #[derive(Facet)]
    struct ArgsWithRequiredCliArg {
        #[facet(args::named)]
        required_field: String,
    }

    #[test]
    fn test_missing_required_cli_arg() {
        let schema = Schema::from_shape(ArgsWithRequiredCliArg::SHAPE).unwrap();
        let value = cv_object([]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(
            missing.len(),
            1,
            "Expected 1 missing field, got: {:?}",
            missing
        );
        assert_eq!(missing[0].field_name, "required_field");
    }

    #[test]
    fn test_required_cli_arg_present() {
        let schema = Schema::from_shape(ArgsWithRequiredCliArg::SHAPE).unwrap();
        let value = cv_object([("required_field", cv_string("value"))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert!(
            missing.is_empty(),
            "Required CLI arg present, should have no missing: {:?}",
            missing
        );
    }

    // ========================================================================
    // Tests: Type name reporting
    // ========================================================================

    #[test]
    fn test_type_name_for_string() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let value = cv_object([("config", cv_object([("port", cv_int(8080))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(missing.len(), 1);
        assert!(!missing[0].type_name.is_empty(), "Type name should be set");
    }

    #[test]
    fn test_type_name_for_integer() {
        let schema = Schema::from_shape(ArgsWithSettings::SHAPE).unwrap();
        let value = cv_object([("settings", cv_object([("host", cv_string("localhost"))]))]);

        let mut missing = Vec::new();
        collect_missing_fields(&value, &schema, &mut missing);

        assert_eq!(missing.len(), 1);
        assert!(!missing[0].type_name.is_empty(), "Type name should be set");
    }

    #[test]
    fn test_normalize_program_name() {
        // Test with cargo test binary pattern and full path
        assert_eq!(
            normalize_program_name(
                "/Users/amos/bearcove/figue/target/debug/deps/main-138217976bbdb088"
            ),
            "main"
        );
        assert_eq!(
            normalize_program_name(
                "C:\\Users\\runner\\work\\figue\\target\\debug\\deps\\main-138217976bbdb088.exe"
            ),
            "main"
        );
        assert_eq!(
            normalize_program_name(
                "/home/runner/work/figue/figue/target/debug/deps/main-b36e7ccd11ac5f87"
            ),
            "main"
        );
        assert_eq!(normalize_program_name("main-b36e7ccd11ac5f87.exe"), "main");
        assert_eq!(normalize_program_name("main-b36e7ccd11ac5f87.EXE"), "main");

        // Test with just binary name and hash
        assert_eq!(normalize_program_name("main-138217976bbdb088"), "main");
        assert_eq!(normalize_program_name("main-b36e7ccd11ac5f87"), "main");

        // Test with regular binary names (no hash)
        assert_eq!(normalize_program_name("myapp"), "myapp");
        assert_eq!(normalize_program_name("my-app"), "my-app");
        assert_eq!(normalize_program_name("/usr/local/bin/myapp"), "myapp");

        // Test with names that have dashes but not the hash pattern
        assert_eq!(normalize_program_name("my-app-test"), "my-app-test");
        assert_eq!(normalize_program_name("app-v1-final"), "app-v1-final");

        // Test with hash that's too short
        assert_eq!(normalize_program_name("app-123abc"), "app-123abc");

        // Test with hash that's too long
        assert_eq!(
            normalize_program_name("app-123456789abcdef01"),
            "app-123456789abcdef01"
        );

        // Test with non-hex characters
        assert_eq!(
            normalize_program_name("app-123456789abcdexg"),
            "app-123456789abcdexg"
        );
    }
}