sen 0.8.1

Script to System CLI Engine - A type-safe, macro-powered CLI framework
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
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
//! # SEN: Script to System CLI Engine
//!
//! A type-safe, macro-powered CLI framework inspired by Axum's ergonomics.
//!
//! ## Core Principles
//!
//! - **Compile-time safety**: Enum-based routing with exhaustiveness checking
//! - **Zero boilerplate**: Derive macros generate all wiring code
//! - **Type-driven DI**: Handler parameters are injected based on type signature
//! - **Fixed workflows**: Predictable behavior for humans and AI agents
//!
//! ## Quick Start
//!
//! ```rust,ignore
//! use sen::{CliResult, State, SenRouter};
//!
//! // Define application state
//! pub struct AppState {
//!     pub config: Config,
//! }
//!
//! // Define commands with derive macro
//! #[derive(SenRouter)]
//! #[sen(state = AppState)]
//! enum Commands {
//!     #[sen(handler = handlers::status)]
//!     Status,
//!
//!     #[sen(handler = handlers::build)]
//!     Build(BuildArgs),
//! }
//!
//! // Implement handlers as async functions
//! mod handlers {
//!     use super::*;
//!
//!     pub async fn status(state: State<AppState>) -> CliResult<String> {
//!         let app = state.read().await;
//!         Ok("Status: OK".to_string())
//!     }
//!
//!     pub async fn build(state: State<AppState>, args: BuildArgs) -> CliResult<()> {
//!         // Build logic here (can use async DB, API calls, etc.)
//!         Ok(())
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let state = State::new(AppState { config: Config::load() });
//!     let cmd = Commands::parse();
//!     let response = cmd.execute(state).await;
//!
//!     if !response.output.is_empty() {
//!         println!("{}", response.output);
//!     }
//!     std::process::exit(response.exit_code);
//! }
//! ```

use std::sync::Arc;

// Re-export macros
pub use sen_rs_macros::handler;
pub use sen_rs_macros::sen;
pub use sen_rs_macros::SenRouter;

// Optional modules
pub mod build_info;
pub mod tracing_support;

#[cfg(feature = "sensors")]
pub mod sensors;

#[cfg(feature = "mcp")]
pub mod mcp;

// Re-export tracing itself (required for #[instrument] macro)
#[cfg(feature = "tracing")]
pub use tracing_support::tracing;

// Re-export commonly used items
#[cfg(feature = "tracing")]
pub use tracing_support::{
    debug, error, info, init_subscriber, init_subscriber_with_config, instrument, trace, warn,
    TracingConfig, TracingFormat,
};

#[cfg(feature = "build-info")]
pub use build_info::{version_info, version_short};

#[cfg(feature = "sensors")]
pub use sensors::{GitSensor, SensorData, Sensors};

// Re-export clap for convenience when using clap integration
#[cfg(feature = "clap")]
pub use clap;

// ============================================================================
// Core Types
// ============================================================================

/// A grouped command entry: (display_name, full_command, description)
type CommandEntry = (String, String, String);

/// Commands grouped by prefix: Vec<(group_name, Vec<command_entries>)>
type GroupedCommands = Vec<(String, Vec<CommandEntry>)>;

/// Shared application state wrapper with async-safe interior mutability.
///
/// Wraps your application state in `Arc<RwLock<T>>` for safe concurrent access.
/// Handlers receive this by value, but cloning is cheap (just incrementing a ref count).
///
/// # Example
///
/// ```ignore
/// use sen::State;
///
/// struct AppState {
///     config: String,
/// }
///
/// let state = State::new(AppState {
///     config: "production".to_string(),
/// });
///
/// // Access inner state (read-only)
/// let app = state.read().await;
/// assert_eq!(app.config, "production");
///
/// // Mutate inner state
/// let mut app = state.write().await;
/// app.config = "development".to_string();
/// ```
pub struct State<T>(Arc<tokio::sync::RwLock<T>>);

// Manual Clone implementation that doesn't require T: Clone
impl<T> Clone for State<T> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl<T> State<T> {
    /// Create a new state wrapper.
    pub fn new(inner: T) -> Self {
        Self(Arc::new(tokio::sync::RwLock::new(inner)))
    }

    /// Get a read lock to the inner state.
    ///
    /// Multiple readers can hold read locks simultaneously.
    pub async fn read(&self) -> tokio::sync::RwLockReadGuard<'_, T> {
        self.0.read().await
    }

    /// Get a write lock to the inner state.
    ///
    /// Only one writer can hold a write lock at a time.
    pub async fn write(&self) -> tokio::sync::RwLockWriteGuard<'_, T> {
        self.0.write().await
    }
}

/// Global options wrapper for CLI-wide flags.
///
/// Similar to State, but immutable (read-only). Used for global flags like
/// `--verbose`, `--config`, etc. that apply to all commands.
///
/// # Usage Pattern
///
/// ```ignore
/// use sen::{GlobalOptions, FromGlobalArgs, State};
///
/// // 1. Define global options structure
/// #[derive(Clone)]
/// struct GlobalOpts {
///     verbose: bool,
///     config: Option<String>,
/// }
///
/// // 2. Implement FromGlobalArgs (or use clap::Parser derive)
/// impl FromGlobalArgs for GlobalOpts {
///     fn from_global_args(args: &[String]) -> Result<(Self, Vec<String>), CliError> {
///         // Parse global flags and return remaining args
///         // ...
///     }
/// }
///
/// // 3. In main(), parse global options first
/// #[tokio::main]
/// async fn main() {
///     let args: Vec<String> = std::env::args().skip(1).collect();
///
///     // Parse global options
///     let (global_opts, remaining_args) = GlobalOpts::from_global_args(&args).unwrap();
///
///     // Include in application state
///     let state = State::new(AppState {
///         global: global_opts,
///         // ... other state fields
///     });
///
///     let router = Router::new()
///         .route("command", handler)
///         .with_state(state);
///
///     let response = router.execute(&remaining_args).await;
///     std::process::exit(response.exit_code);
/// }
/// ```
///
/// # Alternative: Direct Usage
///
/// You can also wrap global options in `GlobalOptions` and pass them directly:
///
/// ```ignore
/// let global = GlobalOptions::new(GlobalOpts {
///     verbose: true,
///     config: Some("~/.myapp/config.toml".to_string()),
/// });
///
/// // Access inner options (cheap clone)
/// let opts = global.get();
/// assert_eq!(opts.verbose, true);
/// ```
pub struct GlobalOptions<T>(Arc<T>);

// Manual Clone implementation that doesn't require T: Clone
impl<T> Clone for GlobalOptions<T> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl<T> GlobalOptions<T> {
    /// Create a new global options wrapper.
    pub fn new(inner: T) -> Self {
        Self(Arc::new(inner))
    }

    /// Get a reference to the inner options.
    ///
    /// This is cheap - just returns a reference to the Arc'd data.
    pub fn get(&self) -> &T {
        &self.0
    }
}

/// CLI result type.
///
/// All handler functions should return `CliResult<T>` where `T` implements `IntoResponse`.
pub type CliResult<T> = Result<T, CliError>;

// ============================================================================
// Error Types
// ============================================================================

