click-rs 1.0.2

A Rust port of Python's Click library for creating command-line interfaces
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
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
//! Command groups for click-rs.
//!
//! This module provides the [`Group`] struct, which is a command that contains
//! and dispatches to subcommands. Groups can be nested to create hierarchical
//! command-line interfaces.
//!
//! # Reference
//!
//! Based on Python Click's `core.py:Group` class (line 1503+).
//!
//! # Example
//!
//! ```
//! use click::group::{Group, CommandLike};
//! use click::command::Command;
//! use click::context::Context;
//!
//! let cli = Group::new("cli")
//!     .help("A sample CLI application")
//!     .command(
//!         Command::new("init")
//!             .help("Initialize the project")
//!             .callback(|_ctx| {
//!                 println!("Initializing...");
//!                 Ok(())
//!             })
//!             .build()
//!     )
//!     .command(
//!         Command::new("build")
//!             .help("Build the project")
//!             .callback(|_ctx| {
//!                 println!("Building...");
//!                 Ok(())
//!             })
//!             .build()
//!     )
//!     .build();
//!
//! assert_eq!(cli.list_commands().len(), 2);
//! ```

use std::any::Any;
use std::collections::HashMap;
use std::sync::Arc;

use crate::argument::Argument;
use crate::command::{Command, CommandBuilder, CommandCallback};
use crate::context::{get_current_context, pop_context, push_context, Context, ContextBuilder};
use crate::error::ClickError;
use crate::option::ClickOption;
use crate::parameter::Parameter;

// =============================================================================
// CommandLike Trait
// =============================================================================

/// Shared interface for Command and Group.
///
/// This trait provides a common interface that both [`Command`] and [`Group`]
/// implement, allowing them to be used interchangeably in many contexts.
pub trait CommandLike: Send + Sync {
    /// Get the name of this command.
    fn name(&self) -> Option<&str>;

    /// Create a context for executing this command.
    ///
    /// # Arguments
    ///
    /// * `info_name` - The name to display in help/usage
    /// * `args` - The arguments to parse
    /// * `parent` - Optional parent context for nested commands
    fn make_context(
        &self,
        info_name: &str,
        args: Vec<String>,
        parent: Option<Arc<Context>>,
    ) -> Result<Context, ClickError>;

    /// Invoke the command with the given context.
    fn invoke(&self, ctx: &Context) -> Result<(), ClickError>;

    /// Main entry point - make context, parse args, and invoke.
    fn main(&self, args: Vec<String>) -> Result<(), ClickError>;

    /// Get the full help text for this command.
    fn get_help(&self, ctx: &Context) -> String;

    /// Get the short help text for command listings.
    fn get_short_help(&self) -> String;

    /// Check if this command is hidden from help output.
    fn is_hidden(&self) -> bool;

    /// Get the usage line for this command.
    fn get_usage(&self, ctx: &Context) -> String;

    /// Convert to Any for downcasting.
    fn as_any(&self) -> &dyn Any;
}

// =============================================================================
// CommandLike impl for Command
// =============================================================================

impl CommandLike for Command {
    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn make_context(
        &self,
        info_name: &str,
        args: Vec<String>,
        parent: Option<Arc<Context>>,
    ) -> Result<Context, ClickError> {
        Command::make_context(self, info_name, args, parent)
    }

    fn invoke(&self, ctx: &Context) -> Result<(), ClickError> {
        Command::invoke(self, ctx)
    }

    fn main(&self, args: Vec<String>) -> Result<(), ClickError> {
        Command::main(self, args)
    }

    fn get_help(&self, ctx: &Context) -> String {
        Command::get_help(self, ctx)
    }

    fn get_short_help(&self) -> String {
        Command::get_short_help(self)
    }

    fn is_hidden(&self) -> bool {
        self.hidden
    }

    fn get_usage(&self, ctx: &Context) -> String {
        Command::get_usage(self, ctx)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// ResultCallback Type
// =============================================================================

/// Type for result callbacks that process subcommand return values.
///
/// The callback receives the context and a vector of return values from
/// subcommand invocations. In chain mode, this will contain values from
/// all chained commands; otherwise, it will contain a single value.
pub type ResultCallback =
    Box<dyn Fn(&Context, Vec<Box<dyn Any + Send + Sync>>) -> Result<(), ClickError> + Send + Sync>;

// =============================================================================
// Group Struct
// =============================================================================

/// A command group that contains and dispatches to subcommands.
///
/// Groups are the primary way to organize CLI applications with multiple
/// commands. They can be nested to create complex command hierarchies.
///
/// # Features
///
/// - Subcommand registration and dispatch
/// - Optional group callback (runs before subcommand)
/// - Chain mode for executing multiple subcommands
/// - Automatic help generation with command listing
///
/// # Example
///
/// ```
/// use click::group::Group;
/// use click::command::Command;
///
/// let cli = Group::new("myapp")
///     .help("My application")
///     .invoke_without_command(true)
///     .callback(|_ctx| {
///         println!("No subcommand provided");
///         Ok(())
///     })
///     .command(
///         Command::new("hello")
///             .help("Say hello")
///             .build()
///     )
///     .build();
/// ```
pub struct Group {
    /// The underlying command (for the group's own options/arguments).
    pub command: Command,

    /// Registered subcommands (name -> Command or Group).
    pub commands: HashMap<String, Arc<dyn CommandLike>>,

    /// Alias metadata for commands registered through the Group/GroupBuilder APIs.
    ///
    /// This tracks which registered names (keys in `commands`) point at the same underlying
    /// command object, so callers can distinguish:
    /// - canonical command name (`command.name()`)
    /// - registered name (key in the parent group)
    /// - other aliases (other keys mapping to the same command)
    command_ids_by_name: HashMap<String, usize>,
    command_aliases_by_id: HashMap<usize, Vec<String>>,
    next_command_id: usize,

    /// Whether to execute multiple subcommands in sequence.
    pub chain: bool,

    /// Whether to invoke the group callback even if no subcommand is provided.
    pub invoke_without_command: bool,

    /// Optional callback to process subcommand results.
    pub result_callback: Option<ResultCallback>,

    /// Whether a subcommand is required (error if not provided).
    ///
    /// Defaults to `true` unless `invoke_without_command` is `true`.
    pub subcommand_required: bool,

    /// The metavar to show for subcommands in usage.
    pub subcommand_metavar: String,
}

impl std::fmt::Debug for Group {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Group")
            .field("command", &self.command)
            .field(
                "commands",
                &format!("<{} subcommands>", self.commands.len()),
            )
            .field("chain", &self.chain)
            .field("invoke_without_command", &self.invoke_without_command)
            .field("subcommand_required", &self.subcommand_required)
            .field("subcommand_metavar", &self.subcommand_metavar)
            .finish()
    }
}

impl Default for Group {
    fn default() -> Self {
        Self {
            command: Command::default(),
            commands: HashMap::new(),
            command_ids_by_name: HashMap::new(),
            command_aliases_by_id: HashMap::new(),
            next_command_id: 0,
            chain: false,
            invoke_without_command: false,
            result_callback: None,
            subcommand_required: true,
            subcommand_metavar: "COMMAND [ARGS]...".to_string(),
        }
    }
}

impl Group {
    /// Create a new group builder with the given name.
    ///
    /// # Example
    ///
    /// ```
    /// use click::group::Group;
    ///
    /// let group = Group::new("mygroup")
    ///     .help("My command group")
    ///     .build();
    /// ```
    #[allow(clippy::new_ret_no_self)]
    pub fn new(name: &str) -> GroupBuilder {
        GroupBuilder::new(name)
    }

    /// Add a subcommand to this group.
    ///
    /// If `name` is provided, it overrides the command's own name.
    ///
    /// # Example
    ///
    /// ```
    /// use click::group::Group;
    /// use click::command::Command;
    ///
    /// let mut group = Group::new("cli").build();
    /// group.add_command(Command::new("hello").build(), None);
    /// group.add_command(Command::new("greet").build(), Some("hi")); // registered as "hi"
    ///
    /// assert!(group.get_command("hello").is_some());
    /// assert!(group.get_command("hi").is_some());
    /// assert!(group.get_command("greet").is_none()); // not found by original name
    /// ```
    pub fn add_command(&mut self, cmd: impl CommandLike + 'static, name: Option<&str>) {
        let cmd_name = name
            .map(|s| s.to_string())
            .or_else(|| cmd.name().map(|s| s.to_string()));

        if let Some(n) = cmd_name {
            self.add_command_shared(Arc::new(cmd), Some(&n));
        }
    }

    /// Add a subcommand to this group using a shared command object.
    ///
    /// This makes it possible to register the same command under multiple names (aliases)
    /// while still being able to query alias metadata.
    pub fn add_command_shared(&mut self, cmd: Arc<dyn CommandLike>, name: Option<&str>) {
        let cmd_name = name
            .map(|s| s.to_string())
            .or_else(|| cmd.name().map(|s| s.to_string()));

        let Some(name) = cmd_name else { return };

        // If we're replacing an existing name, unlink it from prior alias metadata.
        if let Some(old_id) = self.command_ids_by_name.get(&name).copied() {
            if let Some(names) = self.command_aliases_by_id.get_mut(&old_id) {
                names.retain(|n| n != &name);
            }
        }

        // Find an existing id for this command (if it's already registered under another name).
        let existing_id = self.commands.iter().find_map(|(n, existing)| {
            if Arc::ptr_eq(existing, &cmd) {
                self.command_ids_by_name.get(n).copied()
            } else {
                None
            }
        });

        let id = existing_id.unwrap_or_else(|| {
            let id = self.next_command_id;
            self.next_command_id += 1;
            id
        });

        self.command_ids_by_name.insert(name.clone(), id);
        self.command_aliases_by_id
            .entry(id)
            .or_insert_with(Vec::new)
            .push(name.clone());

        // Keep alias lists deterministic.
        if let Some(names) = self.command_aliases_by_id.get_mut(&id) {
            names.sort();
            names.dedup();
        }

        self.commands.insert(name, cmd);
    }

