kindly-tools 0.11.14

Development tools and utilities for KindlyGuard ecosystem
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
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
// Modules defined inline below
pub mod commands;
pub mod config;
pub mod output;
pub mod platform;

use anyhow::Result;
use dialoguer::Select;
use std::path::{Path, PathBuf};

use crate::platform::Platform;

/// Common trait for all subcommands
#[allow(async_fn_in_trait)]
pub trait Execute {
    async fn execute(&self) -> Result<()>;
}

/// Check if a command exists in PATH
pub fn command_exists(cmd: &str) -> bool {
    which::which(cmd).is_ok()
}

/// Get the user's home directory
pub fn home_dir() -> Result<PathBuf> {
    directories::BaseDirs::new()
        .map(|dirs| dirs.home_dir().to_path_buf())
        .ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))
}

/// Get the KindlyGuard configuration directory
pub fn config_dir() -> Result<PathBuf> {
    let home = home_dir()?;
    Ok(home.join(".kindlyguard"))
}

/// Ensure a directory exists, creating it if necessary
pub fn ensure_dir(path: &Path) -> Result<()> {
    if !path.exists() {
        std::fs::create_dir_all(path)?;
    }
    Ok(())
}

/// Get the MCP configuration file path
pub fn get_mcp_config_path() -> Result<PathBuf> {
    let home = home_dir()?;

    // Check for different possible locations
    let candidates = vec![home.join(".mcp.json"), home.join(".config/claude/mcp.json")];

    for path in &candidates {
        if path.exists() {
            return Ok(path.clone());
        }
    }

    // Default to .mcp.json
    Ok(home.join(".mcp.json"))
}

/// Download a file with progress bar
pub async fn download_file(url: &str, dest: &Path) -> Result<()> {
    use futures_util::StreamExt;
    use indicatif::{ProgressBar, ProgressStyle};
    use std::io::Write;
    
    // Create HTTP client
    let client = reqwest::Client::new();
    
    // Start the download
    let response = client
        .get(url)
        .send()
        .await?;
    
    // Check status
    if !response.status().is_success() {
        anyhow::bail!("Failed to download: HTTP {}", response.status());
    }
    
    // Get content length for progress bar
    let total_size = response
        .content_length()
        .unwrap_or(0);
    
    // Create progress bar
    let pb = ProgressBar::new(total_size);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")?
            .progress_chars("#>-")
    );
    pb.set_message(format!("Downloading {}", dest.file_name().unwrap_or_default().to_string_lossy()));
    
    // Create the destination file
    let mut file = std::fs::File::create(dest)?;
    
    // Download with progress
    let mut downloaded = 0u64;
    let mut stream = response.bytes_stream();
    
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        file.write_all(&chunk)?;
        downloaded += chunk.len() as u64;
        pb.set_position(downloaded);
    }
    
    pb.finish_with_message("Download complete");
    
    Ok(())
}

/// Get the GitHub release download URL for KindlyGuard based on platform
pub fn get_kindlyguard_download_url(version: &str, platform: &Platform) -> String {
    let version_tag = if version == "latest" {
        "latest".to_string()
    } else {
        format!("v{}", version.trim_start_matches('v'))
    };
    
    let (os, arch, ext) = match platform {
        Platform::Windows => ("pc-windows-msvc", "x86_64", "exe"),
        Platform::MacOS => {
            if std::env::consts::ARCH == "aarch64" {
                ("apple-darwin", "aarch64", "")
            } else {
                ("apple-darwin", "x86_64", "")
            }
        },
        Platform::Linux => ("unknown-linux-gnu", "x86_64", ""),
        Platform::Unknown => {
            return format!("https://github.com/kindly-software-inc/kindly-guard/releases/{}", version_tag);
        }
    };
    
    let filename = if ext.is_empty() {
        format!("kindlyguard-{}-{}", arch, os)
    } else {
        format!("kindlyguard-{}-{}.{}", arch, os, ext)
    };
    
    if version_tag == "latest" {
        format!(
            "https://github.com/kindly-software-inc/kindly-guard/releases/latest/download/{}",
            filename
        )
    } else {
        format!(
            "https://github.com/kindly-software-inc/kindly-guard/releases/download/{}/{}",
            version_tag, filename
        )
    }
}

/// Install KindlyGuard binary from GitHub releases
pub async fn install_kindlyguard_from_github(version: &str, platform: &Platform) -> Result<()> {
    use colored::Colorize;
    
    println!("📦 {}", "Downloading KindlyGuard from GitHub releases...".green());
    
    // Get download URL
    let url = get_kindlyguard_download_url(version, platform);
    println!("📍 URL: {}", url.cyan());
    
    // Determine installation directory
    let install_dir = match platform {
        Platform::Windows => {
            // Install to user's local bin directory
            let home = home_dir()?;
            home.join(".kindlyguard").join("bin")
        },
        _ => {
            // Try ~/.local/bin first, then ~/.cargo/bin
            let home = home_dir()?;
            let local_bin = home.join(".local").join("bin");
            if local_bin.exists() {
                local_bin
            } else {
                home.join(".cargo").join("bin")
            }
        }
    };
    
    // Ensure directory exists
    ensure_dir(&install_dir)?;
    
    // Determine binary name
    let binary_name = if platform == &Platform::Windows {
        "kindlyguard.exe"
    } else {
        "kindlyguard"
    };
    
    let dest_path = install_dir.join(binary_name);
    let temp_path = dest_path.with_extension("tmp");
    
    // Download to temporary file
    download_file(&url, &temp_path).await?;
    
    // Make executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&temp_path)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&temp_path, perms)?;
    }
    
    // Move to final location
    std::fs::rename(&temp_path, &dest_path)?;
    
    println!("\n{}", "Installation successful!".green().bold());
    println!("📍 {}: {}", "Binary installed to".cyan(), dest_path.display());
    
    // Check if directory is in PATH
    let path_var = std::env::var("PATH").unwrap_or_default();
    if !path_var.contains(&install_dir.to_string_lossy().to_string()) {
        println!(
            "\n⚠️  {}",
            "Installation directory is not in your PATH!".yellow()
        );
        println!("📋 {}", "Add this to your shell configuration:".cyan());
        
        match platform {
            Platform::Windows => {
                println!(
                    "   {} $env:Path += \";{}\"",
                    "$".dimmed(),
                    install_dir.display()
                );
            },
            _ => {
                println!(
                    "   {} export PATH=\"$PATH:{}\"",
                    "$".dimmed(),
                    install_dir.display()
                );
            }
        }
    }
    
    Ok(())
}

/// Detect various environment characteristics
pub fn detect_environment() -> EnvironmentInfo {
    use std::env;
    use std::path::Path;

    EnvironmentInfo {
        is_docker: Path::new("/.dockerenv").exists(),
        is_wsl: detect_wsl(),
        is_ci: env::var("CI").is_ok() || env::var("CONTINUOUS_INTEGRATION").is_ok(),
        is_ssh: env::var("SSH_CONNECTION").is_ok() || env::var("SSH_CLIENT").is_ok(),
        has_proxy: env::var("HTTP_PROXY").is_ok()
            || env::var("HTTPS_PROXY").is_ok()
            || env::var("http_proxy").is_ok()
            || env::var("https_proxy").is_ok(),
    }
}

/// Check if running in WSL
fn detect_wsl() -> bool {
    #[cfg(target_os = "linux")]
    {
        if let Ok(content) = std::fs::read_to_string("/proc/version") {
            return content.to_lowercase().contains("microsoft");
        }
    }
    false
}

/// Detect Linux distribution
pub fn detect_linux_distro() -> LinuxDistro {
    #[cfg(target_os = "linux")]
    {
        // Try /etc/os-release first (standard on most modern distros)
        if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
            for line in content.lines() {
                if line.starts_with("ID=") {
                    let id = line.trim_start_matches("ID=").trim_matches('"');
                    return match id {
                        "ubuntu" => LinuxDistro::Ubuntu,
                        "debian" => LinuxDistro::Debian,
                        "fedora" => LinuxDistro::Fedora,
                        "centos" => LinuxDistro::CentOS,
                        "rhel" => LinuxDistro::RHEL,
                        "arch" => LinuxDistro::Arch,
                        "manjaro" => LinuxDistro::Manjaro,
                        "opensuse" | "opensuse-leap" | "opensuse-tumbleweed" | "suse" => {
                            LinuxDistro::OpenSUSE
                        },
                        "alpine" => LinuxDistro::Alpine,
                        "nixos" => LinuxDistro::NixOS,
                        "gentoo" => LinuxDistro::Gentoo,
                        "void" => LinuxDistro::Void,
                        "elementary" => LinuxDistro::Elementary,
                        "pop" => LinuxDistro::PopOS,
                        "mint" | "linuxmint" => LinuxDistro::Mint,
                        _ => LinuxDistro::Unknown(id.to_string()),
                    };
                }
            }
        }

        // Fallback checks for older systems
        if Path::new("/etc/debian_version").exists() {
            return LinuxDistro::Debian;
        }
        if Path::new("/etc/redhat-release").exists() {
            return LinuxDistro::RHEL;
        }
        if Path::new("/etc/arch-release").exists() {
            return LinuxDistro::Arch;
        }
        if Path::new("/etc/gentoo-release").exists() {
            return LinuxDistro::Gentoo;
        }
        if Path::new("/etc/alpine-release").exists() {
            return LinuxDistro::Alpine;
        }
    }

    LinuxDistro::Unknown("generic".to_string())
}

/// Detect installed Node.js version managers
pub fn detect_node_managers() -> NodeManagers {
    use std::path::Path;

    let home = home_dir().unwrap_or_default();

    NodeManagers {
        has_nvm: Path::new(&home.join(".nvm")).exists() || std::env::var("NVM_DIR").is_ok(),
        has_fnm: command_exists("fnm")
            || Path::new(&home.join(".fnm")).exists()
            || Path::new(&home.join(".local/share/fnm")).exists(),
        has_n: command_exists("n")
            || Path::new("/usr/local/n").exists()
            || Path::new("/usr/local/bin/n").exists(),
        has_volta: command_exists("volta") || Path::new(&home.join(".volta")).exists(),
        has_asdf: command_exists("asdf") || Path::new(&home.join(".asdf")).exists(),
    }
}

/// Environment information struct
#[derive(Debug, Clone)]
pub struct EnvironmentInfo {
    pub is_docker: bool,
    pub is_wsl: bool,
    pub is_ci: bool,
    pub is_ssh: bool,
    pub has_proxy: bool,
}

/// Linux distribution enum
#[derive(Debug, Clone, PartialEq)]
pub enum LinuxDistro {
    Ubuntu,
    Debian,
    Fedora,
    CentOS,
    RHEL,
    Arch,
    Manjaro,
    OpenSUSE,
    Alpine,
    NixOS,
    Gentoo,
    Void,
    Elementary,
    PopOS,
    Mint,
    Unknown(String),
}