/// Top-level error type for CLI operations.
///
/// Distinguishes between user-fixable errors (exit code 1) and system failures (exit code 101).
#[derive(Debug, thiserror::Error)]
pub enum CliError {
    /// User-fixable errors (exit code 1).
    ///
    /// These should include actionable hints for users.
    #[error(transparent)]
    User(#[from] UserError),

    /// System-level failures (exit code 101).
    ///
    /// These indicate bugs or environmental issues that users can't fix.
    #[error(transparent)]
    System(#[from] SystemError),
}

impl CliError {
    /// Get the appropriate exit code for this error.
    pub fn exit_code(&self) -> i32 {
        match self {
            CliError::User(user_err) => match user_err {
                UserError::Help(_) => 0, // Help is a successful exit
                _ => 1,
            },
            CliError::System(_) => 101,
        }
    }

    /// Convenience constructor for user errors.
    pub fn user(message: impl Into<String>) -> Self {
        CliError::User(UserError::Generic(message.into()))
    }

    /// Convenience constructor for system errors.
    pub fn system(message: impl Into<String>) -> Self {
        CliError::System(SystemError::Internal(message.into()))
    }
}

/// User-fixable errors (exit code 1).
#[derive(Debug, thiserror::Error)]
pub enum UserError {
    /// Generic user error with a message.
    #[error("Error: {0}")]
    Generic(String),

    /// Help message (exit code 0 - success).
    /// This is used when --help is requested.
    #[error("{0}")]
    Help(String),

    /// Invalid argument provided.
    #[error("Error: Invalid argument '{arg}'\n\n{reason}")]
    InvalidArgument { arg: String, reason: String },

    /// Missing required dependency.
    #[error("Error: Missing dependency '{tool}'\n\nHint: {install_hint}")]
    MissingDependency { tool: String, install_hint: String },

    /// Validation failed.
    #[error("Error: Validation failed\n\n{}", .details.join("\n"))]
    ValidationFailed { details: Vec<String> },

    /// Prerequisite not met.
    #[error("Error: Prerequisite not met: {check}\n\nHint: {fix_hint}")]
    PrerequisiteNotMet { check: String, fix_hint: String },
}

/// System-level failures (exit code 101).
#[derive(Debug, thiserror::Error)]
pub enum SystemError {
    /// Generic internal error.
    #[error("Internal Error: {0}\n\nThis is likely a bug.")]
    Internal(String),

    /// I/O error.
    #[error("Internal Error: I/O operation failed\n\n{0:?}\n\nThis is likely a bug.")]
    Io(#[from] std::io::Error),

    /// Configuration parsing error.
    #[error("Internal Error: Config parse failed\n\n{0}\n\nThis is likely a bug.")]
    ConfigParse(String),
}

// ============================================================================
// Response Types
// ============================================================================

/// Response returned by handlers after execution.
///
/// Contains exit code and output to be displayed to the user.
pub struct Response {
    /// Exit code (0 = success, 1 = user error, 101 = system error).
    pub exit_code: i32,

    /// Output to display (text, JSON, or silent).
    pub output: Output,

    /// Whether this response should be output in agent mode (JSON).
    pub agent_mode: bool,

    /// Optional metadata for agent mode (tier, tags, sensors).
    #[cfg(feature = "sensors")]
    pub metadata: Option<ResponseMetadata>,
}

/// Metadata attached to Response for AI agents.
#[cfg(feature = "sensors")]
#[derive(Debug, Clone, serde::Serialize)]
pub struct ResponseMetadata {
    /// Safety tier of the executed command
    pub tier: Option<&'static str>,

    /// Tags of the executed command
    pub tags: Option<Vec<&'static str>>,

    /// Environment sensor data
    pub sensors: Option<crate::sensors::SensorData>,
}

impl Response {
    /// Create a successful response with text output.
    pub fn text(content: impl Into<String>) -> Self {
        Self {
            exit_code: 0,
            output: Output::Text(content.into()),
            agent_mode: false,
            #[cfg(feature = "sensors")]
            metadata: None,
        }
    }

    /// Create a successful silent response.
    pub fn silent() -> Self {
        Self {
            exit_code: 0,
            output: Output::Silent,
            agent_mode: false,
            #[cfg(feature = "sensors")]
            metadata: None,
        }
    }

    /// Create an error response.
    pub fn error(exit_code: i32, message: impl Into<String>) -> Self {
        Self {
            exit_code,
            output: Output::Text(message.into()),
            agent_mode: false,
            #[cfg(feature = "sensors")]
            metadata: None,
        }
    }

    /// Attach metadata to this response (for agent mode).
    #[cfg(feature = "sensors")]
    pub fn with_metadata(mut self, metadata: ResponseMetadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Convert response to agent-friendly JSON format.
    ///
    /// Returns a JSON object with:
    /// - `result`: "success" or "error"
    /// - `exit_code`: numeric exit code
    /// - `output`: command output
    /// - `tier`: safety tier (if available)
    /// - `tags`: command tags (if available)
    /// - `sensors`: environment data (if available)
    #[cfg(feature = "sensors")]
    pub fn to_agent_json(&self) -> String {
        let result = if self.exit_code == 0 {
            "success"
        } else {
            "error"
        };

        let output = match &self.output {
            Output::Silent => String::new(),
            Output::Text(s) => s.clone(),
            Output::Json(s) => s.clone(),
        };

        let mut json = serde_json::json!({
            "result": result,
            "exit_code": self.exit_code,
            "output": output,
        });

        if let Some(ref metadata) = self.metadata {
            if let Some(tier) = metadata.tier {
                json["tier"] = serde_json::json!(tier);
            }
            if let Some(ref tags) = metadata.tags {
                json["tags"] = serde_json::json!(tags);
            }
            if let Some(ref sensors) = metadata.sensors {
                json["sensors"] = serde_json::to_value(sensors).unwrap_or(serde_json::json!(null));
            }
        }

        serde_json::to_string_pretty(&json).unwrap_or_else(|_| "{}".to_string())
    }
}

/// Output type for responses.
#[derive(Debug)]
pub enum Output {
    /// No output.
    Silent,

    /// Text output (printed to stdout).
    Text(String),

    /// JSON output (for machine-readable responses).
    Json(String),
}

impl Output {
    /// Check if output is empty.
    pub fn is_empty(&self) -> bool {
        matches!(self, Output::Silent)
    }
}

impl std::fmt::Display for Output {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Output::Silent => Ok(()),
            Output::Text(s) | Output::Json(s) => write!(f, "{}", s),
        }
    }
}

// ============================================================================
// Response Conversion Trait
// ============================================================================

/// Trait for converting handler return values into responses.
///
/// Implemented for common return types like `String`, `()`, and `Result<T, E>`.
pub trait IntoResponse {
    /// Convert into a response.
    fn into_response(self) -> Response;
}

impl IntoResponse for String {
    fn into_response(self) -> Response {
        Response::text(self)
    }
}

impl IntoResponse for () {
    fn into_response(self) -> Response {
        Response::silent()
    }
}

impl<T: IntoResponse> IntoResponse for CliResult<T> {
    fn into_response(self) -> Response {
        match self {
            Ok(value) => value.into_response(),
            Err(e) => {
                let exit_code = e.exit_code();
                let message = match &e {
                    CliError::User(UserError::Help(help_text)) => {
                        // Help is a successful operation, return as text response with exit code 0
                        return Response {
                            output: Output::Text(help_text.clone()),
                            exit_code: 0,
                            agent_mode: false,
                            metadata: None,
                        };
                    }
                    CliError::User(user_err) => format!("{}", user_err),
                    CliError::System(sys_err) => format!("{}", sys_err),
                };
                Response::error(exit_code, message)
            }
        }
    }
}

// ============================================================================
// Router & Handler System (Axum-style)
// ============================================================================

use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;

/// Boxed future for type erasure
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Safety tier for CLI commands.
///
/// Determines the risk level of a command and whether it requires
/// human approval when executed by AI agents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum Tier {
    /// Safe operations (read-only, information gathering).
    /// Examples: status, list, version, help
    /// Agent permission: Always allow
    Safe,

    /// Standard operations (idempotent or reversible).
    /// Examples: fmt, build, test, lint
    /// Agent permission: Auto-approve
    Standard,

    /// Critical operations (destructive, deployment, authentication).
    /// Examples: deploy, publish, delete, drop-database
    /// Agent permission: Require human confirmation
    Critical,
}

impl Tier {
    /// Parse tier from string (case-insensitive).
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "safe" => Some(Tier::Safe),
            "standard" => Some(Tier::Standard),
            "critical" => Some(Tier::Critical),
            _ => None,
        }
    }

    /// Convert tier to static string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Tier::Safe => "safe",
            Tier::Standard => "standard",
            Tier::Critical => "critical",
        }
    }

    /// Check if this tier requires human approval for AI agents.
    pub fn requires_approval(&self) -> bool {
        matches!(self, Tier::Critical)
    }
}

impl std::fmt::Display for Tier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[cfg(feature = "clap")]
impl std::str::FromStr for Tier {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or_else(|| {
            format!(
                "Invalid tier: '{}'. Valid options: safe, standard, critical",
                s
            )
        })
    }
}

/// Metadata for CLI application and commands.
///
/// This is used by the `#[sen(...)]` attribute macro to provide
/// help generation and CLI documentation.
#[derive(Debug, Clone)]
pub struct RouterMetadata {
    /// Application name
    pub name: &'static str,
    /// Version string (optional)
    pub version: Option<&'static str>,
    /// Short description
    pub about: Option<&'static str>,
}

/// Metadata for individual command handlers.
///
/// This is used by the `#[sen::handler(...)]` attribute macro.
#[derive(Debug, Clone)]
pub struct HandlerMetadata {
    /// Short description of what this handler does
    pub desc: Option<&'static str>,
    /// Safety tier for this command
    pub tier: Option<Tier>,
    /// Tags for command categorization and discovery
    pub tags: Option<Vec<&'static str>>,
}

/// Metadata for a specific route in the router.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct RouteMetadata {
    /// Handler-level metadata (from #[sen::handler])
    handler_meta: Option<HandlerMetadata>,
    /// Route description (can be set via .describe())
    description: Option<String>,
    /// CLI argument schema (from Clap, if available)
    args_schema: Option<serde_json::Value>,
}

impl RouteMetadata {
    /// Get the description for this route
    ///
    /// Prefers route-level description over handler-level description
    pub fn get_description(&self) -> Option<&str> {
        self.description
            .as_deref()
            .or_else(|| self.handler_meta.as_ref()?.desc)
    }

    /// Get the CLI argument schema for this route
    pub fn get_args_schema(&self) -> Option<&serde_json::Value> {
        self.args_schema.as_ref()
    }
}

/// Handler trait - allows functions with various signatures to be used as handlers.
///
/// This trait is automatically implemented for async functions with compatible signatures.
/// Inspired by Axum's handler system.
pub trait Handler<T, S>: Clone + Send + Sync + Sized + 'static {
    /// Future type returned by the handler
    type Future: Future<Output = Response> + Send + 'static;

    /// Call the handler with state and arguments
    fn call(self, state: State<S>, args: Vec<String>) -> Self::Future;

    /// Get handler metadata (optional)
    fn metadata(&self) -> Option<HandlerMetadata> {
        None
    }

    /// Get CLI argument schema (optional)
    fn args_schema(&self) -> Option<serde_json::Value> {
        None
    }
}

/// Wrapper that attaches metadata to a handler.
///
/// This is typically created by the `#[sen::handler]` macro.
pub struct HandlerWithMeta<H, T, S> {
    pub handler: H,
    pub metadata: HandlerMetadata,
    _marker: PhantomData<fn() -> (T, S)>,
}

