flag-rs 0.10.0

A Cobra-inspired CLI framework with dynamic completions
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
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
//! Command execution and management
//!
//! This module provides the core [`Command`] struct and [`CommandBuilder`] for creating
//! CLI applications with subcommands, flags, and dynamic completions.

use crate::completion::{CompletionFunc, CompletionResult};
use crate::completion_format::CompletionFormat;
use crate::context::Context;
use crate::error::{Error, Result};
use crate::flag::{Flag, FlagConstraint, FlagType, FlagValue};
use crate::suggestion::{DEFAULT_SUGGESTION_DISTANCE, find_suggestions};
use crate::terminal::{format_help_entry, get_terminal_width, wrap_text_to_terminal};
use crate::validator::ArgValidator;
use std::collections::{HashMap, HashSet};

/// Type alias for the function that executes when a command runs
pub type RunFunc = Box<dyn Fn(&mut Context) -> Result<()> + Send + Sync>;

/// Type alias for lifecycle hook functions
pub type HookFunc = Box<dyn Fn(&mut Context) -> Result<()> + Send + Sync>;

/// Represents a command in the CLI application
///
/// Commands can have:
/// - Subcommands for nested command structures
/// - Flags that modify behavior
/// - A run function that executes the command logic
/// - Dynamic completion functions for arguments and flags
/// - Help text and aliases
///
/// # Examples
///
/// ```rust
/// use flag_rs::{Command, CommandBuilder, Context};
///
/// // Using the builder pattern (recommended)
/// let cmd = CommandBuilder::new("serve")
///     .short("Start the web server")
///     .run(|ctx| {
///         println!("Server starting...");
///         Ok(())
///     })
///     .build();
///
/// // Direct construction
/// let mut cmd = Command::new("serve");
/// ```
pub struct Command {
    name: String,
    aliases: Vec<String>,
    short: String,
    long: String,
    examples: Vec<String>,
    group_id: Option<String>,
    subcommands: HashMap<String, Self>,
    flags: HashMap<String, Flag>,
    run: Option<RunFunc>,
    parent: Option<*mut Self>,
    arg_completions: Option<CompletionFunc>,
    flag_completions: HashMap<String, CompletionFunc>,
    arg_validator: Option<ArgValidator>,
    suggestions_enabled: bool,
    suggestion_distance: usize,
    // Lifecycle hooks
    persistent_pre_run: Option<HookFunc>,
    pre_run: Option<HookFunc>,
    post_run: Option<HookFunc>,
    persistent_post_run: Option<HookFunc>,
}

unsafe impl Send for Command {}
unsafe impl Sync for Command {}

impl Command {
    /// Creates a new command with the given name
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::Command;
    ///
    /// let cmd = Command::new("myapp");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            aliases: Vec::new(),
            short: String::new(),
            long: String::new(),
            examples: Vec::new(),
            group_id: None,
            subcommands: HashMap::new(),
            flags: HashMap::new(),
            run: None,
            parent: None,
            arg_completions: None,
            flag_completions: HashMap::new(),
            arg_validator: None,
            suggestions_enabled: true,
            suggestion_distance: DEFAULT_SUGGESTION_DISTANCE,
            persistent_pre_run: None,
            pre_run: None,
            post_run: None,
            persistent_post_run: None,
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the short description
    pub fn short(&self) -> &str {
        &self.short
    }

    /// Returns the long description
    pub fn long(&self) -> &str {
        &self.long
    }

    pub fn subcommands(&self) -> &HashMap<String, Self> {
        &self.subcommands
    }

    pub fn flags(&self) -> &HashMap<String, Flag> {
        &self.flags
    }

    /// Finds a subcommand by name or alias
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use flag_rs::{Command, CommandBuilder};
    /// let mut root = Command::new("app");
    /// let sub = CommandBuilder::new("server")
    ///     .aliases(vec!["serve", "s"])
    ///     .build();
    /// root.add_command(sub);
    ///
    /// assert!(root.find_subcommand("server").is_some());
    /// assert!(root.find_subcommand("serve").is_some());
    /// assert!(root.find_subcommand("s").is_some());
    /// ```
    pub fn find_subcommand(&self, name: &str) -> Option<&Self> {
        self.subcommands.get(name).or_else(|| {
            self.subcommands
                .values()
                .find(|cmd| cmd.aliases.contains(&name.to_string()))
        })
    }

    /// Finds a mutable reference to a subcommand by name or alias
    pub fn find_subcommand_mut(&mut self, name: &str) -> Option<&mut Self> {
        let name_string = name.to_string();
        if self.subcommands.contains_key(name) {
            self.subcommands.get_mut(name)
        } else {
            self.subcommands
                .values_mut()
                .find(|cmd| cmd.aliases.contains(&name_string))
        }
    }

    /// Adds a subcommand to this command
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{Command, CommandBuilder};
    ///
    /// let mut root = Command::new("myapp");
    /// let serve = CommandBuilder::new("serve")
    ///     .short("Start the server")
    ///     .build();
    ///
    /// root.add_command(serve);
    /// ```
    pub fn add_command(&mut self, mut cmd: Self) {
        cmd.parent = Some(std::ptr::from_mut::<Self>(self));
        self.subcommands.insert(cmd.name.clone(), cmd);
    }

    /// Executes the command with the given arguments
    ///
    /// This is the main entry point for running your CLI application.
    /// It handles:
    /// - Shell completion requests
    /// - Flag parsing
    /// - Subcommand routing
    /// - Execution of the appropriate run function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let app = CommandBuilder::new("myapp")
    ///     .run(|ctx| {
    ///         println!("Hello from myapp!");
    ///         Ok(())
    ///     })
    ///     .build();
    ///
    /// // In main():
    /// // let args: Vec<String> = std::env::args().skip(1).collect();
    /// // if let Err(e) = app.execute(args) {
    /// //     eprintln!("Error: {}", e);
    /// //     std::process::exit(1);
    /// // }
    /// ```
    pub fn execute(&self, args: Vec<String>) -> Result<()> {
        // Check if we're in completion mode
        if let Ok(_shell) = std::env::var(format!("{}_COMPLETE", self.name.to_uppercase())) {
            // Disable colors during completion to avoid terminal rendering issues
            unsafe { std::env::set_var("NO_COLOR", "1") };

            match self.handle_completion_request(&args) {
                Ok(suggestions) => {
                    for suggestion in suggestions {
                        println!("{suggestion}");
                    }
                    return Ok(());
                }
                Err(e) => {
                    // Don't write to stderr during completion - it can mess up the terminal
                    return Err(e);
                }
            }
        }

        let mut ctx = Context::new(args);
        self.execute_with_context(&mut ctx)
    }