impl LinuxDistro {
    /// Get display name with emoji
    pub fn display_name(&self) -> String {
        match self {
            LinuxDistro::Ubuntu => "🟠 Ubuntu".to_string(),
            LinuxDistro::Debian => "🔴 Debian".to_string(),
            LinuxDistro::Fedora => "🔵 Fedora".to_string(),
            LinuxDistro::CentOS => "🟣 CentOS".to_string(),
            LinuxDistro::RHEL => "🔴 Red Hat Enterprise Linux".to_string(),
            LinuxDistro::Arch => "🔷 Arch Linux".to_string(),
            LinuxDistro::Manjaro => "🟢 Manjaro".to_string(),
            LinuxDistro::OpenSUSE => "🦎 openSUSE".to_string(),
            LinuxDistro::Alpine => "🏔️ Alpine Linux".to_string(),
            LinuxDistro::NixOS => "❄️ NixOS".to_string(),
            LinuxDistro::Gentoo => "🟣 Gentoo".to_string(),
            LinuxDistro::Void => "🌑 Void Linux".to_string(),
            LinuxDistro::Elementary => "🦚 elementary OS".to_string(),
            LinuxDistro::PopOS => "🚀 Pop!_OS".to_string(),
            LinuxDistro::Mint => "🌿 Linux Mint".to_string(),
            LinuxDistro::Unknown(name) => format!("🐧 Linux ({})", name),
        }
    }

    /// Get package manager command
    pub fn package_manager(&self) -> &'static str {
        match self {
            LinuxDistro::Ubuntu
            | LinuxDistro::Debian
            | LinuxDistro::Elementary
            | LinuxDistro::PopOS
            | LinuxDistro::Mint => "apt",
            LinuxDistro::Fedora | LinuxDistro::CentOS | LinuxDistro::RHEL => "dnf",
            LinuxDistro::Arch | LinuxDistro::Manjaro => "pacman",
            LinuxDistro::OpenSUSE => "zypper",
            LinuxDistro::Alpine => "apk",
            LinuxDistro::NixOS => "nix-env",
            LinuxDistro::Gentoo => "emerge",
            LinuxDistro::Void => "xbps-install",
            LinuxDistro::Unknown(_) => "apt", // fallback
        }
    }
}

/// Node.js version managers struct
#[derive(Debug, Clone)]
pub struct NodeManagers {
    pub has_nvm: bool,
    pub has_fnm: bool,
    pub has_n: bool,
    pub has_volta: bool,
    pub has_asdf: bool,
}

impl NodeManagers {
    /// Get the recommended manager if any is installed
    pub fn recommended(&self) -> Option<&'static str> {
        if self.has_volta {
            Some("volta")
        } else if self.has_fnm {
            Some("fnm")
        } else if self.has_nvm {
            Some("nvm")
        } else if self.has_n {
            Some("n")
        } else if self.has_asdf {
            Some("asdf")
        } else {
            None
        }
    }

    /// Check if any manager is installed
    pub fn has_any(&self) -> bool {
        self.has_nvm || self.has_fnm || self.has_n || self.has_volta || self.has_asdf
    }
}

/// Recovery options for installation failures
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RecoveryMethod {
    TryWithSudo,
    InstallToHome,
    UseDifferentPackageManager,
    DownloadBinary,
    OfflineInstallation,
    ShowDiagnostics,
    Cancel,
}

/// Show interactive recovery menu when installation fails
pub fn show_recovery_menu(failed_method: &str) -> Result<RecoveryMethod> {
    use colored::*;

    println!(
        "\n🚨 {}",
        format!("Installation failed using {}", failed_method)
            .red()
            .bold()
    );
    println!("🔄 {}", "Let's try a different approach...".yellow());

    let options = vec![
        format!("🔐 Try with sudo privileges"),
        format!("🏠 Install to home directory (~/.local)"),
        format!("📦 Use different package manager"),
        format!("💿 Download binary directly"),
        format!("📴 Offline installation"),
        format!("🔍 Show diagnostics"),
        format!("❌ Cancel installation"),
    ];

    let selection = Select::new()
        .with_prompt("Select recovery method")
        .items(&options)
        .default(0)
        .interact()?;

    let method = match selection {
        0 => RecoveryMethod::TryWithSudo,
        1 => RecoveryMethod::InstallToHome,
        2 => RecoveryMethod::UseDifferentPackageManager,
        3 => RecoveryMethod::DownloadBinary,
        4 => RecoveryMethod::OfflineInstallation,
        5 => RecoveryMethod::ShowDiagnostics,
        _ => RecoveryMethod::Cancel,
    };

    Ok(method)
}

/// Execute recovery method based on user selection
pub async fn execute_recovery(
    method: RecoveryMethod,
    original_method: &str,
    package: &str,
    platform: &crate::platform::Platform,
) -> Result<()> {
    use colored::*;

    match method {
        RecoveryMethod::TryWithSudo => {
            println!("\n🔐 {}", "Retrying with sudo privileges...".cyan());
            match original_method {
                "npm" => {
                    println!("📋 {}", "Command:".cyan());
                    println!(
                        "   {} sudo npm install -g {}",
                        "$".dimmed(),
                        package.bright_white()
                    );
                    println!(
                        "\n⚠️  {}",
                        "This will install globally with root privileges".yellow()
                    );
                },
                "cargo" => {
                    println!("📋 {}", "Command:".cyan());
                    println!(
                        "   {} sudo cargo install {}",
                        "$".dimmed(),
                        package.bright_white()
                    );
                    println!(
                        "\n⚠️  {}",
                        "Note: Using sudo with cargo is not recommended".yellow()
                    );
                    println!(
                        "💡 {}",
                        "Consider using --root ~/.local/cargo instead".yellow()
                    );
                },
                _ => return Err(anyhow::anyhow!("Sudo not applicable for this method")),
            }
        },
        RecoveryMethod::InstallToHome => {
            println!("\n🏠 {}", "Installing to home directory...".cyan());
            match original_method {
                "npm" => {
                    println!("📋 {}", "Commands:".cyan());
                    println!("   {} mkdir -p ~/.local/npm", "$".dimmed());
                    println!("   {} npm config set prefix ~/.local/npm", "$".dimmed());
                    println!(
                        "   {} npm install -g {}",
                        "$".dimmed(),
                        package.bright_white()
                    );
                    println!("\n💡 {}", "Add to PATH:".yellow());
                    println!("   {} export PATH=$HOME/.local/npm/bin:$PATH", "$".dimmed());
                },
                "cargo" => {
                    println!("📋 {}", "Command:".cyan());
                    println!(
                        "   {} cargo install --root ~/.local/cargo {}",
                        "$".dimmed(),
                        package.bright_white()
                    );
                    println!("\n💡 {}", "Add to PATH:".yellow());
                    println!(
                        "   {} export PATH=$HOME/.local/cargo/bin:$PATH",
                        "$".dimmed()
                    );
                },
                _ => {
                    println!("📋 {}", "Manual installation to ~/.local/bin:".cyan());
                    println!("   1️⃣  Download the binary");
                    println!("   2️⃣  {} mkdir -p ~/.local/bin", "$".dimmed());
                    println!("   3️⃣  {} mv kindlyguard ~/.local/bin/", "$".dimmed());
                    println!("   4️⃣  {} chmod +x ~/.local/bin/kindlyguard", "$".dimmed());
                },
            }
        },
        RecoveryMethod::UseDifferentPackageManager => {
            println!("\n📦 {}", "Alternative package managers:".cyan());
            match platform {
                crate::platform::Platform::MacOS => {
                    println!("🍺 {}", "Homebrew:".green());
                    println!("   {} brew tap kindly-software-inc/tap", "$".dimmed());
                    println!("   {} brew install kindlyguard", "$".dimmed());
                    println!("\n🌊 {}", "MacPorts:".green());
                    println!("   {} sudo port install kindlyguard", "$".dimmed());
                },
                crate::platform::Platform::Linux => {
                    println!("📦 {}", "Snap:".green());
                    println!("   {} sudo snap install kindlyguard", "$".dimmed());
                    println!("\n📦 {}", "Flatpak:".green());
                    println!(
                        "   {} flatpak install flathub com.kindly.guard",
                        "$".dimmed()
                    );
                    println!("\n📦 {}", "AppImage:".green());
                    println!("   Download from releases page");
                },
                crate::platform::Platform::Windows => {
                    println!("🍫 {}", "Chocolatey:".green());
                    println!("   {} choco install kindlyguard", "$".dimmed());
                    println!("\n🔷 {}", "Scoop:".green());
                    println!("   {} scoop install kindlyguard", "$".dimmed());
                    println!("\n🔶 {}", "WinGet:".green());
                    println!(
                        "   {} winget install KindlySoftware.KindlyGuard",
                        "$".dimmed()
                    );
                },
                _ => {},
            }
        },
        RecoveryMethod::DownloadBinary => {
            println!("\n💿 {}", "Direct binary download:".cyan());
            println!("🌐 {}", "Visit:".cyan());
            println!(
                "   {}",
                "https://github.com/kindly-software-inc/kindly-guard/releases"
                    .blue()
                    .underline()
            );

            let arch = crate::platform::Architecture::detect();
            match platform {
                crate::platform::Platform::MacOS => {
                    let arch_str = if arch == crate::platform::Architecture::Arm64 {
                        "aarch64"
                    } else {
                        "x86_64"
                    };
                    println!(
                        "\n🍎 {}",
                        format!(
                            "Download: kindly-guard-server-{}-apple-darwin.tar.gz",
                            arch_str
                        )
                        .bright_white()
                    );
                },
                crate::platform::Platform::Linux => {
                    println!(
                        "\n🐧 {}",
                        "Download: kindly-guard-server-x86_64-unknown-linux-gnu.tar.gz"
                            .bright_white()
                    );
                },
                crate::platform::Platform::Windows => {
                    println!(
                        "\n🪟 {}",
                        "Download: kindly-guard-server-x86_64-pc-windows-msvc.zip".bright_white()
                    );
                },
                _ => {},
            }

            println!("\n📋 {}", "Manual installation steps:".cyan());
            println!("   1️⃣  Download the appropriate file");
            println!("   2️⃣  Extract the archive");
            println!("   3️⃣  Move binary to PATH location");
            println!("   4️⃣  Make it executable (Unix/Linux/macOS)");
        },
        RecoveryMethod::OfflineInstallation => {
            println!("\n📴 {}", "Offline installation:".cyan());
            println!("💡 {}", "For offline environments:".yellow());
            println!("\n📋 {}", "Steps:".cyan());
            println!("   1️⃣  Download on a connected machine:");
            println!("      - Binary from GitHub releases");
            println!(
                "      - Or npm package: {} npm pack kindly-guard-server",
                "$".dimmed()
            );
            println!("   2️⃣  Transfer to target machine via USB/network");
            println!("   3️⃣  Install locally:");
            println!("      - Binary: Copy to /usr/local/bin/");
            println!(
                "      - npm: {} npm install -g kindly-guard-server-*.tgz",
                "$".dimmed()
            );
        },
        RecoveryMethod::ShowDiagnostics => {
            println!("\n🔍 {}", "Running diagnostics...".cyan());

            // Check disk space
            println!("\n💾 {}", "Disk space:".yellow());
            #[cfg(not(target_os = "windows"))]
            {
                if let Ok(output) = std::process::Command::new("df").args(["-h", "."]).output() {
                    println!("{}", String::from_utf8_lossy(&output.stdout));
                }
            }

            // Check permissions
            println!("\n🔒 {}", "Permissions:".yellow());
            match original_method {
                "npm" => {
                    if let Ok(output) = std::process::Command::new("npm")
                        .args(["config", "get", "prefix"])
                        .output()
                    {
                        let prefix = String::from_utf8_lossy(&output.stdout).trim().to_string();
                        println!("   npm prefix: {}", prefix);

                        #[cfg(not(target_os = "windows"))]
                        {
                            if let Ok(output) = std::process::Command::new("ls")
                                .args(["-ld", &prefix])
                                .output()
                            {
                                println!("   {}", String::from_utf8_lossy(&output.stdout).trim());
                            }
                        }
                    }
                },
                "cargo" => {
                    if let Ok(home) = home_dir() {
                        let cargo_home = home.join(".cargo");
                        println!("   CARGO_HOME: {:?}", cargo_home);

                        #[cfg(not(target_os = "windows"))]
                        {
                            if let Ok(output) = std::process::Command::new("ls")
                                .args(["-ld", cargo_home.to_str().unwrap_or("")])
                                .output()
                            {
                                println!("   {}", String::from_utf8_lossy(&output.stdout).trim());
                            }
                        }
                    }
                },
                _ => {},
            }

            // Check network
            println!("\n🌐 {}", "Network connectivity:".yellow());
            #[cfg(not(target_os = "windows"))]
            {
                if let Ok(output) = std::process::Command::new("ping")
                    .args(["-c", "1", "-W", "2", "8.8.8.8"])
                    .output()
                {
                    if output.status.success() {
                        println!("   ✅ Internet connection OK");
                    } else {
                        println!("   ❌ No internet connection");
                    }
                }
            }

            // Check environment
            let env_info = detect_environment();
            println!("\n🌍 {}", "Environment detection:".yellow());
            if env_info.is_docker {
                println!("   🐳 Running in Docker container");
            }
            if env_info.is_wsl {
                println!("   🪟 Running in WSL");
            }
            if env_info.is_ci {
                println!("   🤖 Running in CI/CD environment");
            }
            if env_info.is_ssh {
                println!("   🔐 Connected via SSH");
            }
            if env_info.has_proxy {
                println!("   🌐 Proxy detected:");
                if let Ok(http_proxy) =
                    std::env::var("HTTP_PROXY").or_else(|_| std::env::var("http_proxy"))
                {
                    println!("      HTTP_PROXY: {}", http_proxy);
                }
                if let Ok(https_proxy) =
                    std::env::var("HTTPS_PROXY").or_else(|_| std::env::var("https_proxy"))
                {
                    println!("      HTTPS_PROXY: {}", https_proxy);
                }

                // Show proxy configuration for package managers
                match original_method {
                    "npm" => {
                        println!("\n   💡 {}", "Configure npm for proxy:".yellow());
                        println!("      {} npm config set proxy $HTTP_PROXY", "$".dimmed());
                        println!(
                            "      {} npm config set https-proxy $HTTPS_PROXY",
                            "$".dimmed()
                        );
                    },
                    "cargo" => {
                        println!(
                            "\n   💡 {}",
                            "Cargo uses system proxy automatically".yellow()
                        );
                    },
                    _ => {},
                }
            }

            // Check Node.js managers if npm failed
            if original_method == "npm" {
                let node_managers = detect_node_managers();
                if node_managers.has_any() {
                    println!("\n🚀 {}", "Node.js version managers detected:".yellow());
                    if node_managers.has_nvm {
                        println!("   ✅ nvm - Try: nvm install --lts");
                    }
                    if node_managers.has_fnm {
                        println!("   ✅ fnm - Try: fnm install --lts");
                    }
                    if node_managers.has_n {
                        println!("   ✅ n - Try: n lts");
                    }
                    if node_managers.has_volta {
                        println!("   ✅ volta - Try: volta install node");
                    }
                    if node_managers.has_asdf {
                        println!("   ✅ asdf - Try: asdf install nodejs latest");
                    }
                }
            }

            // Check proxy settings
            println!("\n🔐 {}", "Proxy settings:".yellow());
            for var in ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"] {
                if let Ok(value) = std::env::var(var) {
                    println!("   {}: {}", var, value);
                }
            }

            println!("\n💡 {}", "Common fixes:".cyan());
            println!("   - Free up disk space (200MB needed)");
            println!("   - Check file permissions");
            println!("   - Configure proxy if behind firewall");
            println!("   - Try different installation method");
        },
        RecoveryMethod::Cancel => {
            println!("\n{}", "Installation cancelled".red());
            return Err(anyhow::anyhow!("Installation cancelled by user"));
        },
    }

    Ok(())
}