impl<H, T, S> Clone for HandlerWithMeta<H, T, S>
where
    H: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            metadata: self.metadata.clone(),
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> HandlerWithMeta<H, T, S>
where
    H: Handler<T, S>,
{
    pub fn new(handler: H, metadata: HandlerMetadata) -> Self {
        Self {
            handler,
            metadata,
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> Handler<T, S> for HandlerWithMeta<H, T, S>
where
    H: Handler<T, S>,
    T: 'static,
    S: Send + Sync + Clone + 'static,
{
    type Future = H::Future;

    fn call(self, state: State<S>, args: Vec<String>) -> Self::Future {
        self.handler.call(state, args)
    }

    fn metadata(&self) -> Option<HandlerMetadata> {
        Some(self.metadata.clone())
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        self.handler.args_schema()
    }
}

/// Type-erased handler for storage in Router
trait ErasedHandler<S>: Send + Sync {
    fn call_boxed<'a>(&'a self, state: State<S>, args: Vec<String>) -> BoxFuture<'a, Response>;

    fn clone_box(&self) -> Box<dyn ErasedHandler<S>>;

    #[allow(dead_code)]
    fn metadata(&self) -> Option<HandlerMetadata>;

    #[allow(dead_code)]
    fn args_schema(&self) -> Option<serde_json::Value>;
}

impl<S> Clone for Box<dyn ErasedHandler<S>> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

/// Wrapper that implements ErasedHandler for any Handler
struct HandlerService<H, T, S> {
    handler: H,
    _marker: PhantomData<fn() -> (T, S)>,
}

impl<H, T, S> HandlerService<H, T, S> {
    fn new(handler: H) -> Self {
        Self {
            handler,
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> Clone for HandlerService<H, T, S>
where
    H: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> ErasedHandler<S> for HandlerService<H, T, S>
where
    H: Handler<T, S>,
    S: Send + Sync + 'static,
    T: 'static,
{
    fn call_boxed<'a>(&'a self, state: State<S>, args: Vec<String>) -> BoxFuture<'a, Response> {
        let handler = self.handler.clone();
        Box::pin(async move { handler.call(state, args).await })
    }

    fn clone_box(&self) -> Box<dyn ErasedHandler<S>> {
        Box::new(self.clone())
    }

    fn metadata(&self) -> Option<HandlerMetadata> {
        self.handler.metadata()
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        self.handler.args_schema()
    }
}

/// Router for CLI commands.
///
/// Similar to Axum's Router, this allows dynamic registration of command handlers.
/// The generic parameter `S` represents the "missing state type" - handlers need
/// `State<S>` to execute.
///
/// # Example
///
/// ```ignore
/// use sen::{Router, State, CliResult};
///
/// async fn status(state: State<AppState>) -> CliResult<String> {
///     Ok("Status: OK".to_string())
/// }
///
/// let router = Router::new()
///     .route("status", status)
///     .with_state(app_state);
///
/// let response = router.execute(&["status"]).await;
/// ```
pub struct Router<S = ()> {
    routes: HashMap<String, Box<dyn ErasedHandler<S>>>,
    route_metadata: HashMap<String, RouteMetadata>,
    metadata: Option<RouterMetadata>,
    agent_mode_enabled: bool,
    #[cfg(feature = "mcp")]
    mcp_enabled: bool,
    _marker: PhantomData<S>,
}

impl<S> Default for Router<S>
where
    S: Send + Sync + Clone + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S> Router<S>
where
    S: Send + Sync + Clone + 'static,
{
    /// Create a new empty router.
    pub fn new() -> Self {
        Self {
            routes: HashMap::new(),
            route_metadata: HashMap::new(),
            metadata: None,
            agent_mode_enabled: false,
            #[cfg(feature = "mcp")]
            mcp_enabled: false,
            _marker: PhantomData,
        }
    }

    /// Register a handler for a command.
    ///
    /// # Example
    ///
    /// ```ignore
    /// router.route("build", handlers::build)
    /// ```
    pub fn route<H, T: 'static>(mut self, command: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, S>,
    {
        let command_name = command.into();
        if self.routes.contains_key(&command_name) {
            panic!("Duplicate route: {}", command_name);
        }

        // Collect handler metadata and schema information
        let handler_meta = handler.metadata();
        let args_schema = handler.args_schema();

        // Store metadata
        self.route_metadata.insert(
            command_name.clone(),
            RouteMetadata {
                handler_meta,
                description: None,
                args_schema,
            },
        );

        self.routes
            .insert(command_name, Box::new(HandlerService::new(handler)));
        self
    }

    /// Nest a router under a prefix.
    ///
    /// This allows organizing commands into hierarchies (subcommands).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let db_router = Router::new()
    ///     .route("create", handlers::db::create)
    ///     .route("list", handlers::db::list)
    ///     .route("delete", handlers::db::delete);
    ///
    /// let app = Router::new()
    ///     .nest("db", db_router)
    ///     .nest("server", server_router)
    ///     .with_state(state);
    ///
    /// // Routes: "db:create", "db:list", "db:delete", "server:start", ...
    /// ```
    pub fn nest(mut self, prefix: impl Into<String>, router: Router<S>) -> Self {
        let prefix = prefix.into();

        // Add all routes from the nested router with the prefix
        for (path, handler) in router.routes {
            let nested_path = if path.is_empty() {
                prefix.clone()
            } else {
                format!("{}:{}", prefix, path)
            };

            if self.routes.contains_key(&nested_path) {
                panic!("Duplicate route: {}", nested_path);
            }

            self.routes.insert(nested_path.clone(), handler);

            // Transfer route metadata if exists
            if let Some(meta) = router.route_metadata.get(&path) {
                self.route_metadata.insert(nested_path, meta.clone());
            }
        }

        self
    }

    /// Attach metadata to the router.
    ///
    /// This is typically used by the `#[sen(...)]` attribute macro to provide
    /// CLI metadata for help generation.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let router = Router::new()
    ///     .route("status", handlers::status)
    ///     .with_metadata(RouterMetadata {
    ///         name: "myctl",
    ///         version: Some("1.0.0"),
    ///         about: Some("My CLI tool"),
    ///     })
    ///     .with_state(state);
    /// ```
    pub fn with_metadata(mut self, metadata: RouterMetadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Enable automatic agent mode support.
    ///
    /// When enabled, the router will:
    /// - Automatically detect `--agent-mode` flag in arguments
    /// - Strip the flag before routing to handlers
    /// - Set `agent_mode` in the Response for automatic JSON output
    ///
    /// # Example
    ///
    /// ```ignore
    /// let router = Router::new()
    ///     .route("build", handlers::build)
    ///     .with_agent_mode()
    ///     .with_state(state);
    ///
    /// // User runs: myapp --agent-mode build
    /// // Router automatically handles the flag and outputs JSON
    /// ```
    pub fn with_agent_mode(mut self) -> Self {
        self.agent_mode_enabled = true;
        self
    }

    /// Enable MCP (Model Context Protocol) support.
    ///
    /// When enabled, the router will recognize and handle MCP-specific flags:
    /// - `--mcp-server`: Start in MCP server mode (JSON-RPC over stdio)
    /// - `--mcp-init <client>`: Generate MCP configuration for the specified client
    ///
    /// # Example
    ///
    /// ```ignore
    /// let router = Router::new()
    ///     .route("build", handlers::build)
    ///     .with_mcp()
    ///     .with_state(state);
    ///
    /// // Usage:
    /// // $ mycli --mcp-server              # Start MCP server
    /// // $ mycli --mcp-init claude         # Generate claude_desktop_config.json
    /// ```
    #[cfg(feature = "mcp")]
    pub fn with_mcp(mut self) -> Self {
        self.mcp_enabled = true;
        self
    }

    /// Provide the application state, converting `Router<S>` to `Router<()>`.
    ///
    /// This follows Axum's pattern where the type system ensures all required
    /// state is provided before the router can execute requests.
    pub fn with_state(self, state: S) -> Router<()> {
        let routes: HashMap<String, Box<dyn ErasedHandler<()>>> = self
            .routes
            .into_iter()
            .map(|(cmd, handler)| {
                let state = state.clone();
                let boxed: Box<dyn ErasedHandler<()>> =
                    Box::new(StatefulHandler { handler, state });
                (cmd, boxed)
            })
            .collect();

        Router {
            routes,
            route_metadata: self.route_metadata,
            metadata: self.metadata,
            agent_mode_enabled: self.agent_mode_enabled,
            #[cfg(feature = "mcp")]
            mcp_enabled: self.mcp_enabled,
            _marker: PhantomData,
        }
    }
}

/// Handler that has been bound to a state
struct StatefulHandler<S> {
    handler: Box<dyn ErasedHandler<S>>,
    state: S,
}

impl<S> Clone for StatefulHandler<S>
where
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            state: self.state.clone(),
        }
    }
}

impl<S> ErasedHandler<()> for StatefulHandler<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn call_boxed<'a>(&'a self, _state: State<()>, args: Vec<String>) -> BoxFuture<'a, Response> {
        let handler = self.handler.clone();
        let state = State::new(self.state.clone());
        Box::pin(async move { handler.call_boxed(state, args).await })
    }

    fn clone_box(&self) -> Box<dyn ErasedHandler<()>> {
        Box::new(self.clone())
    }

    fn metadata(&self) -> Option<HandlerMetadata> {
        self.handler.metadata()
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        self.handler.args_schema()
    }
}

impl Router<()> {
    /// Execute a command using environment arguments.
    ///
    /// This is the most common usage - automatically reads from `std::env::args()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[tokio::main]
    /// async fn main() {
    ///     let router = Router::new()
    ///         .route("build", build_handler)
    ///         .route("test", test_handler);
    ///
    ///     let response = router.execute().await;
    ///     std::process::exit(response.exit_code);
    /// }
    /// ```
    pub async fn execute(&self) -> Response {
        let args: Vec<String> = std::env::args().collect();
        self.execute_with(&args).await
    }