    /// Executes the command with an existing context
    ///
    /// This method is useful when you need to provide pre-configured context
    /// or when implementing custom command routing.
    pub fn execute_with_context(&self, ctx: &mut Context) -> Result<()> {
        // Call the internal method with an empty hook chain
        self.execute_with_context_and_hooks(ctx, &mut Vec::new())
    }

    /// Internal method that executes the command while collecting parent hooks
    fn execute_with_context_and_hooks<'a>(
        &'a self,
        ctx: &mut Context,
        parent_hooks: &mut Vec<(&'a Option<HookFunc>, &'a Option<HookFunc>)>,
    ) -> Result<()> {
        let args = ctx.args().to_vec();

        // Parse flags first, before checking for empty args
        let (flags, remaining_args) = self.parse_flags(&args)?;

        *ctx.args_mut() = remaining_args;

        if let Some(subcommand_name) = ctx.args().first() {
            if let Some(subcommand) = self.find_subcommand(subcommand_name) {
                if flags.contains_key("help") {
                    subcommand.print_help();
                    return Ok(());
                }

                self.validate_flags(&flags)?;

                for (name, value) in flags {
                    ctx.set_flag(name, value);
                }

                // Add our persistent hooks to the chain for subcommands
                parent_hooks.push((&self.persistent_pre_run, &self.persistent_post_run));

                ctx.args_mut().remove(0);
                return subcommand.execute_with_context_and_hooks(ctx, parent_hooks);
            }
        }

        if flags.contains_key("help") {
            self.print_help();
            return Ok(());
        }

        self.validate_flags(&flags)?;

        for (name, value) in flags {
            ctx.set_flag(name, value);
        }

        if let Some(ref run) = self.run {
            // Validate arguments before running
            if let Some(ref validator) = self.arg_validator {
                validator.validate(ctx.args())?;
            }
            self.execute_with_parent_hooks(ctx, run, parent_hooks)
        } else if ctx.args().is_empty() {
            // No args and no run function - show help
            Err(Error::SubcommandRequired(self.name.clone()))
        } else {
            let unknown_command = ctx.args().first().unwrap_or(&String::new()).clone();
            let suggestions = if self.suggestions_enabled {
                self.find_command_suggestions(&unknown_command)
            } else {
                Vec::new()
            };

            Err(Error::CommandNotFound {
                command: unknown_command,
                suggestions,
            })
        }
    }

    fn parse_flags(&self, args: &[String]) -> Result<(HashMap<String, String>, Vec<String>)> {
        let mut flags = HashMap::new();
        let mut remaining = Vec::new();
        let mut i = 0;

        while i < args.len() {
            let arg = &args[i];

            if arg == "--" {
                remaining.extend_from_slice(&args[i + 1..]);
                break;
            } else if arg.starts_with("--") {
                let flag_name = arg.trim_start_matches("--");

                if flag_name == "help" {
                    flags.insert("help".to_string(), "true".to_string());
                } else if let Some((name, value)) = flag_name.split_once('=') {
                    // Validate the flag value
                    if let Some(flag) = self.find_flag(name) {
                        flag.parse_value(value)?;
                    }
                    flags.insert(name.to_string(), value.to_string());
                } else if let Some(flag) = self.find_flag(flag_name) {
                    if i + 1 < args.len() && !args[i + 1].starts_with('-') {
                        let value = &args[i + 1];
                        // Validate the flag value
                        flag.parse_value(value)?;
                        flags.insert(flag_name.to_string(), value.clone());
                        i += 1;
                    } else {
                        flags.insert(flag_name.to_string(), "true".to_string());
                    }
                } else {
                    // Unknown flag - might belong to a subcommand
                    remaining.push(arg.clone());
                }
            } else if arg.starts_with('-') && arg.len() > 1 {
                let short_flags = arg.trim_start_matches('-');
                let chars: Vec<char> = short_flags.chars().collect();

                for (idx, ch) in chars.iter().enumerate() {
                    if *ch == 'h' {
                        flags.insert("help".to_string(), "true".to_string());
                    } else if let Some(flag) = self.find_flag_by_short(*ch) {
                        // If this is the last char and the flag takes a value
                        if idx == chars.len() - 1
                            && i + 1 < args.len()
                            && !args[i + 1].starts_with('-')
                        {
                            let value = &args[i + 1];
                            // Validate the flag value
                            flag.parse_value(value)?;
                            flags.insert(flag.name.clone(), value.clone());
                            i += 1;
                        } else {
                            flags.insert(flag.name.clone(), "true".to_string());
                        }
                    } else {
                        // Unknown short flag - might belong to a subcommand
                        remaining.push(format!("-{}", chars[idx..].iter().collect::<String>()));
                        break;
                    }
                }
            } else {
                remaining.push(arg.clone());
            }

            i += 1;
        }

        Ok((flags, remaining))
    }

    /// Sets the argument completion function for this command
    ///
    /// The completion function is called when the user presses TAB to complete
    /// command arguments. It receives the current context and the prefix to complete.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{Command, CompletionResult};
    ///
    /// let mut cmd = Command::new("get");
    /// cmd.set_arg_completion(|ctx, prefix| {
    ///     let items = vec!["users", "posts", "comments"];
    ///     Ok(CompletionResult::new().extend(
    ///         items.into_iter()
    ///             .filter(|i| i.starts_with(prefix))
    ///             .map(String::from)
    ///     ))
    /// });
    /// ```
    pub fn set_arg_completion<F>(&mut self, f: F)
    where
        F: Fn(&Context, &str) -> Result<CompletionResult> + Send + Sync + 'static,
    {
        self.arg_completions = Some(Box::new(f));
    }

    /// Sets the completion function for a specific flag
    ///
    /// This allows dynamic completion of flag values based on runtime state.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{Command, CompletionResult};
    ///
    /// let mut cmd = Command::new("deploy");
    /// cmd.set_flag_completion("environment", |ctx, prefix| {
    ///     let envs = vec!["dev", "staging", "production"];
    ///     Ok(CompletionResult::new().extend(
    ///         envs.into_iter()
    ///             .filter(|e| e.starts_with(prefix))
    ///             .map(String::from)
    ///     ))
    /// });
    /// ```
    pub fn set_flag_completion<F>(&mut self, flag_name: impl Into<String>, f: F)
    where
        F: Fn(&Context, &str) -> Result<CompletionResult> + Send + Sync + 'static,
    {
        self.flag_completions.insert(flag_name.into(), Box::new(f));
    }

    /// Gets completion suggestions for the current context
    ///
    /// This method is primarily used internally by the shell completion system.
    pub fn get_completions(
        &self,
        ctx: &Context,
        to_complete: &str,
        completing_flag: Option<&str>,
    ) -> Result<CompletionResult> {
        if let Some(flag_name) = completing_flag {
            if let Some(completion_func) = self.flag_completions.get(flag_name) {
                return completion_func(ctx, to_complete);
            }
        } else if let Some(ref completion_func) = self.arg_completions {
            return completion_func(ctx, to_complete);
        }

        Ok(CompletionResult::new())
    }

    fn find_flag(&self, name: &str) -> Option<&Flag> {
        self.flags.get(name).or_else(|| {
            self.parent
                .and_then(|parent| unsafe { (*parent).find_flag(name) })
        })
    }

    fn find_flag_by_short(&self, short: char) -> Option<&Flag> {
        self.flags
            .values()
            .find(|f| f.short == Some(short))
            .or_else(|| {
                self.parent
                    .and_then(|parent| unsafe { (*parent).find_flag_by_short(short) })
            })
    }

    /// Validates all flags including required flags and constraints
    fn validate_flags(&self, provided_flags: &HashMap<String, String>) -> Result<()> {
        let provided_flag_names: HashSet<String> = provided_flags.keys().cloned().collect();

        // Check required flags
        for (flag_name, flag) in &self.flags {
            if flag.required && !provided_flag_names.contains(flag_name) {
                return Err(Error::flag_parsing_with_suggestions(
                    format!("Required flag '--{flag_name}' not provided"),
                    flag_name.clone(),
                    vec![format!("add --{flag_name} <value>")],
                ));
            }
        }

        // TODO: Fix unsafe parent flag validation
        // Check parent flags if any
        // if let Some(parent) = self.parent {
        //     unsafe {
        //         for (flag_name, flag) in &(*parent).flags {
        //             if flag.required && !provided_flag_names.contains(flag_name) {
        //                 return Err(Error::flag_parsing_with_suggestions(
        //                     format!("Required flag '--{flag_name}' not provided"),
        //                     flag_name.to_string(),
        //                     vec![format!("add --{flag_name} <value>")],
        //                 ));
        //             }
        //         }
        //     }
        // }

        // Validate constraints for all flags
        for (flag_name, flag) in &self.flags {
            flag.validate_constraints(flag_name, &provided_flag_names)?;
        }

        // TODO: Fix unsafe parent flag constraint validation
        // The current approach with raw pointers can lead to undefined behavior
        // when the parent Command is moved or when accessing heap-allocated data
        // through the pointer (like Vec<FlagConstraint>).
        //
        // Validate parent flag constraints
        // if let Some(parent) = self.parent {
        //     unsafe {
        //         for (flag_name, flag) in &(*parent).flags {
        //             flag.validate_constraints(flag_name, &provided_flag_names)?;
        //         }
        //     }
        // }

        Ok(())
    }

    /// Executes the command with lifecycle hooks including parent hooks
    fn execute_with_parent_hooks(
        &self,
        ctx: &mut Context,
        run: &RunFunc,
        parent_hooks: &[(&Option<HookFunc>, &Option<HookFunc>)],
    ) -> Result<()> {
        // Execute parent persistent pre-run hooks (from root to immediate parent)
        for (pre_hook, _) in parent_hooks {
            if let Some(hook) = pre_hook {
                hook(ctx)?;
            }
        }

        // Execute own persistent pre-run hook if present
        if let Some(ref hook) = self.persistent_pre_run {
            hook(ctx)?;
        }

        // Execute pre-run hook if present
        if let Some(ref pre_run) = self.pre_run {
            pre_run(ctx)?;
        }

        // Execute the main run function
        let result = run(ctx);

        // Execute post-run hook if present, but preserve the original error
        let post_run_result = if let Some(ref post_run) = self.post_run {
            match result {
                Ok(()) => post_run(ctx),
                Err(e) => {
                    // Try to run post-run even if main failed, but return original error
                    let _ = post_run(ctx);
                    Err(e)
                }
            }
        } else {
            result
        };

        // Execute own persistent post-run hook if present
        let persistent_result = if let Some(ref hook) = self.persistent_post_run {
            let result = hook(ctx);
            match post_run_result {
                Ok(()) => result,
                Err(e) => {
                    // Try to run persistent post-run even if post-run failed
                    let _ = result;
                    Err(e)
                }
            }
        } else {
            post_run_result
        };

        // Execute parent persistent post-run hooks (from immediate parent to root)
        let mut final_result = persistent_result;
        for (_, post_hook) in parent_hooks.iter().rev() {
            if let Some(hook) = post_hook {
                match final_result {
                    Ok(()) => final_result = hook(ctx),
                    Err(e) => {
                        // Try to run parent post-run even if child failed
                        let _ = hook(ctx);
                        final_result = Err(e);
                    }
                }
            }
        }

        final_result
    }

    /// Prints the help message for this command
    ///
    /// The help message includes:
    /// - Command description
    /// - Usage information
    /// - Available subcommands
    /// - Local and global flags
    ///
    /// Help text is automatically colored when outputting to a TTY.
    #[allow(clippy::cognitive_complexity)]
    pub fn print_help(&self) {
        use crate::color;

        // Print description with text wrapping
        if !self.long.is_empty() {
            println!("{}", wrap_text_to_terminal(&self.long, None));
            println!();
        } else if !self.short.is_empty() {
            println!("{}", wrap_text_to_terminal(&self.short, None));
            println!();
        }

        // Print usage line
        print!("{}:\n  {}", color::bold("Usage"), self.name);
        if !self.flags.is_empty() {
            print!(" {}", color::yellow("[flags]"));
        }
        if !self.subcommands.is_empty() {
            print!(" {}", color::yellow("[command]"));
        }

        // Show if command requires args
        if let Some(validator) = &self.arg_validator {
            match validator {
                ArgValidator::MinimumArgs(n) if n > &0 => {
                    print!(" {}", color::yellow("<args>"));
                }
                ArgValidator::ExactArgs(n) if n > &0 => {
                    let arg_str = if n == &1 { "<arg>" } else { "<args>" };
                    print!(" {}", color::yellow(arg_str));
                }
                ArgValidator::RangeArgs(min, _) if min > &0 => {
                    print!(" {}", color::yellow("<args>"));
                }
                _ => {}
            }
        }
        println!("\n");

        // Print available commands
        if !self.subcommands.is_empty() {
            let mut commands: Vec<_> = self.subcommands.values().collect();
            commands.sort_by_key(|cmd| &cmd.name);

            // Group commands by their group_id
            let mut grouped: std::collections::BTreeMap<Option<String>, Vec<&Self>> =
                std::collections::BTreeMap::new();
            for cmd in commands {
                grouped.entry(cmd.group_id.clone()).or_default().push(cmd);
            }

            let terminal_width = get_terminal_width();
            let left_column_width = 24;

            // Print commands without groups first
            if let Some(ungrouped) = grouped.get(&None) {
                println!("{}:", color::bold("Available Commands"));
                for &cmd in ungrouped {
                    Self::print_command_entry(cmd, left_column_width, terminal_width);
                }
                println!();
            }

            // Print grouped commands
            for (group_id, cmds) in grouped {
                if let Some(group) = group_id {
                    println!("{}:", color::bold(&group));
                    for cmd in cmds {
                        Self::print_command_entry(cmd, left_column_width, terminal_width);
                    }
                    println!();
                }
            }
        }

        // Print flags
        if !self.flags.is_empty() || self.parent.is_some() {
            // Separate required and optional flags
            let mut required_flags: Vec<_> = self.flags.values().filter(|f| f.required).collect();
            let mut optional_flags: Vec<_> = self.flags.values().filter(|f| !f.required).collect();

            required_flags.sort_by_key(|f| &f.name);
            optional_flags.sort_by_key(|f| &f.name);

            // Print required flags first
            if !required_flags.is_empty() {
                println!("{} {}:", color::bold("Required Flags"), color::red("*"));
                for flag in required_flags {
                    Self::print_flag(flag);
                }
                if !optional_flags.is_empty() {
                    println!();
                }
            }

            // Print optional flags
            if !optional_flags.is_empty() {
                println!("{}:", color::bold("Flags"));
                for flag in optional_flags {
                    Self::print_flag(flag);
                }
            }
        }

        // Print global flags from parent
        if let Some(parent) = self.parent {
            unsafe {
                let parent_flags = &(*parent).flags;
                if !parent_flags.is_empty() {
                    println!("\n{}:", color::bold("Global Flags"));
                    let mut global_flags: Vec<_> = parent_flags.values().collect();
                    global_flags.sort_by_key(|f| &f.name);

                    for flag in global_flags {
                        Self::print_flag(flag);
                    }
                }
            }
        }

        // Print examples if available
        if !self.examples.is_empty() {
            println!("{}:", color::bold("Examples"));
            for example in &self.examples {
                println!("  {}", color::dim(example));
            }
            println!();
        }

        // Print help about help
        println!(
            "Use \"{} {} --help\" for more information about a command.",
            self.name,
            color::yellow("[command]")
        );
    }

    fn print_command_entry(cmd: &Self, left_column_width: usize, terminal_width: usize) {
        use crate::color;

        let mut name_with_aliases = color::green(&cmd.name);
        if !cmd.aliases.is_empty() {
            let aliases = cmd.aliases.join(", ");
            name_with_aliases = format!(
                "{} {}",
                name_with_aliases,
                color::dim(&format!("({aliases})"))
            );
        }

        let formatted = format_help_entry(
            &format!("  {name_with_aliases}"),
            &cmd.short,
            left_column_width + 2,
            terminal_width,
        );
        println!("{formatted}");
    }

    fn print_flag(flag: &Flag) {
        use crate::color;
        use std::fmt::Write;

        let short = flag
            .short
            .map_or_else(|| "    ".to_string(), |s| format!("-{s}, "));

        // Build constraint indicators
        let mut constraint_info = String::new();
        for constraint in &flag.constraints {
            match constraint {
                FlagConstraint::RequiredIf(other) => {
                    let _ = write!(
                        &mut constraint_info,
                        " {}",
                        color::yellow(&format!("[required if --{other}]"))
                    );
                }
                FlagConstraint::ConflictsWith(others) => {
                    let conflicts = others.join(", --");
                    let _ = write!(
                        &mut constraint_info,
                        " {}",
                        color::yellow(&format!("[conflicts with --{conflicts}]"))
                    );
                }
                FlagConstraint::Requires(others) => {
                    let requires = others.join(", --");
                    let _ = write!(
                        &mut constraint_info,
                        " {}",
                        color::yellow(&format!("[requires --{requires}]"))
                    );
                }
            }
        }

        // Handle special formatting for Choice and Range types
        match &flag.value_type {
            FlagType::Choice(choices) => {
                let choices_str = choices.join("|");
                let default = flag
                    .default
                    .as_ref()
                    .map(|d| match d {
                        FlagValue::String(s) => format!(" (default \"{s}\")"),
                        _ => String::new(),
                    })
                    .unwrap_or_default();
                let flag_name_formatted = format!("{} {{{}}}", flag.name, choices_str);
                Self::print_flag_line(
                    &flag_name_formatted,
                    &default,
                    &short,
                    &flag.usage,
                    &constraint_info,
                );
                return;
            }
            FlagType::Range(min, max) => {
                let default = flag
                    .default
                    .as_ref()
                    .map(|d| match d {
                        FlagValue::Int(i) => format!(" (default {i})"),
                        _ => String::new(),
                    })
                    .unwrap_or_default();
                let flag_name_formatted = format!("{} int[{}-{}]", flag.name, min, max);
                Self::print_flag_line(
                    &flag_name_formatted,
                    &default,
                    &short,
                    &flag.usage,
                    &constraint_info,
                );
                return;
            }
            _ => {}
        }

        let flag_type = match &flag.value_type {
            FlagType::String => " string",
            FlagType::Int => " int",
            FlagType::Float => " float",
            FlagType::Bool => "",
            FlagType::StringSlice | FlagType::StringArray => " strings",
            FlagType::File => " file",
            FlagType::Directory => " dir",
            FlagType::Choice(_) | FlagType::Range(_, _) => unreachable!(),
        };

        let default = flag
            .default
            .as_ref()
            .map(|d| match d {
                FlagValue::String(s) => format!(" (default \"{s}\")"),
                FlagValue::Bool(b) => format!(" (default {b})"),
                FlagValue::Int(i) => format!(" (default {i})"),
                FlagValue::Float(f) => format!(" (default {f})"),
                FlagValue::StringSlice(v) => format!(" (default {v:?})"),
            })
            .unwrap_or_default();

        let flag_name_formatted = format!("{}{flag_type}", flag.name);
        Self::print_flag_line(
            &flag_name_formatted,
            &default,
            &short,
            &flag.usage,
            &constraint_info,
        );
    }

    fn print_flag_line(
        flag_name_formatted: &str,
        default: &str,
        short: &str,
        usage: &str,
        constraint_info: &str,
    ) {
        use crate::color;

        let left_part = format!(
            "      {}--{}",
            color::cyan(short),
            color::cyan(flag_name_formatted)
        );
        let description = format!("{}{}{}", usage, color::dim(default), constraint_info);
        let terminal_width = get_terminal_width();
        let left_column_width = 30;
        let formatted =
            format_help_entry(&left_part, &description, left_column_width, terminal_width);
        println!("{formatted}");
    }

    /// Finds command suggestions based on similarity
    fn find_command_suggestions(&self, input: &str) -> Vec<String> {
        let candidates: Vec<String> = self.subcommands.keys().cloned().collect();
        find_suggestions(input, &candidates, self.suggestion_distance)
    }

    /// Collects all available flags with their descriptions for completion.
    /// Walks up the parent chain so global flags surface alongside local ones.
    fn collect_all_flags_with_descriptions(&self, result: &mut CompletionResult, prefix: &str) {
        for (flag_name, flag) in &self.flags {
            if flag_name.starts_with(prefix) {
                let formatted_flag = format!("--{flag_name}");
                result.values.push(formatted_flag);
                result.descriptions.push(flag.usage.clone());
            }
        }

        if let Some(parent) = self.parent {
            unsafe {
                (*parent).collect_all_flags_with_descriptions(result, prefix);
            }
        }
    }

    /// Handles shell completion requests
    ///
    /// This method is called when the shell requests completions via the
    /// environment variable (e.g., `MYAPP_COMPLETE=bash`).
    pub fn handle_completion_request(&self, args: &[String]) -> Result<Vec<String>> {
        // Detect shell type from environment variable
        let shell_type = self.detect_completion_shell();

        // args format: ["__complete", ...previous_args, current_word]
        if args.is_empty() || args[0] != "__complete" {
            return Err(Error::Completion("Invalid completion request".to_string()));
        }

        let args = &args[1..];
        if args.is_empty() {
            // Complete root level
            return Ok(self.get_completion_suggestions("", None, shell_type.as_deref()));
        }

        let current_word = args.last().unwrap_or(&String::new()).clone();
        let previous_args = &args[..args.len().saturating_sub(1)];

        // Parse through the command hierarchy
        let mut current_cmd = self;
        let mut ctx = Context::new(vec![]);
        let mut i = 0;

        while i < previous_args.len() {
            let arg = &previous_args[i];

            if arg.starts_with("--") {
                // Long flag
                let flag_name = arg.trim_start_matches("--");
                if let Some((name, _)) = flag_name.split_once('=') {
                    // Flag with value
                    ctx.set_flag(name.to_string(), String::new());
                } else if let Some(_flag) = current_cmd.find_flag(flag_name) {
                    // Flag that might need a value
                    if i + 1 < previous_args.len() && !previous_args[i + 1].starts_with('-') {
                        ctx.set_flag(flag_name.to_string(), previous_args[i + 1].clone());
                        i += 1;
                    }
                }
            } else if arg.starts_with('-') && arg.len() > 1 {
                // Short flags
                for ch in arg.chars().skip(1) {
                    if let Some(flag) = current_cmd.find_flag_by_short(ch) {
                        ctx.set_flag(flag.name.clone(), String::new());
                    }
                }
            } else {
                // Potential subcommand
                if let Some(subcmd) = current_cmd.find_subcommand(arg) {
                    current_cmd = subcmd;
                } else {
                    ctx.args_mut().push(arg.clone());
                }
            }
            i += 1;
        }

        // Now determine what to complete
        if current_word.starts_with("--") {
            // Complete long flags only (when user explicitly started typing --)
            let prefix = current_word.trim_start_matches("--");
            let mut flag_completions = CompletionResult::new();

            // Collect flags with descriptions from current command and parents
            current_cmd.collect_all_flags_with_descriptions(&mut flag_completions, prefix);

            let format = CompletionFormat::from_shell_type(shell_type.as_deref());
            Ok(format.format(&flag_completions, Some(&ctx)))
        } else if current_word.starts_with('-') && current_word.len() > 1 {
            // For short flags, we don't complete (too complex)
            Ok(vec![])
        } else {
            // Check if previous arg was a flag that needs a value
            if let Some(prev) = previous_args.last() {
                if prev.starts_with("--") {
                    let flag_name = prev.trim_start_matches("--");

                    // First check if the flag itself has a completion function
                    if let Some(flag) = current_cmd.flags.get(flag_name) {
                        if let Some(ref completion_func) = flag.completion {
                            return Self::run_flag_completion(
                                completion_func,
                                &ctx,
                                &current_word,
                                shell_type.as_deref(),
                            );
                        }
                    }

                    // Fall back to flag_completions HashMap
                    if let Some(completion_func) = current_cmd.flag_completions.get(flag_name) {
                        return Self::run_flag_completion(
                            completion_func,
                            &ctx,
                            &current_word,
                            shell_type.as_deref(),
                        );
                    }
                } else if prev.starts_with('-') && prev.len() == 2 {
                    // Handle short flag completions
                    let Some(short_flag) = prev.chars().nth(1) else {
                        // This should not happen given the length check, but handle gracefully
                        return Ok(vec![]);
                    };
                    if let Some(flag) = current_cmd.find_flag_by_short(short_flag) {
                        if let Some(ref completion_func) = flag.completion {
                            return Self::run_flag_completion(
                                completion_func,
                                &ctx,
                                &current_word,
                                shell_type.as_deref(),
                            );
                        }

                        // Also check flag_completions HashMap by flag name
                        if let Some(completion_func) = current_cmd.flag_completions.get(&flag.name)
                        {
                            return Self::run_flag_completion(
                                completion_func,
                                &ctx,
                                &current_word,
                                shell_type.as_deref(),
                            );
                        }
                    }
                }
            }

            // Complete subcommands, arguments AND flags together
            let mut combined_completions = CompletionResult::new();

            // Get subcommand/argument completions
            let subcommand_suggestions = current_cmd.get_completion_suggestions(
                &current_word,
                Some(&ctx),
                shell_type.as_deref(),
            );

            // Add flags that don't start with current_word (so user can discover them)
            // Only add flags if current_word is empty or doesn't look like it's trying to complete a specific subcommand
            if current_word.is_empty()
                || !current_cmd
                    .subcommands
                    .keys()
                    .any(|name| name.starts_with(&current_word))
            {
                current_cmd.collect_all_flags_with_descriptions(&mut combined_completions, "");
            }

            // Convert subcommand suggestions to CompletionResult format and combine
            let format = CompletionFormat::from_shell_type(shell_type.as_deref());
            let mut final_suggestions = subcommand_suggestions;
            let flag_suggestions = format.format(&combined_completions, Some(&ctx));
            final_suggestions.extend(flag_suggestions);

            Ok(final_suggestions)
        }
    }

    /// Detects the shell type from the environment variable
    fn detect_completion_shell(&self) -> Option<String> {
        use std::env;

        // Look for shell-specific completion environment variables
        let env_var = format!("{}_COMPLETE", self.name.to_uppercase());
        env::var(&env_var).ok()
    }

    fn get_completion_suggestions(
        &self,
        prefix: &str,
        ctx: Option<&Context>,
        shell_type: Option<&str>,
    ) -> Vec<String> {
        let mut completion_result = CompletionResult::new();
        let mut has_suggestions = false;

        // Add subcommands with their descriptions
        for (name, cmd) in &self.subcommands {
            if name.starts_with(prefix) {
                completion_result =
                    completion_result.add_with_description(name.clone(), cmd.short.clone());
                has_suggestions = true;
            }
            // Also check aliases
            for alias in &cmd.aliases {
                if alias.starts_with(prefix) {
                    completion_result = completion_result
                        .add_with_description(alias.clone(), format!("Alias for {name}"));
                    has_suggestions = true;
                }
            }
        }

        // If we have arg completions and no subcommands match, try those
        if !has_suggestions {
            if let Some(ref completion_func) = self.arg_completions {
                let default_ctx = Context::new(vec![]);
                let ctx = ctx.unwrap_or(&default_ctx);
                if let Ok(result) = completion_func(ctx, prefix) {
                    let format = CompletionFormat::from_shell_type(shell_type);
                    return format.format(&result, Some(ctx));
                }
            }
        }

        // Format the results
        let format = CompletionFormat::from_shell_type(shell_type);
        let default_ctx = Context::new(vec![]);
        let ctx_to_use = ctx.unwrap_or(&default_ctx);
        let mut suggestions = format.format(&completion_result, Some(ctx_to_use));
        suggestions.sort();
        suggestions.dedup();
        suggestions
    }

    fn run_flag_completion(
        completion_func: &CompletionFunc,
        ctx: &Context,
        current_word: &str,
        shell_type: Option<&str>,
    ) -> Result<Vec<String>> {
        let result = completion_func(ctx, current_word)?;
        let format = CompletionFormat::from_shell_type(shell_type);
        Ok(format.format(&result, Some(ctx)))
    }
}