pub mod dev {
    use super::*;
    use clap::Subcommand;

    #[derive(clap::Args)]
    pub struct DevCommand {
        #[command(subcommand)]
        command: DevSubcommands,
    }

    #[derive(Subcommand)]
    enum DevSubcommands {
        /// Set up development environment
        Setup {
            /// Skip installing Rust tools
            #[arg(long)]
            skip_rust: bool,
        },
        /// Run security audit
        Audit,
        /// Generate documentation
        Docs {
            /// Open in browser after generation
            #[arg(long)]
            open: bool,
        },
    }

    impl Execute for DevCommand {
        async fn execute(&self) -> Result<()> {
            match &self.command {
                DevSubcommands::Setup { skip_rust } => setup_dev_env(*skip_rust).await,
                DevSubcommands::Audit => run_security_audit().await,
                DevSubcommands::Docs { open } => generate_docs(*open).await,
            }
        }
    }

    async fn setup_dev_env(skip_rust: bool) -> Result<()> {
        use crate::platform::Platform;
        use colored::*;

        println!(
            "\n🚀 {}",
            "Setting up development environment...".bold().blue()
        );

        let platform = Platform::detect();

        // Platform-specific emoji
        let platform_display = match platform {
            Platform::MacOS => format!("🍎 Platform: {}", platform),
            Platform::Windows => format!("🪟 Platform: {}", platform),
            Platform::Linux => format!("🐧 Platform: {}", platform),
            _ => format!("🖥️  Platform: {}", platform),
        };
        println!("{}", platform_display.cyan());

        // Check development dependencies inline
        println!("\n📋 {}", "Checking system dependencies...".cyan());
        check_basic_dev_deps(&platform)?;

        if !skip_rust {
            println!("\n🦀 {}", "Installing Rust development tools...".cyan());

            let tools = [
                ("cargo-audit", "🛡️  Security vulnerability scanner"),
                ("cargo-geiger", "☢️  Unsafe code detector"),
                ("cargo-dist", "📦 Distribution packaging tool"),
            ];

            for (tool, description) in &tools {
                println!(
                    "\n   {} {}: {}",
                    "".dimmed(),
                    tool.bright_white(),
                    description
                );

                // Check if already installed
                if command_exists(tool) {
                    println!("{}", "Already installed".green());
                } else {
                    println!("{}", "Installing...".yellow());

                    let status = std::process::Command::new("cargo")
                        .args(["install", tool])
                        .status()?;

                    if status.success() {
                        println!("{}", "Installed successfully!".green());
                    } else {
                        println!("{}", "Installation failed".red());
                        println!(
                            "     💡 {}",
                            format!("Try: cargo install {} --force", tool).yellow()
                        );
                    }
                }
            }
        } else {
            println!(
                "\n⏭️  {}",
                "Skipping Rust tools installation (--skip-rust)".dimmed()
            );
        }

        println!(
            "\n{}",
            "Development environment setup complete!".bold().green()
        );
        println!("🎯 {}", "You're ready to start developing!".green());

        Ok(())
    }

    async fn run_security_audit() -> Result<()> {
        tracing::info!("Running security audit...");

        let output = std::process::Command::new("cargo")
            .args(["audit"])
            .output()?;

        if !output.status.success() {
            anyhow::bail!("Security audit failed");
        }

        tracing::info!("Security audit passed!");
        Ok(())
    }

    async fn generate_docs(open: bool) -> Result<()> {
        tracing::info!("Generating documentation...");

        let mut cmd = std::process::Command::new("cargo");
        cmd.args(["doc", "--no-deps"]);

        if open {
            cmd.arg("--open");
        }

        cmd.status()?;
        Ok(())
    }

    fn check_basic_dev_deps(platform: &crate::platform::Platform) -> Result<()> {
        use colored::*;

        let essentials = match platform {
            crate::platform::Platform::Linux => vec![
                ("gcc", "🔨 C compiler", "sudo apt install build-essential"),
                ("git", "🌿 Version control", "sudo apt install git"),
            ],
            crate::platform::Platform::MacOS => vec![
                ("git", "🌿 Version control", "xcode-select --install"),
                ("cc", "🔨 C compiler", "xcode-select --install"),
            ],
            crate::platform::Platform::Windows => vec![(
                "git",
                "🌿 Version control",
                "https://git-scm.com/download/win",
            )],
            _ => vec![],
        };

        let mut missing = false;

        for (cmd, desc, install_hint) in essentials {
            print!("   {} {}: ", "".dimmed(), desc);
            if command_exists(cmd) {
                println!("{}", "".green());
            } else {
                println!("{}", "❌ Missing".red());
                println!("     💡 Install: {}", install_hint.yellow());
                missing = true;
            }
        }

        if missing {
            println!("\n⚠️  {}", "Some essential tools are missing!".yellow());
        }

        Ok(())
    }
}

pub mod install {
    use super::*;
    use clap::Subcommand;
    use std::env;
    use std::process::Command;

    #[derive(clap::Args)]
    pub struct InstallCommand {
        #[command(subcommand)]
        command: InstallSubcommands,
    }

    #[derive(Subcommand)]
    enum InstallSubcommands {
        /// Install KindlyGuard MCP server
        #[command(visible_alias = "kindlyguard")]
        KindlyGuard {
            /// Installation method (auto-detected if not specified)
            #[arg(short, long)]
            method: Option<String>,

            /// Version to install (latest if not specified)
            #[arg(long)]
            version: Option<String>,
        },
        /// Install all recommended tools
        All,
        /// Install MCP servers
        McpServers {
            /// Specific server to install
            #[arg(short, long)]
            server: Option<String>,
        },
        /// Install development dependencies
        DevDeps,
    }

    impl Execute for InstallCommand {
        async fn execute(&self) -> Result<()> {
            match &self.command {
                InstallSubcommands::KindlyGuard { method, version } => {
                    install_kindlyguard(method.as_deref(), version.as_deref()).await
                },
                InstallSubcommands::All => install_all().await,
                InstallSubcommands::McpServers { server } => {
                    install_mcp_servers(server.as_deref()).await
                },
                InstallSubcommands::DevDeps => install_dev_deps().await,
            }
        }
    }