    /// Execute a command with custom arguments.
    ///
    /// Useful for testing or when you need to provide arguments programmatically.
    /// The first element (`args[0]`) should be the program name (like `std::env::args()`).
    ///
    /// Supports both flat and nested command structures:
    /// - `["myapp", "build"]` → matches route "build"
    /// - `["myapp", "db", "create"]` → matches route "db:create"
    /// - `["myapp", "db", "backup", "create"]` → matches route "db:backup:create"
    ///
    /// Special handling:
    /// - `--help` or `-h` → displays help message
    /// - `version` → displays version (if metadata.version is set)
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Testing
    /// let response = router.execute_with(&["myapp", "build", "--release"]).await;
    /// assert_eq!(response.exit_code, 0);
    /// ```
    ///
    /// Returns a Response with exit code and output.
    pub async fn execute_with(&self, args: &[String]) -> Response {
        // Skip program name (args[0])
        let command_args = if args.is_empty() { &[] } else { &args[1..] };

        // Detect and strip --agent-mode flag if agent_mode is enabled
        let (agent_mode_active, command_args) = if self.agent_mode_enabled {
            let agent_mode = command_args.contains(&"--agent-mode".to_string());
            let filtered: Vec<String> = command_args
                .iter()
                .filter(|arg| *arg != "--agent-mode")
                .cloned()
                .collect();
            (agent_mode, filtered)
        } else {
            (false, command_args.to_vec())
        };

        let command_args_slice: &[String] = &command_args;

        // Handle MCP flags if MCP is enabled
        #[cfg(feature = "mcp")]
        if self.mcp_enabled {
            // Handle --mcp-server flag
            if command_args_slice.contains(&"--mcp-server".to_string()) {
                // Convert route_metadata to MCP tool schemas
                let tools: Vec<crate::mcp::McpTool> = self
                    .route_metadata
                    .iter()
                    .map(|(name, metadata)| {
                        crate::mcp::McpTool::from_route_metadata(name.clone(), metadata)
                    })
                    .collect();

                // Get program name for building full command args
                let program_name = args
                    .get(0)
                    .cloned()
                    .unwrap_or_else(|| "program".to_string());

                return crate::mcp::run_mcp_server(tools, |tool_name, tool_args| {
                    // Build full args: ["program_name", "command", "subcommand", ...tool_args]
                    let mut full_args = vec![program_name.clone()];

                    // Split tool_name by ":" to get command path (e.g., "db:create" -> ["db", "create"])
                    for part in tool_name.split(':') {
                        full_args.push(part.to_string());
                    }

                    // Add tool arguments
                    full_args.extend(tool_args);

                    // Execute the command (block on async function)
                    futures::executor::block_on(self.execute_with(&full_args))
                });
            }

            // Handle --mcp-init flag
            if let Some(pos) = command_args_slice
                .iter()
                .position(|arg| arg == "--mcp-init")
            {
                // Get client name (next argument after --mcp-init)
                let client = command_args_slice
                    .get(pos + 1)
                    .map(|s| s.as_str())
                    .unwrap_or("claude");

                // Get command path (first arg in original args, or current executable)
                let command_path = args
                    .get(0)
                    .cloned()
                    .or_else(|| {
                        std::env::current_exe()
                            .ok()
                            .and_then(|p| p.to_str().map(String::from))
                    })
                    .unwrap_or_else(|| "myctl".to_string());

                // Convert route_metadata to MCP tool schemas
                let tools: Vec<crate::mcp::McpTool> = self
                    .route_metadata
                    .iter()
                    .map(|(name, metadata)| {
                        crate::mcp::McpTool::from_route_metadata(name.clone(), metadata)
                    })
                    .collect();

                return crate::mcp::generate_mcp_config(client, command_path, tools);
            }
        }

        // Handle --help flag ONLY if no command is specified yet
        // If a command is specified (e.g., "build --help"), let Clap handle it
        if command_args_slice.is_empty()
            || (command_args_slice.len() == 1
                && (command_args_slice[0] == "--help" || command_args_slice[0] == "-h"))
        {
            // Show general CLI help
            let mut response = self.generate_help(&[], false);
            response.agent_mode = agent_mode_active;
            return response;
        }

        // Handle --help --json for schema output
        if command_args_slice.contains(&"--help".to_string())
            && command_args_slice.contains(&"--json".to_string())
        {
            let mut response = self.generate_cli_schema_json();
            response.agent_mode = agent_mode_active;
            return response;
        }

        // Handle --help --md for AI/Agent-friendly markdown output
        if command_args_slice.contains(&"--help".to_string())
            && command_args_slice.contains(&"--md".to_string())
        {
            let mut response = self.generate_help_markdown();
            response.agent_mode = agent_mode_active;
            return response;
        }

        // Handle built-in version command
        if command_args_slice.len() == 1
            && (command_args_slice[0] == "version"
                || command_args_slice[0] == "--version"
                || command_args_slice[0] == "-V")
        {
            let mut response = self.handle_version();
            response.agent_mode = agent_mode_active;
            return response;
        }

        // Try to match nested commands first (longest match wins)
        // e.g., ["db", "create", "--flag"] tries:
        //   1. "db:create" (found!)
        //   2. "db" (fallback)
        let (matched_handler, remaining_args) = self.find_route(command_args_slice);

        let mut response = match matched_handler {
            Some(handler) => {
                let state = State::new(());
                handler.call_boxed(state, remaining_args).await
            }
            None => {
                let command = command_args_slice.join(" ");
                let err: CliResult<()> =
                    Err(CliError::user(format!("Unknown command: {}", command)));
                err.into_response()
            }
        };

        // Set agent_mode flag if it was detected
        response.agent_mode = agent_mode_active;
        response
    }

    /// Generate help message based on router metadata and available commands.
    fn generate_help(&self, _args: &[String], json_output: bool) -> Response {
        if json_output {
            self.generate_cli_schema_json()
        } else {
            self.generate_help_text()
        }
    }

    /// Generate clean, human-readable help text for terminal display.
    ///
    /// Supports colored output when stdout is a terminal.
    fn generate_help_text(&self) -> Response {
        use anstyle::{AnsiColor, Effects, Style};

        // Define styles
        let use_color = std::io::IsTerminal::is_terminal(&std::io::stdout());

        let header_style = if use_color {
            Style::new()
                .fg_color(Some(AnsiColor::Green.into()))
                .effects(Effects::BOLD)
        } else {
            Style::new()
        };

        let section_style = if use_color {
            Style::new()
                .fg_color(Some(AnsiColor::Yellow.into()))
                .effects(Effects::BOLD)
        } else {
            Style::new()
        };

        let cmd_style = if use_color {
            Style::new().fg_color(Some(AnsiColor::Cyan.into()))
        } else {
            Style::new()
        };

        let dim_style = if use_color {
            Style::new().effects(Effects::DIMMED)
        } else {
            Style::new()
        };

        let reset = if use_color {
            Style::new().render_reset().to_string()
        } else {
            String::new()
        };

        let mut help = String::new();

        // Header: name + version + about
        if let Some(meta) = &self.metadata {
            help.push_str(&format!("{}", header_style.render()));
            help.push_str(meta.name);
            if let Some(version) = meta.version {
                help.push_str(&format!(" {}", version));
            }
            help.push_str(&reset);
            help.push('\n');

            if let Some(about) = meta.about {
                help.push_str(about);
                help.push('\n');
            }
            help.push('\n');
        }

        // Usage line
        let cli_name = self
            .metadata
            .as_ref()
            .map(|m| m.name)
            .unwrap_or("<command>");
        help.push_str(&format!(
            "{}Usage:{} {} [OPTIONS] <COMMAND>\n\n",
            section_style.render(),
            reset,
            cli_name
        ));

        // Group commands by prefix
        let grouped_commands = self.group_commands_by_prefix();

        // Calculate global max length for consistent alignment across all groups
        let global_max_len = grouped_commands
            .iter()
            .flat_map(|(_, cmds)| cmds.iter().map(|(name, _, _)| name.len()))
            .max()
            .unwrap_or(8)
            .max(8); // Minimum 8 chars

        // Display grouped commands
        for (group_name, commands) in &grouped_commands {
            if !group_name.is_empty() {
                help.push_str(&format!(
                    "{}{}:{}\n",
                    section_style.render(),
                    group_name,
                    reset
                ));
            } else {
                help.push_str(&format!("{}Commands:{}\n", section_style.render(), reset));
            }

            for (name, _full_name, desc) in commands {
                if desc.is_empty() {
                    help.push_str(&format!("  {}{}{}\n", cmd_style.render(), name, reset));
                } else {
                    help.push_str(&format!(
                        "  {}{:width$}{}  {}{}{}\n",
                        cmd_style.render(),
                        name,
                        reset,
                        dim_style.render(),
                        desc,
                        reset,
                        width = global_max_len
                    ));
                }
            }
            help.push('\n');
        }

        // Options section
        help.push_str(&format!("{}Options:{}\n", section_style.render(), reset));
        help.push_str(&format!(
            "  {}-h{}, {}--help{}            Print help\n",
            cmd_style.render(),
            reset,
            cmd_style.render(),
            reset
        ));
        if self.metadata.as_ref().and_then(|m| m.version).is_some() {
            help.push_str(&format!(
                "  {}-V{}, {}--version{}         Print version\n",
                cmd_style.render(),
                reset,
                cmd_style.render(),
                reset
            ));
        }
        help.push('\n');

        // Alternative formats for automation
        help.push_str(&format!(
            "{}For AI/Agent:{}\n",
            section_style.render(),
            reset
        ));
        help.push_str(&format!(
            "      {}--help --md{}       Print help in Markdown format\n",
            cmd_style.render(),
            reset
        ));
        help.push('\n');
        help.push_str(&format!(
            "{}For Programs:{}\n",
            section_style.render(),
            reset
        ));
        help.push_str(&format!(
            "      {}--help --json{}     Print CLI schema in JSON format\n",
            cmd_style.render(),
            reset
        ));

        Response::text(help)
    }