/// Builder for creating commands with a fluent API
///
/// `CommandBuilder` provides a convenient way to construct commands
/// with method chaining. This is the recommended way to create commands.
///
/// # Examples
///
/// ```rust
/// use flag_rs::{CommandBuilder, Flag, FlagType, FlagValue};
///
/// let cmd = CommandBuilder::new("serve")
///     .short("Start the web server")
///     .long("Start the web server on the specified port with the given configuration")
///     .aliases(vec!["server", "s"])
///     .flag(
///         Flag::new("port")
///             .short('p')
///             .usage("Port to listen on")
///             .value_type(FlagType::Int)
///             .default(FlagValue::Int(8080))
///     )
///     .flag(
///         Flag::new("config")
///             .short('c')
///             .usage("Configuration file path")
///             .value_type(FlagType::String)
///             .required()
///     )
///     .run(|ctx| {
///         let port = ctx.flag("port")
///             .and_then(|s| s.parse::<i64>().ok())
///             .unwrap_or(8080);
///         let config = ctx.flag("config")
///             .map(|s| s.as_str())
///             .unwrap_or("config.toml");
///
///         println!("Starting server on port {} with config {}", port, config);
///         Ok(())
///     })
///     .build();
/// ```
pub struct CommandBuilder {
    command: Command,
}