    async fn install_kindlyguard(method: Option<&str>, version: Option<&str>) -> Result<()> {
        use crate::platform::Platform;
        use colored::*;

        // Run pre-flight checks
        println!("\n🔍 {}", "Running pre-installation checks...".cyan());
        let platform = Platform::detect();
        let env_info = detect_environment();

        // Platform validation
        if platform == Platform::Unknown {
            println!(
                "🤔 {}",
                "Hmm, couldn't detect your platform. Are you on a supported OS?".yellow()
            );
            println!(
                "💡 {}",
                "Supported platforms: Linux, macOS, Windows".yellow()
            );
            println!(
                "💡 {}",
                "Try specifying method manually: kindly-tools install kindlyguard --method npm"
                    .yellow()
            );
            return Err(anyhow::anyhow!("Unsupported platform"));
        }

        // Version validation and normalization
        let version_str = if let Some(v) = version {
            validate_and_normalize_version(v)?
        } else {
            "latest".to_string()
        };

        // Auto-detect best installation method if not specified
        let install_method = if let Some(m) = method {
            m.to_string()
        } else {
            detect_best_install_method(&platform)?
        };

        // Display installation plan
        println!("\n🎯 {}", "Installation Plan".bold().blue());
        println!(
            "   📦 Package: {}",
            "🛡️ KindlyGuard MCP Server".bright_white()
        );

        // Platform-specific emoji
        let platform_display = match platform {
            Platform::MacOS => format!("🍎 {}", platform.to_string()),
            Platform::Windows => format!("🪟 {}", platform.to_string()),
            Platform::Linux => {
                let distro = detect_linux_distro();
                distro.display_name()
            },
            _ => format!("🖥️  {}", platform.to_string()),
        };
        println!("   {}", platform_display.green());

        // Show environment details if relevant
        if env_info.is_docker {
            println!("   🐳 Environment: {}", "Docker Container".cyan());
        }
        if env_info.is_wsl {
            println!(
                "   🪟 Environment: {}",
                "Windows Subsystem for Linux".cyan()
            );
        }
        if env_info.is_ci {
            println!("   🤖 Environment: {}", "CI/CD Pipeline".cyan());
        }
        if env_info.is_ssh {
            println!("   🔐 Connection: {}", "SSH Session".cyan());
        }
        if env_info.has_proxy {
            println!("   🌐 Network: {}", "Behind Proxy".yellow());
        }

        println!("   ⚙️ Method: {}", install_method.green());
        println!("   🏷️ Version: {}", version_str.green());

        // Run additional pre-flight checks
        if let Err(e) = run_preflight_checks(&platform, &install_method).await {
            println!("\n⚠️  {}", "Pre-flight check warnings:".yellow());
            println!("   {}", e.to_string().yellow());
            // Continue anyway, these are just warnings
        }

        println!("\n{}", "Preparing installation...".cyan());

        match install_method.as_str() {
            "homebrew" | "brew" => {
                println!("🍺 {}", "Installing via Homebrew...".green());

                if !command_exists("brew") {
                    println!("\n{}", "Homebrew not found!".red());
                    println!("🔧 {}", "Install Homebrew first:".yellow());
                    println!("   {}", "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"".bright_white());
                    println!("\n💡 {}", "Or try a different method:".yellow());
                    println!(
                        "   {}",
                        "kindly-tools install kindlyguard --method npm".bright_white()
                    );
                    return Err(anyhow::anyhow!("Homebrew not installed"));
                }

                println!("\n📋 {}", "Installation steps:".cyan());
                println!("   1️⃣  Add our tap:");
                println!(
                    "      {} {}",
                    "$".dimmed(),
                    "brew tap kindly-software-inc/tap".bright_white()
                );
                println!("   2️⃣  Install KindlyGuard:");
                println!(
                    "      {} {}",
                    "$".dimmed(),
                    "brew install kindlyguard".bright_white()
                );

                if version_str != "latest" {
                    println!(
                        "\n⚠️  {}",
                        "Note: Homebrew installs the latest version by default.".yellow()
                    );
                    println!(
                        "💡 {}",
                        "For specific versions, use npm or cargo instead.".yellow()
                    );
                }

                // Check if tap exists
                let output = std::process::Command::new("brew").args(["tap"]).output()?;

                let taps = String::from_utf8_lossy(&output.stdout);
                let tap_exists = taps.contains("kindly-software-inc/tap");

                if !tap_exists {
                    println!("\n{}", "Adding tap...".yellow());
                    let tap_status = std::process::Command::new("brew")
                        .args(["tap", "kindly-software-inc/tap"])
                        .status();

                    if tap_status.is_err() || !tap_status.unwrap().success() {
                        // Tap failed, show recovery menu
                        loop {
                            let recovery_method = show_recovery_menu("homebrew")?;

                            if recovery_method == RecoveryMethod::Cancel {
                                return Err(anyhow::anyhow!("Installation cancelled"));
                            }

                            execute_recovery(recovery_method, "homebrew", "kindlyguard", &platform)
                                .await?;

                            let try_again = dialoguer::Confirm::new()
                                .with_prompt("Try another recovery method?")
                                .default(true)
                                .interact()?;

                            if !try_again {
                                break;
                            }
                        }
                        return Ok(());
                    }
                }

                println!("\n{}", "Installing package...".yellow());
                let install_status = std::process::Command::new("brew")
                    .args(["install", "kindlyguard"])
                    .status();

                match install_status {
                    Ok(s) if s.success() => {
                        println!("\n{}", "Installation successful!".green().bold());
                    },
                    _ => {
                        // Installation failed, show recovery menu
                        loop {
                            let recovery_method = show_recovery_menu("homebrew")?;

                            if recovery_method == RecoveryMethod::Cancel {
                                return Err(anyhow::anyhow!("Installation cancelled"));
                            }

                            execute_recovery(recovery_method, "homebrew", "kindlyguard", &platform)
                                .await?;

                            let try_again = dialoguer::Confirm::new()
                                .with_prompt("Try another recovery method?")
                                .default(true)
                                .interact()?;

                            if !try_again {
                                break;
                            }
                        }
                    },
                }
            },
            "npm" => {
                println!("📦 {}", "Installing via npm...".green());

                if !command_exists("npm") {
                    println!("\n{}", "npm not found!".red());

                    // Check for Node.js version managers
                    let node_managers = detect_node_managers();
                    if node_managers.has_any() {
                        println!("🔍 {}", "Detected Node.js version managers:".cyan());
                        if node_managers.has_nvm {
                            println!(
                                "   ✅ nvm detected! Try: {}",
                                "nvm install --lts && nvm use --lts".bright_white()
                            );
                        }
                        if node_managers.has_fnm {
                            println!(
                                "   ✅ fnm detected! Try: {}",
                                "fnm install --lts && fnm use lts-latest".bright_white()
                            );
                        }
                        if node_managers.has_n {
                            println!("   ✅ n detected! Try: {}", "n lts".bright_white());
                        }
                        if node_managers.has_volta {
                            println!(
                                "   ✅ volta detected! Try: {}",
                                "volta install node".bright_white()
                            );
                        }
                        if node_managers.has_asdf {
                            println!(
                                "   ✅ asdf detected! Try: {}",
                                "asdf plugin add nodejs && asdf install nodejs latest"
                                    .bright_white()
                            );
                        }
                        println!(
                            "\n💡 {}",
                            "After activating Node.js, run this command again!".yellow()
                        );
                    } else {
                        println!("🤖 {}", "Let's fix this! Choose your platform:".yellow());

                        match platform {
                            Platform::MacOS => {
                                println!("\n🍎 {}", "macOS Options:".cyan());
                                println!(
                                    "   🍺 Using Homebrew: {}",
                                    "brew install node".bright_white()
                                );
                                println!(
                                    "   📥 Direct download: {}",
                                    "https://nodejs.org/".blue().underline()
                                );
                                println!("\n🚀 {}", "Recommended: Use a version manager".green());
                                println!("   • fnm (fast): {}", "brew install fnm".bright_white());
                                println!(
                                    "   • volta (reliable): {}",
                                    "brew install volta".bright_white()
                                );
                            },
                            Platform::Linux => {
                                let distro = detect_linux_distro();
                                println!("\n{} {}", distro.display_name(), "Options:".cyan());

                                match distro {
                                    LinuxDistro::Ubuntu
                                    | LinuxDistro::Debian
                                    | LinuxDistro::Mint => {
                                        println!(
                                            "   📦 System package: {}",
                                            "sudo apt update && sudo apt install nodejs npm"
                                                .bright_white()
                                        );
                                    },
                                    LinuxDistro::Fedora
                                    | LinuxDistro::CentOS
                                    | LinuxDistro::RHEL => {
                                        println!(
                                            "   📦 System package: {}",
                                            "sudo dnf install nodejs npm".bright_white()
                                        );
                                    },
                                    LinuxDistro::Arch | LinuxDistro::Manjaro => {
                                        println!(
                                            "   📦 System package: {}",
                                            "sudo pacman -S nodejs npm".bright_white()
                                        );
                                    },
                                    LinuxDistro::Alpine => {
                                        println!(
                                            "   📦 System package: {}",
                                            "sudo apk add nodejs npm".bright_white()
                                        );
                                    },
                                    LinuxDistro::NixOS => {
                                        println!(
                                            "   📦 System package: {}",
                                            "nix-env -iA nixpkgs.nodejs".bright_white()
                                        );
                                    },
                                    _ => {
                                        println!(
                                            "   📥 Direct download: {}",
                                            "https://nodejs.org/".blue().underline()
                                        );
                                    },
                                }

                                println!("\n🚀 {}", "Recommended: Use a version manager".green());
                                println!(
                                    "   • fnm (fast): {}",
                                    "curl -fsSL https://fnm.vercel.app/install | bash"
                                        .bright_white()
                                );
                                println!(
                                    "   • volta (reliable): {}",
                                    "curl https://get.volta.sh | bash".bright_white()
                                );
                            },
                            Platform::Windows => {
                                println!("\n🪟 {}", "Windows Options:".cyan());
                                println!(
                                    "   🍫 Using Chocolatey: {}",
                                    "choco install nodejs".bright_white()
                                );
                                println!(
                                    "   🍞 Using Scoop: {}",
                                    "scoop install nodejs".bright_white()
                                );
                                println!(
                                    "   🌀 Using winget: {}",
                                    "winget install OpenJS.NodeJS".bright_white()
                                );
                                println!(
                                    "   📥 Direct download: {}",
                                    "https://nodejs.org/".blue().underline()
                                );
                                println!("\n🚀 {}", "Recommended: Use volta".green());
                                println!("   • Install: {}", "choco install volta".bright_white());
                            },
                            _ => {
                                println!(
                                    "   📥 Direct download: {}",
                                    "https://nodejs.org/".blue().underline()
                                );
                            },
                        }
                    }

                    println!(
                        "\n💡 {}",
                        "After installing Node.js, run this command again!".yellow()
                    );
                    return Err(anyhow::anyhow!("npm not installed"));
                }

                let package = if version_str != "latest" {
                    format!("kindly-guard-server@{}", version_str)
                } else {
                    "kindly-guard-server".to_string()
                };

                println!("\n📋 {}", "Installation command:".cyan());
                println!(
                    "   {} npm install -g {}",
                    "$".dimmed(),
                    package.bright_white()
                );

                println!("\n{}", "Attempting installation...".yellow());
                let status = std::process::Command::new("npm")
                    .args(["install", "-g", &package])
                    .status();

                match status {
                    Ok(s) if s.success() => {
                        println!("\n{}", "Installation successful!".green().bold());
                    },
                    _ => {
                        // Installation failed, show recovery menu
                        loop {
                            let recovery_method = show_recovery_menu("npm")?;

                            if recovery_method == RecoveryMethod::Cancel {
                                return Err(anyhow::anyhow!("Installation cancelled"));
                            }

                            execute_recovery(recovery_method, "npm", &package, &platform).await?;

                            // Ask if user wants to try another recovery method
                            let try_again = dialoguer::Confirm::new()
                                .with_prompt("Try another recovery method?")
                                .default(true)
                                .interact()?;

                            if !try_again {
                                break;
                            }
                        }
                    },
                }
            },
            "cargo" => {
                println!("🦀 {}", "Installing KindlyGuard...".green());
                println!("📦 {}", "Using GitHub releases for faster installation".cyan());

                // Try to install from GitHub releases
                match install_kindlyguard_from_github(&version_str, &platform).await {
                    Ok(_) => {
                        // Success - installation complete
                    },
                    Err(e) => {
                        println!("\n⚠️  {}", format!("GitHub download failed: {}", e).yellow());
                        println!("🔄 {}", "Falling back to cargo install...".cyan());

                        // Check if cargo is available for fallback
                        if !command_exists("cargo") {
                            println!("\n{}", "Cargo not found!".red());
                            println!("🦀 {}", "Let's install Rust and Cargo:".yellow());
                            println!("\n📋 {}", "Quick install (all platforms):".cyan());
                            println!(
                                "   {} {}",
                                "$".dimmed(),
                                "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
                                    .bright_white()
                            );

                            match platform {
                                Platform::Windows => {
                                    println!("\n🪟 {}", "Windows alternative:".cyan());
                                    println!(
                                        "   📥 Download installer: {}",
                                        "https://rustup.rs/".blue().underline()
                                    );
                                },
                                _ => {},
                            }

                            println!(
                                "\n💡 {}",
                                "After installing Rust, restart your terminal and try again!".yellow()
                            );
                            return Err(anyhow::anyhow!("Installation failed - no fallback available"));
                        }

                        // Fallback to cargo install
                        let package = if version_str != "latest" {
                            format!("kindlyguard@{}", version_str)
                        } else {
                            "kindlyguard".to_string()
                        };

                        println!("\n📋 {}", "Fallback installation command:".cyan());
                        println!(
                            "   {} cargo install {}",
                            "$".dimmed(),
                            package.bright_white()
                        );

                        println!(
                            "\n{}",
                            "Attempting installation (this may take a while)...".yellow()
                        );
                        let status = std::process::Command::new("cargo")
                            .args(["install", &package])
                            .status();

                        match status {
                            Ok(s) if s.success() => {
                                println!("\n{}", "Installation successful!".green().bold());
                                println!("📍 {}", "Binary installed to ~/.cargo/bin/".cyan());
                            },
                            _ => {
                                // Installation failed, show recovery menu
                                loop {
                                    let recovery_method = show_recovery_menu("cargo")?;

                                    if recovery_method == RecoveryMethod::Cancel {
                                        return Err(anyhow::anyhow!("Installation cancelled"));
                                    }

                                    execute_recovery(recovery_method, "cargo", &package, &platform).await?;

                                    // Ask if user wants to try another recovery method
                                    let try_again = dialoguer::Confirm::new()
                                        .with_prompt("Try another recovery method?")
                                        .default(true)
                                        .interact()?;

                                    if !try_again {
                                        break;
                                    }
                                }
                            },
                        }
                    }
                }
            },
            "binary" => {
                println!("💿 {}", "Direct binary installation...".green());

                let arch = crate::platform::Architecture::detect();
                println!(
                    "\n🏗️  {}",
                    format!("Detected architecture: {}", arch.name()).cyan()
                );

                // Ask if user wants automatic download
                let auto_download = dialoguer::Confirm::new()
                    .with_prompt("Download and install automatically?")
                    .default(true)
                    .interact()?;

                if auto_download {
                    // Use the same GitHub download functionality
                    match install_kindlyguard_from_github(&version_str, &platform).await {
                        Ok(_) => {
                            // Success - installation complete
                        },
                        Err(e) => {
                            println!("\n⚠️  {}", format!("Automatic download failed: {}", e).yellow());
                            println!("📋 {}", "You can download manually:".cyan());
                            
                            // Fall through to manual instructions
                            show_manual_download_instructions(&platform, &arch);
                        }
                    }
                } else {
                    show_manual_download_instructions(&platform, &arch);
                }
            },
            _ => {
                println!(
                    "\n{}",
                    format!("Unknown installation method: {}", install_method).red()
                );
                println!(
                    "🤔 {}",
                    "Valid methods: homebrew, npm, cargo, binary".yellow()
                );

                // Suggest best method
                let suggested = detect_best_install_method(&platform)?;
                println!(
                    "\n💡 {}",
                    format!(
                        "Try: kindly-tools install kindlyguard --method {}",
                        suggested
                    )
                    .green()
                );

                return Err(anyhow::anyhow!("Invalid installation method"));
            },
        }

        println!("\n🎯 {}", "Next steps:".bold().green());
        println!(
            "   🚀 Start server: {}",
            "kindlyguard --stdio".bright_white()
        );
        println!("   📖 Get help: {}", "kindlyguard --help".bright_white());
        println!("   🔧 Configure: {}", "kindlyguard config".bright_white());

        println!("\n🩺 {}", "If something goes wrong:".cyan());
        show_troubleshooting_tips();

        // Run post-installation verification
        println!("\n🔎 {}", "Verifying installation...".bold().cyan());
        verify_installation(&install_method)?;

        Ok(())
    }

    /// Verify that the installation succeeded
    fn verify_installation(method: &str) -> Result<()> {
        use colored::*;
        use std::path::Path;

        let mut checks_passed = true;
        let mut warnings = Vec::new();

        // 1. Check if binary exists in expected locations
        println!("\n📍 {}", "Checking binary locations...".cyan());

        let binary_locations: Vec<String> = match method {
            "homebrew" | "brew" => vec![
                "/usr/local/bin/kindlyguard".to_string(),
                "/opt/homebrew/bin/kindlyguard".to_string(),
            ],
            "npm" => {
                let npm_prefix = Command::new("npm")
                    .args(["prefix", "-g"])
                    .output()
                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                    .unwrap_or_default();

                if npm_prefix.is_empty() {
                    vec![
                        "/usr/local/bin/kindlyguard".to_string(),
                        "/usr/bin/kindlyguard".to_string(),
                    ]
                } else {
                    vec![
                        format!("{}/bin/kindlyguard", npm_prefix),
                        "/usr/local/bin/kindlyguard".to_string(),
                    ]
                }
            },
            "cargo" => vec![
                format!(
                    "{}/.cargo/bin/kindlyguard",
                    env::var("HOME").unwrap_or_default()
                ),
                "/usr/local/bin/kindlyguard".to_string(),
            ],
            "binary" => vec![
                "/usr/local/bin/kindlyguard".to_string(),
                "/opt/kindlyguard/bin/kindlyguard".to_string(),
                format!("{}/bin/kindlyguard", env::var("HOME").unwrap_or_default()),
            ],
            _ => vec!["/usr/local/bin/kindlyguard".to_string()],
        };

        let mut found_binary = None;
        for location in &binary_locations {
            if Path::new(location).exists() {
                println!("   ✅ Found binary at: {}", location.green());
                found_binary = Some(location.clone());
                break;
            }
        }

        if found_binary.is_none() {
            println!("{}", "Binary not found in expected locations".red());
            checks_passed = false;

            // Additional check using 'which'
            if let Ok(output) = Command::new("which").arg("kindlyguard").output() {
                if output.status.success() {
                    let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
                    if !path.is_empty() {
                        println!("   ✅ Found binary via PATH at: {}", path.green());
                        found_binary = Some(path);
                        checks_passed = true;
                    }
                }
            }
        }

        // 2. Run --version to verify it works
        if let Some(binary_path) = &found_binary {
            println!("\n🔧 {}", "Checking binary execution...".cyan());

            match Command::new(binary_path).arg("--version").output() {
                Ok(output) => {
                    if output.status.success() {
                        let version = String::from_utf8_lossy(&output.stdout);
                        println!("   ✅ Binary executes successfully");
                        println!("   📌 Version: {}", version.trim().green());
                    } else {
                        println!("{}", "Binary failed to execute".red());
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        if !stderr.is_empty() {
                            println!("   💡 Error: {}", stderr.trim().yellow());
                        }
                        checks_passed = false;
                    }
                },
                Err(e) => {
                    println!("{}", format!("Failed to run binary: {}", e).red());
                    checks_passed = false;
                },
            }
        }

        // 3. Check file permissions (Unix only)
        #[cfg(unix)]
        if let Some(binary_path) = &found_binary {
            println!("\n🔐 {}", "Checking file permissions...".cyan());

            use std::os::unix::fs::PermissionsExt;
            match std::fs::metadata(binary_path) {
                Ok(metadata) => {
                    let mode = metadata.permissions().mode();
                    let is_executable = mode & 0o111 != 0;

                    if is_executable {
                        println!("   ✅ Binary has executable permissions");
                    } else {
                        println!("{}", "Binary is not executable".red());
                        println!(
                            "   💡 Fix with: {}",
                            format!("chmod +x {}", binary_path).yellow()
                        );
                        checks_passed = false;
                    }
                },
                Err(e) => {
                    println!(
                        "   ⚠️  {}",
                        format!("Could not check permissions: {}", e).yellow()
                    );
                    warnings.push("Could not verify file permissions");
                },
            }
        }

        // 4. Check if PATH contains the install directory
        println!("\n🌐 {}", "Checking PATH configuration...".cyan());

        if let Ok(path_var) = env::var("PATH") {
            let path_contains_binary = if let Some(binary_path) = &found_binary {
                if let Some(parent) = Path::new(binary_path).parent() {
                    path_var.split(':').any(|p| Path::new(p) == parent)
                } else {
                    false
                }
            } else {
                false
            };

            if path_contains_binary || command_exists("kindlyguard") {
                println!("   ✅ kindlyguard is accessible via PATH");
            } else {
                println!("   ⚠️  {}", "kindlyguard directory not in PATH".yellow());
                warnings.push("PATH configuration needed");

                // Detect shell and provide instructions
                detect_and_show_path_instructions(method);
            }
        }

        // Summary
        println!("\n📋 {}", "Verification Summary".bold().blue());

        if checks_passed && warnings.is_empty() {
            println!(
                "\n{}",
                "All checks passed! Installation verified.".bold().green()
            );
            println!("🚀 {}", "You can now run: kindlyguard --help".green());
        } else if checks_passed && !warnings.is_empty() {
            println!(
                "\n{}",
                "Installation succeeded with warnings:".bold().yellow()
            );
            for warning in &warnings {
                println!("   ⚠️  {}", warning.yellow());
            }
        } else {
            println!("\n{}", "Installation verification failed!".bold().red());
            println!(
                "🔧 {}",
                "Please check the errors above and try again.".yellow()
            );
            return Err(anyhow::anyhow!("Installation verification failed"));
        }

        Ok(())
    }

    /// Show manual download instructions for binary installation
    fn show_manual_download_instructions(platform: &Platform, arch: &crate::platform::Architecture) {
        use colored::*;
        
        println!("\n📥 {}", "Download options:".cyan());
        println!(
            "   🌐 Visit: {}",
            "https://github.com/kindly-software-inc/kindly-guard/releases"
                .blue()
                .underline()
        );

        match platform {
            Platform::MacOS => {
                let arch_str = if *arch == crate::platform::Architecture::Arm64 {
                    "aarch64"
                } else {
                    "x86_64"
                };
                println!("\n🍎 {}", "macOS binary:".cyan());
                println!(
                    "   📦 File: {}",
                    format!("kindlyguard-{}-apple-darwin", arch_str)
                        .bright_white()
                );

                println!("\n📋 {}", "Installation steps:".cyan());
                println!("   1️⃣  Download the binary file");
                println!(
                    "   2️⃣  Move to PATH: {}",
                    "sudo mv kindlyguard /usr/local/bin/".bright_white()
                );
                println!(
                    "   3️⃣  Make executable: {}",
                    "sudo chmod +x /usr/local/bin/kindlyguard".bright_white()
                );
            },
            Platform::Linux => {
                println!("\n🐧 {}", "Linux binary:".cyan());
                println!(
                    "   📦 File: {}",
                    "kindlyguard-x86_64-unknown-linux-gnu".bright_white()
                );

                println!("\n📋 {}", "Installation steps:".cyan());
                println!("   1️⃣  Download the binary file");
                println!(
                    "   2️⃣  Move to PATH: {}",
                    "sudo mv kindlyguard /usr/local/bin/".bright_white()
                );
                println!(
                    "   3️⃣  Make executable: {}",
                    "sudo chmod +x /usr/local/bin/kindlyguard".bright_white()
                );
            },
            Platform::Windows => {
                println!("\n🪟 {}", "Windows binary:".cyan());
                println!(
                    "   📦 File: {}",
                    "kindlyguard-x86_64-pc-windows-msvc.exe".bright_white()
                );

                println!("\n📋 {}", "Installation steps:".cyan());
                println!("   1️⃣  Download the .exe file");
                println!("   📂 Move to C:\\Program Files\\KindlyGuard\\");
                println!(
                    "   🔧 Add to PATH: {}",
                    "%ProgramFiles%\\KindlyGuard".yellow()
                );
            },
            Platform::Unknown => {
                println!("\n{}", "Unknown platform:".yellow());
                println!("   Please visit the releases page for manual download");
            },
        }

        println!("\n⚠️  {}", "Important:".yellow());
        println!("   🔍 Verify checksums after download");
        println!("   🔒 Check file permissions are correct");
        println!("   📍 Ensure binary is in your PATH");
    }

    /// Detect shell and show PATH configuration instructions
    fn detect_and_show_path_instructions(method: &str) -> () {
        use colored::*;

        // Detect current shell
        let shell = env::var("SHELL").unwrap_or_default();
        let shell_name = if shell.contains("bash") {
            "bash"
        } else if shell.contains("zsh") {
            "zsh"
        } else if shell.contains("fish") {
            "fish"
        } else {
            "sh"
        };

        println!("\n💡 {}", "To add kindlyguard to your PATH:".cyan());

        let path_to_add = match method {
            "npm" => {
                let npm_prefix = Command::new("npm")
                    .args(["prefix", "-g"])
                    .output()
                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                    .unwrap_or_else(|_| "/usr/local".to_string());
                format!("{}/bin", npm_prefix)
            },
            "cargo" => format!("$HOME/.cargo/bin"),
            "homebrew" | "brew" => {
                if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
                    "/opt/homebrew/bin".to_string()
                } else {
                    "/usr/local/bin".to_string()
                }
            },
            _ => "/usr/local/bin".to_string(),
        };

        match shell_name {
            "bash" => {
                println!("\n   🐚 For Bash:");
                println!("      1. Add to ~/.bashrc:");
                println!(
                    "         {} echo 'export PATH=\"{}:$PATH\"' >> ~/.bashrc",
                    "$".dimmed(),
                    path_to_add.bright_white()
                );
                println!("      2. Reload:");
                println!("         {} source ~/.bashrc", "$".dimmed());
            },
            "zsh" => {
                println!("\n   🐚 For Zsh:");
                println!("      1. Add to ~/.zshrc:");
                println!(
                    "         {} echo 'export PATH=\"{}:$PATH\"' >> ~/.zshrc",
                    "$".dimmed(),
                    path_to_add.bright_white()
                );
                println!("      2. Reload:");
                println!("         {} source ~/.zshrc", "$".dimmed());
            },
            "fish" => {
                println!("\n   🐚 For Fish:");
                println!("      1. Add to config:");
                println!(
                    "         {} fish_add_path {}",
                    "$".dimmed(),
                    path_to_add.bright_white()
                );
                println!("      2. Or manually:");
                println!(
                    "         {} set -Ua fish_user_paths {}",
                    "$".dimmed(),
                    path_to_add.bright_white()
                );
            },
            _ => {
                println!("\n   🐚 For your shell:");
                println!("      1. Add to your shell config file:");
                println!(
                    "         export PATH=\"{}:$PATH\"",
                    path_to_add.bright_white()
                );
                println!("      2. Reload your shell configuration");
            },
        }

        println!("\n   💡 After updating PATH, restart your terminal or run the reload command");
    }