    /// Get a subcommand by name.
    ///
    /// # Example
    ///
    /// ```
    /// use click::group::Group;
    /// use click::command::Command;
    ///
    /// let group = Group::new("cli")
    ///     .command(Command::new("hello").build())
    ///     .build();
    ///
    /// assert!(group.get_command("hello").is_some());
    /// assert!(group.get_command("unknown").is_none());
    /// ```
    pub fn get_command(&self, name: &str) -> Option<&dyn CommandLike> {
        self.commands.get(name).map(|c| c.as_ref())
    }

    /// List all command registrations as `(registered_name, command)` pairs.
    ///
    /// This is useful when you need both the registered key and the canonical name
    /// stored inside the command itself (`command.name()`).
    pub fn list_command_entries(&self) -> Vec<(String, &dyn CommandLike)> {
        let mut names: Vec<&String> = self.commands.keys().collect();
        names.sort();
        names
            .into_iter()
            .filter_map(|name| {
                self.commands
                    .get(name)
                    .map(|cmd| (name.clone(), cmd.as_ref()))
            })
            .collect()
    }

    /// List other registered names (aliases) that map to the same command.
    ///
    /// Returns an empty list if the command is not found or if it has no aliases.
    pub fn list_command_aliases(&self, name: &str) -> Vec<String> {
        let Some(id) = self.command_ids_by_name.get(name).copied() else {
            return Vec::new();
        };
        let Some(names) = self.command_aliases_by_id.get(&id) else {
            return Vec::new();
        };

        let mut out: Vec<String> = names
            .iter()
            .filter(|n| n.as_str() != name)
            .cloned()
            .collect();
        out.sort();
        out.dedup();
        out
    }

    /// List all subcommand names (sorted alphabetically).
    ///
    /// # Example
    ///
    /// ```
    /// use click::group::Group;
    /// use click::command::Command;
    ///
    /// let group = Group::new("cli")
    ///     .command(Command::new("build").build())
    ///     .command(Command::new("init").build())
    ///     .command(Command::new("deploy").build())
    ///     .build();
    ///
    /// let commands = group.list_commands();
    /// assert_eq!(commands, vec!["build", "deploy", "init"]);
    /// ```
    pub fn list_commands(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.commands.keys().map(|s| s.as_str()).collect();
        names.sort();
        names
    }

    /// Resolve a command from arguments.
    ///
    /// Returns the command name, the command, and the remaining arguments.
    /// Returns an error if the command is not found (unless in resilient parsing mode).
    ///
    /// # Arguments
    ///
    /// * `ctx` - The current context
    /// * `args` - The arguments to parse
    pub fn resolve_command<'a>(
        &'a self,
        ctx: &Context,
        args: &[String],
    ) -> Result<Option<(&'a str, &'a dyn CommandLike, Vec<String>)>, ClickError> {
        if args.is_empty() {
            return Ok(None);
        }

        let cmd_name = &args[0];
        let remaining = args[1..].to_vec();

        // Try to find the command
        if let Some(cmd) = self.commands.get(cmd_name) {
            // Find the key that matches (for returning &str with correct lifetime)
            for (key, _) in &self.commands {
                if key == cmd_name {
                    return Ok(Some((key.as_str(), cmd.as_ref(), remaining)));
                }
            }
        }

        // Command not found
        if ctx.resilient_parsing() {
            return Ok(None);
        }

        // Check if the first arg looks like an option
        if cmd_name.starts_with('-') {
            // It's an option, not a command name - let the parser handle it
            return Ok(None);
        }

        Err(ClickError::usage(format!(
            "No such command '{}'.",
            cmd_name
        )))
    }

    /// Format the commands section for help output.
    ///
    /// Returns a formatted string listing all visible subcommands.
    pub fn format_commands(&self, _ctx: &Context) -> String {
        let mut lines = Vec::new();

        // Get visible commands (not hidden)
        let visible_cmds: Vec<(&str, &dyn CommandLike)> = self
            .list_commands()
            .into_iter()
            .filter_map(|name| {
                self.get_command(name)
                    .filter(|cmd| !cmd.is_hidden())
                    .map(|cmd| (name, cmd))
            })
            .collect();

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

        // Calculate the max command name width
        let max_width = visible_cmds
            .iter()
            .map(|(name, _)| name.len())
            .max()
            .unwrap_or(0);

        lines.push("Commands:".to_string());

        for (name, cmd) in visible_cmds {
            let help = cmd.get_short_help();
            let padding = max_width - name.len() + 2;
            lines.push(format!(
                "  {}{:padding$}{}",
                name,
                "",
                help,
                padding = padding
            ));
        }

        lines.join("\n")
    }

    /// Get the usage line including the subcommand metavar.
    fn get_usage_with_subcommand(&self, ctx: &Context) -> String {
        let base_usage = self.command.get_usage(ctx);
        format!("{} {}", base_usage, self.subcommand_metavar)
    }

    /// Get help text including the subcommand listing.
    fn get_help_with_commands(&self, ctx: &Context) -> String {
        let mut parts = Vec::new();

        // Usage line with subcommand metavar
        parts.push(self.get_usage_with_subcommand(ctx));

        // Help text
        if let Some(ref help) = self.command.help {
            let text = help.lines().next().unwrap_or("");
            if !text.is_empty() {
                parts.push(String::new());
                let help_text = if let Some(ref dep) = self.command.deprecated {
                    if dep.is_empty() {
                        format!("{}  (DEPRECATED)", text)
                    } else {
                        format!("{}  (DEPRECATED: {})", text, dep)
                    }
                } else {
                    text.to_string()
                };
                parts.push(format!("  {}", help_text));
            }
        }

        // Options section
        let opt_records: Vec<(String, String)> = self
            .command
            .options
            .iter()
            .filter_map(|opt| opt.get_help_record())
            .collect();

        let help_opt = self.command.get_help_option(ctx);
        let help_record = help_opt.as_ref().and_then(|h| h.get_help_record());

        if !opt_records.is_empty() || help_record.is_some() {
            parts.push(String::new());
            parts.push("Options:".to_string());

            for (opt_str, help) in &opt_records {
                parts.push(format!("  {}  {}", opt_str, help));
            }
            if let Some((opt_str, help)) = help_record {
                parts.push(format!("  {}  {}", opt_str, help));
            }
        }

        // Commands section
        let commands_section = self.format_commands(ctx);
        if !commands_section.is_empty() {
            parts.push(String::new());
            parts.push(commands_section);
        }

        // Epilog
        if let Some(ref epilog) = self.command.epilog {
            parts.push(String::new());
            parts.push(epilog.clone());
        }

        parts.join("\n")
    }
}

// =============================================================================
// CommandLike impl for Group
// =============================================================================

impl CommandLike for Group {
    fn name(&self) -> Option<&str> {
        self.command.name.as_deref()
    }

    fn make_context(
        &self,
        info_name: &str,
        args: Vec<String>,
        parent: Option<Arc<Context>>,
    ) -> Result<Context, ClickError> {
        // Groups need to allow extra args for subcommand dispatch
        let mut builder = ContextBuilder::new()
            .info_name(info_name)
            .allow_extra_args(true)
            .allow_interspersed_args(false);

        if let Some(parent) = parent {
            builder = builder.parent(parent);
        }

        let mut ctx = builder.build();

        // Parse the group's own arguments
        self.command.parse_args(&mut ctx, args)?;

        Ok(ctx)
    }