impl CommandBuilder {
    /// Creates a new command builder with the given name
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            command: Command::new(name),
        }
    }

    /// Adds a single alias for this command
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("remove")
    ///     .alias("rm")
    ///     .alias("delete")
    ///     .build();
    /// ```
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.command.aliases.push(alias.into());
        self
    }

    /// Adds multiple aliases for this command
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("remove")
    ///     .aliases(vec!["rm", "delete", "del"])
    ///     .build();
    /// ```
    #[must_use]
    pub fn aliases<I, S>(mut self, aliases: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.command
            .aliases
            .extend(aliases.into_iter().map(Into::into));
        self
    }

    /// Sets the short description for this command
    ///
    /// The short description is shown in the parent command's help output.
    #[must_use]
    pub fn short(mut self, short: impl Into<String>) -> Self {
        self.command.short = short.into();
        self
    }

    /// Sets the long description for this command
    ///
    /// The long description is shown in this command's help output.
    #[must_use]
    pub fn long(mut self, long: impl Into<String>) -> Self {
        self.command.long = long.into();
        self
    }

    /// Adds an example for this command
    ///
    /// Examples are shown in the help output to demonstrate command usage.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("deploy")
    ///     .short("Deploy the application")
    ///     .example("deploy --env production")
    ///     .example("deploy --env staging --dry-run")
    ///     .build();
    /// ```
    #[must_use]
    pub fn example(mut self, example: impl Into<String>) -> Self {
        self.command.examples.push(example.into());
        self
    }

    /// Sets the group ID for this command
    ///
    /// Commands with the same group ID will be displayed together in help output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let app = CommandBuilder::new("kubectl")
    ///     .subcommand(
    ///         CommandBuilder::new("get")
    ///             .short("Display resources")
    ///             .group_id("Basic Commands")
    ///             .build()
    ///     )
    ///     .subcommand(
    ///         CommandBuilder::new("create")
    ///             .short("Create resources")
    ///             .group_id("Basic Commands")
    ///             .build()
    ///     )
    ///     .subcommand(
    ///         CommandBuilder::new("config")
    ///             .short("Modify kubeconfig files")
    ///             .group_id("Settings Commands")
    ///             .build()
    ///     )
    ///     .build();
    /// ```
    #[must_use]
    pub fn group_id(mut self, group_id: impl Into<String>) -> Self {
        self.command.group_id = Some(group_id.into());
        self
    }

    /// Adds a subcommand to this command
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let app = CommandBuilder::new("myapp")
    ///     .subcommand(
    ///         CommandBuilder::new("init")
    ///             .short("Initialize a new project")
    ///             .build()
    ///     )
    ///     .subcommand(
    ///         CommandBuilder::new("build")
    ///             .short("Build the project")
    ///             .build()
    ///     )
    ///     .build();
    /// ```
    #[must_use]
    pub fn subcommand(mut self, cmd: Command) -> Self {
        self.command.add_command(cmd);
        self
    }

    /// Adds multiple subcommands to this command at once
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("git")
    ///     .subcommands(vec![
    ///         CommandBuilder::new("add")
    ///             .short("Add file contents to the index")
    ///             .build(),
    ///         CommandBuilder::new("commit")
    ///             .short("Record changes to the repository")
    ///             .build(),
    ///         CommandBuilder::new("push")
    ///             .short("Update remote refs along with associated objects")
    ///             .build(),
    ///     ])
    ///     .build();
    /// ```
    #[must_use]
    pub fn subcommands(mut self, cmds: Vec<Command>) -> Self {
        for cmd in cmds {
            self.command.add_command(cmd);
        }
        self
    }

    /// Adds a flag to this command
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{CommandBuilder, Flag, FlagType};
    ///
    /// let cmd = CommandBuilder::new("deploy")
    ///     .flag(
    ///         Flag::new("force")
    ///             .short('f')
    ///             .usage("Force deployment without confirmation")
    ///             .value_type(FlagType::Bool)
    ///     )
    ///     .build();
    /// ```
    #[must_use]
    pub fn flag(mut self, flag: Flag) -> Self {
        self.command.flags.insert(flag.name.clone(), flag);
        self
    }

    /// Adds multiple flags to this command at once
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{CommandBuilder, Flag};
    ///
    /// let cmd = CommandBuilder::new("server")
    ///     .flags(vec![
    ///         Flag::bool("verbose").short('v').usage("Enable verbose output"),
    ///         Flag::bool("quiet").short('q').usage("Suppress output"),
    ///         Flag::int("port").short('p').usage("Port to listen on").default_int(8080),
    ///     ])
    ///     .build();
    /// ```
    #[must_use]
    pub fn flags(mut self, flags: Vec<Flag>) -> Self {
        for flag in flags {
            self.command.flags.insert(flag.name.clone(), flag);
        }
        self
    }

    /// Sets the function to run when this command is executed
    ///
    /// The run function receives a mutable reference to the [`Context`]
    /// which provides access to parsed flags and arguments.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("greet")
    ///     .run(|ctx| {
    ///         let name = ctx.args().first()
    ///             .map(|s| s.as_str())
    ///             .unwrap_or("World");
    ///         println!("Hello, {}!", name);
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn run<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
    {
        self.command.run = Some(Box::new(f));
        self
    }

    /// Sets the argument validator for this command
    ///
    /// The validator will be called before the run function to ensure
    /// arguments meet the specified constraints.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{CommandBuilder, ArgValidator};
    ///
    /// let cmd = CommandBuilder::new("delete")
    ///     .args(ArgValidator::MinimumArgs(1))
    ///     .run(|ctx| {
    ///         for file in ctx.args() {
    ///             println!("Deleting: {}", file);
    ///         }
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn args(mut self, validator: ArgValidator) -> Self {
        self.command.arg_validator = Some(validator);
        self
    }

    /// Sets the persistent pre-run hook for this command
    ///
    /// This hook runs before the command and all its subcommands.
    /// It's inherited by all subcommands and runs in parent-to-child order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("app")
    ///     .persistent_pre_run(|ctx| {
    ///         println!("Setting up logging...");
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn persistent_pre_run<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
    {
        self.command.persistent_pre_run = Some(Box::new(f));
        self
    }

    /// Sets the pre-run hook for this command
    ///
    /// This hook runs only for this specific command, after any persistent
    /// pre-run hooks but before the main run function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("deploy")
    ///     .pre_run(|ctx| {
    ///         println!("Validating deployment configuration...");
    ///         Ok(())
    ///     })
    ///     .run(|ctx| {
    ///         println!("Deploying application...");
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn pre_run<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
    {
        self.command.pre_run = Some(Box::new(f));
        self
    }

    /// Sets the post-run hook for this command
    ///
    /// This hook runs only for this specific command, after the main run
    /// function but before any persistent post-run hooks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("test")
    ///     .run(|ctx| {
    ///         println!("Running tests...");
    ///         Ok(())
    ///     })
    ///     .post_run(|ctx| {
    ///         println!("Generating test report...");
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn post_run<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
    {
        self.command.post_run = Some(Box::new(f));
        self
    }

    /// Sets the persistent post-run hook for this command
    ///
    /// This hook runs after the command and all its subcommands.
    /// It's inherited by all subcommands and runs in child-to-parent order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("app")
    ///     .persistent_post_run(|ctx| {
    ///         println!("Cleaning up resources...");
    ///         Ok(())
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn persistent_post_run<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
    {
        self.command.persistent_post_run = Some(Box::new(f));
        self
    }

    /// Sets the argument completion function
    ///
    /// This function is called when the user presses TAB to complete arguments.
    /// It enables dynamic completions based on runtime state.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{CommandBuilder, CompletionResult};
    ///
    /// let cmd = CommandBuilder::new("edit")
    ///     .arg_completion(|ctx, prefix| {
    ///         // In a real app, list files from the filesystem
    ///         let files = vec!["main.rs", "lib.rs", "Cargo.toml"];
    ///         Ok(CompletionResult::new().extend(
    ///             files.into_iter()
    ///                 .filter(|f| f.starts_with(prefix))
    ///                 .map(String::from)
    ///         ))
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn arg_completion<F>(mut self, f: F) -> Self
    where
        F: Fn(&Context, &str) -> Result<CompletionResult> + Send + Sync + 'static,
    {
        self.command.set_arg_completion(f);
        self
    }

    /// Sets the completion function for a specific flag
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::{CommandBuilder, CompletionResult, Flag, FlagType};
    ///
    /// let cmd = CommandBuilder::new("connect")
    ///     .flag(
    ///         Flag::new("server")
    ///             .usage("Server to connect to")
    ///             .value_type(FlagType::String)
    ///     )
    ///     .flag_completion("server", |ctx, prefix| {
    ///         // In a real app, discover available servers
    ///         let servers = vec!["prod-1", "prod-2", "staging", "dev"];
    ///         Ok(CompletionResult::new().extend(
    ///             servers.into_iter()
    ///                 .filter(|s| s.starts_with(prefix))
    ///                 .map(String::from)
    ///         ))
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn flag_completion<F>(mut self, flag_name: impl Into<String>, f: F) -> Self
    where
        F: Fn(&Context, &str) -> Result<CompletionResult> + Send + Sync + 'static,
    {
        self.command.set_flag_completion(flag_name, f);
        self
    }

    /// Enables or disables command suggestions
    ///
    /// When enabled, the framework will suggest similar commands when
    /// a user types an unknown command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("myapp")
    ///     .suggestions(true)  // Enable suggestions (default)
    ///     .build();
    /// ```
    #[must_use]
    pub fn suggestions(mut self, enabled: bool) -> Self {
        self.command.suggestions_enabled = enabled;
        self
    }

    /// Sets the maximum Levenshtein distance for suggestions
    ///
    /// Commands within this distance will be suggested as alternatives.
    /// Default is 2.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use flag_rs::CommandBuilder;
    ///
    /// let cmd = CommandBuilder::new("myapp")
    ///     .suggestion_distance(3)  // Allow more distant suggestions
    ///     .build();
    /// ```
    #[must_use]
    pub fn suggestion_distance(mut self, distance: usize) -> Self {
        self.command.suggestion_distance = distance;
        self
    }

    /// Builds and returns the completed [`Command`]
    #[must_use]
    pub fn build(self) -> Command {
        self.command
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::flag::FlagType;
    use std::sync::{Arc, Mutex};

    #[test]
    fn test_simple_command_execution() {
        let executed = Arc::new(Mutex::new(false));
        let executed_clone = executed.clone();

        let cmd = CommandBuilder::new("test")
            .run(move |_ctx| {
                *executed_clone.lock().unwrap() = true;
                Ok(())
            })
            .build();

        cmd.execute(vec![]).unwrap();
        assert!(*executed.lock().unwrap());
    }

    #[test]
    fn test_command_with_args() {
        let received_args = Arc::new(Mutex::new(Vec::new()));
        let args_clone = received_args.clone();

        let cmd = CommandBuilder::new("test")
            .run(move |ctx| {
                *args_clone.lock().unwrap() = ctx.args().to_vec();
                Ok(())
            })
            .build();

        cmd.execute(vec!["arg1".to_string(), "arg2".to_string()])
            .unwrap();
        assert_eq!(*received_args.lock().unwrap(), vec!["arg1", "arg2"]);
    }

    #[test]
    fn test_subcommand_execution() {
        let main_executed = Arc::new(Mutex::new(false));
        let sub_executed = Arc::new(Mutex::new(false));
        let sub_clone = sub_executed.clone();

        let subcmd = CommandBuilder::new("sub")
            .run(move |_ctx| {
                *sub_clone.lock().unwrap() = true;
                Ok(())
            })
            .build();

        let main_clone = main_executed.clone();
        let cmd = CommandBuilder::new("main")
            .run(move |_ctx| {
                *main_clone.lock().unwrap() = true;
                Ok(())
            })
            .subcommand(subcmd)
            .build();

        // Execute subcommand
        cmd.execute(vec!["sub".to_string()]).unwrap();
        assert!(*sub_executed.lock().unwrap());
        assert!(!*main_executed.lock().unwrap());
    }

    #[test]
    fn test_flag_parsing() {
        let cmd = CommandBuilder::new("test")
            .flag(Flag::new("verbose").short('v').value_type(FlagType::Bool))
            .flag(Flag::new("output").short('o').value_type(FlagType::String))
            .flag(Flag::new("count").value_type(FlagType::Int))
            .run(|ctx| {
                assert_eq!(ctx.flag("verbose"), Some(&"true".to_string()));
                assert_eq!(ctx.flag("output"), Some(&"file.txt".to_string()));
                assert_eq!(ctx.flag("count"), Some(&"42".to_string()));
                assert_eq!(ctx.args(), &["remaining"]);
                Ok(())
            })
            .build();

        cmd.execute(vec![
            "-v".to_string(),
            "--output".to_string(),
            "file.txt".to_string(),
            "--count=42".to_string(),
            "remaining".to_string(),
        ])
        .unwrap();
    }

    #[test]
    fn test_flag_inheritance() {
        let sub_executed = Arc::new(Mutex::new(false));
        let sub_clone = sub_executed.clone();

        let subcmd = CommandBuilder::new("sub")
            .run(move |ctx| {
                assert_eq!(ctx.flag("global"), Some(&"value".to_string()));
                *sub_clone.lock().unwrap() = true;
                Ok(())
            })
            .build();

        let cmd = CommandBuilder::new("main")
            .flag(Flag::new("global").value_type(FlagType::String))
            .subcommand(subcmd)
            .build();

        cmd.execute(vec![
            "--global".to_string(),
            "value".to_string(),
            "sub".to_string(),
        ])
        .unwrap();

        assert!(*sub_executed.lock().unwrap());
    }

    #[test]
    fn test_command_aliases() {
        let executed = Arc::new(Mutex::new(String::new()));
        let exec_clone = executed.clone();

        let subcmd = CommandBuilder::new("subcommand")
            .aliases(vec!["sub", "s"])
            .run(move |_ctx| {
                *exec_clone.lock().unwrap() = "subcommand".to_string();
                Ok(())
            })
            .build();

        let cmd = CommandBuilder::new("main").subcommand(subcmd).build();

        // Test main name
        cmd.execute(vec!["subcommand".to_string()]).unwrap();
        assert_eq!(*executed.lock().unwrap(), "subcommand");

        // Test alias
        cmd.execute(vec!["sub".to_string()]).unwrap();
        assert_eq!(*executed.lock().unwrap(), "subcommand");

        // Test short alias
        cmd.execute(vec!["s".to_string()]).unwrap();
        assert_eq!(*executed.lock().unwrap(), "subcommand");
    }

    #[test]
    fn test_error_cases() {
        let cmd = CommandBuilder::new("main").build();

        // No subcommand when required
        let result = cmd.execute(vec![]);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::SubcommandRequired(_)));

        // Unknown subcommand
        let result = cmd.execute(vec!["unknown".to_string()]);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::CommandNotFound { .. }));

        // Unknown flag (now treated as argument, so it becomes unknown command)
        let result = cmd.execute(vec!["--unknown".to_string()]);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::CommandNotFound { .. }));
    }

    #[test]
    fn test_completion() {
        let cmd = CommandBuilder::new("test")
            .arg_completion(|_ctx, prefix| {
                Ok(CompletionResult::new().extend(
                    vec!["file1.txt", "file2.txt", "folder/"]
                        .into_iter()
                        .filter(|f| f.starts_with(prefix))
                        .map(String::from),
                ))
            })
            .flag_completion("type", |_ctx, prefix| {
                Ok(CompletionResult::new().extend(
                    vec!["json", "yaml", "xml"]
                        .into_iter()
                        .filter(|t| t.starts_with(prefix))
                        .map(String::from),
                ))
            })
            .build();

        let ctx = Context::new(vec![]);

        // Test arg completion
        let result = cmd.get_completions(&ctx, "fi", None).unwrap();
        assert_eq!(result.values, vec!["file1.txt", "file2.txt"]);

        // Test flag completion
        let result = cmd.get_completions(&ctx, "j", Some("type")).unwrap();
        assert_eq!(result.values, vec!["json"]);
    }

    #[test]
    fn test_flag_with_equals() {
        let cmd = CommandBuilder::new("test")
            .flag(Flag::new("output").value_type(FlagType::String))
            .run(|ctx| {
                assert_eq!(
                    ctx.flag("output"),
                    Some(&"/path/with=equals.txt".to_string())
                );
                Ok(())
            })
            .build();

        cmd.execute(vec!["--output=/path/with=equals.txt".to_string()])
            .unwrap();
    }

    #[test]
    fn test_help_flag() {
        let cmd = CommandBuilder::new("test")
            .short("Test command")
            .long("This is a test command")
            .flag(
                Flag::new("verbose")
                    .short('v')
                    .usage("Enable verbose output"),
            )
            .build();

        // Test --help
        let result = cmd.execute(vec!["--help".to_string()]);
        assert!(result.is_ok());

        // Test -h
        let result = cmd.execute(vec!["-h".to_string()]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_subcommand_help() {
        let subcmd = CommandBuilder::new("sub")
            .short("Subcommand")
            .flag(Flag::new("subflag").usage("A flag for the subcommand"))
            .build();

        let cmd = CommandBuilder::new("main")
            .flag(Flag::new("global").usage("A global flag"))
            .subcommand(subcmd)
            .build();

        // Test help on subcommand
        let result = cmd.execute(vec!["sub".to_string(), "--help".to_string()]);
        assert!(result.is_ok());
    }
}