dynamic-cli 0.7.0

A framework for building configurable CLI and REPL applications from YAML/JSON configuration files
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
//! Configuration validation
//!
//! This module validates the consistency and correctness of
//! configuration after it has been loaded and parsed.
//!
//! # Validation Levels
//!
//! 1. **Structural validation** - Ensures required fields are present
//! 2. **Semantic validation** - Checks for logical inconsistencies
//! 3. **Uniqueness validation** - Prevents duplicate names/aliases
//!
//! # Example
//!
//! ```
//! use dynamic_cli::config::schema::{CommandsConfig, Metadata};
//! use dynamic_cli::config::validator::validate_config;
//!
//! # let config = CommandsConfig {
//!       metadata: Metadata {
//!         version: "1.0.0".to_string(),
//!         prompt: "test".to_string(),
//!         prompt_suffix: " >".to_string()
//!         },
//!       commands: vec![],
//!       global_options: vec![]
//! };
//! // After loading configuration
//! validate_config(&config)?;
//! # Ok::<(), dynamic_cli::error::DynamicCliError>(())
//! ```

use crate::config::schema::{
    ArgumentDefinition, ArgumentType, CommandDefinition, CommandsConfig, OptionDefinition,
    ValidationRule,
};
use crate::error::{ConfigError, Result};
use std::collections::{HashMap, HashSet};

/// Validate the entire configuration
///
/// Performs comprehensive validation of the configuration structure,
/// checking for:
/// - Duplicate command names and aliases
/// - Valid argument types
/// - Consistent validation rules
/// - Option/argument naming conflicts
///
/// # Arguments
///
/// * `config` - The configuration to validate
///
/// # Errors
///
/// - [`ConfigError::DuplicateCommand`] if command names/aliases conflict
/// - [`ConfigError::InvalidSchema`] if structural issues are found
/// - [`ConfigError::Inconsistency`] if logical inconsistencies are detected
///
/// # Example
///
/// ```
/// use dynamic_cli::config::schema::{CommandsConfig, Metadata};
/// use dynamic_cli::config::validator::validate_config;
///
/// # let config = CommandsConfig {
///       metadata: Metadata {
///         version: "1.0.0".to_string(),
///         prompt: "test".to_string(),
///         prompt_suffix: " >".to_string()
///         },
///       commands: vec![],
///       global_options: vec![]
/// };
/// // After loading configuration
/// validate_config(&config)?;
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
pub fn validate_config(config: &CommandsConfig) -> Result<()> {
    // Track all command names and aliases to detect duplicates
    let mut seen_names: HashSet<String> = HashSet::new();

    for (idx, command) in config.commands.iter().enumerate() {
        // Validate the command itself
        validate_command(command)?;

        // Check for duplicate command name
        if !seen_names.insert(command.name.clone()) {
            return Err(ConfigError::DuplicateCommand {
                name: command.name.clone(),
                suggestion: None,
            }
            .into());
        }

        // Check for duplicate aliases
        for alias in &command.aliases {
            if !seen_names.insert(alias.clone()) {
                return Err(ConfigError::DuplicateCommand {
                    name: alias.clone(),
                    suggestion: None,
                }
                .into());
            }
        }

        // Validate that command has a non-empty name
        if command.name.trim().is_empty() {
            return Err(ConfigError::InvalidSchema {
                reason: "Command name cannot be empty".to_string(),
                path: Some(format!("commands[{}].name", idx)),
                suggestion: None,
            }
            .into());
        }

        // Validate that implementation is specified
        if command.implementation.trim().is_empty() {
            return Err(ConfigError::InvalidSchema {
                reason: "Command implementation cannot be empty".to_string(),
                path: Some(format!("commands[{}].implementation", idx)),
                suggestion: None,
            }
            .into());
        }
    }

    // Validate global options
    validate_options(&config.global_options, "global_options")?;

    Ok(())
}

