ramparts 0.8.7

Security scanner for Model Context Protocol (MCP) servers and AI agent skills (Claude Code commands, agentskills.io bundles, Cursor / Codex / Windsurf / Gemini equivalents).
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
use crate::security::{SecurityIssue, SecurityIssueType};
use crate::types::{ScanResult, ScanStatus};
use anyhow::{anyhow, Result};
use colored::Colorize;
use std::fs::File;
use std::io::Write;
use std::time::Instant;
use tracing::{debug, warn};

use tabled::{Table, Tabled};

// ============================================================================
// UTILITY FUNCTIONS FOR REDUCING REDUNDANCY
// ============================================================================

/// Timing utility for measuring execution time
pub struct Timer {
    start_time: Instant,
}

impl Timer {
    pub fn start() -> Self {
        Self {
            start_time: Instant::now(),
        }
    }

    pub fn elapsed_ms(&self) -> u64 {
        #[allow(clippy::cast_possible_truncation)]
        {
            self.start_time.elapsed().as_millis() as u64
        }
    }
}

/// Enhanced error handling utilities
pub mod error_utils {
    use super::{anyhow, Result};

    /// Format a standardized error message
    pub fn format_error(operation: &str, details: &str) -> String {
        format!("{operation} failed: {details}")
    }

    /// Render the full `std::error::Error` source chain as a single string.
    ///
    /// Some libraries (notably reqwest) print very terse `Display`
    /// representations like `"builder error"` while the actual diagnosis lives
    /// in the underlying `source()`. Walking the chain surfaces those causes
    /// when a user reports an error.
    pub fn format_error_chain<E: std::error::Error + ?Sized>(err: &E) -> String {
        let mut out = err.to_string();
        let mut source = err.source();
        while let Some(s) = source {
            out.push_str(": ");
            out.push_str(&s.to_string());
            source = s.source();
        }
        out
    }

    /// Wrap an error with context
    /// Wraps an error with additional context information
    #[allow(dead_code)] // Used in tests and for error context enhancement
    pub fn wrap_error<T>(result: Result<T>, context: &str) -> Result<T> {
        result.map_err(|e| anyhow!("{context}: {e}"))
    }
}

/// Performance monitoring utilities
pub mod performance {
    use super::{debug, warn, Result, Timer};

    /// Track performance metrics
    pub struct PerformanceTracker {
        timer: Timer,
        operation_name: String,
    }

    impl PerformanceTracker {
        pub fn start(operation_name: &str) -> Self {
            Self {
                timer: Timer::start(),
                operation_name: operation_name.to_string(),
            }
        }

        pub fn finish(self) -> u64 {
            let elapsed = self.timer.elapsed_ms();
            if elapsed > 5000 {
                // Only warn if over 5 seconds
                warn!("Slow operation: {} took {}ms", self.operation_name, elapsed);
            } else if elapsed > 1000 {
                debug!("{} completed in {}ms", self.operation_name, elapsed);
            }
            elapsed
        }
    }

    /// Execute an operation with performance tracking
    pub async fn track_performance<F, Fut, T>(operation_name: &str, operation: F) -> Result<T>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<T>>,
    {
        let tracker = PerformanceTracker::start(operation_name);
        let result = operation().await;
        let _elapsed = tracker.finish();
        result
    }
}

// ============================================================================
// EXISTING PRINTING FUNCTIONS
// ============================================================================

pub fn print_result(result: &ScanResult, format: &str, detailed: bool) {
    // Skill scans go through their own renderer for terminal/text formats —
    // the live-MCP renderer's "Tools/Resources" framing collapses to garbage
    // ("Tools scanned: 0", "Unknown MCP Server") on a skill result whose
    // primary content is `prompts`. JSON / SARIF / raw stay shape-identical
    // regardless of source so machine consumers see the same fields.
    if is_skill_scan(result) {
        match format.to_lowercase().as_str() {
            "json" => print_json_result(result),
            "raw" => print_raw_json_result(result),
            "sarif" => print_sarif_result(result),
            "text" | "table" => print_skill_table_result(result, detailed),
            _ => {
                eprintln!("Unknown format: {format}. Using skill table format.");
                print_skill_table_result(result, detailed);
            }
        }
        return;
    }
    match format.to_lowercase().as_str() {
        "json" => print_json_result(result),
        "table" => print_table_result(result, detailed),
        "text" => print_text_result(result),
        "raw" => print_raw_json_result(result),
        "sarif" => print_sarif_result(result),
        _ => {
            eprintln!("Unknown format: {format}. Using table format.");
            print_table_result(result, detailed);
        }
    }
}

/// True when this `ScanResult` came from `ramparts skills scan` /
/// `skills scan-config`. The handler stamps the URL with the
/// `skills:` scheme so renderers can branch on it.
fn is_skill_scan(result: &ScanResult) -> bool {
    result.url.starts_with("skills:")
}

/// Skill-aware terminal renderer. Replaces the live-MCP framing
/// (tools / resources / "Unknown MCP Server") with per-skill grouping
/// (skill name + source path + findings + severity counts).
///
/// Layout (Option C — verdict-first, compact chrome):
///
///   Path: <stripped of `skills:`>
///   ✅ N skills, M findings (X HIGH, Y MEDIUM) · 1.2s
///
///   ⚠️ skill_a (2 findings)
///        source: ...
///        [HIGH] RuleName [OWASP: ...]
///               wrapped description
///
///   ✅ skill_b
///
///   Cross-Skill Findings
///      [MEDIUM] SkillNameCollision [OWASP: ...]
///               ...
///
///   Tip: --json | --sarif | --report
fn print_skill_table_result(result: &ScanResult, _detailed: bool) {
    use crate::security::SecurityIssue;
    use crate::types::YaraScanResult;

    /// Cross-skill findings have semantics that bind to multiple skill
    /// files at once (collision across paths, etc.). Rendering them
    /// under a single skill would either duplicate (every colliding
    /// file shows the same finding) or confuse (only one of N
    /// colliding files shows it). Carve them out for a dedicated
    /// section after the per-skill loop.
    fn is_cross_skill_rule(rule_name: &str) -> bool {
        matches!(rule_name, "SkillNameCollision")
    }

    // Strip the `skills:` prefix so the displayed path looks normal.
    // Multi-root scans produce `skills:[a,b](N files)` — show that
    // verbatim minus the prefix.
    let display_url = result.url.strip_prefix("skills:").unwrap_or(&result.url);

    // Findings per-skill: yara_results target_name + prompt-issue prompt_name.
    let yara_findings: Vec<&YaraScanResult> = result
        .yara_results
        .iter()
        .filter(|y| y.target_type.as_str() == "prompt")
        .collect();

    let prompt_issues: &[SecurityIssue] = result
        .security_issues
        .as_ref()
        .map_or(&[][..], |s| s.prompt_issues.as_slice());

    let cross_findings: Vec<&YaraScanResult> = yara_findings
        .iter()
        .copied()
        .filter(|y| is_cross_skill_rule(&y.rule_name))
        .collect();

    // First pass: compute totals + per-severity breakdown for the
    // verdict line. We render the verdict at the top so the user sees
    // pass/fail immediately rather than after scrolling through
    // per-skill rows.
    let mut total_findings = 0_usize;
    let mut sev_counts = std::collections::BTreeMap::<String, usize>::new();
    let mut bump = |sev: &str| {
        let s = sev.to_uppercase();
        *sev_counts.entry(s).or_insert(0) += 1;
        total_findings += 1;
    };
    // A finding belongs to a skill when its target_name equals the
    // skill name OR is `<skill>/scripts/<file>` / `<skill>/references/<file>`
    // (the synthetic naming agentskills.io bundles use for their
    // bundled-script and bundled-reference YARA findings).
    let belongs_to_skill = |target: &str, skill: &str| -> bool {
        if target == skill {
            return true;
        }
        if let Some(rest) = target.strip_prefix(skill) {
            return rest.starts_with('/');
        }
        false
    };
    for prompt in &result.prompts {
        for y in yara_findings.iter().filter(|y| {
            belongs_to_skill(&y.target_name, &prompt.name) && !is_cross_skill_rule(&y.rule_name)
        }) {
            bump(
                y.rule_metadata
                    .as_ref()
                    .and_then(|m| m.severity.as_deref())
                    .unwrap_or("INFO"),
            );
        }
        for issue in prompt_issues
            .iter()
            .filter(|i| i.prompt_name.as_deref() == Some(&prompt.name))
        {
            bump(&issue.severity);
        }
    }
    for y in &cross_findings {
        bump(
            y.rule_metadata
                .as_ref()
                .and_then(|m| m.severity.as_deref())
                .unwrap_or("INFO"),
        );
    }

    // Verdict line. ✅ when 0 findings, ⚠️ otherwise; ❌ when the scan
    // itself failed (errors recorded). Severity breakdown only when
    // there's at least one finding.
    let prompt_count = result.prompts.len();
    let secs = result.response_time_ms as f64 / 1000.0;
    let icon = if !result.errors.is_empty() {
        ""
    } else if total_findings == 0 {
        ""
    } else {
        "⚠️"
    };
    let breakdown = if sev_counts.is_empty() {
        String::new()
    } else {
        // Render in fixed severity order so output is stable.
        let order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"];
        let parts: Vec<String> = order
            .iter()
            .filter_map(|k| sev_counts.get(*k).map(|v| format!("{v} {k}")))
            .collect();
        format!(" ({})", parts.join(", "))
    };
    println!("Path: {}", display_url.blue());
    println!(
        "{icon} {prompt_count} skill{} scanned, {total_findings} finding{}{breakdown} · {secs:.1}s",
        if prompt_count == 1 { "" } else { "s" },
        if total_findings == 1 { "" } else { "s" }
    );

    if !result.errors.is_empty() {
        println!("\n{}", "Errors".bold().red());
        for e in &result.errors {
            println!("{e}");
        }
    }

    for prompt in &result.prompts {
        let yara_for_skill: Vec<&&YaraScanResult> = yara_findings
            .iter()
            .filter(|y| belongs_to_skill(&y.target_name, &prompt.name))
            .filter(|y| !is_cross_skill_rule(&y.rule_name))
            .collect();
        let llm_for_skill: Vec<&SecurityIssue> = prompt_issues
            .iter()
            .filter(|i| i.prompt_name.as_deref() == Some(&prompt.name))
            .collect();

        let count = yara_for_skill.len() + llm_for_skill.len();

        let head = if count == 0 {
            format!("  {} {}", "".green(), prompt.name.bold())
        } else {
            format!(
                "  {} {} ({} finding{})",
                "⚠️".yellow(),
                prompt.name.bold(),
                count,
                if count == 1 { "" } else { "s" },
            )
        };
        println!("\n{head}");

        // Best-effort source path: heuristic findings carry the path
        // in `context = "source: <path>"`. Show it under the skill name
        // so the user can navigate to the file.
        if let Some(src) = yara_for_skill
            .iter()
            .find_map(|y| y.context.strip_prefix("source: "))
        {
            println!("    {} {}", "source:".dimmed(), src.dimmed());
        }

        // Counts already accumulated in the upfront verdict pass;
        // these loops only render. Severity colorization comes from
        // the rule metadata (YARA findings) or the SecurityIssue
        // (LLM findings).
        for y in &yara_for_skill {
            let sev = y
                .rule_metadata
                .as_ref()
                .and_then(|m| m.severity.as_deref())
                .unwrap_or("INFO")
                .to_uppercase();
            let sev_disp = colored_severity(&sev);
            let owasp = format_owasp_tags(&y.owasp_tags);
            // For bundled-script/reference findings the target_name
            // carries `<skill>/scripts/<file>` or `<skill>/references/<file>`.
            // Surface the suffix inline so the user sees which sibling
            // file the rule fired on without having to read the JSON.
            let bundle_suffix = y
                .target_name
                .strip_prefix(&format!("{}/", prompt.name))
                .map(|rest| format!(" in {rest}"))
                .unwrap_or_default();
            println!(
                "    [{sev_disp}] {}{bundle_suffix}{owasp}",
                y.rule_name.bold()
            );
            if let Some(desc) = y
                .rule_metadata
                .as_ref()
                .and_then(|m| m.description.as_deref())
            {
                for line in wrap_for_terminal(desc, 90) {
                    println!("        {line}");
                }
            }
        }

        for issue in &llm_for_skill {
            let sev = issue.severity.to_uppercase();
            let sev_disp = colored_severity(&sev);
            let owasp = format_owasp_tags(&issue.owasp_tags);
            // SecurityIssueType doesn't implement Display, so use Debug
            // (the variant names like `PromptInjection` are already
            // user-readable).
            println!(
                "    [{sev_disp}] {}{owasp} (LLM)",
                format!("{:?}", issue.issue_type).bold()
            );
            for line in wrap_for_terminal(&issue.message, 90) {
                println!("        {line}");
            }
        }
    }

    // Cross-skill section — findings that bind to multiple skills,
    // not any single one (currently just SkillNameCollision; add
    // future cross-skill rules to `is_cross_skill_rule`).
    if !cross_findings.is_empty() {
        println!("\n{}", "Cross-Skill Findings".bold());
        for y in &cross_findings {
            let sev = y
                .rule_metadata
                .as_ref()
                .and_then(|m| m.severity.as_deref())
                .unwrap_or("INFO")
                .to_uppercase();
            let sev_disp = colored_severity(&sev);
            let owasp = format_owasp_tags(&y.owasp_tags);
            println!("  [{sev_disp}] {}{owasp}", y.rule_name.bold());
            if let Some(desc) = y
                .rule_metadata
                .as_ref()
                .and_then(|m| m.description.as_deref())
            {
                for line in wrap_for_terminal(desc, 90) {
                    println!("      {line}");
                }
            }
        }
    }

    // Footer: discoverability hints + a one-line scan-completion
    // marker. Output formats are surfaced here so the user knows how
    // to pipe to CI / get richer detail without `--help`-spelunking.
    let yara_rules = result
        .yara_results
        .iter()
        .find(|y| y.rule_name == "YARA_PRE_SCAN_SUMMARY")
        .and_then(|s| s.rules_executed.as_ref())
        .map_or(0, std::vec::Vec::len);
    println!();
    println!(
        "  {} {} YARA rule{} executed",
        "·".dimmed(),
        yara_rules,
        if yara_rules == 1 { "" } else { "s" }
    );
    println!(
        "  {} Tip: {}",
        "·".dimmed(),
        "--json | --sarif | --report".dimmed()
    );
}