    fn invoke(&self, ctx: &Context) -> Result<(), ClickError> {
        // Get the remaining args after parsing group options
        let args = ctx.args().to_vec();

        // Helper function to process results through result_callback
        let process_result = |result_callback: &Option<ResultCallback>,
                              ctx: &Context,
                              results: Vec<Box<dyn Any + Send + Sync>>|
         -> Result<(), ClickError> {
            if let Some(ref callback) = result_callback {
                callback(ctx, results)?;
            }
            Ok(())
        };

        // Get the parent context Arc from the thread-local stack for proper inheritance
        let parent_arc = get_current_context();

        // Resolve first subcommand to check if there's any
        let resolved = self.resolve_command(ctx, &args)?;

        if resolved.is_none() {
            // No subcommand provided
            if self.invoke_without_command {
                // Invoke group callback and process result
                let group_result = self.command.invoke(ctx);
                if group_result.is_ok() {
                    // For invoke_without_command, result is empty list in chain mode
                    // or the group's return value (which we don't capture) otherwise
                    let results: Vec<Box<dyn Any + Send + Sync>> = if self.chain {
                        Vec::new()
                    } else {
                        // In non-chain mode, we pass an empty result since Rust callbacks
                        // return Result<(), ClickError> not arbitrary values
                        Vec::new()
                    };
                    process_result(&self.result_callback, ctx, results)?;
                }
                return group_result;
            } else if self.subcommand_required && !ctx.resilient_parsing() {
                return Err(ClickError::usage("Missing command."));
            } else {
                return Ok(());
            }
        }

        // We have at least one subcommand
        if !self.chain {
            // Non-chain mode: invoke single subcommand
            let (cmd_name, cmd, remaining) = resolved.unwrap();

            // Note: Setting invoked_subcommand requires interior mutability in Context.
            // The Context struct uses RefCell for close_callbacks but not for invoked_subcommand.
            // For now, we skip setting it; a future refactor could add RefCell<Option<String>>.

            // Invoke group callback first (if present)
            if self.command.callback.is_some() {
                self.command.invoke(ctx)?;
            }

            // Create subcommand context with proper parent inheritance.
            // Exit{0} here means an eager option (--help) fired during the
            // subcommand's own parsing: mirror Command::main and render THAT
            // subcommand's help with its full command path, instead of letting
            // the exit bubble up and terminate silently.
            let sub_ctx = match cmd.make_context(cmd_name, remaining, parent_arc) {
                Ok(sub_ctx) => sub_ctx,
                Err(ClickError::Exit { code: 0 }) => {
                    let help_ctx = ContextBuilder::new()
                        .info_name(format!("{} {}", ctx.command_path(), cmd_name))
                        .build();
                    let help_text = if let Some(renderer) = ctx.help_renderer() {
                        renderer(cmd, &help_ctx)
                    } else {
                        cmd.get_help(&help_ctx)
                    };
                    println!("{}", help_text);
                    return Ok(());
                }
                Err(e) => return Err(e),
            };

            // Push and invoke subcommand
            let sub_ctx_arc = Arc::new(sub_ctx);
            push_context(Arc::clone(&sub_ctx_arc));
            let result = cmd.invoke(&sub_ctx_arc);
            pop_context();

            // Close subcommand context
            sub_ctx_arc.close();

            // Process result callback if set
            if result.is_ok() {
                // In non-chain mode, result is a single value (empty since we don't capture return)
                process_result(&self.result_callback, ctx, Vec::new())?;
            }

            result
        } else {
            // Chain mode: invoke multiple subcommands in sequence
            // Note: In Python Click, invoked_subcommand is set to "*" in chain mode

            // Invoke group callback first (if present)
            if self.command.callback.is_some() {
                self.command.invoke(ctx)?;
            }

            // Collect all subcommand contexts first (like Python Click does)
            let mut contexts: Vec<(Arc<Context>, &dyn CommandLike)> = Vec::new();
            let mut remaining_args = args;

            while !remaining_args.is_empty() {
                let resolved = self.resolve_command(ctx, &remaining_args)?;
                match resolved {
                    Some((cmd_name, cmd, rest)) => {
                        // In chain mode, subcommands allow extra args and no interspersed args
                        // so remaining tokens are passed to the next command resolution.
                        // We create the context with chain mode settings, overriding the command's defaults.
                        let mut sub_ctx = ContextBuilder::new()
                            .info_name(cmd_name)
                            .allow_extra_args(true) // Chain mode: allow extra args for next cmd
                            .allow_interspersed_args(false) // Chain mode: no interspersed
                            .parent(
                                parent_arc
                                    .clone()
                                    .unwrap_or_else(|| Arc::new(Context::default())),
                            )
                            .build();

                        // Parse args using the command (this populates the context).
                        // Exit{0} = an eager --help fired for this chain member:
                        // render its help (full path) instead of a silent exit.
                        let parse_result =
                            if let Some(command) = cmd.as_any().downcast_ref::<Command>() {
                                command.parse_args(&mut sub_ctx, rest)
                            } else if let Some(group) = cmd.as_any().downcast_ref::<Group>() {
                                // For nested groups, use make_context which handles group-specific parsing
                                group.make_context(cmd_name, rest, parent_arc.clone()).map(
                                    |nested_ctx| {
                                        sub_ctx = nested_ctx;
                                    },
                                )
                            } else {
                                // Fallback: use make_context (may error on extra args)
                                cmd.make_context(cmd_name, rest, parent_arc.clone()).map(
                                    |fallback_ctx| {
                                        sub_ctx = fallback_ctx;
                                    },
                                )
                            };
                        match parse_result {
                            Ok(()) => {}
                            Err(ClickError::Exit { code: 0 }) => {
                                let help_ctx = ContextBuilder::new()
                                    .info_name(format!("{} {}", ctx.command_path(), cmd_name))
                                    .build();
                                let help_text = if let Some(renderer) = ctx.help_renderer() {
                                    renderer(cmd, &help_ctx)
                                } else {
                                    cmd.get_help(&help_ctx)
                                };
                                println!("{}", help_text);
                                return Ok(());
                            }
                            Err(e) => return Err(e),
                        }

                        // The subcommand's unparsed args become input for next command
                        remaining_args = sub_ctx.args().to_vec();

                        contexts.push((Arc::new(sub_ctx), cmd));
                    }
                    None => {
                        // No more commands found - remaining args are truly extra
                        // In chain mode, we don't error on extra args that look like commands
                        // but couldn't be resolved. However, if they look like options,
                        // that's an error (unless resilient_parsing)
                        if !remaining_args.is_empty()
                            && remaining_args[0].starts_with('-')
                            && !ctx.resilient_parsing()
                        {
                            return Err(ClickError::usage(format!(
                                "No such option: {}",
                                remaining_args[0]
                            )));
                        }
                        break;
                    }
                }
            }

            // Invoke all subcommands and collect results
            let mut results: Vec<Box<dyn Any + Send + Sync>> = Vec::new();
            for (sub_ctx_arc, cmd) in contexts {
                push_context(Arc::clone(&sub_ctx_arc));
                let result = cmd.invoke(&sub_ctx_arc);
                pop_context();
                sub_ctx_arc.close();

                // If any subcommand fails, propagate the error
                result?;

                // We don't capture return values since Rust callbacks return Result<(), ClickError>
                // In a more advanced implementation, callbacks could return arbitrary values
                results.push(Box::new(()));
            }

            // Process result callback with collected results
            process_result(&self.result_callback, ctx, results)?;

            Ok(())
        }
    }