/// Validate a single command definition
///
/// Checks:
/// - Argument types are valid
/// - No duplicate argument/option names
/// - Validation rules are consistent with types
/// - Required arguments come before optional ones
///
/// # Arguments
///
/// * `cmd` - The command definition to validate
///
/// # Errors
///
/// - [`ConfigError::InvalidSchema`] for structural issues
/// - [`ConfigError::Inconsistency`] for logical problems
///
/// # Example
///
/// ```
/// use dynamic_cli::config::{
///     schema::{CommandDefinition, ArgumentType},
///     validator::validate_command,
/// };
///
/// let cmd = CommandDefinition {
///     name: "test".to_string(),
///     aliases: vec![],
///     description: "Test command".to_string(),
///     required: false,
///     arguments: vec![],
///     options: vec![],
///     implementation: "test_handler".to_string(),
/// };
///
/// validate_command(&cmd)?;
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
pub fn validate_command(cmd: &CommandDefinition) -> Result<()> {
    // Validate arguments
    validate_argument_types(&cmd.arguments)?;
    validate_argument_ordering(&cmd.arguments, &cmd.name)?;
    validate_argument_names(&cmd.arguments, &cmd.name)?;
    validate_argument_validation_rules(&cmd.arguments, &cmd.name)?;

    // Validate options
    validate_options(&cmd.options, &cmd.name)?;
    validate_option_flags(&cmd.options, &cmd.name)?;

    // Check for name conflicts between arguments and options
    check_name_conflicts(&cmd.arguments, &cmd.options, &cmd.name)?;

    Ok(())
}

/// Validate argument types
///
/// Currently, all [`ArgumentType`] variants are valid, but this function
/// exists for future extensibility and to ensure types are properly defined.
///
/// # Arguments
///
/// * `args` - List of argument definitions to validate
///
/// # Example
///
/// ```
/// use dynamic_cli::config::{
///     schema::{ArgumentDefinition, ArgumentType},
///     validator::validate_argument_types,
/// };
///
/// let args = vec![
///     ArgumentDefinition {
///         name: "count".to_string(),
///         arg_type: ArgumentType::Integer,
///         required: true,
///         description: "Count".to_string(),
///         validation: vec![],
///         secure: false,
///     }
/// ];
///
/// validate_argument_types(&args)?;
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
pub fn validate_argument_types(args: &[ArgumentDefinition]) -> Result<()> {
    // Currently all ArgumentType variants are valid
    // This function exists for future extensibility

    for arg in args {
        // Validate that the type is properly defined
        // (In the current implementation, all enum variants are valid)
        let _ = arg.arg_type;
    }

    Ok(())
}

/// Validate that required arguments come before optional ones
///
/// This prevents confusing situations where an optional argument
/// appears before a required one in the command line.
///
/// # Arguments
///
/// * `args` - List of argument definitions
/// * `context` - Context string for error messages (command name)
fn validate_argument_ordering(args: &[ArgumentDefinition], context: &str) -> Result<()> {
    let mut seen_optional = false;

    for (idx, arg) in args.iter().enumerate() {
        if !arg.required {
            seen_optional = true;
        } else if seen_optional {
            return Err(ConfigError::InvalidSchema {
                reason: format!(
                    "Required argument '{}' cannot come after optional arguments",
                    arg.name
                ),
                path: Some(format!("{}.arguments[{}]", context, idx)),
                suggestion: None,
            }
            .into());
        }
    }

    Ok(())
}

/// Validate that argument names are unique
fn validate_argument_names(args: &[ArgumentDefinition], context: &str) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();

    for (idx, arg) in args.iter().enumerate() {
        if arg.name.trim().is_empty() {
            return Err(ConfigError::InvalidSchema {
                reason: "Argument name cannot be empty".to_string(),
                path: Some(format!("{}.arguments[{}]", context, idx)),
                suggestion: None,
            }
            .into());
        }

        if !seen_names.insert(arg.name.clone()) {
            return Err(ConfigError::InvalidSchema {
                reason: format!("Duplicate argument name: '{}'", arg.name),
                path: Some(format!("{}.arguments", context)),
                suggestion: None,
            }
            .into());
        }
    }

    Ok(())
}