    fn validate_and_normalize_version(version: &str) -> Result<String> {
        use colored::*;

        // Remove common prefixes
        let normalized = version
            .trim()
            .trim_start_matches('v')
            .trim_start_matches('V');

        // Basic validation
        if normalized.is_empty() {
            println!("⚠️  {}", "Empty version specified, using 'latest'".yellow());
            return Ok("latest".to_string());
        }

        // Check format (basic semver validation)
        let parts: Vec<&str> = normalized.split('.').collect();
        if parts.len() != 3 && normalized != "latest" {
            println!(
                "⚠️  {}",
                format!(
                    "Version '{}' doesn't look like semantic versioning",
                    version
                )
                .yellow()
            );
            println!("💡 {}", "Expected format: X.Y.Z (e.g., 0.10.3)".yellow());
            println!(
                "📋 {}",
                "Available versions: latest, 0.10.3, 0.10.2, 0.10.1".cyan()
            );

            // Still allow it, just warn
        }

        Ok(normalized.to_string())
    }

    fn detect_best_install_method(platform: &crate::platform::Platform) -> Result<String> {
        match platform {
            crate::platform::Platform::MacOS => {
                if command_exists("brew") {
                    Ok("homebrew".to_string())
                } else if command_exists("npm") {
                    Ok("npm".to_string())
                } else if command_exists("cargo") {
                    Ok("cargo".to_string())
                } else {
                    Ok("binary".to_string())
                }
            },
            crate::platform::Platform::Linux => {
                if command_exists("npm") {
                    Ok("npm".to_string())
                } else if command_exists("cargo") {
                    Ok("cargo".to_string())
                } else {
                    Ok("binary".to_string())
                }
            },
            crate::platform::Platform::Windows => {
                if command_exists("npm") {
                    Ok("npm".to_string())
                } else if command_exists("cargo") {
                    Ok("cargo".to_string())
                } else {
                    Ok("binary".to_string())
                }
            },
            _ => Ok("npm".to_string()),
        }
    }