/// Map a severity label (`CRITICAL` / `HIGH` / `MEDIUM` / `LOW`) to
/// a color-styled `ColoredString`. Pulled into a helper so the
/// skill renderer's three rendering sites (per-skill YARA, per-skill
/// LLM, cross-skill YARA) all colorize identically.
fn colored_severity(sev: &str) -> colored::ColoredString {
    match sev {
        "CRITICAL" => sev.red().bold(),
        "HIGH" => sev.yellow().bold(),
        "MEDIUM" => sev.yellow(),
        "LOW" => sev.cyan(),
        _ => sev.normal(),
    }
}

/// Render `[OWASP: MCP06, MCP09]` if any tags are present, empty
/// string otherwise. Same layout as the LLM-finding tag list — kept
/// in one place so both sites use identical formatting.
fn format_owasp_tags(tags: &[crate::taxonomy::OwaspTag]) -> String {
    if tags.is_empty() {
        return String::new();
    }
    format!(
        " [OWASP: {}]",
        tags.iter()
            .map(|t| t.id.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

/// Wrap `text` to lines of at most `width` chars, breaking on word
/// boundaries. Single-purpose helper for the skill renderer; not
/// internationalized (skill content is overwhelmingly English in
/// practice and we don't want a `unicode-segmentation` dep here).
fn wrap_for_terminal(text: &str, width: usize) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if current.is_empty() {
            current.push_str(word);
        } else if current.len() + 1 + word.len() <= width {
            current.push(' ');
            current.push_str(word);
        } else {
            out.push(std::mem::take(&mut current));
            current.push_str(word);
        }
    }
    if !current.is_empty() {
        out.push(current);
    }
    out
}

fn print_sarif_result(result: &ScanResult) {
    let log = crate::sarif::scan_result_to_sarif(result);
    match serde_json::to_string_pretty(&log) {
        Ok(s) => println!("{s}"),
        Err(e) => eprintln!("Error serializing SARIF: {e}"),
    }
}

fn print_json_result(result: &ScanResult) {
    match serde_json::to_string_pretty(result) {
        Ok(json) => println!("{json}"),
        Err(e) => {
            eprintln!("Error serializing result to JSON: {e}");
            println!("{{\"error\": \"Failed to serialize scan result\"}}");
        }
    }
}

fn print_raw_json_result(result: &ScanResult) {
    let raw_result = build_raw_json_result(result);
    println!(
        "{}",
        serde_json::to_string_pretty(&raw_result)
            .unwrap_or_else(|e| { format!("{{\"error\": \"Failed to serialize result: {e}\"}}") })
    );
}

/// Builds a raw JSON structure that preserves the original MCP server schema with embedded security results
fn build_raw_json_result(result: &ScanResult) -> serde_json::Map<String, serde_json::Value> {
    let mut raw_result = serde_json::Map::new();

    add_basic_scan_info(&mut raw_result, result);
    add_server_info(&mut raw_result, result);
    add_tools_info(&mut raw_result, result);
    add_resources_info(&mut raw_result, result);
    add_prompts_info(&mut raw_result, result);
    add_errors_info(&mut raw_result, result);

    // Add comprehensive security issues section
    add_security_issues_section(&mut raw_result, result);

    // Add summary of security scan results
    add_security_summary(&mut raw_result, result);

    raw_result
}

/// Adds basic scan information to the raw JSON result
fn add_basic_scan_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    raw_result.insert(
        "url".to_string(),
        serde_json::Value::String(result.url.clone()),
    );
    raw_result.insert(
        "status".to_string(),
        serde_json::Value::String(format!("{:?}", result.status)),
    );
    raw_result.insert(
        "response_time_ms".to_string(),
        serde_json::Value::Number(serde_json::Number::from(result.response_time_ms)),
    );
    raw_result.insert(
        "timestamp".to_string(),
        serde_json::Value::String(result.timestamp.to_rfc3339()),
    );
}

/// Adds server information to the raw JSON result
fn add_server_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    if let Some(server_info) = &result.server_info {
        let mut server_info_obj = serde_json::Map::new();
        server_info_obj.insert(
            "name".to_string(),
            serde_json::Value::String(server_info.name.clone()),
        );
        server_info_obj.insert(
            "version".to_string(),
            serde_json::Value::String(server_info.version.clone()),
        );

        if let Some(desc) = &server_info.description {
            server_info_obj.insert(
                "description".to_string(),
                serde_json::Value::String(desc.clone()),
            );
        }

        server_info_obj.insert(
            "capabilities".to_string(),
            serde_json::Value::Array(
                server_info
                    .capabilities
                    .iter()
                    .map(|c| serde_json::Value::String(c.clone()))
                    .collect(),
            ),
        );

        raw_result.insert(
            "server_info".to_string(),
            serde_json::Value::Object(server_info_obj),
        );
    }
}

/// Adds tools information to the raw JSON result with embedded security and YARA results
fn add_tools_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    if !result.tools.is_empty() {
        let tools_array = result
            .tools
            .iter()
            .map(|tool| {
                let mut tool_json = tool.raw_json.clone().unwrap_or_else(|| {
                    serde_json::to_value(tool).unwrap_or(serde_json::Value::Null)
                });

                // Add security scan results for this tool
                let mut security_results = Vec::new();
                if let Some(ref security_issues) = result.security_issues {
                    // Find LLM-based security issues for this tool
                    let tool_issues: Vec<_> = security_issues
                        .tool_issues
                        .iter()
                        .filter(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                        .collect();

                    for issue in tool_issues {
                        security_results.push(serde_json::json!({
                            "scan_type": "llm_analysis",
                            "issue_type": issue.issue_type,
                            "severity": issue.severity,
                            "message": issue.message,
                            "description": issue.description,
                            "details": issue.details
                        }));
                    }

                    // Add LLM analysis details if available
                    if let Some(analysis_details) =
                        security_issues.tool_analysis_details.get(&tool.name)
                    {
                        if let Some(tool_obj) = tool_json.as_object_mut() {
                            tool_obj.insert(
                                "llm_analysis".to_string(),
                                serde_json::Value::String(analysis_details.clone()),
                            );
                        }
                    }
                }

                // Find YARA results for this tool
                let tool_yara_results: Vec<_> = result
                    .yara_results
                    .iter()
                    .filter(|yara| yara.target_type == "tool" && yara.target_name == tool.name)
                    .collect();

                for yara_result in tool_yara_results {
                    security_results.push(serde_json::json!({
                        "scan_type": "yara_rules",
                        "rule_name": yara_result.rule_name,
                        "rule_file": yara_result.rule_file,
                        "matched_text": yara_result.matched_text,
                        "context": yara_result.context,
                        "rule_metadata": yara_result.rule_metadata
                    }));
                }

                // Add security results to the tool JSON
                if !security_results.is_empty() {
                    if let Some(tool_obj) = tool_json.as_object_mut() {
                        tool_obj.insert(
                            "security_scan_results".to_string(),
                            serde_json::Value::Array(security_results),
                        );
                    }
                }

                tool_json
            })
            .collect();
        raw_result.insert("tools".to_string(), serde_json::Value::Array(tools_array));
    }
}

/// Adds resources information to the raw JSON result with embedded security and YARA results
fn add_resources_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    if !result.resources.is_empty() {
        let resources_array = result
            .resources
            .iter()
            .map(|resource| {
                let mut resource_json = resource.raw_json.clone().unwrap_or_else(|| {
                    serde_json::to_value(resource).unwrap_or(serde_json::Value::Null)
                });

                // Add security scan results for this resource
                let mut security_results = Vec::new();
                if let Some(ref security_issues) = result.security_issues {
                    // Find LLM-based security issues for this resource
                    let resource_issues: Vec<_> = security_issues
                        .resource_issues
                        .iter()
                        .filter(|issue| issue.resource_uri.as_ref() == Some(&resource.uri))
                        .collect();

                    for issue in resource_issues {
                        security_results.push(serde_json::json!({
                            "scan_type": "llm_analysis",
                            "issue_type": issue.issue_type,
                            "severity": issue.severity,
                            "message": issue.message,
                            "description": issue.description,
                            "details": issue.details
                        }));
                    }
                }

                // Find YARA results for this resource
                let resource_yara_results: Vec<_> = result
                    .yara_results
                    .iter()
                    .filter(|yara| {
                        yara.target_type == "resource" && yara.target_name == resource.uri
                    })
                    .collect();

                for yara_result in resource_yara_results {
                    security_results.push(serde_json::json!({
                        "scan_type": "yara_rules",
                        "rule_name": yara_result.rule_name,
                        "rule_file": yara_result.rule_file,
                        "matched_text": yara_result.matched_text,
                        "context": yara_result.context,
                        "rule_metadata": yara_result.rule_metadata
                    }));
                }

                // Add security results to the resource JSON
                if !security_results.is_empty() {
                    if let Some(resource_obj) = resource_json.as_object_mut() {
                        resource_obj.insert(
                            "security_scan_results".to_string(),
                            serde_json::Value::Array(security_results),
                        );
                    }
                }

                resource_json
            })
            .collect();
        raw_result.insert(
            "resources".to_string(),
            serde_json::Value::Array(resources_array),
        );
    }
}