/// Validate that validation rules are consistent with argument types
fn validate_argument_validation_rules(args: &[ArgumentDefinition], _context: &str) -> Result<()> {
    for arg in args.iter() {
        for rule in arg.validation.iter() {
            match rule {
                ValidationRule::MustExist { .. } | ValidationRule::Extensions { .. } => {
                    // These rules only make sense for Path arguments
                    if arg.arg_type != ArgumentType::Path {
                        return Err(ConfigError::Inconsistency {
                            details: format!(
                                "Validation rule 'must_exist' or 'extensions' can only be used with 'path' type, \
                                but argument '{}' has type '{}'",
                                arg.name,
                                arg.arg_type.as_str()
                            ),
                            suggestion: None,
                        }.into());
                    }
                }
                ValidationRule::Range { min, max } => {
                    // Range rules only make sense for numeric types
                    if !matches!(arg.arg_type, ArgumentType::Integer | ArgumentType::Float) {
                        return Err(ConfigError::Inconsistency {
                            details: format!(
                                "Validation rule 'range' can only be used with numeric types, \
                                but argument '{}' has type '{}'",
                                arg.name,
                                arg.arg_type.as_str()
                            ),
                            suggestion: None,
                        }
                        .into());
                    }

                    // Validate that min <= max if both are specified
                    if let (Some(min_val), Some(max_val)) = (min, max) {
                        if min_val > max_val {
                            return Err(ConfigError::Inconsistency {
                                details: format!(
                                    "Invalid range for argument '{}': min ({}) > max ({})",
                                    arg.name, min_val, max_val
                                ),
                                suggestion: None,
                            }
                            .into());
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

/// Validate option definitions
fn validate_options(options: &[OptionDefinition], context: &str) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();

    for (idx, opt) in options.iter().enumerate() {
        // Validate name is not empty
        if opt.name.trim().is_empty() {
            return Err(ConfigError::InvalidSchema {
                reason: "Option name cannot be empty".to_string(),
                path: Some(format!("{}.options[{}]", context, idx)),
                suggestion: None,
            }
            .into());
        }

        // Check for duplicate names
        if !seen_names.insert(opt.name.clone()) {
            return Err(ConfigError::InvalidSchema {
                reason: format!("Duplicate option name: '{}'", opt.name),
                path: Some(format!("{}.options", context)),
                suggestion: None,
            }
            .into());
        }

        // Validate that at least one of short or long is specified
        if opt.short.is_none() && opt.long.is_none() {
            return Err(ConfigError::InvalidSchema {
                reason: format!(
                    "Option '{}' must have at least a short or long form",
                    opt.name
                ),
                path: Some(format!("{}.options[{}]", context, idx)),
                suggestion: None,
            }
            .into());
        }

        // --- DD-024: repeatable options and their option_parameters shapes ---
        if opt.repeatable {
            // Rule: a repeatable option's absence already means zero
            // occurrences, so a default value would be ambiguous — reject
            // it before the generic default/choices check below, so the
            // repeatable-specific message takes priority.
            if let Some(ref default) = opt.default {
                return Err(ConfigError::Inconsistency {
                    details: format!(
                        "Repeatable option '{}' cannot have a default value ('{}')",
                        opt.name, default
                    ),
                    suggestion: Some(
                        "Remove `default` — a repeatable option's absence already \
                         means zero occurrences, not an implicit one."
                            .to_string(),
                    ),
                }
                .into());
            }

            // Rule: choices doubles as the discriminant list, so it must
            // be non-empty for a repeatable option.
            if opt.choices.is_empty() {
                return Err(ConfigError::InvalidSchema {
                    reason: format!(
                        "Repeatable option '{}' must declare at least one discriminant in choices",
                        opt.name
                    ),
                    path: Some(format!("{}.options[{}].choices", context, idx)),
                    suggestion: Some(
                        "Add `choices: [...]` listing the valid discriminants for \
                         this repeatable option."
                            .to_string(),
                    ),
                }
                .into());
            }

            // Rule: option_parameters keys must equal choices exactly —
            // no discriminant left undeclared, no orphan key.
            for discriminant in &opt.choices {
                if !opt.option_parameters.contains_key(discriminant) {
                    return Err(ConfigError::InvalidSchema {
                        reason: format!(
                            "Discriminant '{}' is declared in choices for repeatable \
                             option '{}' but has no matching entry in option_parameters",
                            discriminant, opt.name
                        ),
                        path: Some(format!("{}.options[{}].option_parameters", context, idx)),
                        suggestion: Some(format!(
                            "Add an `option_parameters.{}` entry describing this \
                             discriminant's key=value parameters.",
                            discriminant
                        )),
                    }
                    .into());
                }
            }
            let choices_set: HashSet<&String> = opt.choices.iter().collect();
            for key in opt.option_parameters.keys() {
                if !choices_set.contains(key) {
                    return Err(ConfigError::InvalidSchema {
                        reason: format!(
                            "option_parameters key '{}' on option '{}' is not declared in choices",
                            key, opt.name
                        ),
                        path: Some(format!(
                            "{}.options[{}].option_parameters.{}",
                            context, idx, key
                        )),
                        suggestion: Some(format!(
                            "Add '{}' to choices, or remove this option_parameters entry.",
                            key
                        )),
                    }
                    .into());
                }
            }

            // Rule: each discriminant's key=value shape reuses the
            // existing argument validation — names and types, but
            // explicitly not ordering, which is meaningless for named
            // key=value pairs rather than positional arguments.
            for (discriminant, params) in &opt.option_parameters {
                let sub_context = format!(
                    "{}.options[{}].option_parameters.{}",
                    context, idx, discriminant
                );
                validate_argument_names(params, &sub_context)?;
                validate_argument_types(params)?;
            }
        } else if !opt.option_parameters.is_empty() {
            // Rule: option_parameters is meaningless without repeatable.
            return Err(ConfigError::Inconsistency {
                details: format!(
                    "Option '{}' has option_parameters but repeatable is false",
                    opt.name
                ),
                suggestion: Some(
                    "Set `repeatable: true`, or remove `option_parameters`.".to_string(),
                ),
            }
            .into());
        }

        // Validate choices are consistent with default
        if let Some(ref default) = opt.default {
            if !opt.choices.is_empty() && !opt.choices.contains(default) {
                return Err(ConfigError::Inconsistency {
                    details: format!(
                        "Default value '{}' for option '{}' is not in choices: [{}]",
                        default,
                        opt.name,
                        opt.choices.join(", ")
                    ),
                    suggestion: None,
                }
                .into());
            }
        }

        // Validate that boolean options don't have choices
        if opt.option_type == ArgumentType::Bool && !opt.choices.is_empty() {
            return Err(ConfigError::Inconsistency {
                details: format!("Boolean option '{}' cannot have choices", opt.name),
                suggestion: None,
            }
            .into());
        }
    }

    Ok(())
}

/// Validate option flags (short and long forms)
fn validate_option_flags(options: &[OptionDefinition], context: &str) -> Result<()> {
    let mut seen_short: HashMap<String, String> = HashMap::new();
    let mut seen_long: HashMap<String, String> = HashMap::new();

    for opt in options {
        // Check short form
        if let Some(ref short) = opt.short {
            if short.len() != 1 {
                return Err(ConfigError::InvalidSchema {
                    reason: format!(
                        "Short option '{}' for '{}' must be a single character",
                        short, opt.name
                    ),
                    path: Some(format!("{}.options", context)),
                    suggestion: None,
                }
                .into());
            }

            if let Some(existing) = seen_short.insert(short.clone(), opt.name.clone()) {
                return Err(ConfigError::InvalidSchema {
                    reason: format!(
                        "Short option '-{}' is used by both '{}' and '{}'",
                        short, existing, opt.name
                    ),
                    path: Some(format!("{}.options", context)),
                    suggestion: None,
                }
                .into());
            }
        }

        // Check long form
        if let Some(ref long) = opt.long {
            if long.is_empty() {
                return Err(ConfigError::InvalidSchema {
                    reason: format!("Long option for '{}' cannot be empty", opt.name),
                    path: Some(format!("{}.options", context)),
                    suggestion: None,
                }
                .into());
            }

            if let Some(existing) = seen_long.insert(long.clone(), opt.name.clone()) {
                return Err(ConfigError::InvalidSchema {
                    reason: format!(
                        "Long option '--{}' is used by both '{}' and '{}'",
                        long, existing, opt.name
                    ),
                    path: Some(format!("{}.options", context)),
                    suggestion: None,
                }
                .into());
            }
        }
    }

    Ok(())
}

/// Check for name conflicts between arguments and options
fn check_name_conflicts(
    args: &[ArgumentDefinition],
    options: &[OptionDefinition],
    context: &str,
) -> Result<()> {
    let arg_names: HashSet<String> = args.iter().map(|a| a.name.clone()).collect();

    for opt in options {
        if arg_names.contains(&opt.name) {
            return Err(ConfigError::InvalidSchema {
                reason: format!("Option '{}' has the same name as an argument", opt.name),
                path: Some(format!("{}.options", context)),
                suggestion: None,
            }
            .into());
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::schema::CommandsConfig;
    use std::collections::HashMap;

    #[test]
    fn test_validate_config_empty() {
        let config = CommandsConfig::minimal();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_config_duplicate_command_name() {
        let mut config = CommandsConfig::minimal();
        config.commands = vec![
            CommandDefinition {
                name: "test".to_string(),
                aliases: vec![],
                description: "Test 1".to_string(),
                required: false,
                arguments: vec![],
                options: vec![],
                implementation: "handler1".to_string(),
            },
            CommandDefinition {
                name: "test".to_string(), // Duplicate!
                aliases: vec![],
                description: "Test 2".to_string(),
                required: false,
                arguments: vec![],
                options: vec![],
                implementation: "handler2".to_string(),
            },
        ];

        let result = validate_config(&config);
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Config(ConfigError::DuplicateCommand {
                name, ..
            }) => {
                assert_eq!(name, "test");
            }
            other => panic!("Expected DuplicateCommand error, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_config_duplicate_alias() {
        let mut config = CommandsConfig::minimal();
        config.commands = vec![
            CommandDefinition {
                name: "cmd1".to_string(),
                aliases: vec!["c".to_string()],
                description: "Command 1".to_string(),
                required: false,
                arguments: vec![],
                options: vec![],
                implementation: "handler1".to_string(),
            },
            CommandDefinition {
                name: "cmd2".to_string(),
                aliases: vec!["c".to_string()], // Duplicate alias!
                description: "Command 2".to_string(),
                required: false,
                arguments: vec![],
                options: vec![],
                implementation: "handler2".to_string(),
            },
        ];

        let result = validate_config(&config);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_command_empty_name() {
        let cmd = CommandDefinition {
            name: "".to_string(), // Empty name!
            aliases: vec![],
            description: "Test".to_string(),
            required: false,
            arguments: vec![],
            options: vec![],
            implementation: "handler".to_string(),
        };

        let mut config = CommandsConfig::minimal();
        config.commands = vec![cmd];

        let result = validate_config(&config);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_argument_ordering() {
        let args = vec![
            ArgumentDefinition {
                name: "optional".to_string(),
                arg_type: ArgumentType::String,
                required: false,
                description: "Optional".to_string(),
                validation: vec![],
                secure: false,
            },
            ArgumentDefinition {
                name: "required".to_string(),
                arg_type: ArgumentType::String,
                required: true, // Required after optional!
                description: "Required".to_string(),
                validation: vec![],
                secure: false,
            },
        ];

        let result = validate_argument_ordering(&args, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_argument_names_duplicate() {
        let args = vec![
            ArgumentDefinition {
                name: "arg1".to_string(),
                arg_type: ArgumentType::String,
                required: true,
                description: "Arg 1".to_string(),
                validation: vec![],
                secure: false,
            },
            ArgumentDefinition {
                name: "arg1".to_string(), // Duplicate!
                arg_type: ArgumentType::Integer,
                required: true,
                description: "Arg 1 again".to_string(),
                validation: vec![],
                secure: false,
            },
        ];

        let result = validate_argument_names(&args, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_validation_rules_type_mismatch() {
        let args = vec![ArgumentDefinition {
            name: "count".to_string(),
            arg_type: ArgumentType::Integer,
            required: true,
            description: "Count".to_string(),
            validation: vec![
                ValidationRule::MustExist { must_exist: true }, // Wrong for integer!
            ],
            secure: false,
        }];

        let result = validate_argument_validation_rules(&args, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_validation_rules_invalid_range() {
        let args = vec![ArgumentDefinition {
            name: "percentage".to_string(),
            arg_type: ArgumentType::Float,
            required: true,
            description: "Percentage".to_string(),
            validation: vec![ValidationRule::Range {
                min: Some(100.0),
                max: Some(0.0), // min > max!
            }],
            secure: false,
        }];

        let result = validate_argument_validation_rules(&args, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_options_no_flags() {
        let options = vec![OptionDefinition {
            name: "opt1".to_string(),
            short: None,
            long: None, // Neither short nor long!
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Option".to_string(),
            choices: vec![],
            repeatable: false,
            option_parameters: HashMap::new(),
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_options_default_not_in_choices() {
        let options = vec![OptionDefinition {
            name: "mode".to_string(),
            short: Some("m".to_string()),
            long: Some("mode".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: Some("invalid".to_string()), // Not in choices!
            description: "Mode".to_string(),
            choices: vec!["fast".to_string(), "slow".to_string()],
            repeatable: false,
            option_parameters: HashMap::new(),
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_option_flags_duplicate_short() {
        let options = vec![
            OptionDefinition {
                name: "opt1".to_string(),
                short: Some("o".to_string()),
                long: None,
                option_type: ArgumentType::String,
                required: false,
                default: None,
                description: "Option 1".to_string(),
                choices: vec![],
                repeatable: false,
                option_parameters: HashMap::new(),
            },
            OptionDefinition {
                name: "opt2".to_string(),
                short: Some("o".to_string()), // Duplicate!
                long: None,
                option_type: ArgumentType::String,
                required: false,
                default: None,
                description: "Option 2".to_string(),
                choices: vec![],
                repeatable: false,
                option_parameters: HashMap::new(),
            },
        ];

        let result = validate_option_flags(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_option_flags_invalid_short() {
        let options = vec![OptionDefinition {
            name: "opt1".to_string(),
            short: Some("opt".to_string()), // Too long!
            long: None,
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Option".to_string(),
            choices: vec![],
            repeatable: false,
            option_parameters: HashMap::new(),
        }];

        let result = validate_option_flags(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_check_name_conflicts() {
        let args = vec![ArgumentDefinition {
            name: "output".to_string(),
            arg_type: ArgumentType::Path,
            required: true,
            description: "Output".to_string(),
            validation: vec![],
            secure: false,
        }];

        let options = vec![OptionDefinition {
            name: "output".to_string(), // Same name as argument!
            short: Some("o".to_string()),
            long: Some("output".to_string()),
            option_type: ArgumentType::Path,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec![],
            repeatable: false,
            option_parameters: HashMap::new(),
        }];

        let result = check_name_conflicts(&args, &options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_command_valid() {
        let cmd = CommandDefinition {
            name: "process".to_string(),
            aliases: vec!["proc".to_string()],
            description: "Process data".to_string(),
            required: false,
            arguments: vec![ArgumentDefinition {
                name: "input".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Input file".to_string(),
                validation: vec![
                    ValidationRule::MustExist { must_exist: true },
                    ValidationRule::Extensions {
                        extensions: vec!["csv".to_string()],
                    },
                ],
                secure: false,
            }],
            options: vec![OptionDefinition {
                name: "output".to_string(),
                short: Some("o".to_string()),
                long: Some("output".to_string()),
                option_type: ArgumentType::Path,
                required: false,
                default: Some("out.csv".to_string()),
                description: "Output file".to_string(),
                choices: vec![],
                repeatable: false,
                option_parameters: HashMap::new(),
            }],
            implementation: "process_handler".to_string(),
        };

        assert!(validate_command(&cmd).is_ok());
    }

    #[test]
    fn test_validate_boolean_with_choices() {
        let options = vec![OptionDefinition {
            name: "flag".to_string(),
            short: Some("f".to_string()),
            long: Some("flag".to_string()),
            option_type: ArgumentType::Bool,
            required: false,
            default: None,
            description: "A flag".to_string(),
            choices: vec!["true".to_string(), "false".to_string()], // Boolean can't have choices!
            repeatable: false,
            option_parameters: HashMap::new(),
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    // ── DD-024: repeatable options / option_parameters ──────────────────────

    #[test]
    fn test_validate_repeatable_requires_non_empty_choices() {
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec![], // Repeatable but no discriminants!
            repeatable: true,
            option_parameters: HashMap::new(),
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_repeatable_missing_option_parameters_entry() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        // "plot" is in choices but has no option_parameters entry.
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec!["csv".to_string(), "plot".to_string()],
            repeatable: true,
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_repeatable_orphan_option_parameters_key() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        // "json" has an option_parameters entry but is not in choices.
        option_parameters.insert(
            "json".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec!["csv".to_string()],
            repeatable: true,
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_repeatable_option_parameters_reuses_argument_validation() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![ArgumentDefinition {
                name: "".to_string(), // Empty name — invalid per validate_argument_names.
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec!["csv".to_string()],
            repeatable: true,
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_non_repeatable_with_option_parameters_is_error() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Output".to_string(),
            choices: vec!["csv".to_string()],
            repeatable: false, // option_parameters set despite repeatable: false!
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_repeatable_with_default_is_error() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: Some("csv".to_string()), // Forbidden when repeatable: true!
            description: "Output".to_string(),
            choices: vec!["csv".to_string()],
            repeatable: true,
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_repeatable_valid_config_passes() {
        let mut option_parameters = HashMap::new();
        option_parameters.insert(
            "csv".to_string(),
            vec![
                ArgumentDefinition {
                    name: "file".to_string(),
                    arg_type: ArgumentType::Path,
                    required: true,
                    description: "Destination CSV file".to_string(),
                    validation: vec![],
                    secure: false,
                },
                ArgumentDefinition {
                    name: "resolution".to_string(),
                    arg_type: ArgumentType::Integer,
                    required: false,
                    description: "Time-step resolution".to_string(),
                    validation: vec![],
                    secure: false,
                },
            ],
        );
        option_parameters.insert(
            "plot".to_string(),
            vec![ArgumentDefinition {
                name: "file".to_string(),
                arg_type: ArgumentType::Path,
                required: true,
                description: "Destination image file".to_string(),
                validation: vec![],
                secure: false,
            }],
        );
        let options = vec![OptionDefinition {
            name: "output".to_string(),
            short: None,
            long: Some("output".to_string()),
            option_type: ArgumentType::String,
            required: false,
            default: None,
            description: "Write simulation results in one or more output kinds".to_string(),
            choices: vec!["csv".to_string(), "plot".to_string()],
            repeatable: true,
            option_parameters,
        }];

        let result = validate_options(&options, "test");
        assert!(result.is_ok());
    }
}