    async fn run_preflight_checks(
        _platform: &crate::platform::Platform,
        method: &str,
    ) -> Result<()> {
        use colored::*;

        // Check disk space (simplified - just a warning)
        #[cfg(not(target_os = "windows"))]
        {
            if let Ok(output) = std::process::Command::new("df").args(["-h", "/"]).output() {
                let output_str = String::from_utf8_lossy(&output.stdout);
                // Very basic check - just warn if root partition seems full
                if output_str.contains("100%")
                    || output_str.contains("99%")
                    || output_str.contains("98%")
                {
                    println!("💾 {}", "Warning: Disk space is running low!".yellow());
                    println!("   {}", "Installation needs approximately 200MB".yellow());
                }
            }
        }

        // Check network connectivity for non-binary methods
        if method != "binary" {
            // Simple check - try to resolve a common domain
            #[cfg(not(target_os = "windows"))]
            {
                if let Err(_) = std::process::Command::new("ping")
                    .args(["-c", "1", "-W", "2", "8.8.8.8"])
                    .output()
                {
                    println!("🌐 {}", "Network connectivity might be limited".yellow());
                    println!(
                        "   {}",
                        "If installation fails, check your internet connection".yellow()
                    );
                }
            }
        }

        Ok(())
    }

    fn show_troubleshooting_tips() {
        use colored::*;

        println!("   📝 Check internet connection");
        println!("   📝 Verify disk space (200MB needed)");
        println!("   📝 Ensure admin/sudo permissions");
        println!("   📝 Try a different installation method");
        println!("\n🆘 {}", "Need help?".cyan());
        println!(
            "   📚 Docs: {}",
            "https://github.com/kindly-software-inc/kindly-guard/wiki"
                .blue()
                .underline()
        );
        println!(
            "   🐛 Issues: {}",
            "https://github.com/kindly-software-inc/kindly-guard/issues"
                .blue()
                .underline()
        );
    }

    async fn install_all() -> Result<()> {
        use colored::*;

        println!(
            "\n🎁 {}",
            "Installing all recommended tools...".bold().blue()
        );
        println!("📦 {}", "This will install:".cyan());
        println!("   1️⃣  KindlyGuard MCP Server");
        println!("   2️⃣  Recommended MCP servers");
        println!("   3️⃣  Development dependencies");

        println!("\n{}", "Step 1/3: Installing KindlyGuard...".cyan());
        install_kindlyguard(None, None).await?;

        println!("\n{}", "Step 2/3: Installing MCP servers...".cyan());
        install_mcp_servers(None).await?;

        println!("\n{}", "Step 3/3: Installing dev dependencies...".cyan());
        install_dev_deps().await?;

        println!(
            "\n🎉 {}",
            "All tools installed successfully!".bold().green()
        );
        println!("{}", "Your development environment is ready!".green());

        Ok(())
    }

    async fn install_mcp_servers(server: Option<&str>) -> Result<()> {
        use colored::*;
        use dialoguer::Confirm;

        let servers = if let Some(s) = server {
            vec![(s, get_server_description(s))]
        } else {
            vec![
                ("tree-sitter", "🌳 Parse and analyze code structure"),
                ("ast-grep", "🔍 Search code with AST patterns"),
                ("filesystem", "📁 Enhanced file system access"),
            ]
        };

        println!("\n🔌 {}", "MCP Server Installation".bold().blue());

        for (server_name, description) in servers {
            println!("\n📦 {}: {}", server_name.cyan(), description);

            if Confirm::new()
                .with_prompt(format!("   Install '{}'?", server_name))
                .default(true)
                .interact()?
            {
                println!(
                    "{}",
                    format!("Installing {}...", server_name).yellow()
                );

                // TODO: Add actual installation logic
                println!(
                    "{}",
                    format!("{} installed successfully!", server_name).green()
                );

                // Provide configuration tips
                match server_name {
                    "tree-sitter" => {
                        println!(
                            "   💡 {}",
                            "Tip: Use for code navigation and refactoring".yellow()
                        );
                    },
                    "ast-grep" => {
                        println!("   💡 {}", "Tip: Great for finding code patterns".yellow());
                    },
                    "filesystem" => {
                        println!(
                            "   💡 {}",
                            "Tip: Provides secure file access to Claude".yellow()
                        );
                    },
                    _ => {},
                }
            } else {
                println!("   ⏭️  {}", format!("Skipping {}", server_name).dimmed());
            }
        }

        println!(
            "\n📝 {}",
            "Note: Restart Claude Desktop after installing MCP servers".cyan()
        );

        Ok(())
    }