/// Adds prompts information to the raw JSON result with embedded security and YARA results
fn add_prompts_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    if !result.prompts.is_empty() {
        let prompts_array = result
            .prompts
            .iter()
            .map(|prompt| {
                let mut prompt_json = prompt.raw_json.clone().unwrap_or_else(|| {
                    serde_json::to_value(prompt).unwrap_or(serde_json::Value::Null)
                });

                // Add security scan results for this prompt
                let mut security_results = Vec::new();
                if let Some(ref security_issues) = result.security_issues {
                    // Find LLM-based security issues for this prompt
                    let prompt_issues: Vec<_> = security_issues
                        .prompt_issues
                        .iter()
                        .filter(|issue| issue.prompt_name.as_ref() == Some(&prompt.name))
                        .collect();

                    for issue in prompt_issues {
                        security_results.push(serde_json::json!({
                            "scan_type": "llm_analysis",
                            "issue_type": issue.issue_type,
                            "severity": issue.severity,
                            "message": issue.message,
                            "description": issue.description,
                            "details": issue.details
                        }));
                    }
                }

                // Find YARA results for this prompt
                let prompt_yara_results: Vec<_> = result
                    .yara_results
                    .iter()
                    .filter(|yara| yara.target_type == "prompt" && yara.target_name == prompt.name)
                    .collect();

                for yara_result in prompt_yara_results {
                    security_results.push(serde_json::json!({
                        "scan_type": "yara_rules",
                        "rule_name": yara_result.rule_name,
                        "rule_file": yara_result.rule_file,
                        "matched_text": yara_result.matched_text,
                        "context": yara_result.context,
                        "rule_metadata": yara_result.rule_metadata
                    }));
                }

                // Add security results to the prompt JSON
                if !security_results.is_empty() {
                    if let Some(prompt_obj) = prompt_json.as_object_mut() {
                        prompt_obj.insert(
                            "security_scan_results".to_string(),
                            serde_json::Value::Array(security_results),
                        );
                    }
                }

                prompt_json
            })
            .collect();
        raw_result.insert(
            "prompts".to_string(),
            serde_json::Value::Array(prompts_array),
        );
    }
}

/// Adds comprehensive security issues section with both LLM and YARA results
fn add_security_issues_section(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    let mut security_issues = serde_json::Map::new();
    let mut all_issues = Vec::new();

    // Add LLM-based security issues
    if let Some(ref sec_issues) = result.security_issues {
        // Tool issues
        for issue in &sec_issues.tool_issues {
            all_issues.push(serde_json::json!({
                "scan_type": "llm_analysis",
                "target_type": "tool",
                "target_name": issue.tool_name,
                "issue_type": issue.issue_type,
                "severity": issue.severity,
                "message": issue.message,
                "description": issue.description,
                "details": issue.details
            }));
        }

        // Resource issues
        for issue in &sec_issues.resource_issues {
            all_issues.push(serde_json::json!({
                "scan_type": "llm_analysis",
                "target_type": "resource",
                "target_name": issue.resource_uri,
                "issue_type": issue.issue_type,
                "severity": issue.severity,
                "message": issue.message,
                "description": issue.description,
                "details": issue.details
            }));
        }

        // Prompt issues
        for issue in &sec_issues.prompt_issues {
            all_issues.push(serde_json::json!({
                "scan_type": "llm_analysis",
                "target_type": "prompt",
                "target_name": issue.prompt_name,
                "issue_type": issue.issue_type,
                "severity": issue.severity,
                "message": issue.message,
                "description": issue.description,
                "details": issue.details
            }));
        }
    }

    // Add YARA scan results
    for yara_result in &result.yara_results {
        all_issues.push(serde_json::json!({
            "scan_type": "yara_rules",
            "target_type": yara_result.target_type,
            "target_name": yara_result.target_name,
            "rule_name": yara_result.rule_name,
            "rule_file": yara_result.rule_file,
            "matched_text": yara_result.matched_text,
            "context": yara_result.context,
            "rule_metadata": yara_result.rule_metadata
        }));
    }

    // Sort by severity (Critical > High > Medium > Low)
    all_issues.sort_by(|a, b| {
        let severity_a = a
            .get("severity")
            .or_else(|| a.get("rule_metadata").and_then(|m| m.get("severity")))
            .and_then(|s| s.as_str())
            .unwrap_or("LOW");
        let severity_b = b
            .get("severity")
            .or_else(|| b.get("rule_metadata").and_then(|m| m.get("severity")))
            .and_then(|s| s.as_str())
            .unwrap_or("LOW");

        let order_a = match severity_a {
            "CRITICAL" => 0,
            "HIGH" => 1,
            "MEDIUM" => 2,
            _ => 3,
        };
        let order_b = match severity_b {
            "CRITICAL" => 0,
            "HIGH" => 1,
            "MEDIUM" => 2,
            _ => 3,
        };

        order_a.cmp(&order_b)
    });

    security_issues.insert("issues".to_string(), serde_json::Value::Array(all_issues));

    // Add counts by type
    let llm_count = result.security_issues.as_ref().map_or(0, |si| {
        si.tool_issues.len() + si.resource_issues.len() + si.prompt_issues.len()
    });
    let yara_count = result.yara_results.len();

    security_issues.insert("llm_issues_count".to_string(), serde_json::json!(llm_count));
    security_issues.insert(
        "yara_issues_count".to_string(),
        serde_json::json!(yara_count),
    );
    security_issues.insert(
        "total_issues_count".to_string(),
        serde_json::json!(llm_count + yara_count),
    );

    raw_result.insert(
        "security_issues".to_string(),
        serde_json::Value::Object(security_issues),
    );
}

/// Adds security scan summary to the raw JSON result
fn add_security_summary(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    let mut summary = serde_json::Map::new();

    // Count security issues by type and severity
    if let Some(ref security_issues) = result.security_issues {
        let total_tool_issues = security_issues.tool_issues.len();
        let total_resource_issues = security_issues.resource_issues.len();
        let total_prompt_issues = security_issues.prompt_issues.len();
        let total_llm_issues = total_tool_issues + total_resource_issues + total_prompt_issues;

        summary.insert(
            "llm_scan_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(total_llm_issues)),
        );
        summary.insert(
            "tool_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(total_tool_issues)),
        );
        summary.insert(
            "resource_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(total_resource_issues)),
        );
        summary.insert(
            "prompt_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(total_prompt_issues)),
        );
    } else {
        summary.insert(
            "llm_scan_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(0)),
        );
        summary.insert(
            "tool_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(0)),
        );
        summary.insert(
            "resource_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(0)),
        );
        summary.insert(
            "prompt_issues".to_string(),
            serde_json::Value::Number(serde_json::Number::from(0)),
        );
    }

    // Count YARA scan results
    let total_yara_issues = result.yara_results.len();
    summary.insert(
        "yara_scan_issues".to_string(),
        serde_json::Value::Number(serde_json::Number::from(total_yara_issues)),
    );

    // Add total security issues
    let total_security_issues = summary
        .get("llm_scan_issues")
        .and_then(|v| v.as_u64())
        .unwrap_or(0)
        + summary
            .get("yara_scan_issues")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
    summary.insert(
        "total_security_issues".to_string(),
        serde_json::Value::Number(serde_json::Number::from(total_security_issues)),
    );

    raw_result.insert(
        "security_scan_summary".to_string(),
        serde_json::Value::Object(summary),
    );
}

/// Adds error information to the raw JSON result
fn add_errors_info(
    raw_result: &mut serde_json::Map<String, serde_json::Value>,
    result: &ScanResult,
) {
    if !result.errors.is_empty() {
        let errors_array = result
            .errors
            .iter()
            .map(|e| serde_json::Value::String(e.clone()))
            .collect();
        raw_result.insert("errors".to_string(), serde_json::Value::Array(errors_array));
    }
}