    /// Generate Markdown-formatted help for AI/Agent consumption.
    ///
    /// This format is designed to be:
    /// - Parseable by LLMs and agents
    /// - Rich with metadata (tiers, tags, arguments)
    /// - Suitable for documentation generation
    fn generate_help_markdown(&self) -> Response {
        let mut md = String::new();

        // Header
        let cli_name = self.metadata.as_ref().map(|m| m.name).unwrap_or("CLI");
        let version = self
            .metadata
            .as_ref()
            .and_then(|m| m.version)
            .unwrap_or("0.0.0");
        let about = self
            .metadata
            .as_ref()
            .and_then(|m| m.about)
            .unwrap_or("Command-line interface");

        md.push_str(&format!("# {} v{}\n\n", cli_name, version));
        md.push_str(&format!("{}\n\n", about));

        // Usage
        md.push_str("## Usage\n\n");
        md.push_str(&format!("```\n{} [OPTIONS] <COMMAND>\n```\n\n", cli_name));

        // Commands by group
        md.push_str("## Commands\n\n");

        let grouped_commands = self.group_commands_by_prefix();

        for (group_name, commands) in &grouped_commands {
            if !group_name.is_empty() && group_name != "Other Commands" {
                md.push_str(&format!("### {}\n\n", group_name));
            } else if group_name == "Other Commands" {
                md.push_str("### Other Commands\n\n");
            }

            md.push_str("| Command | Description | Tier | Tags |\n");
            md.push_str("|---------|-------------|------|------|\n");

            for (_name, full_name, desc) in commands {
                // Get metadata for this command
                let meta = self.route_metadata.get(full_name.as_str());
                let handler_meta = meta.and_then(|m| m.handler_meta.as_ref());

                let tier = handler_meta
                    .and_then(|h| h.tier)
                    .map(|t| t.as_str())
                    .unwrap_or("-");

                let tags = handler_meta
                    .and_then(|h| h.tags.as_ref())
                    .map(|t| t.join(", "))
                    .unwrap_or_else(|| "-".to_string());

                let desc_escaped = if desc.is_empty() {
                    "-".to_string()
                } else {
                    desc.replace('|', "\\|")
                };

                md.push_str(&format!(
                    "| `{}` | {} | {} | {} |\n",
                    full_name, desc_escaped, tier, tags
                ));
            }
            md.push('\n');
        }

        // Options
        md.push_str("## Options\n\n");
        md.push_str("| Option | Description |\n");
        md.push_str("|--------|-------------|\n");
        md.push_str("| `-h, --help` | Print help |\n");
        md.push_str("| `--help --md` | Print help (Markdown format) |\n");
        md.push_str("| `--help --json` | Print CLI schema (JSON format) |\n");
        if self.metadata.as_ref().and_then(|m| m.version).is_some() {
            md.push_str("| `-V, --version` | Print version |\n");
        }
        md.push('\n');

        // Command Details (for AI context)
        md.push_str("## Command Details\n\n");

        let mut sorted_commands: Vec<_> = self.routes.keys().collect();
        sorted_commands.sort();

        for cmd in sorted_commands {
            let meta = self.route_metadata.get(cmd.as_str());
            let handler_meta = meta.and_then(|m| m.handler_meta.as_ref());
            let desc = handler_meta.and_then(|h| h.desc).unwrap_or("");

            md.push_str(&format!("### `{}`\n\n", cmd));

            if !desc.is_empty() {
                md.push_str(&format!("{}\n\n", desc));
            }

            // Show usage
            md.push_str(&format!(
                "```\n{} {}\n```\n\n",
                cli_name,
                cmd.replace(':', " ")
            ));
        }

        Response::text(md)
    }

    /// Group commands by their prefix (e.g., "db:*" -> "Database Commands").
    /// Returns groups in order: named groups first (sorted), then "Other Commands" last.
    fn group_commands_by_prefix(&self) -> GroupedCommands {
        use std::collections::HashMap;

        let mut groups: HashMap<String, Vec<CommandEntry>> = HashMap::new();
        let mut commands: Vec<_> = self.routes.keys().collect();
        commands.sort();

        for cmd in commands {
            let desc = self
                .route_metadata
                .get(cmd.as_str())
                .and_then(|meta| meta.get_description())
                .unwrap_or("");

            // Check if command has a prefix (e.g., "db:create" -> prefix "db")
            if let Some(colon_pos) = cmd.find(':') {
                let prefix = &cmd[..colon_pos];
                let suffix = &cmd[colon_pos + 1..];

                // Generate group name (e.g., "db" -> "Database Commands")
                let group_name = self.format_group_name(prefix);

                groups.entry(group_name).or_default().push((
                    suffix.to_string(),
                    cmd.to_string(),
                    desc.to_string(),
                ));
            } else {
                // No prefix - add to "Other Commands"
                groups
                    .entry("Other Commands".to_string())
                    .or_default()
                    .push((cmd.to_string(), cmd.to_string(), desc.to_string()));
            }
        }

        // Sort commands within each group
        for (_, commands) in groups.iter_mut() {
            commands.sort_by(|a, b| a.0.cmp(&b.0));
        }

        // Sort groups: named groups alphabetically, "Other Commands" last
        let mut result: Vec<_> = groups.into_iter().collect();
        result.sort_by(|a, b| {
            if a.0 == "Other Commands" {
                std::cmp::Ordering::Greater
            } else if b.0 == "Other Commands" {
                std::cmp::Ordering::Less
            } else {
                a.0.cmp(&b.0)
            }
        });

        result
    }

    /// Format a command prefix into a nice group name.
    /// Examples: "db" -> "Database Commands", "config" -> "Configuration Commands"
    fn format_group_name(&self, prefix: &str) -> String {
        let capitalized = match prefix {
            "db" => "Database",
            "config" => "Configuration",
            "deploy" => "Deployment",
            "server" => "Server",
            "network" => "Network",
            "storage" => "Storage",
            _ => {
                // Default: capitalize first letter
                let mut chars = prefix.chars();
                match chars.next() {
                    None => return "Commands".to_string(),
                    Some(first) => {
                        return format!(
                            "{}{} Commands",
                            first.to_uppercase(),
                            chars.collect::<String>()
                        );
                    }
                }
            }
        };
        format!("{} Commands", capitalized)
    }

    /// Generate CLI schema JSON specification.
    ///
    /// Outputs a CLI-friendly JSON format that includes all commands with their
    /// arguments, options, and metadata in a single dump.
    fn generate_cli_schema_json(&self) -> Response {
        use serde_json::json;

        let name = self.metadata.as_ref().map(|m| m.name).unwrap_or("cli");
        let version = self
            .metadata
            .as_ref()
            .and_then(|m| m.version)
            .unwrap_or("unknown");
        let description = self.metadata.as_ref().and_then(|m| m.about);

        let mut commands = serde_json::Map::new();

        // Collect all routes and their metadata
        let mut command_names: Vec<_> = self.routes.keys().collect();
        command_names.sort();

        for cmd in command_names {
            // Get handler metadata
            let handler_meta = self
                .route_metadata
                .get(cmd)
                .and_then(|meta| meta.handler_meta.as_ref());

            // Get handler description
            let desc = handler_meta
                .and_then(|h| h.desc)
                .unwrap_or("No description available");

            // Get tier information
            let tier = handler_meta.and_then(|h| h.tier).map(|t| t.as_str());

            // Get tags
            let tags = handler_meta.and_then(|h| h.tags.as_ref());

            // Build usage string
            let usage = format!("{} {}", name, cmd.replace(':', " "));

            let mut command_schema = json!({
                "description": desc,
                "usage": usage,
            });

            // Add tier if available
            if let Some(tier_str) = tier {
                command_schema["tier"] = json!(tier_str);
                command_schema["requires_approval"] = json!(Tier::parse(tier_str)
                    .map(|t| t.requires_approval())
                    .unwrap_or(false));
            }

            // Add tags if available
            if let Some(tag_list) = tags {
                command_schema["tags"] = json!(tag_list);
            }

            // Add argument schema if available
            if let Some(meta) = self.route_metadata.get(cmd) {
                if let Some(args_schema) = &meta.args_schema {
                    command_schema["arguments"] = args_schema["arguments"].clone();
                    command_schema["options"] = args_schema["options"].clone();
                }
            }

            commands.insert(cmd.to_string(), command_schema);
        }

        let spec = json!({
            "name": name,
            "version": version,
            "description": description.unwrap_or(""),
            "commands": commands,
        });

        match serde_json::to_string_pretty(&spec) {
            Ok(json) => Response::text(json),
            Err(e) => Response::error(1, format!("Failed to generate JSON: {}", e)),
        }
    }

    /// Handle version command.
    fn handle_version(&self) -> Response {
        if let Some(meta) = &self.metadata {
            if let Some(version) = meta.version {
                return Response::text(format!("{} {}", meta.name, version));
            }
        }

        #[cfg(feature = "build-info")]
        {
            Response::text(crate::version_info())
        }

        #[cfg(not(feature = "build-info"))]
        Response::text("version information not available")
    }

    /// Find the longest matching route for the given arguments.
    ///
    /// Returns the matched handler and remaining arguments.
    fn find_route(&self, args: &[String]) -> (Option<&dyn ErasedHandler<()>>, Vec<String>) {
        // Try matching from longest to shortest
        for depth in (1..=args.len()).rev() {
            let route_parts = &args[..depth];
            let route_key = route_parts.join(":");

            if let Some(handler) = self.routes.get(&route_key) {
                let remaining = args[depth..].to_vec();
                return (Some(handler.as_ref()), remaining);
            }
        }

        (None, args.to_vec())
    }
}

// ============================================================================
// Args Extractor (Axum-style)
// ============================================================================

/// Extractor for command-line arguments.
///
/// Similar to Axum's `Path` or `Query`, this allows handlers to receive
/// parsed arguments.
///
/// # Example
///
/// ```ignore
/// #[derive(Debug)]
/// struct BuildArgs {
///     release: bool,
/// }
///
/// impl FromArgs for BuildArgs {
///     fn from_args(args: &[String]) -> Result<Self, CliError> {
///         Ok(BuildArgs {
///             release: args.get(0).map(|s| s == "--release").unwrap_or(false),
///         })
///     }
/// }
///
/// async fn build(State(app): State<AppState>, Args(args): Args<BuildArgs>) -> CliResult<String> {
///     if args.release {
///         Ok("Release build".to_string())
///     } else {
///         Ok("Debug build".to_string())
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Args<T>(pub T);