    fn get_server_description(server: &str) -> &'static str {
        match server {
            "tree-sitter" => "🌳 Parse and analyze code structure",
            "ast-grep" => "🔍 Search code with AST patterns",
            "filesystem" => "📁 Enhanced file system access",
            "semgrep" => "🛡️  Security vulnerability scanning",
            "github" => "🐙 GitHub repository integration",
            _ => "📦 MCP server extension",
        }
    }

    async fn install_dev_deps() -> Result<()> {
        use colored::*;

        println!("\n🛠️  {}", "Development Dependencies Check".bold().blue());

        let platform = crate::platform::Platform::detect();
        let packages = match platform {
            crate::platform::Platform::Linux => vec![
                (
                    "build-essential",
                    "🔨 C/C++ compiler toolchain",
                    "sudo apt install build-essential",
                ),
                (
                    "pkg-config",
                    "📦 Library configuration tool",
                    "sudo apt install pkg-config",
                ),
                (
                    "libssl-dev",
                    "🔐 SSL development headers",
                    "sudo apt install libssl-dev",
                ),
            ],
            crate::platform::Platform::MacOS => vec![
                (
                    "xcode-select",
                    "🍎 Xcode command line tools",
                    "xcode-select --install",
                ),
                (
                    "pkg-config",
                    "📦 Library configuration tool",
                    "brew install pkg-config",
                ),
            ],
            crate::platform::Platform::Windows => vec![(
                "visual-studio",
                "🪟 Visual Studio Build Tools",
                "Download from https://visualstudio.microsoft.com/downloads/",
            )],
            _ => vec![],
        };

        let mut missing = Vec::new();

        println!("\n🔍 {}", "Checking system dependencies...".cyan());

        for (pkg, description, install_cmd) in &packages {
            print!("   {} {}: ", "".dimmed(), description);

            // Simple check - just see if command exists or path exists
            let is_installed = match *pkg {
                "xcode-select" => command_exists("xcodebuild"),
                "visual-studio" => {
                    // Check common VS paths
                    std::path::Path::new("C:\\Program Files\\Microsoft Visual Studio").exists()
                        || std::path::Path::new("C:\\Program Files (x86)\\Microsoft Visual Studio")
                            .exists()
                },
                _ => command_exists(pkg),
            };

            if is_installed {
                println!("{}", "✅ Installed".green());
            } else {
                println!("{}", "❌ Not found".red());
                missing.push((pkg, description, install_cmd));
            }
        }

        if !missing.is_empty() {
            println!("\n⚠️  {}", "Missing dependencies detected!".yellow());
            println!("📋 {}", "Installation commands:".cyan());

            for (pkg, _desc, cmd) in missing {
                println!("\n   {} {}:", "".dimmed(), pkg.bright_white());
                println!("     {}", cmd.bright_white());
            }

            println!(
                "\n💡 {}",
                "Install these dependencies for optimal development experience".yellow()
            );
        } else {
            println!(
                "\n{}",
                "All development dependencies are installed!".green()
            );
        }

        // Additional recommendations
        println!("\n🚀 {}", "Recommended Rust tools:".cyan());
        println!(
            "   {} cargo-watch - {}",
            "".dimmed(),
            "Auto-rebuild on file changes".yellow()
        );
        println!(
            "   {} cargo-nextest - {}",
            "".dimmed(),
            "3x faster test runner".yellow()
        );
        println!(
            "   {} sccache - {}",
            "".dimmed(),
            "Compilation cache for faster builds".yellow()
        );

        println!(
            "\n💡 {}",
            "Install with: cargo install cargo-watch cargo-nextest sccache".cyan()
        );

        Ok(())
    }
}

pub mod mcp {
    use super::*;
    use clap::Subcommand;
    use serde::{Deserialize, Serialize};
    use std::collections::HashMap;
    use std::io::Write;
    use std::process::{Command, Stdio};

    #[derive(clap::Args)]
    pub struct McpCommand {
        #[command(subcommand)]
        command: McpSubcommands,
    }

    #[derive(Subcommand)]
    enum McpSubcommands {
        /// Set up and install MCP server for KindlyGuard
        Setup {
            /// Skip interactive prompts and use defaults
            #[arg(short, long)]
            non_interactive: bool,

            /// Force reinstall even if already set up
            #[arg(short, long)]
            force: bool,
        },

        /// Verify MCP configuration and server status
        Verify {
            /// Show detailed verification output
            #[arg(short, long)]
            verbose: bool,
        },

        /// Show current MCP server status
        Status {
            /// Show process information
            #[arg(short, long)]
            processes: bool,
        },

        /// Start the MCP server
        Start {
            /// Run in background (daemon mode)
            #[arg(short, long)]
            daemon: bool,
        },

        /// Stop the MCP server
        Stop {
            /// Force stop all instances
            #[arg(short, long)]
            force: bool,
        },

        /// List installed MCP servers
        List,

        /// Configure MCP servers
        Config {
            /// Path to custom configuration file
            #[arg(short, long)]
            file: Option<PathBuf>,

            /// Show current configuration
            #[arg(short, long)]
            show: bool,
        },

        /// Test MCP server connection
        Test {
            /// Server to test
            server: String,
        },
    }

    #[derive(Serialize, Deserialize)]
    struct McpConfig {
        #[serde(rename = "mcpServers")]
        servers: std::collections::HashMap<String, ServerConfig>,
    }

    #[derive(Serialize, Deserialize)]
    struct ServerConfig {
        #[serde(rename = "type", default)]
        server_type: Option<String>,
        command: String,
        args: Vec<String>,
        #[serde(default)]
        env: std::collections::HashMap<String, String>,
    }

    impl Execute for McpCommand {
        async fn execute(&self) -> Result<()> {
            match &self.command {
                McpSubcommands::Setup {
                    non_interactive,
                    force,
                } => setup_mcp_server(*non_interactive, *force).await,
                McpSubcommands::Verify { verbose } => verify_mcp_setup(*verbose).await,
                McpSubcommands::Status { processes } => show_mcp_status(*processes).await,
                McpSubcommands::Start { daemon } => start_mcp_server(*daemon).await,
                McpSubcommands::Stop { force } => stop_mcp_server(*force).await,
                McpSubcommands::List => list_mcp_servers().await,
                McpSubcommands::Config { file, show } => {
                    configure_mcp(file.as_deref(), *show).await
                },
                McpSubcommands::Test { server } => test_mcp_server(server).await,
            }
        }
    }