#[allow(clippy::too_many_lines)]
fn print_table_result(result: &ScanResult, detailed: bool) {
    println!("Ramparts MCP Server Scan Result");

    // Server Info. Version + commit are NOT printed here — the
    // startup banner already shows them via `display_banner`. JSON /
    // raw / SARIF outputs (which suppress the banner) carry the
    // version on the `ScanResult` shape (`ramparts_version`,
    // `ramparts_commit`).
    println!("URL: {}", result.url.blue());
    println!("Status: {}", format_status(&result.status));
    println!("Response Time: {}ms", result.response_time_ms);
    println!(
        "Timestamp: {}",
        result.timestamp.format("%Y-%m-%d %H:%M:%S UTC")
    );

    if let Some(server_info) = &result.server_info {
        println!("\n{}", "Server Information".bold());
        println!("Name: {}", server_info.name);
        println!("Version: {}", server_info.version);
        if let Some(desc) = &server_info.description {
            println!("Description: {desc}");
        }
        if !server_info.capabilities.is_empty() {
            println!("Capabilities: {}", server_info.capabilities.join(", "));
        }
    }

    // Tools
    if !result.tools.is_empty() {
        println!("\n{}", "Tools".bold());
        if detailed {
            // Show detailed tool information
            for tool in &result.tools {
                println!("Tool: {}", tool.name.bold());
                if let Some(desc) = &tool.description {
                    println!("Description: {desc}");
                }
                if let Some(category) = &tool.category {
                    println!("Category: {category}");
                }
                if !tool.tags.is_empty() {
                    println!("Tags: {}", tool.tags.join(", "));
                }
                if tool.deprecated {
                    println!("Status: {}", "DEPRECATED".red().bold());
                }
                if let Some(input_schema) = &tool.input_schema {
                    println!(
                        "Input Schema: {}",
                        serde_json::to_string_pretty(input_schema)
                            .unwrap_or_else(|_| "Invalid JSON".to_string())
                    );
                }
                if let Some(output_schema) = &tool.output_schema {
                    println!(
                        "Output Schema: {}",
                        serde_json::to_string_pretty(output_schema)
                            .unwrap_or_else(|_| "Invalid JSON".to_string())
                    );
                }
                if !tool.parameters.is_empty() {
                    println!("Parameters:");
                    for (key, value) in &tool.parameters {
                        println!(
                            "  {}: {}",
                            key,
                            serde_json::to_string_pretty(value)
                                .unwrap_or_else(|_| "Invalid JSON".to_string())
                        );
                    }
                }
                if let Some(raw_json) = &tool.raw_json {
                    println!("Raw JSON Schema:");
                    println!(
                        "{}",
                        serde_json::to_string_pretty(raw_json)
                            .unwrap_or_else(|_| "Invalid JSON".to_string())
                    );
                }
                println!();
            }
        } else {
            // Only print the number of tools
            println!("Number of tools: {}", result.tools.len());
        }
    }

    // Resources
    if !result.resources.is_empty() {
        println!("\n{}", "Resources".bold());
        let resource_table = Table::new(result.resources.iter().map(|r| ResourceRow {
            uri: r.uri.clone(),
            name: r.name.clone(),
            description: r.description.clone().unwrap_or_else(|| "N/A".to_string()),
            mime_type: r.mime_type.clone().unwrap_or_else(|| "N/A".to_string()),
        }))
        .with(tabled::settings::Style::empty())
        .to_string();
        println!("{resource_table}");
    }

    // Security Assessments Completed
    println!("\n{}", "Security Assessments".bold());
    let mut assessments = Vec::new();

    if !result.tools.is_empty() {
        assessments.push("Tool Security (Tool Poisoning, Secrets Leakage, SQL Injection, Command Injection, Path Traversal, Auth Bypass)");
    }
    if !result.tools.is_empty() || !result.prompts.is_empty() {
        assessments.push("Input Security (Prompt Injection, PII Leakage, Jailbreak)");
    }
    if !result.resources.is_empty() {
        assessments.push("Resource Security (Path Traversal, Sensitive Data)");
    }

    if assessments.is_empty() {
        println!("Assessments executed: None");
    } else {
        println!("Assessments executed: {}", assessments.join(", "));
    }

    // Security issues - use enhanced table format only
    if result.security_issues.is_some() {
        print_enhanced_security_table(result);
    }

    // YARA scan results
    if result.yara_results.is_empty() {
        // Show YARA execution status even when no results at all
        println!("\n{}", "YARA Scan Results".bold());
        println!("❌ YARA scanning not executed or no results available");
        println!();
    } else {
        println!("\n{}", "YARA Scan Results".bold());

        // Separate summary results from individual match results
        let summary_results: Vec<_> = result
            .yara_results
            .iter()
            .filter(|r| r.target_type == "summary")
            .collect();
        let match_results: Vec<_> = result
            .yara_results
            .iter()
            .filter(|r| r.target_type != "summary")
            .collect();

        // Show summary information first
        for summary in &summary_results {
            let status_icon = match summary.status.as_deref() {
                Some("passed") => "",
                Some("warning") => "⚠️",
                _ => "🔍",
            };

            let status_text = match summary.status.as_deref() {
                Some("passed") => "PASSED".green(),
                Some("warning") => "WARNING".yellow(),
                _ => "UNKNOWN".white(),
            };

            println!(
                "{} {} - {}",
                status_icon,
                summary.target_name.to_uppercase(),
                status_text
            );
            println!("  Context: {}", summary.context);

            if let Some(total_items) = summary.total_items_scanned {
                println!("  Items scanned: {total_items}");
            }
            if let Some(total_matches) = summary.total_matches {
                println!("  Security matches: {total_matches}");
            }
            if let Some(rules) = &summary.rules_executed {
                if !rules.is_empty() {
                    println!("  Rules executed: {}", rules.join(", "));
                }
            }
            if let Some(security_issues) = &summary.security_issues_detected {
                if !security_issues.is_empty() {
                    println!("  Security issues detected: {}", security_issues.join(", "));
                }
            }
            println!();
        }

        // Show individual match results if any
        if !match_results.is_empty() {
            println!(
                "🔍 {} Individual Security Matches:",
                "Detailed Results".bold()
            );
            println!();

            for yara_result in &match_results {
                let status_icon = match yara_result.status.as_deref() {
                    Some("warning") => "⚠️",
                    _ => "🔍",
                };

                println!(
                    "{} {} ({})",
                    status_icon, yara_result.target_name, yara_result.target_type
                );

                if let Some(metadata) = &yara_result.rule_metadata {
                    let severity = metadata.severity.as_deref().unwrap_or("MEDIUM");
                    let severity_color = match severity {
                        "CRITICAL" => severity.red().bold(),
                        "HIGH" => severity.yellow().bold(),
                        "MEDIUM" => severity.blue().bold(),
                        _ => severity.green().bold(),
                    };

                    println!("  Rule: {} ({})", yara_result.rule_name, severity_color);

                    if let Some(name) = &metadata.name {
                        println!("  Name: {name}");
                    }
                    if let Some(desc) = &metadata.description {
                        println!("  Description: {desc}");
                    }
                    if let Some(author) = &metadata.author {
                        println!("  Author: {author}");
                    }
                    if let Some(version) = &metadata.version {
                        println!("  Version: {version}");
                    }
                    if let Some(confidence) = &metadata.confidence {
                        println!("  Confidence: {confidence}");
                    }
                    if !metadata.tags.is_empty() {
                        println!("  Tags: {}", metadata.tags.join(", "));
                    }
                } else {
                    println!("  Rule: {} (MEDIUM)", yara_result.rule_name);
                }

                if !yara_result.owasp_tags.is_empty() {
                    let mcp: Vec<&str> = yara_result
                        .owasp_tags
                        .iter()
                        .filter(|t| t.framework == crate::taxonomy::FRAMEWORK_MCP)
                        .map(|t| t.id.as_str())
                        .collect();
                    let ast: Vec<&str> = yara_result
                        .owasp_tags
                        .iter()
                        .filter(|t| t.framework == crate::taxonomy::FRAMEWORK_AST)
                        .map(|t| t.id.as_str())
                        .collect();
                    if !mcp.is_empty() {
                        println!("  OWASP MCP Top 10: {}", mcp.join(", "));
                    }
                    if !ast.is_empty() {
                        println!("  OWASP Agentic Skills Top 10: {}", ast.join(", "));
                    }
                }

                if let Some(matched_text) = &yara_result.matched_text {
                    println!("  Matched: {matched_text}");
                }
                println!("  Context: {}", yara_result.context);
                println!();
            }
        }
    }

    // Errors
    if !result.errors.is_empty() {
        println!("\n{}", "Errors".bold().red());
        for error in &result.errors {
            println!("- {error}");
        }
    }
}

#[allow(clippy::too_many_lines)]
fn print_text_result(result: &ScanResult) {
    println!("Scan Result for: {}", result.url);
    println!("Status: {}", format_status(&result.status));
    println!("Response Time: {}ms", result.response_time_ms);

    if let Some(server_info) = &result.server_info {
        println!("Server: {} v{}", server_info.name, server_info.version);
        if let Some(desc) = &server_info.description {
            println!("Description: {desc}");
        }
        if !server_info.capabilities.is_empty() {
            println!("Capabilities: {}", server_info.capabilities.join(", "));
        }
    }

    println!("Tools: {}", result.tools.len());
    for tool in &result.tools {
        println!("  - {}", tool.name);
    }

    println!("Resources: {}", result.resources.len());
    for resource in &result.resources {
        println!("  - {} ({})", resource.name, resource.uri);
    }

    println!("Prompts: {}", result.prompts.len());
    for prompt in &result.prompts {
        println!(
            "  - {} ({})",
            prompt.name,
            prompt.description.as_deref().unwrap_or("No description")
        );
    }

    // Security issues
    if let Some(security_issues) = &result.security_issues {
        println!("Security Issues: {}", security_issues.total_issues());
        if security_issues.has_critical_issues() {
            println!("  ⚠️  CRITICAL ISSUES DETECTED");
        }
        if security_issues.has_high_issues() {
            println!("  ⚠️  HIGH SEVERITY ISSUES DETECTED");
        }

        if !security_issues.tool_issues.is_empty() {
            println!("  Tool Issues: {}", security_issues.tool_issues.len());
            for issue in &security_issues.tool_issues {
                println!("    - {}: {}", issue.severity, issue.message);
            }
        }

        if !security_issues.prompt_issues.is_empty() {
            println!("  Prompt Issues: {}", security_issues.prompt_issues.len());
            for issue in &security_issues.prompt_issues {
                println!("    - {}: {}", issue.severity, issue.message);
            }
        }

        if !security_issues.resource_issues.is_empty() {
            println!(
                "  Resource Issues: {}",
                security_issues.resource_issues.len()
            );
            for issue in &security_issues.resource_issues {
                println!("    - {}: {}", issue.severity, issue.message);
            }
        }
    }

    // YARA scan results
    if !result.yara_results.is_empty() {
        // Separate summary and match results
        let summary_results: Vec<_> = result
            .yara_results
            .iter()
            .filter(|r| r.target_type == "summary")
            .collect();
        let match_results: Vec<_> = result
            .yara_results
            .iter()
            .filter(|r| r.target_type != "summary")
            .collect();

        println!(
            "YARA Scan Results: {} total results",
            result.yara_results.len()
        );

        // Show summary results
        for summary in &summary_results {
            let status = summary.status.as_deref().unwrap_or("unknown");
            println!(
                "  {} - {}: {}",
                summary.target_name.to_uppercase(),
                status.to_uppercase(),
                summary.context
            );
            if let Some(total_matches) = summary.total_matches {
                println!("    Security matches found: {total_matches}");
            }
        }

        // Show individual matches
        for yara_result in &match_results {
            let severity = yara_result
                .rule_metadata
                .as_ref()
                .and_then(|m| m.severity.as_ref())
                .map_or("MEDIUM", String::as_str);
            let status = yara_result.status.as_deref().unwrap_or("unknown");

            println!(
                "    {} ({}): {} - {} [{}]",
                yara_result.target_name,
                yara_result.target_type,
                yara_result.rule_name,
                severity,
                status.to_uppercase()
            );
        }
    }

    if !result.errors.is_empty() {
        println!("Errors:");
        for error in &result.errors {
            println!("  - {error}");
        }
    }
}

fn format_status(status: &ScanStatus) -> String {
    match status {
        ScanStatus::Success => "SUCCESS".green().to_string(),
        ScanStatus::Failed(msg) => format!("FAILED: {msg}").red().to_string(),
        ScanStatus::Timeout => "TIMEOUT".yellow().to_string(),
        ScanStatus::ConnectionError(msg) => format!("CONNECTION ERROR: {msg}").red().to_string(),
        ScanStatus::AuthenticationError(msg) => {
            format!("AUTHENTICATION ERROR: {msg}").red().to_string()
        }
    }
}

#[derive(Tabled)]
struct ResourceRow {
    #[tabled(rename = "URI")]
    uri: String,
    #[tabled(rename = "Name")]
    name: String,
    #[tabled(rename = "Description")]
    description: String,
    #[tabled(rename = "MIME Type")]
    mime_type: String,
}