/// Trait for parsing command-line arguments into a type.
///
/// This is similar to Axum's `FromRequest` trait and provides a lightweight
/// way to parse per-command arguments.
///
/// # When to use `FromArgs`
///
/// Use `FromArgs` when:
/// - ✅ You have simple per-command arguments (e.g., `--release`, `--output file.txt`)
/// - ✅ You don't need global flags that apply to all commands
/// - ✅ You want the framework to handle argument injection automatically
///
/// **Don't use `FromArgs` when:**
/// - ❌ You need global flags (e.g., `--verbose`, `--config`) → use `FromGlobalArgs`
/// - ❌ You need complex validation or conflicting flag logic → use `clap` directly
/// - ❌ You're building a production CLI with many commands → see `examples/practical-cli`
///
/// # Example
///
/// ```rust
/// use sen::{Args, FromArgs, CliError, CliResult};
///
/// #[derive(Debug)]
/// struct BuildArgs {
///     release: bool,
///     output: Option<String>,
/// }
///
/// impl FromArgs for BuildArgs {
///     fn from_args(args: &[String]) -> Result<Self, CliError> {
///         let mut release = false;
///         let mut output = None;
///
///         let mut iter = args.iter();
///         while let Some(arg) = iter.next() {
///             match arg.as_str() {
///                 "--release" => release = true,
///                 "--output" => output = iter.next().map(|s| s.clone()),
///                 _ => {}
///             }
///         }
///
///         Ok(BuildArgs { release, output })
///     }
/// }
///
/// // Use in handler
/// async fn build(Args(args): Args<BuildArgs>) -> CliResult<String> {
///     let mode = if args.release { "release" } else { "debug" };
///     Ok(format!("Building in {} mode", mode))
/// }
/// ```
///
/// # Comparison with `FromGlobalArgs`
///
/// | Feature | `FromArgs` | `FromGlobalArgs` |
/// |---------|-----------|------------------|
/// | Scope | Per-command | All commands |
/// | Injection | Via `Args<T>` extractor | Via `State<AppState>` |
/// | Use case | Simple flags | Global configuration |
/// | Example | `--release`, `--output` | `--verbose`, `--config` |
///
/// See README.md § "Argument Parsing: FromArgs vs Global Options" for detailed guide.
pub trait FromArgs: Sized {
    /// Parse arguments into Self, or return an error.
    fn from_args(args: &[String]) -> Result<Self, CliError>;

    /// Get CLI schema information for this argument type (optional).
    ///
    /// Returns JSON representation of the command structure, including
    /// arguments, options, and descriptions.
    fn cli_schema() -> Option<serde_json::Value> {
        None
    }
}

/// Trait for parsing global options from command-line arguments.
///
/// Global options are flags that apply to **all commands** in your CLI,
/// such as `--verbose`, `--config`, or `--output-format`.
///
/// # When to use `FromGlobalArgs`
///
/// Use `FromGlobalArgs` when:
/// - ✅ You have flags that apply to **all** commands (e.g., `--verbose`, `--config`)
/// - ✅ You want to avoid repeating the same flags in every handler
/// - ✅ You're building a production CLI with multiple commands
/// - ✅ You need integration with `clap` or other complex parsers
///
/// # Comparison with `FromArgs`
///
/// | Feature | `FromArgs` | `FromGlobalArgs` |
/// |---------|-----------|------------------|
/// | Scope | Per-command | All commands |
/// | Injection | Via `Args<T>` extractor | Via `State<AppState>` |
/// | Parsing time | During handler call | Before routing |
/// | Use case | Command-specific flags | CLI-wide configuration |
///
/// # Example: Production CLI Pattern
///
/// ```ignore
/// use sen::FromGlobalArgs;
///
/// #[derive(Clone)]
/// struct GlobalOpts {
///     verbose: bool,
///     config: Option<String>,
/// }
///
/// impl FromGlobalArgs for GlobalOpts {
///     fn from_global_args(args: &[String]) -> Result<(Self, Vec<String>), CliError> {
///         let mut verbose = false;
///         let mut config = None;
///         let mut remaining = Vec::new();
///
///         for arg in args {
///             match arg.as_str() {
///                 "--verbose" | "-v" => verbose = true,
///                 s if s.starts_with("--config=") => {
///                     config = Some(s.strip_prefix("--config=").unwrap().to_string());
///                 }
///                 _ => remaining.push(arg.clone()),
///             }
///         }
///
///         Ok((GlobalOpts { verbose, config }, remaining))
///     }
/// }
///
/// #[derive(Clone)]
/// struct AppState {
///     global: GlobalOpts,
///     // ... other state fields
/// }
///
/// #[tokio::main]
/// async fn main() {
///     let args: Vec<String> = std::env::args().skip(1).collect();
///     let (global_opts, remaining) = GlobalOpts::from_global_args(&args).unwrap();
///
///     let state = AppState { global: global_opts };
///     let router = Router::new()
///         .route("build", handlers::build)
///         .with_state(state);
///
///     // Execute with remaining args (global flags already parsed)
///     let program_name = std::env::args().next().unwrap_or_default();
///     let mut execute_args = vec![program_name];
///     execute_args.extend(remaining);
///     let response = router.execute_with(&execute_args).await;
/// }
/// ```
///
/// # Real-World Pattern
///
/// This pattern mirrors production CLIs like `kubectl`, `docker`, `aws`:
///
/// ```bash
/// kubectl --context=prod get pods          # global: --context, command: get
/// docker --debug run nginx                 # global: --debug, command: run
/// myctl --verbose --config=prod db create  # global: --verbose --config, command: db create
/// ```
///
/// See `examples/practical-cli` for a complete implementation with nested commands.
///
/// See README.md § "Argument Parsing: FromArgs vs Global Options" for detailed guide.
pub trait FromGlobalArgs: Sized + Clone {
    /// Parse global options from command-line arguments.
    ///
    /// This is called before routing, so it receives all arguments.
    /// It should extract global flags and return the remaining non-global args.
    ///
    /// Returns `(parsed_options, remaining_args)` where `remaining_args` should be
    /// passed to the router for command routing.
    fn from_global_args(args: &[String]) -> Result<(Self, Vec<String>), CliError>;
}

// ============================================================================
// Clap Integration (when clap feature is enabled)
// ============================================================================

#[cfg(feature = "clap")]
/// Blanket implementation: any type implementing `clap::Parser` can be used with `Args<T>`.
///
/// This allows seamless integration with clap's derive macros:
///
/// ```ignore
/// use clap::Parser;
/// use sen::{Args, CliResult, State};
///
/// #[derive(Parser)]
/// struct BuildArgs {
///     /// Database name
///     name: String,
///
///     /// Build in release mode
///     #[arg(long)]
///     release: bool,
///
///     /// Target architecture (can also be set via env var)
///     #[arg(long, env = "BUILD_TARGET")]
///     target: Option<String>,
/// }
///
/// async fn build(
///     state: State<AppState>,
///     Args(args): Args<BuildArgs>  // Clap automatically parses!
/// ) -> CliResult<String> {
///     if args.release {
///         Ok("Building in release mode".to_string())
///     } else {
///         Ok("Building in debug mode".to_string())
///     }
/// }
/// ```
impl<T> FromArgs for T
where
    T: clap::Parser,
{
    fn from_args(args: &[String]) -> Result<Self, CliError> {
        // Clap expects the command name as the first argument
        // Since we're parsing subcommand args, we need to prepend a dummy command name
        let args_with_cmd = std::iter::once("cmd".to_string())
            .chain(args.iter().cloned())
            .collect::<Vec<_>>();

        T::try_parse_from(args_with_cmd).map_err(|e| {
            // Clap's DisplayHelp and DisplayVersion are not errors - they're successful exits
            // We want to preserve the formatted output, not treat it as an error
            use clap::error::ErrorKind;
            match e.kind() {
                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => {
                    // Extract the formatted help/version text and return as Help variant
                    // This will result in exit code 0
                    CliError::User(UserError::Help(e.to_string()))
                }
                _ => CliError::user(e.to_string()),
            }
        })
    }

    fn cli_schema() -> Option<serde_json::Value> {
        let cmd = T::command();
        Some(clap_command_to_json(&cmd))
    }
}

#[cfg(feature = "clap")]
/// Convert a clap::Command to a JSON representation.
fn clap_command_to_json(cmd: &clap::Command) -> serde_json::Value {
    use serde_json::json;

    // Extract positional arguments
    let mut positionals = Vec::new();
    let mut options = Vec::new();

    for arg in cmd.get_arguments() {
        if arg.is_positional() {
            positionals.push(json!({
                "name": arg.get_id().as_str(),
                "type": format!("{:?}", arg.get_value_parser().type_id()),
                "required": arg.is_required_set(),
                "description": arg.get_help().map(|h| h.to_string()).unwrap_or_default(),
            }));
        } else {
            let mut option = json!({
                "name": format!("--{}", arg.get_id().as_str()),
                "type": format!("{:?}", arg.get_value_parser().type_id()),
                "required": arg.is_required_set(),
                "description": arg.get_help().map(|h| h.to_string()).unwrap_or_default(),
            });

            // Add short flag if available
            if let Some(short) = arg.get_short() {
                option["short"] = json!(format!("-{}", short));
            }

            // Add default value if available
            let defaults = arg.get_default_values();
            if !defaults.is_empty() {
                option["default"] = json!(defaults[0].to_string_lossy().to_string());
            }

            // Add env var if available
            if let Some(env) = arg.get_env() {
                option["env"] = json!(env.to_string_lossy().to_string());
            }

            options.push(option);
        }
    }

    json!({
        "arguments": positionals,
        "options": options,
    })
}

#[cfg(feature = "clap")]
/// Blanket implementation for global options using clap::Parser.
///
/// This allows using clap's derive macros for global flags:
///
/// ```ignore
/// use clap::Parser;
///
/// #[derive(Parser, Clone)]
/// struct GlobalOpts {
///     /// Enable verbose logging
///     #[arg(long, short, global = true)]
///     verbose: bool,
///
///     /// Configuration file path
///     #[arg(long, global = true)]
///     config: Option<String>,
/// }
/// ```
impl<T> FromGlobalArgs for T
where
    T: clap::Parser + Clone,
{
    fn from_global_args(args: &[String]) -> Result<(Self, Vec<String>), CliError> {
        // Try to parse global options using clap
        // We need to use clap's API to extract global flags and return remaining args

        // For now, parse all args and let clap handle it
        // In a real implementation, we'd need to separate global from command-specific args
        let args_with_cmd = std::iter::once("cmd".to_string())
            .chain(args.iter().cloned())
            .collect::<Vec<_>>();

        match T::try_parse_from(&args_with_cmd) {
            Ok(global) => {
                // For simplicity, return empty remaining args
                // In practice, clap would need to be configured to allow unknown args
                Ok((global, vec![]))
            }
            Err(e) => Err(CliError::user(e.to_string())),
        }
    }
}

// ============================================================================
// Manual FromArgs implementations (when clap feature is NOT enabled)
// ============================================================================