    #[allow(clippy::arc_with_non_send_sync)]
    fn main(&self, args: Vec<String>) -> Result<(), ClickError> {
        let prog_name = self.command.name.clone().unwrap_or_else(|| {
            std::env::args()
                .next()
                .unwrap_or_else(|| "program".to_string())
        });

        let args_for_eager = args.clone();

        // Try to make context - this may fail early for --help or --version
        let ctx_result = self.make_context(&prog_name, args, None);

        match ctx_result {
            Ok(ctx) => {
                let ctx = Arc::new(ctx);

                // Push context onto thread-local stack
                push_context(Arc::clone(&ctx));

                // Invoke the group
                let result = self.invoke(&ctx);

                // Pop context
                pop_context();

                // Run close callbacks
                ctx.close();

                result
            }
            Err(ClickError::Exit { code: 0 }) => {
                // Help or version (or other eager exits) was requested.
                //
                // Version is implemented as an eager option that signals Exit(0) and stores the
                // output string in the option metavar with a reserved prefix.
                if let Some(version_output) =
                    self.command.get_version_output_from_args(&args_for_eager)
                {
                    println!("{}", version_output);
                    return Ok(());
                }

                // Default: print help.
                // Create a minimal context for help formatting.
                let ctx = ContextBuilder::new().info_name(&prog_name).build();
                println!("{}", self.get_help(&ctx));
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    fn get_help(&self, ctx: &Context) -> String {
        self.get_help_with_commands(ctx)
    }

    fn get_short_help(&self) -> String {
        self.command.get_short_help()
    }

    fn is_hidden(&self) -> bool {
        self.command.hidden
    }

    fn get_usage(&self, ctx: &Context) -> String {
        self.get_usage_with_subcommand(ctx)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// CommandCollection
// =============================================================================

/// A group-like command that merges commands from multiple groups.
///
/// This is the click-rs equivalent of Python Click's `CommandCollection`.
/// Commands are resolved by searching the base group first, then each source
/// group in insertion order.
///
/// Only the base group's parameters (options/arguments/callback/help) are used.
#[derive(Debug)]
pub struct CommandCollection {
    /// The base group providing parameters and help formatting.
    pub base: Group,

    /// Additional groups to source subcommands from.
    pub sources: Vec<Group>,
}

impl CommandCollection {
    /// Create a new `CommandCollection` builder with the given base name.
    ///
    /// The base group can register its own subcommands via `.command(...)`.
    #[allow(clippy::new_ret_no_self)]
    pub fn new(name: &str) -> CommandCollectionBuilder {
        CommandCollectionBuilder::new(name)
    }

    /// Add a source group.
    pub fn add_source(&mut self, group: Group) {
        self.sources.push(group);
    }

    /// Get a subcommand by name, searching base first then sources.
    pub fn get_command(&self, name: &str) -> Option<&dyn CommandLike> {
        if let Some(cmd) = self.base.get_command(name) {
            return Some(cmd);
        }
        for src in &self.sources {
            if let Some(cmd) = src.get_command(name) {
                return Some(cmd);
            }
        }
        None
    }

    /// List all unique subcommand names from base + sources, sorted.
    pub fn list_commands(&self) -> Vec<String> {
        let mut names: std::collections::HashSet<String> =
            self.base.commands.keys().cloned().collect();

        for src in &self.sources {
            for name in src.commands.keys() {
                names.insert(name.clone());
            }
        }

        let mut out: Vec<String> = names.into_iter().collect();
        out.sort();
        out
    }

    fn resolve_command<'a>(
        &'a self,
        ctx: &Context,
        args: &[String],
    ) -> Result<Option<(String, &'a dyn CommandLike, Vec<String>)>, ClickError> {
        if args.is_empty() {
            return Ok(None);
        }

        let cmd_name = &args[0];
        let remaining = args[1..].to_vec();

        if let Some(cmd) = self.base.commands.get(cmd_name) {
            return Ok(Some((cmd_name.clone(), cmd.as_ref(), remaining)));
        }
        for src in &self.sources {
            if let Some(cmd) = src.commands.get(cmd_name) {
                return Ok(Some((cmd_name.clone(), cmd.as_ref(), remaining)));
            }
        }

        if ctx.resilient_parsing() {
            return Ok(None);
        }
        if cmd_name.starts_with('-') {
            return Ok(None);
        }

        Err(ClickError::usage(format!(
            "No such command '{}'.",
            cmd_name
        )))
    }

    fn format_commands(&self, _ctx: &Context) -> String {
        let mut visible_cmds: Vec<(String, &dyn CommandLike)> = self
            .list_commands()
            .into_iter()
            .filter_map(|name| {
                self.get_command(&name)
                    .filter(|cmd| !cmd.is_hidden())
                    .map(|cmd| (name, cmd))
            })
            .collect();

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

        visible_cmds.sort_by(|a, b| a.0.cmp(&b.0));

        let max_width = visible_cmds
            .iter()
            .map(|(name, _)| name.len())
            .max()
            .unwrap_or(0);

        let mut lines = Vec::new();
        lines.push("Commands:".to_string());

        for (name, cmd) in visible_cmds {
            let help = cmd.get_short_help();
            let padding = max_width - name.len() + 2;
            lines.push(format!(
                "  {}{:padding$}{}",
                name,
                "",
                help,
                padding = padding
            ));
        }

        lines.join("\n")
    }

    fn get_usage_with_subcommand(&self, ctx: &Context) -> String {
        let base_usage = self.base.command.get_usage(ctx);
        format!("{} {}", base_usage, self.base.subcommand_metavar)
    }

    fn get_help_with_commands(&self, ctx: &Context) -> String {
        let mut parts = Vec::new();

        parts.push(self.get_usage_with_subcommand(ctx));

        if let Some(ref help) = self.base.command.help {
            let text = help.lines().next().unwrap_or("");
            if !text.is_empty() {
                parts.push(String::new());
                let help_text = if let Some(ref dep) = self.base.command.deprecated {
                    if dep.is_empty() {
                        format!("{}  (DEPRECATED)", text)
                    } else {
                        format!("{}  (DEPRECATED: {})", text, dep)
                    }
                } else {
                    text.to_string()
                };
                parts.push(format!("  {}", help_text));
            }
        }

        let opt_records: Vec<(String, String)> = self
            .base
            .command
            .options
            .iter()
            .filter_map(|opt| opt.get_help_record())
            .collect();

        let help_opt = self.base.command.get_help_option(ctx);
        let help_record = help_opt.as_ref().and_then(|h| h.get_help_record());

        if !opt_records.is_empty() || help_record.is_some() {
            parts.push(String::new());
            parts.push("Options:".to_string());

            for (opt_str, help) in &opt_records {
                parts.push(format!("  {}  {}", opt_str, help));
            }
            if let Some((opt_str, help)) = help_record {
                parts.push(format!("  {}  {}", opt_str, help));
            }
        }

        let commands_section = self.format_commands(ctx);
        if !commands_section.is_empty() {
            parts.push(String::new());
            parts.push(commands_section);
        }

        if let Some(ref epilog) = self.base.command.epilog {
            parts.push(String::new());
            parts.push(epilog.clone());
        }

        parts.join("\n")
    }
}

impl CommandLike for CommandCollection {
    fn name(&self) -> Option<&str> {
        self.base.command.name.as_deref()
    }

    fn make_context(
        &self,
        info_name: &str,
        args: Vec<String>,
        parent: Option<Arc<Context>>,
    ) -> Result<Context, ClickError> {
        let mut builder = ContextBuilder::new()
            .info_name(info_name)
            .allow_extra_args(true)
            .allow_interspersed_args(false);

        if let Some(parent) = parent {
            builder = builder.parent(parent);
        }

        let mut ctx = builder.build();
        self.base.command.parse_args(&mut ctx, args)?;
        Ok(ctx)
    }

    fn invoke(&self, ctx: &Context) -> Result<(), ClickError> {
        let args = ctx.args().to_vec();

        let process_result = |result_callback: &Option<ResultCallback>,
                              ctx: &Context,
                              results: Vec<Box<dyn Any + Send + Sync>>|
         -> Result<(), ClickError> {
            if let Some(ref callback) = result_callback {
                callback(ctx, results)?;
            }
            Ok(())
        };

        let parent_arc = get_current_context();
        let resolved = self.resolve_command(ctx, &args)?;

        if resolved.is_none() {
            if self.base.invoke_without_command {
                let group_result = self.base.command.invoke(ctx);
                if group_result.is_ok() {
                    process_result(&self.base.result_callback, ctx, Vec::new())?;
                }
                return group_result;
            } else if self.base.subcommand_required && !ctx.resilient_parsing() {
                return Err(ClickError::usage("Missing command."));
            } else {
                return Ok(());
            }
        }

        if !self.base.chain {
            let (cmd_name, cmd, remaining) = resolved.unwrap();

            if self.base.command.callback.is_some() {
                self.base.command.invoke(ctx)?;
            }

            let sub_ctx = cmd.make_context(&cmd_name, remaining, parent_arc)?;

            let sub_ctx_arc = Arc::new(sub_ctx);
            push_context(Arc::clone(&sub_ctx_arc));
            let result = cmd.invoke(&sub_ctx_arc);
            pop_context();
            sub_ctx_arc.close();

            if result.is_ok() {
                process_result(&self.base.result_callback, ctx, Vec::new())?;
            }

            result
        } else {
            if self.base.command.callback.is_some() {
                self.base.command.invoke(ctx)?;
            }

            let mut contexts: Vec<(Arc<Context>, &dyn CommandLike)> = Vec::new();
            let mut remaining_args = args;

            while !remaining_args.is_empty() {
                let resolved = self.resolve_command(ctx, &remaining_args)?;
                match resolved {
                    Some((cmd_name, cmd, rest)) => {
                        let mut sub_ctx = ContextBuilder::new()
                            .info_name(&cmd_name)
                            .allow_extra_args(true)
                            .allow_interspersed_args(false)
                            .parent(
                                parent_arc
                                    .clone()
                                    .unwrap_or_else(|| Arc::new(Context::default())),
                            )
                            .build();

                        if let Some(command) = cmd.as_any().downcast_ref::<Command>() {
                            command.parse_args(&mut sub_ctx, rest)?;
                        } else if let Some(group) = cmd.as_any().downcast_ref::<Group>() {
                            sub_ctx = group.make_context(&cmd_name, rest, parent_arc.clone())?;
                        } else if let Some(collection) =
                            cmd.as_any().downcast_ref::<CommandCollection>()
                        {
                            sub_ctx =
                                collection.make_context(&cmd_name, rest, parent_arc.clone())?;
                        } else {
                            sub_ctx = cmd.make_context(&cmd_name, rest, parent_arc.clone())?;
                        }

                        remaining_args = sub_ctx.args().to_vec();
                        contexts.push((Arc::new(sub_ctx), cmd));
                    }
                    None => {
                        if !remaining_args.is_empty()
                            && remaining_args[0].starts_with('-')
                            && !ctx.resilient_parsing()
                        {
                            return Err(ClickError::usage(format!(
                                "No such option: {}",
                                remaining_args[0]
                            )));
                        }
                        break;
                    }
                }
            }

            let mut results: Vec<Box<dyn Any + Send + Sync>> = Vec::new();
            for (sub_ctx_arc, cmd) in contexts {
                push_context(Arc::clone(&sub_ctx_arc));
                let result = cmd.invoke(&sub_ctx_arc);
                pop_context();
                sub_ctx_arc.close();
                result?;
                results.push(Box::new(()));
            }

            process_result(&self.base.result_callback, ctx, results)?;
            Ok(())
        }
    }

    #[allow(clippy::arc_with_non_send_sync)]
    fn main(&self, args: Vec<String>) -> Result<(), ClickError> {
        let prog_name = self.base.command.name.clone().unwrap_or_else(|| {
            std::env::args()
                .next()
                .unwrap_or_else(|| "program".to_string())
        });

        let args_for_eager = args.clone();

        // Try to make context - this may fail early for --help or --version
        let ctx_result = self.make_context(&prog_name, args, None);

        match ctx_result {
            Ok(ctx) => {
                let ctx = Arc::new(ctx);

                push_context(Arc::clone(&ctx));
                let result = self.invoke(&ctx);
                pop_context();
                ctx.close();
                result
            }
            Err(ClickError::Exit { code: 0 }) => {
                // Help or version (or other eager exits) was requested.
                if let Some(version_output) = self
                    .base
                    .command
                    .get_version_output_from_args(&args_for_eager)
                {
                    println!("{}", version_output);
                    return Ok(());
                }

                // Default: print help.
                let ctx = ContextBuilder::new().info_name(&prog_name).build();
                println!("{}", self.get_help(&ctx));
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    fn get_help(&self, ctx: &Context) -> String {
        self.get_help_with_commands(ctx)
    }

    fn get_short_help(&self) -> String {
        self.base.command.get_short_help()
    }

    fn is_hidden(&self) -> bool {
        self.base.command.hidden
    }

    fn get_usage(&self, ctx: &Context) -> String {
        self.get_usage_with_subcommand(ctx)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Builder for [`CommandCollection`].
pub struct CommandCollectionBuilder {
    base: GroupBuilder,
    sources: Vec<Group>,
}

impl CommandCollectionBuilder {
    fn new(name: &str) -> Self {
        Self {
            base: GroupBuilder::new(name),
            sources: Vec::new(),
        }
    }

    /// Add a source group.
    pub fn source(mut self, group: Group) -> Self {
        self.sources.push(group);
        self
    }

    /// Add a subcommand to the base group.
    pub fn command(mut self, cmd: impl CommandLike + 'static) -> Self {
        self.base = self.base.command(cmd);
        self
    }

    /// Build the `CommandCollection`.
    pub fn build(self) -> CommandCollection {
        CommandCollection {
            base: self.base.build(),
            sources: self.sources,
        }
    }
}

// =============================================================================
// GroupBuilder
// =============================================================================

/// Builder for creating [`Group`] instances.
///
/// Use [`Group::new`] to create a builder, then chain methods to configure
/// the group, and finally call [`build`](GroupBuilder::build) to create
/// the group.
///
/// # Example
///
/// ```
/// use click::group::Group;
/// use click::command::Command;
///
/// let group = Group::new("cli")
///     .help("My CLI application")
///     .callback(|_ctx| {
///         println!("Group callback");
///         Ok(())
///     })
///     .invoke_without_command(true)
///     .command(Command::new("hello").build())
///     .build();
/// ```
pub struct GroupBuilder {
    name: String,
    callback: Option<CommandCallback>,
    options: Vec<ClickOption>,
    arguments: Vec<Argument>,
    help: Option<String>,
    epilog: Option<String>,
    short_help: Option<String>,
    hidden: bool,
    deprecated: Option<String>,
    commands: HashMap<String, Arc<dyn CommandLike>>,
    command_ids_by_name: HashMap<String, usize>,
    command_aliases_by_id: HashMap<usize, Vec<String>>,
    next_command_id: usize,
    chain: bool,
    invoke_without_command: bool,
    result_callback: Option<ResultCallback>,
    subcommand_required: Option<bool>,
    subcommand_metavar: Option<String>,
    add_help_option: bool,
    help_option: Option<ClickOption>,
    no_args_is_help: Option<bool>,
}

impl GroupBuilder {
    /// Create a new group builder with the given name.
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            callback: None,
            options: Vec::new(),
            arguments: Vec::new(),
            help: None,
            epilog: None,
            short_help: None,
            hidden: false,
            deprecated: None,
            commands: HashMap::new(),
            command_ids_by_name: HashMap::new(),
            command_aliases_by_id: HashMap::new(),
            next_command_id: 0,
            chain: false,
            invoke_without_command: false,
            result_callback: None,
            subcommand_required: None,
            subcommand_metavar: None,
            add_help_option: true,
            help_option: None,
            no_args_is_help: None,
        }
    }

    // -------------------------------------------------------------------------
    // Inherited from Command
    // -------------------------------------------------------------------------

    /// Set the callback function for this group.
    ///
    /// The callback is invoked before subcommand dispatch (or alone if
    /// `invoke_without_command` is true and no subcommand is given).
    pub fn callback<F>(mut self, f: F) -> Self
    where
        F: Fn(&Context) -> Result<(), ClickError> + Send + Sync + 'static,
    {
        self.callback = Some(Box::new(f));
        self
    }

    /// Add an option to this group.
    pub fn option(mut self, opt: ClickOption) -> Self {
        self.options.push(opt);
        self
    }

    /// Add an argument to this group.
    pub fn argument(mut self, arg: Argument) -> Self {
        self.arguments.push(arg);
        self
    }

    /// Set the help text for this group.
    pub fn help(mut self, help: &str) -> Self {
        self.help = Some(help.to_string());
        self
    }

    /// Set the epilog (text shown after help).
    pub fn epilog(mut self, epilog: &str) -> Self {
        self.epilog = Some(epilog.to_string());
        self
    }

    /// Set the short help text for command listings.
    pub fn short_help(mut self, short_help: &str) -> Self {
        self.short_help = Some(short_help.to_string());
        self
    }

    /// Hide this group from help output.
    pub fn hidden(mut self) -> Self {
        self.hidden = true;
        self
    }

    /// Mark this group as deprecated.
    pub fn deprecated(mut self, message: &str) -> Self {
        self.deprecated = Some(message.to_string());
        self
    }

    /// Set whether to add a --help option (default: true).
    pub fn add_help_option(mut self, add: bool) -> Self {
        self.add_help_option = add;
        self
    }

    /// Override the automatically generated help option.
    ///
    /// Setting a custom help option implicitly enables `add_help_option`.
    pub fn help_option(mut self, opt: ClickOption) -> Self {
        self.add_help_option = true;
        self.help_option = Some(opt);
        self
    }

    /// Set whether to show help if no args provided.
    ///
    /// Defaults to the opposite of `invoke_without_command`.
    pub fn no_args_is_help(mut self, value: bool) -> Self {
        self.no_args_is_help = Some(value);
        self
    }

    // -------------------------------------------------------------------------
    // Group-specific
    // -------------------------------------------------------------------------

    /// Add a subcommand to this group.
    ///
    /// # Example
    ///
    /// ```
    /// use click::group::Group;
    /// use click::command::Command;
    ///
    /// let group = Group::new("cli")
    ///     .command(Command::new("hello").build())
    ///     .command(Command::new("goodbye").build())
    ///     .build();
    /// ```
    pub fn command(self, cmd: impl CommandLike + 'static) -> Self {
        self.command_shared(Arc::new(cmd))
    }

    /// Add a subcommand with a specific name (overriding the command's name).
    pub fn command_with_name(self, name: &str, cmd: impl CommandLike + 'static) -> Self {
        self.command_shared_with_name(name, Arc::new(cmd))
    }

    /// Add a shared subcommand to this group.
    ///
    /// This makes it possible to register a single command under multiple names (aliases).
    pub fn command_shared(mut self, cmd: Arc<dyn CommandLike>) -> Self {
        let name = cmd.name().map(|s| s.to_string());
        if let Some(name) = name {
            self = self.command_shared_with_name(&name, cmd);
        }
        self
    }

    /// Add a shared subcommand with a specific registered name.
    pub fn command_shared_with_name(mut self, name: &str, cmd: Arc<dyn CommandLike>) -> Self {
        // If we're replacing an existing name, unlink it from prior alias metadata.
        if let Some(old_id) = self.command_ids_by_name.get(name).copied() {
            if let Some(names) = self.command_aliases_by_id.get_mut(&old_id) {
                names.retain(|n| n != name);
            }
        }

        // Find an existing id for this command (if it's already registered under another name).
        let existing_id = self.commands.iter().find_map(|(n, existing)| {
            if Arc::ptr_eq(existing, &cmd) {
                self.command_ids_by_name.get(n).copied()
            } else {
                None
            }
        });

        let id = existing_id.unwrap_or_else(|| {
            let id = self.next_command_id;
            self.next_command_id += 1;
            id
        });

        self.command_ids_by_name.insert(name.to_string(), id);
        self.command_aliases_by_id
            .entry(id)
            .or_insert_with(Vec::new)
            .push(name.to_string());

        if let Some(names) = self.command_aliases_by_id.get_mut(&id) {
            names.sort();
            names.dedup();
        }

        self.commands.insert(name.to_string(), cmd);
        self
    }

    /// Enable or disable chain mode.
    ///
    /// In chain mode, multiple subcommands can be invoked in sequence:
    /// `cli cmd1 arg1 cmd2 arg2`
    pub fn chain(mut self, chain: bool) -> Self {
        self.chain = chain;
        if chain {
            self.subcommand_metavar =
                Some("COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...".to_string());
        }
        self
    }

    /// Set whether to invoke the group callback without a subcommand.
    ///
    /// If true, the group's callback is invoked even when no subcommand
    /// is provided.
    pub fn invoke_without_command(mut self, value: bool) -> Self {
        self.invoke_without_command = value;
        self
    }

    /// Set whether a subcommand is required.
    ///
    /// If not explicitly set, defaults to the opposite of `invoke_without_command`.
    pub fn subcommand_required(mut self, required: bool) -> Self {
        self.subcommand_required = Some(required);
        self
    }

    /// Set the metavar for subcommands in usage output.
    ///
    /// Default is "COMMAND [ARGS]..." (or "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
    /// in chain mode).
    pub fn subcommand_metavar(mut self, metavar: &str) -> Self {
        self.subcommand_metavar = Some(metavar.to_string());
        self
    }

    /// Set the result callback for processing subcommand results.
    pub fn result_callback<F>(mut self, f: F) -> Self
    where
        F: Fn(&Context, Vec<Box<dyn Any + Send + Sync>>) -> Result<(), ClickError>
            + Send
            + Sync
            + 'static,
    {
        self.result_callback = Some(Box::new(f));
        self
    }

    /// Build the group.
    pub fn build(self) -> Group {
        // Determine no_args_is_help default
        let no_args_is_help = self.no_args_is_help.unwrap_or(!self.invoke_without_command);

        // Determine subcommand_required default
        let subcommand_required = self
            .subcommand_required
            .unwrap_or(!self.invoke_without_command);

        // Determine subcommand_metavar
        let subcommand_metavar = self.subcommand_metavar.unwrap_or_else(|| {
            if self.chain {
                "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...".to_string()
            } else {
                "COMMAND [ARGS]...".to_string()
            }
        });

        // Build the underlying command
        let mut cmd_builder = CommandBuilder::new(&self.name)
            .allow_extra_args(true)
            .allow_interspersed_args(false)
            .add_help_option(self.add_help_option)
            .no_args_is_help(no_args_is_help);

        if let Some(help_opt) = self.help_option {
            cmd_builder = cmd_builder.help_option(help_opt);
        }

        // Add options
        for opt in self.options {
            cmd_builder = cmd_builder.option(opt);
        }

        // Add arguments
        for arg in self.arguments {
            cmd_builder = cmd_builder.argument(arg);
        }

        // Set other properties
        if let Some(help) = self.help {
            cmd_builder = cmd_builder.help(&help);
        }
        if let Some(epilog) = self.epilog {
            cmd_builder = cmd_builder.epilog(&epilog);
        }
        if let Some(short_help) = self.short_help {
            cmd_builder = cmd_builder.short_help(&short_help);
        }
        if self.hidden {
            cmd_builder = cmd_builder.hidden();
        }
        if let Some(deprecated) = self.deprecated {
            cmd_builder = cmd_builder.deprecated(&deprecated);
        }
        if let Some(callback) = self.callback {
            // We need to wrap the callback
            let callback_wrapper = move |ctx: &Context| callback(ctx);
            cmd_builder = cmd_builder.callback(callback_wrapper);
        }

        let command = cmd_builder.build();

        Group {
            command,
            commands: self.commands,
            command_ids_by_name: self.command_ids_by_name,
            command_aliases_by_id: self.command_aliases_by_id,
            next_command_id: self.next_command_id,
            chain: self.chain,
            invoke_without_command: self.invoke_without_command,
            result_callback: self.result_callback,
            subcommand_required,
            subcommand_metavar,
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    #[test]
    fn test_group_creation_defaults() {
        let group = Group::new("test").build();

        assert_eq!(group.name(), Some("test"));
        assert!(group.commands.is_empty());
        assert!(!group.chain);
        assert!(!group.invoke_without_command);
        assert!(group.subcommand_required);
        assert_eq!(group.subcommand_metavar, "COMMAND [ARGS]...");
    }

    #[test]
    fn test_group_with_subcommands() {
        let group = Group::new("cli")
            .command(Command::new("init").help("Initialize").build())
            .command(Command::new("build").help("Build").build())
            .build();

        assert_eq!(group.commands.len(), 2);
        assert!(group.get_command("init").is_some());
        assert!(group.get_command("build").is_some());
        assert!(group.get_command("unknown").is_none());
    }

    #[test]
    fn test_list_commands_sorted() {
        let group = Group::new("cli")
            .command(Command::new("zebra").build())
            .command(Command::new("alpha").build())
            .command(Command::new("middle").build())
            .build();

        let commands = group.list_commands();
        assert_eq!(commands, vec!["alpha", "middle", "zebra"]);
    }

    #[test]
    fn test_add_command_with_name() {
        let mut group = Group::new("cli").build();

        group.add_command(Command::new("original").build(), Some("renamed"));

        assert!(group.get_command("renamed").is_some());
        assert!(group.get_command("original").is_none());
    }

    #[test]
    fn test_alias_metadata_for_shared_command() {
        let cmd: Arc<dyn CommandLike> = Arc::new(Command::new("original").build());

        let group = Group::new("cli")
            .command_shared(Arc::clone(&cmd))
            .command_shared_with_name("alias", Arc::clone(&cmd))
            .build();

        assert!(group.get_command("original").is_some());
        assert!(group.get_command("alias").is_some());

        assert_eq!(
            group.list_command_aliases("original"),
            vec!["alias".to_string()]
        );
        assert_eq!(
            group.list_command_aliases("alias"),
            vec!["original".to_string()]
        );

        let entries = group.list_command_entries();
        let alias_entry = entries
            .iter()
            .find(|(name, _)| name == "alias")
            .expect("alias entry missing");
        assert_eq!(alias_entry.1.name(), Some("original"));
    }

    #[test]
    fn test_group_chain_mode() {
        let group = Group::new("cli").chain(true).build();

        assert!(group.chain);
        assert_eq!(
            group.subcommand_metavar,
            "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
        );
    }

    #[test]
    fn test_invoke_without_command() {
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = Arc::clone(&called);

        let group = Group::new("cli")
            .invoke_without_command(true)
            .callback(move |_ctx| {
                called_clone.store(true, Ordering::SeqCst);
                Ok(())
            })
            .build();

        // invoke_without_command implies subcommand_required = false
        assert!(!group.subcommand_required);

        // Create context with no subcommand
        let ctx = ContextBuilder::new().info_name("cli").build();

        // Invoke should call the group callback
        let result = group.invoke(&ctx);
        assert!(result.is_ok());
        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_group_help_formatting() {
        let group = Group::new("cli")
            .help("A sample CLI application")
            .command(
                Command::new("init")
                    .short_help("Initialize the project")
                    .build(),
            )
            .command(
                Command::new("build")
                    .short_help("Build the project")
                    .build(),
            )
            .build();

        let ctx = ContextBuilder::new().info_name("cli").build();
        let help = group.get_help(&ctx);

        assert!(help.contains("Usage:"));
        assert!(help.contains("cli"));
        assert!(help.contains("COMMAND [ARGS]..."));
        assert!(help.contains("A sample CLI application"));
        assert!(help.contains("Commands:"));
        assert!(help.contains("init"));
        assert!(help.contains("build"));
    }

    #[test]
    fn test_resolve_command() {
        let group = Group::new("cli")
            .command(Command::new("hello").build())
            .command(Command::new("world").build())
            .build();

        let ctx = ContextBuilder::new().info_name("cli").build();

        // Resolve existing command
        let args = vec!["hello".to_string(), "arg1".to_string()];
        let resolved = group.resolve_command(&ctx, &args);
        assert!(resolved.is_ok());

        let (name, _cmd, remaining) = resolved.unwrap().unwrap();
        assert_eq!(name, "hello");
        assert_eq!(remaining, vec!["arg1".to_string()]);

        // Resolve non-existent command
        let args = vec!["unknown".to_string()];
        let resolved = group.resolve_command(&ctx, &args);
        assert!(resolved.is_err());
    }

    #[test]
    fn test_resolve_command_empty_args() {
        let group = Group::new("cli")
            .command(Command::new("hello").build())
            .build();

        let ctx = ContextBuilder::new().info_name("cli").build();

        let resolved = group.resolve_command(&ctx, &[]);
        assert!(resolved.is_ok());
        assert!(resolved.unwrap().is_none());
    }

    #[test]
    fn test_group_with_options() {
        let group = Group::new("cli")
            .help("A CLI with options")
            .option(
                ClickOption::new(&["--verbose", "-v"])
                    .flag("true")
                    .help("Enable verbose mode")
                    .build(),
            )
            .command(Command::new("run").build())
            .build();

        assert_eq!(group.command.options.len(), 1);

        let ctx = ContextBuilder::new().info_name("cli").build();
        let help = group.get_help(&ctx);

        assert!(help.contains("--verbose"));
        assert!(help.contains("Enable verbose mode"));
    }

    #[test]
    fn test_hidden_commands_not_in_help() {
        let group = Group::new("cli")
            .command(Command::new("visible").build())
            .command(Command::new("hidden").hidden().build())
            .build();

        let ctx = ContextBuilder::new().info_name("cli").build();
        let help = group.format_commands(&ctx);

        assert!(help.contains("visible"));
        assert!(!help.contains("hidden"));
    }

    #[test]
    fn test_subcommand_required_default() {
        // Without invoke_without_command: subcommand_required = true
        let group1 = Group::new("cli").build();
        assert!(group1.subcommand_required);

        // With invoke_without_command: subcommand_required = false
        let group2 = Group::new("cli").invoke_without_command(true).build();
        assert!(!group2.subcommand_required);

        // Explicit override
        let group3 = Group::new("cli")
            .invoke_without_command(true)
            .subcommand_required(true)
            .build();
        assert!(group3.subcommand_required);
    }

    #[test]
    fn test_group_short_help() {
        let group = Group::new("cli")
            .help("This is the long help text. It has multiple sentences.")
            .build();

        let short = group.get_short_help();
        assert_eq!(short, "This is the long help text");

        let group_explicit = Group::new("cli")
            .help("Long help")
            .short_help("Short help")
            .build();

        let short = group_explicit.get_short_help();
        assert_eq!(short, "Short help");
    }

    #[test]
    fn test_group_debug_format() {
        let group = Group::new("cli")
            .command(Command::new("a").build())
            .command(Command::new("b").build())
            .build();

        let debug_str = format!("{:?}", group);
        assert!(debug_str.contains("Group"));
        assert!(debug_str.contains("2 subcommands"));
    }

    #[test]
    fn test_nested_groups() {
        let sub_group = Group::new("sub")
            .help("Subgroup")
            .command(Command::new("cmd").build())
            .build();

        let main_group = Group::new("main")
            .help("Main group")
            .command(sub_group)
            .build();

        assert!(main_group.get_command("sub").is_some());

        // Can get the nested command through the subgroup
        let sub = main_group.get_command("sub").unwrap();
        assert_eq!(sub.name(), Some("sub"));
    }

    #[test]
    fn test_command_with_name_builder() {
        let group = Group::new("cli")
            .command_with_name("alias", Command::new("original").build())
            .build();

        assert!(group.get_command("alias").is_some());
        assert!(group.get_command("original").is_none());
    }

    #[test]
    fn test_missing_command_error() {
        let group = Group::new("cli").subcommand_required(true).build();

        let ctx = ContextBuilder::new().info_name("cli").build();

        // No args and subcommand required should error
        let result = group.invoke(&ctx);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ClickError::UsageError { .. }));
    }

    #[test]
    fn test_commandlike_trait() {
        // Test that both Command and Group implement CommandLike
        let cmd: Box<dyn CommandLike> = Box::new(Command::new("cmd").build());
        let grp: Box<dyn CommandLike> = Box::new(Group::new("grp").build());

        assert_eq!(cmd.name(), Some("cmd"));
        assert_eq!(grp.name(), Some("grp"));

        assert!(!cmd.is_hidden());
        assert!(!grp.is_hidden());
    }

    #[test]
    fn test_group_usage() {
        let group = Group::new("cli")
            .option(ClickOption::new(&["--debug"]).flag("true").build())
            .build();

        let ctx = ContextBuilder::new().info_name("cli").build();
        let usage = group.get_usage(&ctx);

        assert!(usage.contains("cli"));
        assert!(usage.contains("[OPTIONS]"));
        assert!(usage.contains("COMMAND [ARGS]..."));
    }

    #[test]
    fn test_chain_metavar() {
        let group = Group::new("cli")
            .chain(true)
            .subcommand_metavar("CMD1 CMD2...")
            .build();

        // Custom metavar should override chain default
        assert_eq!(group.subcommand_metavar, "CMD1 CMD2...");
    }

    #[test]
    fn test_group_deprecated() {
        let group = Group::new("old")
            .help("Old group")
            .deprecated("Use 'new' instead")
            .build();

        let short = group.get_short_help();
        assert!(short.contains("DEPRECATED"));
        assert!(short.contains("Use 'new' instead"));
    }

    // =========================================================================
    // Tests for context inheritance, chain mode, and result_callback
    // =========================================================================

    #[test]
    fn test_subcommand_context_inheritance() {
        // Test that subcommand context properly inherits from parent context
        let parent_info_name = Arc::new(std::sync::Mutex::new(String::new()));
        let parent_info_clone = Arc::clone(&parent_info_name);

        let group = Group::new("cli")
            .command(
                Command::new("sub")
                    .callback(move |ctx| {
                        // Check that the parent context is accessible
                        if let Some(parent) = ctx.parent() {
                            let mut lock = parent_info_clone.lock().unwrap();
                            if let Some(name) = parent.info_name() {
                                *lock = name.to_string();
                            }
                        }
                        Ok(())
                    })
                    .build(),
            )
            .build();

        // Use main() which sets up proper context stack
        let result = group.main(vec!["sub".to_string()]);
        assert!(result.is_ok());

        // The subcommand should have seen "cli" as parent info_name
        let captured = parent_info_name.lock().unwrap();
        assert_eq!(*captured, "cli");
    }

    #[test]
    fn test_subcommand_inherits_terminal_settings() {
        // Test that subcommand context inherits terminal_width and color settings
        let inherited_width = Arc::new(std::sync::Mutex::new(None::<usize>));
        let inherited_color = Arc::new(std::sync::Mutex::new(None::<bool>));
        let width_clone = Arc::clone(&inherited_width);
        let color_clone = Arc::clone(&inherited_color);

        let group = Group::new("cli")
            .command(
                Command::new("sub")
                    .callback(move |ctx| {
                        *width_clone.lock().unwrap() = ctx.terminal_width();
                        *color_clone.lock().unwrap() = ctx.color();
                        Ok(())
                    })
                    .build(),
            )
            .build();

        // Create parent context with specific settings
        let parent_ctx = ContextBuilder::new()
            .info_name("cli")
            .terminal_width(120)
            .color(true)
            .allow_extra_args(true)
            .build();
        let _parent_ctx = Arc::new(parent_ctx);

        // Parse args through the group
        let ctx = group
            .make_context("cli", vec!["sub".to_string()], None)
            .unwrap();

        // Manually set the inherited values (simulating what ContextBuilder does with parent)
        // In real usage, main() would set these up properly
        push_context(Arc::new(
            ContextBuilder::new()
                .info_name("cli")
                .terminal_width(120)
                .color(true)
                .allow_extra_args(true)
                .build(),
        ));

        let result = group.invoke(&ctx);
        pop_context();

        assert!(result.is_ok());
        // Note: The actual inheritance depends on Context implementation
        // This test verifies the invoke path doesn't break
    }

    #[test]
    fn test_chain_mode_multiple_commands() {
        // Test that chain mode invokes multiple subcommands
        let call_order = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let order1 = Arc::clone(&call_order);
        let order2 = Arc::clone(&call_order);
        let order3 = Arc::clone(&call_order);

        let group = Group::new("cli")
            .chain(true)
            .command(
                Command::new("cmd1")
                    .callback(move |_ctx| {
                        order1.lock().unwrap().push("cmd1".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .command(
                Command::new("cmd2")
                    .callback(move |_ctx| {
                        order2.lock().unwrap().push("cmd2".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .command(
                Command::new("cmd3")
                    .callback(move |_ctx| {
                        order3.lock().unwrap().push("cmd3".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .build();

        // Invoke with multiple commands
        let result = group.main(vec![
            "cmd1".to_string(),
            "cmd2".to_string(),
            "cmd3".to_string(),
        ]);
        assert!(result.is_ok());

        // All commands should have been called in order
        let order = call_order.lock().unwrap();
        assert_eq!(*order, vec!["cmd1", "cmd2", "cmd3"]);
    }

    #[test]
    fn test_chain_mode_with_args() {
        // Test chain mode where commands have arguments
        let captured_args = Arc::new(std::sync::Mutex::new(Vec::<Vec<String>>::new()));
        let args1 = Arc::clone(&captured_args);
        let args2 = Arc::clone(&captured_args);

        let group = Group::new("cli")
            .chain(true)
            .command(
                Command::new("first")
                    .callback(move |ctx| {
                        args1.lock().unwrap().push(ctx.args().to_vec());
                        Ok(())
                    })
                    .build(),
            )
            .command(
                Command::new("second")
                    .callback(move |ctx| {
                        args2.lock().unwrap().push(ctx.args().to_vec());
                        Ok(())
                    })
                    .build(),
            )
            .build();

        // Both commands called without arguments to each
        let result = group.main(vec!["first".to_string(), "second".to_string()]);
        assert!(result.is_ok());

        let args = captured_args.lock().unwrap();
        assert_eq!(args.len(), 2);
    }

    #[test]
    fn test_chain_mode_empty_returns_ok() {
        // Test that chain mode with invoke_without_command returns ok with no commands
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = Arc::clone(&called);

        let group = Group::new("cli")
            .chain(true)
            .invoke_without_command(true)
            .callback(move |_ctx| {
                called_clone.store(true, Ordering::SeqCst);
                Ok(())
            })
            .command(Command::new("sub").build())
            .build();

        let result = group.main(vec![]);
        assert!(result.is_ok());
        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_result_callback_invoked() {
        // Test that result_callback is called after subcommand execution
        let result_callback_called = Arc::new(AtomicBool::new(false));
        let callback_clone = Arc::clone(&result_callback_called);

        let group = Group::new("cli")
            .command(Command::new("sub").callback(|_ctx| Ok(())).build())
            .result_callback(move |_ctx, _results| {
                callback_clone.store(true, Ordering::SeqCst);
                Ok(())
            })
            .build();

        let result = group.main(vec!["sub".to_string()]);
        assert!(result.is_ok());
        assert!(result_callback_called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_result_callback_with_chain_mode() {
        // Test that result_callback receives results from all chained commands
        let result_callback_called = Arc::new(AtomicBool::new(false));
        let callback_clone = Arc::clone(&result_callback_called);
        let results_count = Arc::new(std::sync::Mutex::new(0usize));
        let count_clone = Arc::clone(&results_count);

        let group = Group::new("cli")
            .chain(true)
            .command(Command::new("a").callback(|_| Ok(())).build())
            .command(Command::new("b").callback(|_| Ok(())).build())
            .result_callback(move |_ctx, results| {
                callback_clone.store(true, Ordering::SeqCst);
                *count_clone.lock().unwrap() = results.len();
                Ok(())
            })
            .build();

        let result = group.main(vec!["a".to_string(), "b".to_string()]);
        assert!(result.is_ok());
        assert!(result_callback_called.load(Ordering::SeqCst));

        // Should have 2 results (one for each command)
        let count = *results_count.lock().unwrap();
        assert_eq!(count, 2);
    }

    #[test]
    fn test_result_callback_invoke_without_command() {
        // Test that result_callback is called even when invoke_without_command is used
        let result_callback_called = Arc::new(AtomicBool::new(false));
        let callback_clone = Arc::clone(&result_callback_called);

        let group = Group::new("cli")
            .invoke_without_command(true)
            .callback(|_ctx| Ok(()))
            .result_callback(move |_ctx, _results| {
                callback_clone.store(true, Ordering::SeqCst);
                Ok(())
            })
            .build();

        let result = group.main(vec![]);
        assert!(result.is_ok());
        assert!(result_callback_called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_chain_mode_subcommand_failure_stops_chain() {
        // Test that if a subcommand fails, the chain stops
        let second_called = Arc::new(AtomicBool::new(false));
        let second_clone = Arc::clone(&second_called);

        let group = Group::new("cli")
            .chain(true)
            .command(
                Command::new("fail")
                    .callback(|_ctx| Err(ClickError::usage("intentional failure")))
                    .build(),
            )
            .command(
                Command::new("second")
                    .callback(move |_ctx| {
                        second_clone.store(true, Ordering::SeqCst);
                        Ok(())
                    })
                    .build(),
            )
            .build();

        let result = group.main(vec!["fail".to_string(), "second".to_string()]);
        assert!(result.is_err());
        // Second command should not have been called
        assert!(!second_called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_non_chain_mode_single_command() {
        // Test that non-chain mode only invokes one command
        let calls = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let calls1 = Arc::clone(&calls);

        let group = Group::new("cli")
            .chain(false) // explicitly not chain mode
            .command(
                Command::new("cmd1")
                    .callback(move |_ctx| {
                        calls1.lock().unwrap().push("cmd1".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .command(Command::new("cmd2").build())
            .build();

        // In non-chain mode, "cmd2" would be passed as arg to cmd1, not as separate command
        let result = group.main(vec!["cmd1".to_string()]);
        assert!(result.is_ok());

        let recorded = calls.lock().unwrap();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0], "cmd1");
    }

    #[test]
    fn test_group_callback_called_before_subcommand() {
        // Test that group callback is called before subcommand in non-chain mode
        let call_order = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let order_group = Arc::clone(&call_order);
        let order_sub = Arc::clone(&call_order);

        let group = Group::new("cli")
            .callback(move |_ctx| {
                order_group.lock().unwrap().push("group".to_string());
                Ok(())
            })
            .command(
                Command::new("sub")
                    .callback(move |_ctx| {
                        order_sub.lock().unwrap().push("sub".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .build();

        let result = group.main(vec!["sub".to_string()]);
        assert!(result.is_ok());

        let order = call_order.lock().unwrap();
        assert_eq!(*order, vec!["group", "sub"]);
    }

    #[test]
    fn test_group_callback_called_before_chain() {
        // Test that group callback is called before chained subcommands
        let call_order = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let order_group = Arc::clone(&call_order);
        let order_a = Arc::clone(&call_order);
        let order_b = Arc::clone(&call_order);

        let group = Group::new("cli")
            .chain(true)
            .callback(move |_ctx| {
                order_group.lock().unwrap().push("group".to_string());
                Ok(())
            })
            .command(
                Command::new("a")
                    .callback(move |_ctx| {
                        order_a.lock().unwrap().push("a".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .command(
                Command::new("b")
                    .callback(move |_ctx| {
                        order_b.lock().unwrap().push("b".to_string());
                        Ok(())
                    })
                    .build(),
            )
            .build();

        let result = group.main(vec!["a".to_string(), "b".to_string()]);
        assert!(result.is_ok());

        let order = call_order.lock().unwrap();
        assert_eq!(*order, vec!["group", "a", "b"]);
    }

    #[test]
    fn test_command_collection_list_commands_union_sorted() {
        let src = Group::new("src")
            .command(Command::new("c").help("C").build())
            .command(Command::new("b").help("B").build())
            .build();

        let collection = CommandCollection::new("coll")
            .command(Command::new("a").help("A").build())
            .source(src)
            .build();

        assert_eq!(
            collection.list_commands(),
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );
    }

    #[test]
    fn test_command_collection_prefers_base_over_sources() {
        let src = Group::new("src")
            .command(Command::new("dup").help("Src").build())
            .build();

        let collection = CommandCollection::new("coll")
            .command(Command::new("dup").help("Base").build())
            .source(src)
            .build();

        let ctx = ContextBuilder::new().info_name("coll").build();
        let help = collection.get_help(&ctx);
        assert!(help.contains("dup"));
        assert_eq!(
            collection.get_command("dup").unwrap().get_short_help(),
            "Base"
        );
    }

    // =========================================================================
    // Tests for eager option handling in Groups (--help, --version)
    // =========================================================================

    #[test]
    fn test_group_help_with_missing_subcommand() {
        // --help should work even when subcommand is missing and required
        let group = Group::new("cli")
            .subcommand_required(true)
            .command(Command::new("sub").build())
            .build();

        // Without --help, missing subcommand should fail
        let _ctx = group.make_context("cli", vec![], None);
        // Note: Group doesn't fail in make_context for missing subcommand,
        // it fails in invoke(). So this test verifies --help triggers early.

        // With --help, should exit cleanly (Exit code 0)
        let ctx = group.make_context("cli", vec!["--help".to_string()], None);
        assert!(matches!(ctx, Err(ClickError::Exit { code: 0 })));
    }

    #[test]
    fn test_group_help_with_required_option() {
        // --help should work even when a required option is missing
        let group = Group::new("cli")
            .option(ClickOption::new(&["--name", "-n"]).required().build())
            .command(Command::new("sub").build())
            .build();

        // Without --help, missing required option should fail
        let ctx = group.make_context("cli", vec!["sub".to_string()], None);
        assert!(ctx.is_err());

        // With --help, should exit cleanly (Exit code 0)
        let ctx = group.make_context("cli", vec!["--help".to_string()], None);
        assert!(matches!(ctx, Err(ClickError::Exit { code: 0 })));
    }

    #[test]
    fn test_group_version_option() {
        use crate::option::ClickOption;

        // Create a version option that uses the special metavar prefix
        let version_opt = ClickOption::new(&["--version", "-V"])
            .flag("true")
            .eager()
            .metavar("__click_version__:myapp 1.0.0")
            .help("Show version and exit.")
            .build();

        let group = Group::new("cli")
            .option(version_opt)
            .command(Command::new("sub").build())
            .build();

        // --version should trigger Exit(0)
        let ctx = group.make_context("cli", vec!["--version".to_string()], None);
        assert!(matches!(ctx, Err(ClickError::Exit { code: 0 })));
    }

    // =========================================================================
    // Tests for pluggable help renderer invoked on subcommand --help
    // =========================================================================

    #[test]
    fn test_custom_renderer_invoked_for_subcommand_help() {
        use crate::context::{ContextBuilder, HelpRenderer};
        use std::sync::Mutex;

        // Record what the renderer was called with
        let captured_name: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let captured_clone = Arc::clone(&captured_name);

        let renderer: HelpRenderer = Arc::new(move |_cmd, ctx| {
            let mut lock = captured_clone.lock().unwrap();
            *lock = Some(ctx.info_name().unwrap_or("").to_string());
            format!("RICH:{}", ctx.info_name().unwrap_or(""))
        });

        let group = Group::new("cli")
            .command(Command::new("sub").help("Does something.").build())
            .build();

        // Install renderer on a context, then use main() path through testing::CliRunner
        // Instead, simulate directly: make the root context with renderer, push it, invoke.
        let root_ctx = Arc::new(
            ContextBuilder::new()
                .info_name("cli")
                .allow_extra_args(true)
                .allow_interspersed_args(false)
                .help_renderer(renderer)
                .build(),
        );

        // Parse args for the group (produces root_ctx with args = ["sub", "--help"])
        // We simulate the Group::invoke flow: build a ctx with remaining args.
        let mut ctx = ContextBuilder::new()
            .info_name("cli")
            .allow_extra_args(true)
            .allow_interspersed_args(false)
            .help_renderer(Arc::new(move |_cmd, ctx2| {
                format!("RICH2:{}", ctx2.info_name().unwrap_or(""))
            }))
            .build();
        // Inject the remaining args that would trigger subcommand --help
        ctx.args_mut().push("sub".to_string());
        ctx.args_mut().push("--help".to_string());

        push_context(Arc::clone(&root_ctx));
        let result = group.invoke(&ctx);
        pop_context();

        // Result is Ok because we handled Exit{0} in the renderer path
        assert!(result.is_ok());
    }

    #[test]
    fn test_fallback_renderer_used_when_no_custom_renderer() {
        // Without a renderer, the plain get_help() fallback is used; result is Ok.
        let group = Group::new("cli")
            .command(Command::new("sub").help("Sub help text.").build())
            .build();

        let mut ctx = ContextBuilder::new()
            .info_name("cli")
            .allow_extra_args(true)
            .allow_interspersed_args(false)
            .build();
        ctx.args_mut().push("sub".to_string());
        ctx.args_mut().push("--help".to_string());

        let root_ctx = Arc::new(ContextBuilder::new().info_name("cli").build());
        push_context(Arc::clone(&root_ctx));
        let result = group.invoke(&ctx);
        pop_context();

        assert!(result.is_ok());
    }

    #[test]
    fn test_custom_renderer_invoked_for_chain_subcommand_help() {
        // Chain mode: verify renderer is called for --help on a chain member.
        use crate::context::{ContextBuilder, HelpRenderer};
        use std::sync::atomic::{AtomicBool, Ordering};

        let renderer_called = Arc::new(AtomicBool::new(false));
        let called_clone = Arc::clone(&renderer_called);

        let renderer: HelpRenderer = Arc::new(move |_cmd, _ctx| {
            called_clone.store(true, Ordering::SeqCst);
            "CHAIN_RICH".to_string()
        });

        let group = Group::new("cli")
            .chain(true)
            .command(Command::new("step1").help("Step one.").build())
            .build();

        let mut ctx = ContextBuilder::new()
            .info_name("cli")
            .allow_extra_args(true)
            .allow_interspersed_args(false)
            .help_renderer(renderer)
            .build();
        ctx.args_mut().push("step1".to_string());
        ctx.args_mut().push("--help".to_string());

        let root_ctx = Arc::new(ContextBuilder::new().info_name("cli").build());
        push_context(Arc::clone(&root_ctx));
        let result = group.invoke(&ctx);
        pop_context();

        assert!(result.is_ok());
        assert!(renderer_called.load(Ordering::SeqCst));
    }
}