/// Enhanced security assessment table with per-tool results
#[allow(clippy::too_many_lines)]
fn print_enhanced_security_table(result: &ScanResult) {
    if let Some(security_issues) = &result.security_issues {
        println!("\n{}", "Security Assessment Results".bold());

        // Get server name
        let server_name = if let Some(server_info) = &result.server_info {
            server_info.name.clone()
        } else {
            "Unknown MCP Server".to_string()
        };

        println!("🌐 {}", server_name.bold());

        let mut total_warnings = 0;
        let mut tools_with_warnings = 0;

        // Count warnings first for summary
        for tool in &result.tools {
            let tool_issues: Vec<&SecurityIssue> = security_issues
                .tool_issues
                .iter()
                .filter(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                .collect();
            if !tool_issues.is_empty() {
                tools_with_warnings += 1;
                total_warnings += tool_issues.len();
            }
        }

        // Show quick summary
        if total_warnings == 0 {
            println!("  ✅ All tools passed security checks");
        } else {
            println!(
                "  ⚠️  {tools_with_warnings} tools have security warnings ({total_warnings} total warnings)"
            );
        }
        println!();

        for tool in &result.tools {
            let tool_issues: Vec<&SecurityIssue> = security_issues
                .tool_issues
                .iter()
                .filter(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                .collect();

            let warning_count = tool_issues.len();

            // Determine overall status for this tool
            let status = if warning_count == 0 {
                "passed".green()
            } else {
                "warning".yellow()
            };

            // Print tool with tree structure
            println!("  └── {} {}", tool.name, status);

            // Show detailed analysis only for tools with issues
            if !tool_issues.is_empty() {
                // Show LLM analysis details for tools with issues
                if let Some(analysis_details) =
                    security_issues.tool_analysis_details.get(&tool.name)
                {
                    println!("      📋 Analysis: {analysis_details}");
                }

                // Show specific security issues
                for issue in tool_issues {
                    let severity_color = match issue.severity.as_str() {
                        "CRITICAL" => issue.severity.red().bold(),
                        "HIGH" => issue.severity.yellow().bold(),
                        "MEDIUM" => issue.severity.blue().bold(),
                        _ => issue.severity.green().bold(),
                    };
                    if let Some(details) = &issue.details {
                        println!(
                            "      ├── {}: {} - {}",
                            severity_color, issue.message, details
                        );
                    } else {
                        println!("      ├── {}: {}", severity_color, issue.message);
                    }
                }
            }
        }

        // Show prompt security issues if any
        if !security_issues.prompt_issues.is_empty() {
            println!("\n  📝 Prompts:");
            for issue in &security_issues.prompt_issues {
                let severity_color = match issue.severity.as_str() {
                    "CRITICAL" => issue.severity.red().bold(),
                    "HIGH" => issue.severity.yellow().bold(),
                    "MEDIUM" => issue.severity.blue().bold(),
                    _ => issue.severity.green().bold(),
                };
                println!(
                    "    └── {}: {} ({})",
                    severity_color,
                    issue.message,
                    issue.prompt_name.as_ref().unwrap_or(&"Unknown".to_string())
                );
                if let Some(details) = &issue.details {
                    println!("        Details: {details}");
                }
            }
        }

        // Show resource security issues if any
        if !security_issues.resource_issues.is_empty() {
            println!("\n  📁 Resources:");
            for issue in &security_issues.resource_issues {
                let severity_color = match issue.severity.as_str() {
                    "CRITICAL" => issue.severity.red().bold(),
                    "HIGH" => issue.severity.yellow().bold(),
                    "MEDIUM" => issue.severity.blue().bold(),
                    _ => issue.severity.green().bold(),
                };
                println!(
                    "    └── {}: {} ({})",
                    severity_color,
                    issue.message,
                    issue
                        .resource_uri
                        .as_ref()
                        .unwrap_or(&"Unknown".to_string())
                );
                if let Some(details) = &issue.details {
                    println!("        Details: {details}");
                }
            }
        }

        // Add summary
        println!("\n{}", "Summary:".bold());
        println!("  • Tools scanned: {}", result.tools.len());
        if total_warnings > 0 {
            println!(
                "  • Warnings found: {tools_with_warnings} tools with {total_warnings} total warnings"
            );
        } else {
            println!(
                "  • Status: {} All tools passed security checks",
                "PASSED".green()
            );
        }
    }
}

// ============================================================================
// MULTI-SERVER PRINTING FUNCTIONS
// ============================================================================

/// Print results from multiple MCP servers
pub fn print_multi_server_results(results: &[ScanResult], format: &str, detailed: bool) {
    match format.to_lowercase().as_str() {
        "json" => print_multi_server_json(results),
        "table" => print_multi_server_tree(results, detailed),
        "text" => print_multi_server_text(results),
        "raw" => print_multi_server_raw_json(results),
        "sarif" => print_multi_server_sarif(results),
        _ => {
            eprintln!("Unknown format: {format}. Using tree view format.");
            print_multi_server_tree(results, detailed);
        }
    }
}

fn print_multi_server_sarif(results: &[ScanResult]) {
    let log = crate::sarif::scan_results_to_sarif(results);
    match serde_json::to_string_pretty(&log) {
        Ok(s) => println!("{s}"),
        Err(e) => eprintln!("Error serializing SARIF: {e}"),
    }
}

/// Enhanced tree view for multiple MCP servers grouped by IDE
#[allow(clippy::too_many_lines)]
fn print_multi_server_tree(results: &[ScanResult], _detailed: bool) {
    // Group results by IDE source
    let mut results_by_ide: std::collections::HashMap<String, Vec<&ScanResult>> =
        std::collections::HashMap::new();

    for result in results {
        let ide_name = result
            .ide_source
            .as_deref()
            .unwrap_or("UNKNOWN IDE")
            .to_string();
        results_by_ide.entry(ide_name).or_default().push(result);
    }

    // Print overall summary header
    println!("\n{}", "🌍 MCP Servers Security Scan Summary".bold());
    println!("{}", "".repeat(60));

    let total_servers = results.len();
    let mut successful_servers = 0;
    let mut failed_servers = 0;
    let mut total_tools = 0;
    let mut total_resources = 0;
    let mut total_prompts = 0;
    let mut total_warnings = 0;
    let mut servers_with_warnings = 0;

    // Calculate summary statistics
    for result in results {
        match &result.status {
            crate::types::ScanStatus::Success => successful_servers += 1,
            _ => failed_servers += 1,
        }

        total_tools += result.tools.len();
        total_resources += result.resources.len();
        total_prompts += result.prompts.len();

        if let Some(security_issues) = &result.security_issues {
            let server_warnings = security_issues.tool_issues.len()
                + security_issues.prompt_issues.len()
                + security_issues.resource_issues.len();
            if server_warnings > 0 {
                servers_with_warnings += 1;
                total_warnings += server_warnings;
            }
        }
    }

    // Print scan summary statistics
    println!("📊 Scan Summary:");
    println!(
        "  • Servers: {total_servers} total ({successful_servers} ✅ successful, {failed_servers} ❌ failed)"
    );
    println!(
        "  • Resources: {total_tools} tools, {total_resources} resources, {total_prompts} prompts"
    );
    if total_warnings > 0 {
        println!(
            "  • Security: ⚠️  {servers_with_warnings} servers with {total_warnings} total warnings"
        );
    } else {
        println!("  • Security: ✅ All servers passed security checks");
    }

    println!("\n{}", "📋 Results by IDE:".bold());

    // Sort IDE names for consistent output
    let mut ide_names: Vec<&String> = results_by_ide.keys().collect();
    ide_names.sort();

    // Print results grouped by IDE
    for (ide_index, ide_name) in ide_names.iter().enumerate() {
        let ide_results = &results_by_ide[*ide_name];
        let is_last_ide = ide_index == ide_names.len() - 1;
        let ide_prefix = if is_last_ide {
            "└── "
        } else {
            "├── "
        };
        let ide_continuation = if is_last_ide { "    " } else { "" };

        println!("\n{}{} {}", ide_prefix, "🏢".bold(), ide_name.bold());

        // Print each server within this IDE
        for (i, result) in ide_results.iter().enumerate() {
            let is_last = i == ide_results.len() - 1;
            let prefix = if is_last { "└── " } else { "├── " };
            let continuation = if is_last { "    " } else { "" };

            // Server name and status
            let server_name = result
                .server_info
                .as_ref()
                .map_or_else(|| "Unknown Server".to_string(), |info| info.name.clone());

            let status_emoji = match &result.status {
                crate::types::ScanStatus::Success => "",
                crate::types::ScanStatus::Failed(_) => "",
                crate::types::ScanStatus::Timeout => "⏱️ ",
                crate::types::ScanStatus::ConnectionError(_) => "🔌",
                crate::types::ScanStatus::AuthenticationError(_) => "🔐",
            };

            println!(
                "{}{}{} {} ({})",
                ide_continuation,
                prefix,
                status_emoji,
                server_name.bold(),
                result.url
            );

            // Always show server-level YARA findings (even if scan failed)
            let server_yara_results: Vec<&crate::types::YaraScanResult> = result
                .yara_results
                .iter()
                .filter(|y| y.target_type == "server")
                .collect();

            if !server_yara_results.is_empty() {
                println!("{ide_continuation}{continuation}🔒 Server Security:");
                for (idx, yara_result) in server_yara_results.iter().enumerate() {
                    let is_last_server_issue = idx == server_yara_results.len() - 1;
                    let branch = if is_last_server_issue {
                        "└─"
                    } else {
                        "├─"
                    };

                    let severity = yara_result
                        .rule_metadata
                        .as_ref()
                        .and_then(|m| m.severity.as_ref())
                        .map(|s| s.as_str())
                        .unwrap_or("MEDIUM");
                    let severity_color = match severity {
                        "CRITICAL" => "🔴 CRITICAL".red(),
                        "HIGH" => "🟠 HIGH".yellow(),
                        "MEDIUM" => "🟡 MEDIUM".blue(),
                        _ => "🟢 LOW".green(),
                    };

                    if !yara_result.context.is_empty() {
                        println!(
                            "{}{}    {} {} (YARA) {}{}",
                            ide_continuation,
                            continuation,
                            branch,
                            severity_color,
                            yara_result.rule_name,
                            yara_result.context
                        );
                    } else {
                        println!(
                            "{}{}    {} {} (YARA) {}",
                            ide_continuation,
                            continuation,
                            branch,
                            severity_color,
                            yara_result.rule_name
                        );
                    }
                }
            }

            // Show basic stats and detailed results for successful scans
            if matches!(result.status, crate::types::ScanStatus::Success) {
                println!(
                    "{}{}📋 {} tools, {} resources, {} prompts",
                    ide_continuation,
                    continuation,
                    result.tools.len(),
                    result.resources.len(),
                    result.prompts.len()
                );

                // Show individual tool results with security status
                if !result.tools.is_empty() {
                    println!("{ide_continuation}{continuation}🔧 Tools:");
                    if let Some(security_issues) = &result.security_issues {
                        for tool in &result.tools {
                            let tool_issues: Vec<&crate::security::SecurityIssue> = security_issues
                                .tool_issues
                                .iter()
                                .filter(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                                .collect();

                            // Find YARA results for this tool
                            let tool_yara_results: Vec<&crate::types::YaraScanResult> = result
                                .yara_results
                                .iter()
                                .filter(|yara| {
                                    yara.target_type == "tool" && yara.target_name == tool.name
                                })
                                .collect();

                            let total_security_issues = tool_issues.len() + tool_yara_results.len();

                            if total_security_issues == 0 {
                                println!(
                                    "{}{}    ├── {}",
                                    ide_continuation, continuation, tool.name
                                );
                            } else {
                                println!(
                                    "{}{}    ├── {} ⚠️  {} warning{}",
                                    ide_continuation,
                                    continuation,
                                    tool.name.bold(),
                                    total_security_issues,
                                    if total_security_issues == 1 { "" } else { "s" }
                                );

                                // Show LLM analysis issues
                                for issue in &tool_issues {
                                    let severity_color = match issue.severity.as_str() {
                                        "CRITICAL" => "🔴 CRITICAL".red(),
                                        "HIGH" => "🟠 HIGH".yellow(),
                                        "MEDIUM" => "🟡 MEDIUM".blue(),
                                        _ => "🟢 LOW".green(),
                                    };
                                    if let Some(details) = &issue.details {
                                        println!(
                                            "{}{}    │   └── {} (LLM): {} - {}",
                                            ide_continuation,
                                            continuation,
                                            severity_color,
                                            issue.description,
                                            details
                                        );
                                    } else {
                                        println!(
                                            "{}{}    │   └── {} (LLM): {}",
                                            ide_continuation,
                                            continuation,
                                            severity_color,
                                            issue.description
                                        );
                                    }
                                }

                                // Show YARA rule issues
                                for yara_result in &tool_yara_results {
                                    let severity = yara_result
                                        .rule_metadata
                                        .as_ref()
                                        .and_then(|m| m.severity.as_ref())
                                        .map(|s| s.as_str())
                                        .unwrap_or("MEDIUM");
                                    let severity_color = match severity {
                                        "CRITICAL" => "🔴 CRITICAL".red(),
                                        "HIGH" => "🟠 HIGH".yellow(),
                                        "MEDIUM" => "🟡 MEDIUM".blue(),
                                        _ => "🟢 LOW".green(),
                                    };
                                    if !yara_result.context.is_empty() {
                                        println!(
                                            "{}{}    │   └── {} (YARA): {} - {}",
                                            ide_continuation,
                                            continuation,
                                            severity_color,
                                            yara_result.rule_name,
                                            yara_result.context
                                        );
                                    } else {
                                        println!(
                                            "{}{}    │   └── {} (YARA): {}",
                                            ide_continuation,
                                            continuation,
                                            severity_color,
                                            yara_result.rule_name
                                        );
                                    }
                                }
                            }
                        }
                    } else {
                        // No security analysis available
                        for tool in &result.tools {
                            println!(
                                "{}{}    ├── {}",
                                ide_continuation, continuation, tool.name
                            );
                        }
                    }
                }

                // Show resources if any
                if !result.resources.is_empty() {
                    println!("{ide_continuation}{continuation}📄 Resources:");
                    for resource in &result.resources {
                        println!(
                            "{}{}    ├── {}",
                            ide_continuation, continuation, resource.name
                        );
                    }
                }

                // Show prompts if any
                if !result.prompts.is_empty() {
                    println!("{ide_continuation}{continuation}💬 Prompts:");
                    for prompt in &result.prompts {
                        println!(
                            "{}{}    ├── {}",
                            ide_continuation, continuation, prompt.name
                        );
                    }
                }

                // YARA results are now embedded with each tool above
            } else {
                // Show enhanced error details for failed scans
                print_enhanced_error_details(result, ide_continuation, continuation);
            }
        }
    }

    println!(); // Final newline
}

/// Enhanced error details with troubleshooting suggestions
fn print_enhanced_error_details(result: &ScanResult, ide_continuation: &str, continuation: &str) {
    use colored::*;

    match &result.status {
        crate::types::ScanStatus::Failed(err) => {
            println!(
                "{ide_continuation}{continuation}🔴 {} {}",
                "FAILED:".red().bold(),
                result
                    .server_info
                    .as_ref()
                    .map_or("Unknown Server", |info| &info.name)
            );

            // Show concise, specific error details
            if err.contains("GITHUB_PERSONAL_ACCESS_TOKEN not set") {
                println!("{ide_continuation}{continuation}└─ {}: export GITHUB_PERSONAL_ACCESS_TOKEN=\"your_token\"",
                    "Solution".green().bold());
            } else if err.contains("mounts denied") || err.contains("not shared from the host") {
                println!("{ide_continuation}{continuation}└─ {}: Fix volume mount path (e.g., /Users/username:/workspace)", 
                    "Solution".green().bold());
            } else if err.contains("No such file or directory") {
                println!("{ide_continuation}{continuation}└─ {}: Check if Docker image exists: docker pull <image>", 
                    "Solution".green().bold());
            } else if err.contains("connection closed: initialize response") {
                println!("{ide_continuation}{continuation}└─ {}: Server failed to start - check Docker image and environment", 
                    "Error".red());
            } else {
                println!(
                    "{ide_continuation}{continuation}└─ {}: {}",
                    "Error".red(),
                    err.trim()
                );
            }
        }
        crate::types::ScanStatus::ConnectionError(err) => {
            println!(
                "{ide_continuation}{continuation}🔴 {} {}",
                "CONNECTION ERROR:".red().bold(),
                result
                    .server_info
                    .as_ref()
                    .map_or("Unknown Server", |info| &info.name)
            );

            println!(
                "{ide_continuation}{continuation}└─ {}: {}",
                "Error".red(),
                err.trim()
            );
        }
        crate::types::ScanStatus::AuthenticationError(err) => {
            println!(
                "{ide_continuation}{continuation}🔴 {} {}",
                "AUTHENTICATION ERROR:".red().bold(),
                result
                    .server_info
                    .as_ref()
                    .map_or("Unknown Server", |info| &info.name)
            );

            if err.contains("401") || err.contains("Unauthorized") {
                println!(
                    "{ide_continuation}{continuation}└─ {}: Check API key/token and permissions",
                    "Solution".green().bold()
                );
            } else {
                println!(
                    "{ide_continuation}{continuation}└─ {}: {}",
                    "Error".red(),
                    err.trim()
                );
            }
        }
        crate::types::ScanStatus::Timeout => {
            println!(
                "{ide_continuation}{continuation}🟡 {} {}",
                "TIMEOUT:".yellow().bold(),
                result
                    .server_info
                    .as_ref()
                    .map_or("Unknown Server", |info| &info.name)
            );
            println!(
                "{ide_continuation}{continuation}└─ {}: Increase timeout with --timeout <seconds>",
                "Solution".green().bold()
            );
        }
        crate::types::ScanStatus::Success => {}
    }
}

/// JSON format for multiple servers
fn print_multi_server_json(results: &[ScanResult]) {
    let json_output = serde_json::json!({
        "scan_type": "multi_server",
        "total_servers": results.len(),
        "results": results
    });

    match serde_json::to_string_pretty(&json_output) {
        Ok(json) => println!("{json}"),
        Err(e) => eprintln!("Error serializing multi-server results to JSON: {e}"),
    }
}

/// Raw JSON format for multiple servers
fn print_multi_server_raw_json(results: &[ScanResult]) {
    for result in results {
        print_raw_json_result(result);
    }
}

/// Text format for multiple servers
fn print_multi_server_text(results: &[ScanResult]) {
    println!("Multi-Server Scan Results");
    println!("========================");
    println!("Total servers scanned: {}", results.len());
    println!();

    for (i, result) in results.iter().enumerate() {
        println!("Server {}: {}", i + 1, result.url);
        print_text_result(result);
        println!();
    }
}

/// Generate a detailed markdown report from scan results
#[allow(clippy::too_many_lines)]
pub fn generate_markdown_report(results: &[ScanResult]) -> Result<String> {
    use chrono::Utc;
    use std::fmt::Write;

    let timestamp = Utc::now();
    let mut report = String::new();

    // Title reflects the *current* scanner surface — ramparts scans both
    // live MCP servers and on-disk agent skill files (`ramparts skills
    // scan`). Reports may bundle either or both kinds of result depending
    // on which command produced them; the title is generic-enough to
    // cover the mixed case.
    let scanner_label = "Ramparts MCP & Agent Skill Scanner";

    // Header
    writeln!(report, "# {scanner_label} Report")?;
    writeln!(report)?;
    writeln!(
        report,
        "**Generated:** {}",
        timestamp.format("%Y-%m-%d %H:%M:%S UTC")
    )?;
    writeln!(report, "**Scanner:** {scanner_label}")?;
    // Carry the build identity so a reader of an archived report
    // months later can correlate findings to a specific scanner build.
    // First scan's `ramparts_version`/`commit` are representative — all
    // results in a single report come from the same scanner invocation.
    if let Some(first) = results.first() {
        if !first.ramparts_version.is_empty() {
            // Same is_empty-or-unknown guard as src/banner.rs:20 —
            // build.rs defaults the commit to "unknown" for non-git
            // builds; suppress the `(<sha>)` suffix either way.
            let build = if first.ramparts_commit.is_empty() || first.ramparts_commit == "unknown" {
                format!("v{}", first.ramparts_version)
            } else {
                format!("v{} ({})", first.ramparts_version, first.ramparts_commit)
            };
            writeln!(report, "**Build:** {build}")?;
        }
    }
    writeln!(report)?;

    // Executive Summary
    writeln!(report, "## Executive Summary")?;
    writeln!(report)?;

    let total_servers = results.len();
    let successful_scans = results
        .iter()
        .filter(|r| matches!(r.status, ScanStatus::Success))
        .count();
    let failed_scans = total_servers - successful_scans;

    // Count security issues by severity
    let mut critical_count = 0;
    let mut high_count = 0;
    let mut medium_count = 0;
    let mut low_count = 0;

    for result in results {
        if let Some(ref security_issues) = result.security_issues {
            for issue in &security_issues.tool_issues {
                match issue.severity.as_str() {
                    "CRITICAL" => critical_count += 1,
                    "HIGH" => high_count += 1,
                    "MEDIUM" => medium_count += 1,
                    _ => low_count += 1,
                }
            }
            for issue in &security_issues.prompt_issues {
                match issue.severity.as_str() {
                    "CRITICAL" => critical_count += 1,
                    "HIGH" => high_count += 1,
                    "MEDIUM" => medium_count += 1,
                    _ => low_count += 1,
                }
            }
            for issue in &security_issues.resource_issues {
                match issue.severity.as_str() {
                    "CRITICAL" => critical_count += 1,
                    "HIGH" => high_count += 1,
                    "MEDIUM" => medium_count += 1,
                    _ => low_count += 1,
                }
            }
        }
    }

    writeln!(report, "- **Total Servers Scanned:** {total_servers}")?;
    writeln!(report, "- **Successful Scans:** {successful_scans}")?;
    writeln!(report, "- **Failed Scans:** {failed_scans}")?;
    writeln!(report)?;
    writeln!(report, "### Security Issues Summary")?;
    if critical_count + high_count + medium_count + low_count == 0 {
        writeln!(report, "✅ **No security issues detected**")?;
    } else {
        writeln!(report, "| Severity | Count |")?;
        writeln!(report, "|----------|-------|")?;
        writeln!(report, "| 🔴 **CRITICAL** | {critical_count} |")?;
        writeln!(report, "| 🟠 **HIGH** | {high_count} |")?;
        writeln!(report, "| 🟡 **MEDIUM** | {medium_count} |")?;
        writeln!(report, "| 🟢 **LOW** | {low_count} |")?;
    }
    writeln!(report)?;

    // Detailed Results
    writeln!(report, "## Detailed Scan Results")?;

    for (i, result) in results.iter().enumerate() {
        writeln!(report, "### Server {} - {}", i + 1, result.url)?;

        // Server Info
        if let Some(ref server_info) = result.server_info {
            writeln!(report, "**Server Information:**")?;
            writeln!(report, "- **Name:** {}", server_info.name)?;
            writeln!(report, "- **Version:** {}", server_info.version)?;
            if let Some(ref description) = server_info.description {
                writeln!(report, "- **Description:** {description}")?;
            }
        }

        // Scan Status
        match &result.status {
            ScanStatus::Success => {
                writeln!(report, "**Status:** ✅ Success")?;
                writeln!(report, "**Response Time:** {}ms", result.response_time_ms)?;
            }
            ScanStatus::Failed(error) => {
                writeln!(report, "**Status:** ❌ Failed")?;
                writeln!(report, "**Error:** {error}")?;
                writeln!(report)?;
                continue;
            }
            ScanStatus::Timeout => {
                writeln!(report, "**Status:** ⏰ Timeout")?;
                writeln!(report)?;
                continue;
            }
            ScanStatus::ConnectionError(error) => {
                writeln!(report, "**Status:** ❌ Connection Error")?;
                writeln!(report, "**Error:** {error}")?;
                writeln!(report)?;
                continue;
            }
            ScanStatus::AuthenticationError(error) => {
                writeln!(report, "**Status:** 🔐 Authentication Error")?;
                writeln!(report, "**Error:** {error}")?;
                writeln!(report)?;
                continue;
            }
        }
        writeln!(report)?;

        // Tools - only show tools with security issues
        if let Some(ref security_issues) = result.security_issues {
            let tools_with_issues: Vec<_> = result
                .tools
                .iter()
                .filter(|tool| {
                    security_issues
                        .tool_issues
                        .iter()
                        .any(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                })
                .collect();

            if !tools_with_issues.is_empty() {
                writeln!(
                    report,
                    "#### Tools with Security Issues ({} of {} total)",
                    tools_with_issues.len(),
                    result.tools.len()
                )?;
                writeln!(report)?;

                for tool in tools_with_issues {
                    writeln!(report, "##### {}", tool.name)?;

                    if let Some(ref description) = tool.description {
                        writeln!(report, "{description}")?;
                        writeln!(report)?;
                    }

                    let tool_issues: Vec<_> = security_issues
                        .tool_issues
                        .iter()
                        .filter(|issue| issue.tool_name.as_ref() == Some(&tool.name))
                        .collect();

                    writeln!(report, "**Security Issues:**")?;
                    for issue in tool_issues {
                        write_security_issue_details(&mut report, issue)?;
                    }
                    writeln!(report)?;
                }
            } else if !result.tools.is_empty() {
                writeln!(report, "#### Tools")?;
                writeln!(report)?;
                writeln!(
                    report,
                    "✅ All {} tools passed security checks",
                    result.tools.len()
                )?;
                writeln!(report)?;
            }
        } else if !result.tools.is_empty() {
            writeln!(report, "#### Tools")?;
            writeln!(report)?;
            writeln!(
                report,
                "⚠️ {} tools found but no security analysis available",
                result.tools.len()
            )?;
            writeln!(report)?;
        }

        // Resources - only show resources with security issues
        if let Some(ref security_issues) = result.security_issues {
            let resources_with_issues: Vec<_> = result
                .resources
                .iter()
                .filter(|resource| {
                    security_issues
                        .resource_issues
                        .iter()
                        .any(|issue| issue.resource_uri.as_ref() == Some(&resource.uri))
                })
                .collect();

            if !resources_with_issues.is_empty() {
                writeln!(
                    report,
                    "#### Resources with Security Issues ({} of {} total)",
                    resources_with_issues.len(),
                    result.resources.len()
                )?;
                writeln!(report)?;

                for resource in resources_with_issues {
                    writeln!(report, "##### {}", resource.name)?;
                    writeln!(report, "- **URI:** {}", resource.uri)?;
                    if let Some(ref description) = resource.description {
                        writeln!(report, "- **Description:** {description}")?;
                    }

                    let resource_issues: Vec<_> = security_issues
                        .resource_issues
                        .iter()
                        .filter(|issue| issue.resource_uri.as_ref() == Some(&resource.uri))
                        .collect();

                    writeln!(report)?;
                    writeln!(report, "**Security Issues:**")?;
                    for issue in resource_issues {
                        write_security_issue_details(&mut report, issue)?;
                    }
                    writeln!(report)?;
                }
            } else if !result.resources.is_empty() {
                writeln!(report, "#### Resources")?;
                writeln!(report)?;
                writeln!(
                    report,
                    "✅ All {} resources passed security checks",
                    result.resources.len()
                )?;
                writeln!(report)?;
            }
        } else if !result.resources.is_empty() {
            writeln!(report, "#### Resources")?;
            writeln!(report)?;
            writeln!(
                report,
                "⚠️ {} resources found but no security analysis available",
                result.resources.len()
            )?;
            writeln!(report)?;
        }

        // Prompts - only show prompts with security issues
        if let Some(ref security_issues) = result.security_issues {
            let prompts_with_issues: Vec<_> = result
                .prompts
                .iter()
                .filter(|prompt| {
                    security_issues
                        .prompt_issues
                        .iter()
                        .any(|issue| issue.prompt_name.as_ref() == Some(&prompt.name))
                })
                .collect();

            if !prompts_with_issues.is_empty() {
                writeln!(
                    report,
                    "#### Prompts with Security Issues ({} of {} total)",
                    prompts_with_issues.len(),
                    result.prompts.len()
                )?;
                writeln!(report)?;

                for prompt in prompts_with_issues {
                    writeln!(report, "##### {}", prompt.name)?;
                    if let Some(ref description) = prompt.description {
                        writeln!(report, "{description}")?;
                        writeln!(report)?;
                    }

                    let prompt_issues: Vec<_> = security_issues
                        .prompt_issues
                        .iter()
                        .filter(|issue| issue.prompt_name.as_ref() == Some(&prompt.name))
                        .collect();

                    writeln!(report, "**Security Issues:**")?;
                    for issue in prompt_issues {
                        write_security_issue_details(&mut report, issue)?;
                    }
                    writeln!(report)?;
                }
            } else if !result.prompts.is_empty() {
                writeln!(report, "#### Prompts")?;
                writeln!(report)?;
                writeln!(
                    report,
                    "✅ All {} prompts passed security checks",
                    result.prompts.len()
                )?;
                writeln!(report)?;
            }
        } else if !result.prompts.is_empty() {
            writeln!(report, "#### Prompts")?;
            writeln!(report)?;
            writeln!(
                report,
                "⚠️ {} prompts found but no security analysis available",
                result.prompts.len()
            )?;
            writeln!(report)?;
        }

        // YARA Scan Results - show detailed information for any matches
        if !result.yara_results.is_empty() {
            let match_results: Vec<_> = result
                .yara_results
                .iter()
                .filter(|r| r.target_type != "summary")
                .collect();

            if !match_results.is_empty() {
                writeln!(report, "#### YARA Security Detections")?;
                writeln!(report)?;
                writeln!(
                    report,
                    "**{} security pattern matches detected**",
                    match_results.len()
                )?;
                writeln!(report)?;

                for yara_result in match_results {
                    let severity = yara_result
                        .rule_metadata
                        .as_ref()
                        .and_then(|m| m.severity.as_ref())
                        .map(|s| s.as_str())
                        .unwrap_or("MEDIUM");
                    let severity_emoji = match severity {
                        "CRITICAL" => "🔴",
                        "HIGH" => "🟠",
                        "MEDIUM" => "🟡",
                        _ => "🟢",
                    };

                    writeln!(
                        report,
                        "##### {} **{}:** {}",
                        severity_emoji, severity, yara_result.rule_name
                    )?;

                    // Rule metadata information
                    if let Some(ref metadata) = yara_result.rule_metadata {
                        if let Some(ref description) = metadata.description {
                            writeln!(report, "**Description:** {description}")?;
                        }
                        if let Some(ref author) = metadata.author {
                            writeln!(report, "**Rule Author:** {author}")?;
                        }
                        if let Some(ref confidence) = metadata.confidence {
                            writeln!(
                                report,
                                "**Confidence Level:** {}",
                                confidence.to_uppercase()
                            )?;
                        }
                        if !metadata.tags.is_empty() {
                            writeln!(report, "**Tags:** {}", metadata.tags.join(", "))?;
                        }
                    }

                    // Target information
                    writeln!(
                        report,
                        "**Target:** {} ({})",
                        yara_result.target_name, yara_result.target_type
                    )?;

                    // Matched pattern
                    if let Some(ref matched_text) = yara_result.matched_text {
                        writeln!(report, "**Pattern Match:**")?;
                        writeln!(report, "```")?;
                        writeln!(report, "{matched_text}")?;
                        writeln!(report, "```")?;
                    }

                    // Context information
                    writeln!(report, "**Context:** {}", yara_result.context)?;

                    // Add remediation guidance based on rule name/type
                    let remediation = get_yara_remediation_guidance(&yara_result.rule_name);
                    if !remediation.is_empty() {
                        writeln!(report, "**🔧 Recommended Actions:**")?;
                        for action in remediation {
                            writeln!(report, "- {action}")?;
                        }
                    }

                    writeln!(report)?;
                }
            }
        }

        writeln!(report, "---")?;
        writeln!(report)?;
    }

    // Footer
    writeln!(report, "## Report Information")?;
    writeln!(report)?;
    writeln!(report, "This report was generated by [Ramparts](https://github.com/highflame-ai/ramparts), an MCP security scanner.")?;
    writeln!(report)?;
    writeln!(report, "For more information about security issues and remediation, see the [Ramparts documentation](https://github.com/highflame-ai/ramparts/blob/main/docs/security-features.md).")?;

    Ok(report)
}

/// Write markdown report to file with timestamp
pub fn write_markdown_report(results: &[ScanResult]) -> Result<String> {
    let report_content = generate_markdown_report(results)?;
    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
    let filename = format!("scan_{timestamp}.md");

    let mut file = File::create(&filename)
        .map_err(|e| anyhow!("Failed to create report file {}: {}", filename, e))?;

    file.write_all(report_content.as_bytes())
        .map_err(|e| anyhow!("Failed to write report to {}: {}", filename, e))?;

    Ok(filename)
}

// ============================================================================
// THREAT ANALYSIS AND REMEDIATION HELPER FUNCTIONS
// ============================================================================

/// Write detailed security issue information to markdown report
fn write_security_issue_details(
    report: &mut String,
    issue: &crate::security::SecurityIssue,
) -> Result<()> {
    use std::fmt::Write;

    let severity_emoji = match issue.severity.as_str() {
        "CRITICAL" => "🔴",
        "HIGH" => "🟠",
        "MEDIUM" => "🟡",
        _ => "🟢",
    };

    // Main issue description
    writeln!(
        report,
        "- {} **{}:** {}",
        severity_emoji, issue.severity, issue.description
    )
    .map_err(|e| anyhow!("Failed to write to report: {}", e))?;

    // Detailed threat analysis
    if let Some(ref details) = issue.details {
        writeln!(report, "  - **Impact Analysis:** {details}")
            .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
    }

    // Threat categorization and risk assessment
    let (threat_category, business_impact) = get_threat_category_and_impact(&issue.issue_type);
    writeln!(report, "  - **Threat Category:** {threat_category}")
        .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
    writeln!(report, "  - **Business Impact:** {business_impact}")
        .map_err(|e| anyhow!("Failed to write to report: {}", e))?;

    // Exploitability assessment
    let exploitability = get_exploitability_assessment(&issue.issue_type, &issue.severity);
    writeln!(report, "  - **Exploitability:** {exploitability}")
        .map_err(|e| anyhow!("Failed to write to report: {}", e))?;

    // Attack vectors
    let attack_vectors = get_attack_vectors(&issue.issue_type);
    if !attack_vectors.is_empty() {
        writeln!(report, "  - **Potential Attack Vectors:**")
            .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        for vector in attack_vectors {
            writeln!(report, "    - {vector}")
                .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        }
    }

    // Comprehensive remediation steps
    let remediation_steps = get_comprehensive_remediation(&issue.issue_type);
    if !remediation_steps.is_empty() {
        writeln!(report, "  - **🔧 Remediation Steps:**")
            .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        for (i, step) in remediation_steps.iter().enumerate() {
            writeln!(report, "    {}. {step}", i + 1)
                .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        }
    }

    // Prevention best practices
    let prevention_practices = get_prevention_practices(&issue.issue_type);
    if !prevention_practices.is_empty() {
        writeln!(report, "  - **🛡️ Prevention Best Practices:**")
            .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        for practice in prevention_practices {
            writeln!(report, "    - {practice}")
                .map_err(|e| anyhow!("Failed to write to report: {}", e))?;
        }
    }

    writeln!(report).map_err(|e| anyhow!("Failed to write to report: {}", e))?; // Add spacing between issues

    Ok(())
}

/// Get threat category and business impact for a security issue type
fn get_threat_category_and_impact(issue_type: &SecurityIssueType) -> (&'static str, &'static str) {
    match issue_type {
        SecurityIssueType::ToolPoisoning => (
            "Malicious Tool Injection",
            "High - Could lead to unauthorized actions, data manipulation, or system compromise"
        ),
        SecurityIssueType::SQLInjection => (
            "Data Injection Attack",
            "Critical - Could result in data breach, data loss, or unauthorized database access"
        ),
        SecurityIssueType::CommandInjection => (
            "System Command Execution",
            "Critical - Could lead to complete system compromise, data theft, or service disruption"
        ),
        SecurityIssueType::PathTraversal => (
            "Directory Traversal Attack",
            "High - Could expose sensitive files, configuration data, or system information"
        ),
        SecurityIssueType::AuthBypass => (
            "Authentication Bypass",
            "Critical - Could allow unauthorized access to protected resources and data"
        ),
        SecurityIssueType::PromptInjection => (
            "AI Model Manipulation",
            "High - Could manipulate AI responses, extract sensitive data, or bypass content filters"
        ),
        SecurityIssueType::Jailbreak => (
            "AI Safety Bypass",
            "High - Could circumvent AI safety measures and generate harmful or inappropriate content"
        ),
        SecurityIssueType::PIILeakage => (
            "Personal Data Exposure",
            "Medium-High - Could violate privacy regulations and expose personal information"
        ),
        SecurityIssueType::SecretsLeakage => (
            "Credential Exposure",
            "High - Could expose API keys, passwords, or other sensitive authentication data"
        ),
    }
}

/// Get exploitability assessment based on issue type and severity
fn get_exploitability_assessment(issue_type: &SecurityIssueType, severity: &str) -> &'static str {
    match (issue_type, severity) {
        (SecurityIssueType::SQLInjection | SecurityIssueType::CommandInjection, "CRITICAL") => {
            "Very High - Easily exploitable with readily available tools and techniques"
        }
        (SecurityIssueType::AuthBypass, "CRITICAL") => {
            "Very High - Direct access bypass with minimal technical requirements"
        }
        (SecurityIssueType::PathTraversal, "HIGH") => {
            "High - Common attack patterns with well-documented exploitation methods"
        }
        (SecurityIssueType::ToolPoisoning, "CRITICAL" | "HIGH") => {
            "High - Requires social engineering or supply chain compromise"
        }
        (SecurityIssueType::PromptInjection | SecurityIssueType::Jailbreak, "HIGH") => {
            "Medium-High - Requires understanding of AI model behavior and prompt crafting"
        }
        (SecurityIssueType::SecretsLeakage, "HIGH") => {
            "Medium - Depends on secret exposure method and access controls"
        }
        (SecurityIssueType::PIILeakage, "MEDIUM") => {
            "Medium - Requires access to data processing functions"
        }
        _ => "Medium - Exploitation complexity varies based on implementation details",
    }
}

/// Get potential attack vectors for a security issue type
fn get_attack_vectors(issue_type: &SecurityIssueType) -> Vec<&'static str> {
    match issue_type {
        SecurityIssueType::ToolPoisoning => vec![
            "Malicious tool registration with legitimate-sounding names",
            "Supply chain attacks through compromised dependencies",
            "Social engineering to trick users into installing malicious tools",
        ],
        SecurityIssueType::SQLInjection => vec![
            "Malicious SQL payloads in user input fields",
            "Blind SQL injection through timing attacks",
            "Union-based injection to extract data",
            "Error-based injection exploiting database error messages",
        ],
        SecurityIssueType::CommandInjection => vec![
            "Shell metacharacters in user input",
            "Command chaining with semicolons or pipes",
            "Environment variable manipulation",
            "File upload with executable content",
        ],
        SecurityIssueType::PathTraversal => vec![
            "Directory traversal sequences (../, ....//)",
            "Absolute path manipulation",
            "URL encoding bypass techniques",
            "Symbolic link exploitation",
        ],
        SecurityIssueType::AuthBypass => vec![
            "Missing authentication checks on sensitive endpoints",
            "Token manipulation or forgery",
            "Session fixation or hijacking",
            "Privilege escalation through parameter tampering",
        ],
        SecurityIssueType::PromptInjection => vec![
            "Instruction injection to override system prompts",
            "Context manipulation to change AI behavior",
            "Multi-turn conversation exploitation",
            "Payload injection in user-provided data",
        ],
        SecurityIssueType::Jailbreak => vec![
            "Roleplay scenarios to bypass content filters",
            "Hypothetical question framing",
            "Character encoding or obfuscation techniques",
            "Indirect instruction through creative prompting",
        ],
        SecurityIssueType::PIILeakage => vec![
            "Data extraction through legitimate API calls",
            "Information disclosure in error messages",
            "Metadata leakage in responses",
            "Cross-user data contamination",
        ],
        SecurityIssueType::SecretsLeakage => vec![
            "Hardcoded credentials in source code",
            "Environment variable exposure",
            "Configuration file access",
            "Log file credential leakage",
        ],
    }
}

/// Get comprehensive remediation steps for a security issue type
fn get_comprehensive_remediation(issue_type: &SecurityIssueType) -> Vec<&'static str> {
    match issue_type {
        SecurityIssueType::ToolPoisoning => vec![
            "Implement tool verification and digital signatures",
            "Use allowlists for approved tools and sources",
            "Add user confirmation prompts for high-risk operations",
            "Monitor tool behavior and implement anomaly detection",
            "Regular security audits of installed tools",
        ],
        SecurityIssueType::SQLInjection => vec![
            "Use parameterized queries and prepared statements",
            "Implement input validation and sanitization",
            "Apply principle of least privilege to database accounts",
            "Enable database query logging and monitoring",
            "Use stored procedures with proper parameter handling",
            "Implement Web Application Firewall (WAF) rules",
        ],
        SecurityIssueType::CommandInjection => vec![
            "Avoid system command execution where possible",
            "Use safe APIs instead of shell commands",
            "Implement strict input validation and allowlists",
            "Sanitize all user input before command execution",
            "Run processes with minimal required privileges",
            "Use containerization to limit system access",
        ],
        SecurityIssueType::PathTraversal => vec![
            "Validate and sanitize all file path inputs",
            "Use allowlists for permitted file locations",
            "Implement proper access controls and file permissions",
            "Use absolute paths and avoid relative path construction",
            "Apply input validation to reject traversal sequences",
            "Implement file access logging and monitoring",
        ],
        SecurityIssueType::AuthBypass => vec![
            "Implement proper authentication checks on all endpoints",
            "Use secure session management practices",
            "Apply authorization controls consistently",
            "Implement multi-factor authentication where appropriate",
            "Regular security testing of authentication mechanisms",
            "Use established authentication frameworks",
        ],
        SecurityIssueType::PromptInjection => vec![
            "Implement input validation and sanitization",
            "Use system message protection techniques",
            "Apply content filtering and prompt analysis",
            "Implement context isolation between user inputs",
            "Monitor for injection attempt patterns",
            "Use structured input formats where possible",
        ],
        SecurityIssueType::Jailbreak => vec![
            "Implement robust content filtering systems",
            "Use multiple layers of safety checks",
            "Apply context-aware response filtering",
            "Monitor for jailbreak attempt patterns",
            "Implement response review and approval workflows",
            "Regular updates to safety detection mechanisms",
        ],
        SecurityIssueType::PIILeakage => vec![
            "Implement data classification and handling policies",
            "Use data anonymization and pseudonymization techniques",
            "Apply access controls based on data sensitivity",
            "Implement data loss prevention (DLP) controls",
            "Regular privacy impact assessments",
            "Ensure compliance with data protection regulations",
        ],
        SecurityIssueType::SecretsLeakage => vec![
            "Use secure credential management systems",
            "Implement environment-based configuration",
            "Apply secret scanning tools to code repositories",
            "Use encrypted storage for sensitive configuration",
            "Implement credential rotation policies",
            "Monitor for exposed secrets in logs and outputs",
        ],
    }
}

/// Get prevention best practices for a security issue type
fn get_prevention_practices(issue_type: &SecurityIssueType) -> Vec<&'static str> {
    match issue_type {
        SecurityIssueType::ToolPoisoning => vec![
            "Establish a secure tool development lifecycle",
            "Implement code review processes for all tools",
            "Use dependency scanning and vulnerability assessment",
            "Maintain an inventory of approved tools and versions",
            "Provide security training for tool developers",
        ],
        SecurityIssueType::SQLInjection => vec![
            "Follow secure coding practices for database interactions",
            "Regular security code reviews focusing on data access",
            "Use static analysis tools to detect SQL injection vulnerabilities",
            "Implement automated security testing in CI/CD pipelines",
            "Keep database systems and drivers updated",
        ],
        SecurityIssueType::CommandInjection => vec![
            "Design applications to minimize system command usage",
            "Use security-focused development frameworks",
            "Implement secure coding standards and guidelines",
            "Regular penetration testing and security assessments",
            "Security awareness training for development teams",
        ],
        SecurityIssueType::PathTraversal => vec![
            "Design file handling with security-first principles",
            "Use established libraries for file operations",
            "Implement defense-in-depth strategies",
            "Regular security architecture reviews",
            "Automated security testing for file handling functions",
        ],
        SecurityIssueType::AuthBypass => vec![
            "Follow security-by-design principles",
            "Implement consistent authentication patterns",
            "Use centralized authentication and authorization services",
            "Regular security audits and penetration testing",
            "Security training focused on authentication best practices",
        ],
        SecurityIssueType::PromptInjection => vec![
            "Design AI systems with security considerations",
            "Implement prompt security testing in development",
            "Use AI safety frameworks and guidelines",
            "Regular red team exercises for AI systems",
            "Stay updated on AI security research and best practices",
        ],
        SecurityIssueType::Jailbreak => vec![
            "Implement comprehensive AI safety measures",
            "Use multiple independent safety checking systems",
            "Regular evaluation of AI model behavior",
            "Implement human oversight for sensitive operations",
            "Stay current with AI safety research and techniques",
        ],
        SecurityIssueType::PIILeakage => vec![
            "Implement privacy-by-design principles",
            "Regular privacy training for development teams",
            "Use data minimization strategies",
            "Implement privacy-preserving technologies",
            "Regular compliance audits and assessments",
        ],
        SecurityIssueType::SecretsLeakage => vec![
            "Implement secure development practices",
            "Use automated secret scanning in development workflows",
            "Establish clear policies for credential management",
            "Regular security awareness training",
            "Implement secure configuration management practices",
        ],
    }
}