    async fn setup_mcp_server(non_interactive: bool, force: bool) -> Result<()> {
        tracing::info!("Setting up MCP server for KindlyGuard");

        // Check if already configured
        let config_path = get_mcp_config_path()?;
        if config_path.exists() && !force {
            tracing::warn!("MCP configuration already exists at {:?}", config_path);
            if !non_interactive {
                let proceed = dialoguer::Confirm::new()
                    .with_prompt("Configuration exists. Overwrite?")
                    .default(false)
                    .interact()?;
                if !proceed {
                    tracing::info!("Setup cancelled");
                    return Ok(());
                }
            } else {
                tracing::info!("Use --force to overwrite existing configuration");
                return Ok(());
            }
        }

        // Build the project first if needed
        if !non_interactive {
            let build = dialoguer::Confirm::new()
                .with_prompt("Build kindly-guard-server first?")
                .default(true)
                .interact()?;
            if build {
                tracing::info!("Building kindly-guard-server in release mode...");
                let status = Command::new("cargo")
                    .args(["build", "--release", "--package", "kindly-guard-server"])
                    .current_dir(find_project_root()?)
                    .status()?;
                if !status.success() {
                    return Err(anyhow::anyhow!("Build failed"));
                }
            }
        }

        // Find KindlyGuard server binary
        let kg_server = find_kindlyguard_server()?;
        tracing::info!("Found KindlyGuard server at: {:?}", kg_server);

        // Create MCP server directory
        let mcp_server_dir = home_dir()?.join(".claude/mcp-servers/kindly-guard");
        std::fs::create_dir_all(&mcp_server_dir)?;

        // Copy binary to MCP server directory
        let target_binary = mcp_server_dir.join("kindly-guard");
        std::fs::copy(&kg_server, &target_binary)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&target_binary)?.permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&target_binary, perms)?;
        }

        // Create default configuration file
        let server_config_file = mcp_server_dir.join("config.toml");
        if !server_config_file.exists() || force {
            let config_content = r#"# Kindly Guard Configuration
mode = "standard"
log_level = "info"

[rate_limit]
window_secs = 60
max_requests = 100

[scanner]
max_input_size = 1048576  # 1MB
patterns_file = ""

[metrics]
enabled = true
export_interval_secs = 60

[auth]
require_auth = false
"#;
            std::fs::write(&server_config_file, config_content)?;
        }

        // Create or update MCP configuration
        let mut config = if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)?;
            serde_json::from_str(&content)?
        } else {
            McpConfig {
                servers: HashMap::new(),
            }
        };

        // Add KindlyGuard server
        let mut env = HashMap::new();
        env.insert("RUST_LOG".to_string(), "info".to_string());

        config.servers.insert(
            "kindly-guard".to_string(),
            ServerConfig {
                server_type: Some("stdio".to_string()),
                command: target_binary.to_string_lossy().to_string(),
                args: vec![
                    "--config".to_string(),
                    server_config_file.to_string_lossy().to_string(),
                ],
                env,
            },
        );

        // Save configuration
        let content = serde_json::to_string_pretty(&config)?;
        std::fs::write(&config_path, content)?;

        tracing::info!("MCP configuration saved to: {:?}", config_path);
        tracing::info!("Setup complete! Restart Claude Desktop to use the MCP server.");

        Ok(())
    }

    async fn verify_mcp_setup(verbose: bool) -> Result<()> {
        tracing::info!("Verifying MCP configuration");

        // Check configuration file
        let config_path = get_mcp_config_path()?;
        if !config_path.exists() {
            tracing::error!("MCP configuration not found at {:?}", config_path);
            return Err(anyhow::anyhow!("MCP not configured"));
        }

        // Load configuration
        let content = std::fs::read_to_string(&config_path)?;
        let config: McpConfig = serde_json::from_str(&content)?;

        // Check for KindlyGuard server
        if let Some(server) = config.servers.get("kindly-guard") {
            let command_path = Path::new(&server.command);
            if !command_path.exists() {
                tracing::error!("Server binary not found at: {:?}", command_path);
                return Err(anyhow::anyhow!("Server binary not found"));
            }

            // Test server execution
            if verbose {
                tracing::info!("Testing server execution...");
                let output = Command::new(&server.command).arg("--version").output()?;

                if output.status.success() {
                    let version = String::from_utf8_lossy(&output.stdout);
                    tracing::info!("Server version: {}", version.trim());
                }
            }

            // Test MCP protocol
            tracing::info!("Testing MCP protocol communication...");
            test_mcp_protocol(&server.command, &server.args)?;

            tracing::info!("MCP configuration verified successfully");
        } else {
            tracing::error!("KindlyGuard server not configured");
            return Err(anyhow::anyhow!("Server not in configuration"));
        }

        Ok(())
    }

    async fn show_mcp_status(show_processes: bool) -> Result<()> {
        tracing::info!("Checking MCP server status");

        // Check configuration
        let config_path = get_mcp_config_path()?;
        if !config_path.exists() {
            tracing::error!("MCP not configured");
            return Ok(());
        }

        let content = std::fs::read_to_string(&config_path)?;
        let config: McpConfig = serde_json::from_str(&content)?;

        tracing::info!("Configuration loaded from: {:?}", config_path);

        // Check server configuration
        if let Some(server) = config.servers.get("kindly-guard") {
            tracing::info!("KindlyGuard server configured:");
            tracing::info!("  Command: {}", server.command);
            tracing::info!("  Args: {:?}", server.args);
        } else {
            tracing::warn!("KindlyGuard server not configured");
        }

        // Check running processes
        if show_processes {
            check_running_processes()?;
        }

        Ok(())
    }

    async fn start_mcp_server(daemon: bool) -> Result<()> {
        tracing::info!("Starting MCP server");

        // Load configuration
        let config_path = get_mcp_config_path()?;
        let content = std::fs::read_to_string(&config_path)?;
        let config: McpConfig = serde_json::from_str(&content)?;

        let server = config
            .servers
            .get("kindly-guard")
            .ok_or_else(|| anyhow::anyhow!("KindlyGuard server not configured"))?;

        if daemon {
            // Start in background
            tracing::info!("Starting server in daemon mode");

            let mut cmd = Command::new(&server.command);
            cmd.args(&server.args);
            cmd.stdin(Stdio::null());
            cmd.stdout(Stdio::null());
            cmd.stderr(Stdio::null());

            for (key, value) in &server.env {
                cmd.env(key, value);
            }

            cmd.spawn()?;
            tracing::info!("Server started in background");
        } else {
            // Start in foreground
            tracing::info!("Starting server in foreground mode");
            tracing::info!("Press Ctrl+C to stop");

            let mut cmd = Command::new(&server.command);
            cmd.args(&server.args);

            for (key, value) in &server.env {
                cmd.env(key, value);
            }

            let status = cmd.status()?;
            if !status.success() {
                tracing::error!("Server exited with status: {:?}", status);
            }
        }

        Ok(())
    }

    async fn stop_mcp_server(force: bool) -> Result<()> {
        tracing::info!("Stopping MCP server");

        // Find running processes
        let pids = find_kindlyguard_processes()?;

        if pids.is_empty() {
            tracing::info!("No running KindlyGuard processes found");
            return Ok(());
        }

        tracing::info!("Found {} running process(es)", pids.len());

        for pid in pids {
            if force {
                Command::new("kill")
                    .arg("-9")
                    .arg(pid.to_string())
                    .status()?;
                tracing::info!("Force killed process {}", pid);
            } else {
                Command::new("kill")
                    .arg("-TERM")
                    .arg(pid.to_string())
                    .status()?;
                tracing::info!("Sent TERM signal to process {}", pid);
            }
        }

        Ok(())
    }

    async fn list_mcp_servers() -> Result<()> {
        let config_path = get_mcp_config_path()?;

        if !config_path.exists() {
            tracing::warn!("No MCP configuration found at {:?}", config_path);
            return Ok(());
        }

        let content = tokio::fs::read_to_string(&config_path).await?;
        let config: McpConfig = serde_json::from_str(&content)?;

        tracing::info!("Installed MCP servers:");
        for (name, server) in config.servers.iter() {
            tracing::info!("  {} - {}", name, server.command);
        }

        Ok(())
    }

    async fn configure_mcp(file: Option<&Path>, show: bool) -> Result<()> {
        let config_path = file
            .map(PathBuf::from)
            .unwrap_or_else(|| get_mcp_config_path().unwrap());

        if show {
            if !config_path.exists() {
                tracing::error!("Configuration file not found: {:?}", config_path);
                return Ok(());
            }

            let content = std::fs::read_to_string(&config_path)?;
            println!("{}", content);
        } else if let Some(custom_file) = file {
            tracing::info!("Loading configuration from: {:?}", custom_file);

            if !custom_file.exists() {
                return Err(anyhow::anyhow!("Configuration file not found"));
            }

            // Validate configuration
            let content = std::fs::read_to_string(custom_file)?;
            let _: McpConfig = serde_json::from_str(&content)?;

            // Copy to default location
            let default_path = get_mcp_config_path()?;
            std::fs::copy(custom_file, &default_path)?;
            tracing::info!("Configuration updated at: {:?}", default_path);
        } else {
            // Interactive configuration editor
            tracing::info!("Opening configuration editor...");
            let editor = std::env::var("EDITOR").unwrap_or_else(|_| "nano".to_string());

            Command::new(&editor).arg(&config_path).status()?;
        }

        Ok(())
    }

    async fn test_mcp_server(server: &str) -> Result<()> {
        tracing::info!("Testing MCP server '{}'...", server);

        let config_path = get_mcp_config_path()?;
        let content = std::fs::read_to_string(&config_path)?;
        let config: McpConfig = serde_json::from_str(&content)?;

        if let Some(server_config) = config.servers.get(server) {
            test_mcp_protocol(&server_config.command, &server_config.args)?;
            tracing::info!("Test completed successfully");
        } else {
            tracing::error!("Server '{}' not found in configuration", server);
        }

        Ok(())
    }

    // Helper functions

    fn get_mcp_config_path() -> Result<PathBuf> {
        let home = home_dir()?;

        // Check for different possible locations
        let candidates = vec![home.join(".mcp.json"), home.join(".config/claude/mcp.json")];

        for path in &candidates {
            if path.exists() {
                return Ok(path.clone());
            }
        }

        // Default to .mcp.json
        Ok(home.join(".mcp.json"))
    }

    fn find_project_root() -> Result<PathBuf> {
        let mut current = std::env::current_dir()?;

        loop {
            if current.join("Cargo.toml").exists() && current.join("kindly-guard-server").exists() {
                return Ok(current);
            }

            if let Some(parent) = current.parent() {
                current = parent.to_path_buf();
            } else {
                break;
            }
        }

        // Try common locations
        let home = home_dir()?;
        let candidates = vec![
            home.join("kindly-guard"),
            PathBuf::from("/home/samuel/kindly-guard"),
        ];

        for path in candidates {
            if path.join("Cargo.toml").exists() && path.join("kindly-guard-server").exists() {
                return Ok(path);
            }
        }

        Err(anyhow::anyhow!("Could not find kindly-guard project root"))
    }

    fn find_kindlyguard_server() -> Result<PathBuf> {
        let candidates = vec![
            PathBuf::from("target/release/kindly-guard-server"),
            PathBuf::from("target/debug/kindly-guard-server"),
            PathBuf::from("../kindly-guard-server/target/release/kindly-guard-server"),
            PathBuf::from("../kindly-guard-server/target/debug/kindly-guard-server"),
            PathBuf::from("/usr/local/bin/kindly-guard-server"),
            PathBuf::from("/usr/bin/kindly-guard-server"),
            home_dir()?.join(".cargo/bin/kindly-guard-server"),
        ];

        for path in candidates {
            if path.exists() {
                return Ok(path.canonicalize()?);
            }
        }

        // Try using 'which'
        if let Ok(output) = Command::new("which").arg("kindly-guard-server").output() {
            if output.status.success() {
                let path = String::from_utf8_lossy(&output.stdout);
                return Ok(PathBuf::from(path.trim()));
            }
        }

        Err(anyhow::anyhow!(
            "KindlyGuard server not found. Build it with 'cargo build --release' in the kindly-guard directory"
        ))
    }

    fn test_mcp_protocol(command: &str, args: &[String]) -> Result<()> {
        let init_request = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"kindly-tools","version":"0.1.0"}}}"#;

        let mut child = Command::new(command)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()?;

        if let Some(stdin) = child.stdin.as_mut() {
            stdin.write_all(init_request.as_bytes())?;
            stdin.write_all(b"\n")?;
            stdin.flush()?;
        }

        // Wait briefly for response
        std::thread::sleep(std::time::Duration::from_millis(500));

        let output = child.wait_with_output()?;
        let response = String::from_utf8_lossy(&output.stdout);

        if response.contains("jsonrpc") && response.contains("result") {
            tracing::info!("MCP protocol test successful");
        } else if response.contains("error") {
            tracing::error!("MCP protocol test failed");
            return Err(anyhow::anyhow!("MCP protocol error"));
        } else {
            tracing::warn!("Unexpected MCP protocol response");
        }

        Ok(())
    }

    fn check_running_processes() -> Result<()> {
        tracing::info!("Checking for running processes...");

        let output = Command::new("ps").args(["aux"]).output()?;

        let output_str = String::from_utf8_lossy(&output.stdout);
        let mut found_any = false;

        for line in output_str.lines() {
            if line.contains("kindly-guard-server") && !line.contains("grep") {
                println!("{}", line);
                found_any = true;
            }
        }

        if !found_any {
            tracing::info!("No running KindlyGuard processes found");
        }

        Ok(())
    }

    fn find_kindlyguard_processes() -> Result<Vec<u32>> {
        let output = Command::new("pgrep")
            .arg("-f")
            .arg("kindly-guard-server")
            .output()?;

        if !output.status.success() {
            return Ok(vec![]);
        }

        let output_str = String::from_utf8_lossy(&output.stdout);
        let pids: Vec<u32> = output_str
            .lines()
            .filter_map(|line| line.trim().parse().ok())
            .collect();

        Ok(pids)
    }
} // End of mcp module

/// Wrap command module for protecting AI CLIs
pub mod wrap {
    use super::*;
    use clap::Args;

    /// Wrap any AI CLI command with KindlyGuard protection
    #[derive(Debug, Args)]
    pub struct WrapCommand {
        /// The command to wrap and protect
        #[arg(trailing_var_arg = true, required = true)]
        pub command: Vec<String>,

        /// KindlyGuard server URL
        #[arg(short, long, default_value = "http://localhost:8080")]
        pub server: String,

        /// Block on threat detection instead of warning
        #[arg(short, long)]
        pub block: bool,
    }

    impl Execute for WrapCommand {
        async fn execute(&self) -> Result<()> {
            crate::commands::wrap::wrap_command(
                self.command.clone(),
                self.server.clone(),
                self.block,
            )
            .await
        }
    }
}

pub mod monitor {
    use super::*;
    use clap::Args;

    /// Monitor KindlyGuard server status in real-time
    #[derive(Debug, Args)]
    pub struct MonitorCommand {
        /// Server URL to monitor
        #[arg(short, long, default_value = "http://localhost:8080")]
        pub url: String,

        /// Update interval in seconds
        #[arg(short, long, default_value = "5")]
        pub interval: u64,
    }

    impl Execute for MonitorCommand {
        async fn execute(&self) -> Result<()> {
            crate::commands::monitor::run(self.url.clone(), self.interval).await
        }
    }
}

pub mod shield {
    use super::*;

    pub use crate::commands::shield::ShieldCommand;

    impl Execute for ShieldCommand {
        async fn execute(&self) -> Result<()> {
            // Clone self to call the run method
            let cmd = self.clone();
            cmd.run().await
        }
    }
}

pub mod utils {
    use super::*;
    use std::process::Command;

    /// Run a command and return its output
    pub fn run_command(cmd: &str, args: &[&str]) -> Result<String> {
        let output = Command::new(cmd).args(args).output()?;

        if !output.status.success() {
            anyhow::bail!("Command failed: {} {}", cmd, args.join(" "));
        }

        Ok(String::from_utf8(output.stdout)?)
    }

    /// Check if running in CI environment
    pub fn is_ci() -> bool {
        std::env::var("CI").is_ok()
    }

    /// Get the current git branch
    pub fn current_git_branch() -> Result<String> {
        run_command("git", &["rev-parse", "--abbrev-ref", "HEAD"]).map(|s| s.trim().to_string())
    }
}