#[cfg(not(feature = "clap"))]
// Implement FromArgs for () (no args needed)
impl FromArgs for () {
    fn from_args(_args: &[String]) -> Result<Self, CliError> {
        Ok(())
    }
}

#[cfg(not(feature = "clap"))]
// Implement FromArgs for Vec<String> (raw args)
impl FromArgs for Vec<String> {
    fn from_args(args: &[String]) -> Result<Self, CliError> {
        Ok(args.to_vec())
    }
}

// ============================================================================
// Handler Implementations for Common Function Signatures
// ============================================================================

// Handler for: async fn(State<S>) -> impl IntoResponse
impl<F, Fut, S, Res> Handler<(State<S>,), S> for F
where
    F: Fn(State<S>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Res> + Send + 'static,
    Res: IntoResponse + 'static,
    S: Send + Sync + Clone + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

    fn call(self, state: State<S>, _args: Vec<String>) -> Self::Future {
        Box::pin(async move {
            let result = self(state).await;
            result.into_response()
        })
    }
}

// Handler for: async fn(State<S>, Args<T>) -> impl IntoResponse
impl<F, Fut, S, T, Res> Handler<(State<S>, Args<T>), S> for F
where
    F: Fn(State<S>, Args<T>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Res> + Send + 'static,
    Res: IntoResponse + 'static,
    T: FromArgs + Send + 'static,
    S: Send + Sync + Clone + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

    fn call(self, state: State<S>, args: Vec<String>) -> Self::Future {
        Box::pin(async move {
            // Parse args
            let parsed_args = match T::from_args(&args) {
                Ok(args) => args,
                Err(e) => {
                    let result: CliResult<()> = Err(e);
                    return result.into_response();
                }
            };

            let result = self(state, Args(parsed_args)).await;
            result.into_response()
        })
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        T::cli_schema()
    }
}