/// Get remediation guidance for YARA rule detections
fn get_yara_remediation_guidance(rule_name: &str) -> Vec<&'static str> {
    match rule_name {
        "EnvironmentVariableLeakage" | "SecretsLeakage" => vec![
            "Review the detected code for hardcoded credentials or secrets",
            "Use environment variables or secure credential management systems",
            "Implement secret scanning in your CI/CD pipeline",
            "Rotate any exposed credentials immediately",
        ],
        "PathTraversalVulnerability" => vec![
            "Validate and sanitize all file path inputs",
            "Use allowlists for permitted file locations",
            "Implement proper access controls on file operations",
            "Consider using absolute paths instead of relative paths",
        ],
        "SQLInjectionPattern" => vec![
            "Replace dynamic SQL with parameterized queries",
            "Implement input validation and sanitization",
            "Use prepared statements for database operations",
            "Apply principle of least privilege to database accounts",
        ],
        "CommandInjectionPattern" => vec![
            "Avoid executing system commands with user input",
            "Use safe APIs instead of shell command execution",
            "Implement strict input validation with allowlists",
            "Run processes with minimal required privileges",
        ],
        "CrossOriginContamination" => vec![
            "Review cross-origin resource sharing (CORS) policies",
            "Implement proper origin validation",
            "Use secure headers to prevent cross-origin attacks",
            "Audit and restrict cross-domain requests",
        ],
        "AIAgentInjection" => vec![
            "Implement input sanitization for AI prompts",
            "Use structured input validation",
            "Apply content filtering and safety checks",
            "Monitor for prompt injection attempt patterns",
        ],
        _ => vec![
            "Review the detected pattern for security implications",
            "Implement appropriate input validation and sanitization",
            "Follow security best practices for the identified vulnerability type",
            "Consider additional security testing and code review",
        ],
    }
}

#[cfg(test)]
mod tests {
    use super::{error_utils, format_status, Timer};
    use anyhow::anyhow;

    #[test]
    fn test_timer_functionality() {
        let timer = Timer::start();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed = timer.elapsed_ms();

        assert!(elapsed >= 10);
        println!("Timer elapsed: {elapsed}ms");
    }

    #[test]
    fn test_error_utils() {
        // Test format_error
        let error_msg = error_utils::format_error("Test operation", "Something went wrong");
        assert_eq!(error_msg, "Test operation failed: Something went wrong");

        // Test wrap_error with success
        let result: Result<i32, anyhow::Error> = Ok(42);
        let wrapped = error_utils::wrap_error(result, "Test context");
        assert!(wrapped.is_ok());
        assert_eq!(wrapped.unwrap(), 42);

        // Test wrap_error with failure
        let result: Result<i32, anyhow::Error> = Err(anyhow!("Original error"));
        let wrapped = error_utils::wrap_error(result, "Test context");
        assert!(wrapped.is_err());
        let error_msg = wrapped.unwrap_err().to_string();
        assert!(error_msg.contains("Test context"));
        assert!(error_msg.contains("Original error"));
    }

    // TODO: Add test for track_performance when async closure type inference is resolved

    #[test]
    fn test_format_status() {
        use crate::types::ScanStatus;

        let success = format_status(&ScanStatus::Success);
        assert!(success.contains("SUCCESS"));

        let failed = format_status(&ScanStatus::Failed("Test error".to_string()));
        assert!(failed.contains("FAILED"));
        assert!(failed.contains("Test error"));

        let timeout = format_status(&ScanStatus::Timeout);
        assert!(timeout.contains("TIMEOUT"));

        let connection_error = format_status(&ScanStatus::ConnectionError(
            "Connection failed".to_string(),
        ));
        assert!(connection_error.contains("CONNECTION ERROR"));
        assert!(connection_error.contains("Connection failed"));

        let auth_error = format_status(&ScanStatus::AuthenticationError("Auth failed".to_string()));
        assert!(auth_error.contains("AUTHENTICATION ERROR"));
        assert!(auth_error.contains("Auth failed"));
    }
}