// Handler for: async fn(Args<T>) -> impl IntoResponse (no state)
impl<F, Fut, T, Res> Handler<(Args<T>,), ()> for F
where
    F: Fn(Args<T>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Res> + Send + 'static,
    Res: IntoResponse + 'static,
    T: FromArgs + Send + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

    fn call(self, _state: State<()>, args: Vec<String>) -> Self::Future {
        Box::pin(async move {
            // Parse args
            let parsed_args = match T::from_args(&args) {
                Ok(args) => args,
                Err(e) => {
                    let result: CliResult<()> = Err(e);
                    return result.into_response();
                }
            };

            let result = self(Args(parsed_args)).await;
            result.into_response()
        })
    }

    fn args_schema(&self) -> Option<serde_json::Value> {
        T::cli_schema()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    // ========================================
    // Tier Tests
    // ========================================

    #[test]
    fn test_tier_parse() {
        assert_eq!(Tier::parse("safe"), Some(Tier::Safe));
        assert_eq!(Tier::parse("SAFE"), Some(Tier::Safe));
        assert_eq!(Tier::parse("standard"), Some(Tier::Standard));
        assert_eq!(Tier::parse("critical"), Some(Tier::Critical));
        assert_eq!(Tier::parse("invalid"), None);
    }

    #[test]
    fn test_tier_as_str() {
        assert_eq!(Tier::Safe.as_str(), "safe");
        assert_eq!(Tier::Standard.as_str(), "standard");
        assert_eq!(Tier::Critical.as_str(), "critical");
    }

    #[test]
    fn test_tier_requires_approval() {
        assert!(!Tier::Safe.requires_approval());
        assert!(!Tier::Standard.requires_approval());
        assert!(Tier::Critical.requires_approval());
    }

    #[test]
    fn test_tier_display() {
        assert_eq!(format!("{}", Tier::Safe), "safe");
        assert_eq!(format!("{}", Tier::Standard), "standard");
        assert_eq!(format!("{}", Tier::Critical), "critical");
    }

    // ========================================
    // State Tests
    // ========================================

    #[tokio::test]
    async fn test_state_creation_and_access() {
        struct TestState {
            value: i32,
        }

        let state = State::new(TestState { value: 42 });
        assert_eq!(state.read().await.value, 42);

        let cloned = state.clone();
        assert_eq!(cloned.read().await.value, 42);
    }

    #[tokio::test]
    async fn test_state_write() {
        struct TestState {
            value: i32,
        }

        let state = State::new(TestState { value: 42 });

        // Mutate through write lock
        {
            let mut app = state.write().await;
            app.value = 100;
        }

        // Verify mutation
        assert_eq!(state.read().await.value, 100);
    }

    #[test]
    fn test_user_error_exit_code() {
        let err = CliError::user("test error");
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn test_system_error_exit_code() {
        let err = CliError::system("test error");
        assert_eq!(err.exit_code(), 101);
    }

    #[test]
    fn test_string_into_response() {
        let response = "hello".to_string().into_response();
        assert_eq!(response.exit_code, 0);
        assert!(matches!(response.output, Output::Text(_)));
    }

    #[test]
    fn test_unit_into_response() {
        let response = ().into_response();
        assert_eq!(response.exit_code, 0);
        assert!(matches!(response.output, Output::Silent));
    }

    #[test]
    fn test_result_ok_into_response() {
        let result: CliResult<String> = Ok("success".to_string());
        let response = result.into_response();
        assert_eq!(response.exit_code, 0);
    }

    #[test]
    fn test_result_err_into_response() {
        let result: CliResult<String> = Err(CliError::user("failure"));
        let response = result.into_response();
        assert_eq!(response.exit_code, 1);
    }

    // ========================================
    // Router Tests
    // ========================================

    #[tokio::test]
    async fn test_router_basic() {
        #[derive(Clone)]
        struct AppState {
            value: i32,
        }

        async fn get_value(state: State<AppState>) -> CliResult<String> {
            let app = state.read().await;
            Ok(format!("Value: {}", app.value))
        }

        let state = AppState { value: 42 };
        let router = Router::new().route("status", get_value).with_state(state);

        let response = router
            .execute_with(&["test".to_string(), "status".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        assert!(matches!(response.output, Output::Text(_)));
    }

    #[tokio::test]
    async fn test_router_unknown_command() {
        let router: Router<()> = Router::new().with_state(());
        let response = router
            .execute_with(&["test".to_string(), "unknown".to_string()])
            .await;
        assert_eq!(response.exit_code, 1);
    }

    #[tokio::test]
    async fn test_router_no_command() {
        let router: Router<()> = Router::new().with_state(());
        let response = router.execute_with(&["test".to_string()]).await;
        // Empty args now show help with exit code 0 (changed from error)
        assert_eq!(response.exit_code, 0);
    }

    #[tokio::test]
    async fn test_router_multiple_routes() {
        #[derive(Clone)]
        struct AppState {
            #[allow(dead_code)]
            count: i32,
        }

        async fn status(_state: State<AppState>) -> CliResult<String> {
            Ok("OK".to_string())
        }

        async fn version(_state: State<AppState>) -> CliResult<String> {
            Ok("v1.0.0".to_string())
        }

        let state = AppState { count: 0 };
        let router = Router::new()
            .route("status", status)
            .route("version", version)
            .with_state(state);

        let response1 = router
            .execute_with(&["test".to_string(), "status".to_string()])
            .await;
        assert_eq!(response1.exit_code, 0);

        let response2 = router
            .execute_with(&["test".to_string(), "version".to_string()])
            .await;
        assert_eq!(response2.exit_code, 0);
    }

    // ========================================
    // Args Extractor Tests
    // ========================================

    #[tokio::test]
    async fn test_router_with_args() {
        #[derive(Clone)]
        struct AppState {
            #[allow(dead_code)]
            base_cmd: String,
        }

        #[derive(Debug)]
        struct BuildArgs {
            release: bool,
        }

        impl FromArgs for BuildArgs {
            fn from_args(args: &[String]) -> Result<Self, CliError> {
                Ok(BuildArgs {
                    release: args.first().map(|s| s == "--release").unwrap_or(false),
                })
            }
        }

        async fn build(_state: State<AppState>, Args(args): Args<BuildArgs>) -> CliResult<String> {
            if args.release {
                Ok("release".to_string())
            } else {
                Ok("debug".to_string())
            }
        }

        let state = AppState {
            base_cmd: "cargo build".to_string(),
        };
        let router = Router::new().route("build", build).with_state(state);

        // Test with --release flag
        let response1 = router
            .execute_with(&[
                "test".to_string(),
                "build".to_string(),
                "--release".to_string(),
            ])
            .await;
        assert_eq!(response1.exit_code, 0);
        if let Output::Text(output) = response1.output {
            assert_eq!(output, "release");
        }

        // Test without flag
        let response2 = router
            .execute_with(&["test".to_string(), "build".to_string()])
            .await;
        assert_eq!(response2.exit_code, 0);
        if let Output::Text(output) = response2.output {
            assert_eq!(output, "debug");
        }
    }

    #[tokio::test]
    async fn test_router_args_no_state() {
        #[derive(Debug)]
        struct EchoArgs {
            message: String,
        }

        impl FromArgs for EchoArgs {
            fn from_args(args: &[String]) -> Result<Self, CliError> {
                let message = args.first().cloned().unwrap_or_else(|| "".to_string());
                Ok(EchoArgs { message })
            }
        }

        async fn echo(Args(args): Args<EchoArgs>) -> CliResult<String> {
            Ok(args.message)
        }

        let router = Router::new().route("echo", echo).with_state(());

        let response = router
            .execute_with(&["test".to_string(), "echo".to_string(), "Hello!".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Hello!");
        }
    }

    #[tokio::test]
    async fn test_router_args_parse_error() {
        #[derive(Debug)]
        struct StrictArgs;

        impl FromArgs for StrictArgs {
            fn from_args(args: &[String]) -> Result<Self, CliError> {
                if args.is_empty() {
                    Err(CliError::user("Arguments required"))
                } else {
                    Ok(StrictArgs)
                }
            }
        }

        async fn strict(Args(_args): Args<StrictArgs>) -> CliResult<String> {
            Ok("success".to_string())
        }

        let router = Router::new().route("strict", strict).with_state(());

        // Should fail with no args
        let response = router
            .execute_with(&["test".to_string(), "strict".to_string()])
            .await;
        assert_eq!(response.exit_code, 1);
    }

    // ========================================
    // Router::nest() Tests
    // ========================================

    #[tokio::test]
    async fn test_router_nest_basic() {
        #[derive(Clone)]
        struct AppState;

        async fn db_create(_state: State<AppState>) -> CliResult<String> {
            Ok("DB created".to_string())
        }

        async fn db_list(_state: State<AppState>) -> CliResult<String> {
            Ok("DB list".to_string())
        }

        let db_router = Router::new()
            .route("create", db_create)
            .route("list", db_list);

        let router = Router::new().nest("db", db_router).with_state(AppState);

        // Test nested command: "db create"
        let response = router
            .execute_with(&["test".to_string(), "db".to_string(), "create".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "DB created");
        }

        // Test nested command: "db list"
        let response = router
            .execute_with(&["test".to_string(), "db".to_string(), "list".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "DB list");
        }
    }

    #[tokio::test]
    async fn test_router_nest_with_args() {
        #[derive(Clone)]
        struct AppState;

        #[derive(Debug)]
        struct CreateArgs {
            name: String,
        }

        impl FromArgs for CreateArgs {
            fn from_args(args: &[String]) -> Result<Self, CliError> {
                let name = args
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "default".to_string());
                Ok(CreateArgs { name })
            }
        }

        async fn db_create(
            _state: State<AppState>,
            Args(args): Args<CreateArgs>,
        ) -> CliResult<String> {
            Ok(format!("Created DB: {}", args.name))
        }

        let db_router = Router::new().route("create", db_create);

        let router = Router::new().nest("db", db_router).with_state(AppState);

        // Test: "db create mydb"
        let response = router
            .execute_with(&[
                "test".to_string(),
                "db".to_string(),
                "create".to_string(),
                "mydb".to_string(),
            ])
            .await;

        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Created DB: mydb");
        }
    }

    #[tokio::test]
    async fn test_router_nest_multiple_levels() {
        #[derive(Clone)]
        struct AppState;

        async fn status(_state: State<AppState>) -> CliResult<String> {
            Ok("OK".to_string())
        }

        async fn db_create(_state: State<AppState>) -> CliResult<String> {
            Ok("DB created".to_string())
        }

        async fn server_start(_state: State<AppState>) -> CliResult<String> {
            Ok("Server started".to_string())
        }

        let db_router = Router::new().route("create", db_create);
        let server_router = Router::new().route("start", server_start);

        let router = Router::new()
            .route("status", status) // Top-level command
            .nest("db", db_router) // Nested commands
            .nest("server", server_router)
            .with_state(AppState);

        // Top-level command
        let response = router
            .execute_with(&["test".to_string(), "status".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);

        // Nested command: db create
        let response = router
            .execute_with(&["test".to_string(), "db".to_string(), "create".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);

        // Nested command: server start
        let response = router
            .execute_with(&[
                "test".to_string(),
                "server".to_string(),
                "start".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 0);
    }

    #[tokio::test]
    async fn test_router_nest_unknown_subcommand() {
        #[derive(Clone)]
        struct AppState;

        async fn db_create(_state: State<AppState>) -> CliResult<String> {
            Ok("DB created".to_string())
        }

        let db_router = Router::new().route("create", db_create);
        let router = Router::new().nest("db", db_router).with_state(AppState);

        // Unknown subcommand
        let response = router
            .execute_with(&["test".to_string(), "db".to_string(), "delete".to_string()])
            .await;
        assert_eq!(response.exit_code, 1);
    }

    // ========================================
    // Clap Integration Tests
    // ========================================
    // TODO: These tests need Handler trait implementation for module-scoped async functions
    // Currently blocked - async functions defined in test scope don't satisfy Handler trait bounds
    // Workaround: Move handlers to top-level module or use #[sen::handler] macro

    #[cfg(feature = "unstable-clap-tests")]
    #[tokio::test]
    async fn test_clap_integration_basic() {
        mod test_scope {
            use super::*;
            use clap::Parser;

            #[derive(Clone)]
            pub struct AppState;

            #[derive(Parser, Debug)]
            pub struct BuildArgs {
                /// Database name
                pub name: String,

                /// Build in release mode
                #[arg(long)]
                pub release: bool,
            }

            pub async fn build(
                _state: State<AppState>,
                Args(args): Args<BuildArgs>,
            ) -> CliResult<String> {
                if args.release {
                    Ok(format!("Release build: {}", args.name))
                } else {
                    Ok(format!("Debug build: {}", args.name))
                }
            }
        }

        let router = Router::new()
            .route("build", test_scope::build)
            .with_state(test_scope::AppState);

        // Test with --release
        let response = router
            .execute(&[
                "build".to_string(),
                "myapp".to_string(),
                "--release".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Release build: myapp");
        }

        // Test without --release
        let response = router
            .execute(&["build".to_string(), "myapp".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Debug build: myapp");
        }
    }

    #[cfg(feature = "unstable-clap-tests")]
    #[tokio::test]
    async fn test_clap_integration_with_env() {
        mod test_scope {
            use super::*;
            use clap::Parser;

            #[derive(Clone)]
            pub struct AppState;

            #[derive(Parser, Debug)]
            pub struct DeployArgs {
                /// App name
                pub app: String,

                /// Target environment (from env var or flag)
                #[arg(long, env = "DEPLOY_ENV", default_value = "production")]
                pub env: String,
            }

            pub async fn deploy(
                _state: State<AppState>,
                Args(args): Args<DeployArgs>,
            ) -> CliResult<String> {
                Ok(format!("Deploying {} to {}", args.app, args.env))
            }
        }

        let router = Router::new()
            .route("deploy", test_scope::deploy)
            .with_state(test_scope::AppState);

        // Test with explicit --env flag
        let response = router
            .execute(&[
                "deploy".to_string(),
                "myapp".to_string(),
                "--env".to_string(),
                "staging".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Deploying myapp to staging");
        }

        // Test with default value
        let response = router
            .execute(&["deploy".to_string(), "myapp".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        if let Output::Text(output) = response.output {
            assert_eq!(output, "Deploying myapp to production");
        }
    }

    #[cfg(feature = "unstable-clap-tests")]
    #[tokio::test]
    async fn test_clap_integration_validation() {
        mod test_scope {
            use super::*;
            use clap::Parser;

            #[derive(Clone)]
            pub struct AppState;

            #[derive(Parser, Debug)]
            pub struct CreateArgs {
                /// Name (required)
                pub name: String,

                /// Port number
                #[arg(long, value_parser = clap::value_parser!(u16).range(1..=65535))]
                pub port: Option<u16>,
            }

            pub async fn create(
                _state: State<AppState>,
                Args(args): Args<CreateArgs>,
            ) -> CliResult<String> {
                Ok(format!("Created {} on port {:?}", args.name, args.port))
            }
        }

        let router = Router::new()
            .route("create", test_scope::create)
            .with_state(test_scope::AppState);

        // Valid port
        let response = router
            .execute(&[
                "create".to_string(),
                "mydb".to_string(),
                "--port".to_string(),
                "3000".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 0);

        // Invalid port (out of range) - clap will return error
        let response = router
            .execute(&[
                "create".to_string(),
                "mydb".to_string(),
                "--port".to_string(),
                "99999".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 1);
    }

    // ========================================
    // Agent Mode Tests
    // ========================================

    #[tokio::test]
    async fn test_router_with_agent_mode_enabled() {
        async fn status(_state: State<()>) -> CliResult<String> {
            Ok("Status: OK".to_string())
        }

        let router = Router::new()
            .route("status", status)
            .with_agent_mode()
            .with_state(());

        // Without --agent-mode flag
        let response = router
            .execute_with(&["test".to_string(), "status".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        assert!(!response.agent_mode);

        // With --agent-mode flag
        let response = router
            .execute_with(&[
                "test".to_string(),
                "--agent-mode".to_string(),
                "status".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 0);
        assert!(response.agent_mode);
    }

    #[tokio::test]
    async fn test_router_without_agent_mode_enabled() {
        async fn status(_state: State<()>) -> CliResult<String> {
            Ok("Status: OK".to_string())
        }

        let router = Router::new().route("status", status).with_state(());

        // With --agent-mode flag but agent_mode not enabled
        // The flag is treated as a command, resulting in "Unknown command" error
        let response = router
            .execute_with(&[
                "test".to_string(),
                "--agent-mode".to_string(),
                "status".to_string(),
            ])
            .await;
        assert_eq!(response.exit_code, 1); // Error: unknown command
        assert!(!response.agent_mode);

        // Without --agent-mode flag works fine
        let response = router
            .execute_with(&["test".to_string(), "status".to_string()])
            .await;
        assert_eq!(response.exit_code, 0);
        assert!(!response.agent_mode);
    }

    #[tokio::test]
    async fn test_agent_mode_flag_stripped_from_args() {
        #[derive(Debug)]
        struct TestArgs {
            message: String,
        }

        impl FromArgs for TestArgs {
            fn from_args(args: &[String]) -> Result<Self, CliError> {
                // --agent-mode should NOT appear in args
                for arg in args {
                    if arg == "--agent-mode" {
                        return Err(CliError::user(
                            "Unexpected --agent-mode flag in handler args",
                        ));
                    }
                }

                let message = args.first().cloned().unwrap_or_else(|| "empty".to_string());
                Ok(TestArgs { message })
            }
        }

        async fn echo(Args(args): Args<TestArgs>) -> CliResult<String> {
            Ok(args.message)
        }

        let router = Router::new()
            .route("echo", echo)
            .with_agent_mode()
            .with_state(());

        // --agent-mode should be stripped before passing to handler
        let response = router
            .execute_with(&[
                "test".to_string(),
                "--agent-mode".to_string(),
                "echo".to_string(),
                "hello".to_string(),
            ])
            .await;

        assert_eq!(response.exit_code, 0);
        assert!(response.agent_mode);
        // Should receive "hello", not "--agent-mode" or error
        if let Output::Text(output) = response.output {
            assert_eq!(output, "hello");
        } else {
            panic!("Expected text output");
        }
    }
}