forge-guard 0.3.3

Pre-deployment smart contract auditing framework for Foundry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
//! CLI integration tests for forge-guard.
//!
//! These tests verify argument parsing, shared flags, default values,
//! error handling, and safe run invocations for all CLI subcommands.

use clap::Parser;
use forge_guard::cli::{Cli, Commands, SecurityAction, SharedFlags};

// ─────────────────────────────────────────────────────────────
// Helper: assert shared flag defaults on any parsed command
// ─────────────────────────────────────────────────────────────

fn assert_shared_defaults(
    chain: &str,
    project: &std::path::Path,
    json: bool,
    markdown: bool,
    strict: bool,
    offline: bool,
    production: bool,
    report: bool,
    parallelism: usize,
) {
    assert_eq!(chain, "ethereum", "default chain should be ethereum");
    assert_eq!(
        project.to_string_lossy(),
        ".",
        "default project should be ."
    );
    assert!(!json, "json should default to false");
    assert!(!markdown, "markdown should default to false");
    assert!(!strict, "strict should default to false");
    assert!(!offline, "offline should default to false");
    assert!(!production, "production should default to false");
    assert!(!report, "report should default to false");
    assert_eq!(parallelism, 4, "parallelism should default to 4");
}

fn parse_shared(
    cli: &Cli,
) -> (
    &str,
    &std::path::Path,
    bool,
    bool,
    bool,
    bool,
    bool,
    bool,
    usize,
) {
    let args = match &cli.command {
        Commands::Audit(a) => &a.shared,
        Commands::Deploy(a) => &a.shared,
        Commands::DeploySafe(a) => &a.shared,
        Commands::Fuzz(a) => &a.shared,
        Commands::Invariant(a) => &a.shared,
        Commands::Simulate(a) => &a.shared,
        Commands::Gas(a) => &a.shared,
        Commands::Report(a) => &a.shared,
        Commands::Verify(a) => &a.shared,
        Commands::Doctor(a) => &a.shared,
        Commands::Watch(a) => &a.shared,
        Commands::Dashboard(a) => &a.shared,
        Commands::Ci(a) => &a.shared,
        Commands::Benchmark(a) => &a.shared,
        Commands::Scan(a) => &a.shared,
        Commands::UpgradeCheck(a) => &a.shared,
        Commands::Plugins(a) => &a.shared,
        Commands::Chain(a) => &a.shared,
        Commands::Sbom(a) => &a.shared,
        Commands::Security(a) => &a.shared,
        Commands::InstallHook(_) | Commands::Import(_) | Commands::Notify(_) => {
            static DEFAULT_FLAGS: std::sync::OnceLock<SharedFlags> = std::sync::OnceLock::new();
            DEFAULT_FLAGS.get_or_init(SharedFlags::default)
        }
    };
    (
        &args.chain,
        &args.project,
        args.json,
        args.markdown,
        args.strict,
        args.offline,
        args.production,
        args.report,
        args.parallelism,
    )
}

// ─────────────────────────────────────────────────────────────
// 1. Top-level CLI parsing — all 18 subcommands
// ─────────────────────────────────────────────────────────────

#[test]
fn test_cli_parse_audit() {
    let cli = Cli::try_parse_from(&["forge-guard", "audit"]).unwrap();
    assert!(matches!(cli.command, Commands::Audit(_)));
}

#[test]
fn test_cli_parse_audit_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "audit",
        "--full",
        "--quick",
        "--summary",
        "--ai",
        "--ai-provider",
        "claude",
        "--ai-model",
        "claude-5-opus-20260701",
        "--ai-api-key",
        "sk-test",
        "--ollama-endpoint",
        "http://localhost:11434",
        "--ai-full",
        "--exploit",
        "--gas",
        "--all-chains",
        "--sources",
        "src,contracts",
        "--exclude",
        "test,mock",
        "--chain",
        "polygon",
        "--project",
        "/tmp/test",
        "--json",
        "--strict",
        "--offline",
        "--production",
        "--report",
        "--parallelism",
        "8",
    ])
    .unwrap();

    match cli.command {
        Commands::Audit(args) => {
            assert!(args.full);
            assert!(args.quick);
            assert!(args.summary);
            assert!(args.ai);
            assert_eq!(args.ai_provider, "claude");
            assert_eq!(args.ai_model, "claude-5-opus-20260701");
            assert_eq!(args.ai_api_key, Some("sk-test".into()));
            assert_eq!(args.ollama_endpoint, Some("http://localhost:11434".into()));
            assert!(args.ai_full);
            assert!(args.exploit);
            assert!(args.gas);
            assert!(args.all_chains);
            assert_eq!(args.sources, "src,contracts");
            assert_eq!(args.exclude, Some("test,mock".into()));
            assert_eq!(args.shared.chain, "polygon");
            assert!(args.shared.json);
            assert!(args.shared.strict);
            assert!(args.shared.offline);
            assert!(args.shared.production);
            assert!(args.shared.report);
            assert_eq!(args.shared.parallelism, 8);
        }
        _ => panic!("Expected Audit command"),
    }
}

#[test]
fn test_cli_parse_audit_defaults() {
    let cli = Cli::try_parse_from(&["forge-guard", "audit"]).unwrap();
    match &cli.command {
        Commands::Audit(args) => {
            assert!(!args.full);
            assert!(!args.quick);
            assert!(!args.summary);
            assert!(!args.ai);
            assert_eq!(args.ai_provider, "openai");
            assert_eq!(args.ai_model, "gpt-5");
            assert!(args.ai_api_key.is_none());
            assert!(args.ollama_endpoint.is_none());
            assert!(!args.ai_full);
            assert!(!args.exploit);
            assert!(!args.gas);
            assert!(!args.all_chains);
            assert_eq!(args.sources, "src");
            assert!(args.exclude.is_none());
            let (c, p, j, m, s, o, pr, r, pl) = parse_shared(&cli);
            assert_shared_defaults(c, p, j, m, s, o, pr, r, pl);
        }
        _ => panic!("Expected Audit command"),
    }
}

#[test]
fn test_cli_parse_deploy() {
    let cli = Cli::try_parse_from(&["forge-guard", "deploy"]).unwrap();
    assert!(matches!(cli.command, Commands::Deploy(_)));
}

#[test]
fn test_cli_parse_deploy_with_contract() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "deploy",
        "MyContract",
        "--force",
        "--args",
        "0x1234,100",
        "--salt",
        "0xabcd",
        "--verify",
        "--chain",
        "polygon",
    ])
    .unwrap();

    match cli.command {
        Commands::Deploy(args) => {
            assert_eq!(args.contract, Some("MyContract".into()));
            assert!(args.force);
            assert_eq!(args.args, Some("0x1234,100".into()));
            assert_eq!(args.salt, Some("0xabcd".into()));
            assert!(args.verify);
            assert_eq!(args.shared.chain, "polygon");
        }
        _ => panic!("Expected Deploy command"),
    }
}

#[test]
fn test_cli_parse_deploy_defaults() {
    let cli = Cli::try_parse_from(&["forge-guard", "deploy"]).unwrap();
    match &cli.command {
        Commands::Deploy(args) => {
            assert!(args.contract.is_none());
            assert!(!args.force);
            assert!(args.args.is_none());
            assert!(args.salt.is_none());
            assert!(!args.verify);
            let (c, p, j, m, s, o, pr, r, pl) = parse_shared(&cli);
            assert_shared_defaults(c, p, j, m, s, o, pr, r, pl);
        }
        _ => panic!("Expected Deploy command"),
    }
}

#[test]
fn test_cli_parse_deploy_safe() {
    let cli = Cli::try_parse_from(&["forge-guard", "deploy-safe"]).unwrap();
    assert!(matches!(cli.command, Commands::DeploySafe(_)));
}

#[test]
fn test_cli_parse_deploy_safe_with_contract() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "deploy-safe",
        "MyContract",
        "--args",
        "0x1234",
        "--verify",
    ])
    .unwrap();

    match cli.command {
        Commands::DeploySafe(args) => {
            assert_eq!(args.contract, Some("MyContract".into()));
            assert_eq!(args.args, Some("0x1234".into()));
            assert!(args.verify);
        }
        _ => panic!("Expected DeploySafe command"),
    }
}

#[test]
fn test_cli_parse_fuzz() {
    let cli = Cli::try_parse_from(&["forge-guard", "fuzz"]).unwrap();
    assert!(matches!(cli.command, Commands::Fuzz(_)));
}

#[test]
fn test_cli_parse_fuzz_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "fuzz",
        "MyTest",
        "--runs",
        "50000",
        "--seed",
        "42",
        "--test",
        "test_deposit",
    ])
    .unwrap();

    match cli.command {
        Commands::Fuzz(args) => {
            assert_eq!(args.contract, Some("MyTest".into()));
            assert_eq!(args.runs, 50000);
            assert_eq!(args.seed, Some(42));
            assert_eq!(args.test, Some("test_deposit".into()));
        }
        _ => panic!("Expected Fuzz command"),
    }
}

#[test]
fn test_cli_parse_fuzz_defaults() {
    let cli = Cli::try_parse_from(&["forge-guard", "fuzz"]).unwrap();
    match cli.command {
        Commands::Fuzz(args) => {
            assert!(args.contract.is_none());
            assert_eq!(args.runs, 10000);
            assert!(args.seed.is_none());
            assert!(args.test.is_none());
        }
        _ => panic!("Expected Fuzz command"),
    }
}

#[test]
fn test_cli_parse_invariant() {
    let cli = Cli::try_parse_from(&["forge-guard", "invariant"]).unwrap();
    assert!(matches!(cli.command, Commands::Invariant(_)));
}

#[test]
fn test_cli_parse_invariant_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "invariant",
        "MyInvariant",
        "--runs",
        "5000",
        "--depth",
        "200",
        "--fail-on-revert",
    ])
    .unwrap();

    match cli.command {
        Commands::Invariant(args) => {
            assert_eq!(args.contract, Some("MyInvariant".into()));
            assert_eq!(args.runs, 5000);
            assert_eq!(args.depth, 200);
            assert!(args.fail_on_revert);
        }
        _ => panic!("Expected Invariant command"),
    }
}

#[test]
fn test_cli_parse_simulate() {
    let cli = Cli::try_parse_from(&["forge-guard", "simulate"]).unwrap();
    assert!(matches!(cli.command, Commands::Simulate(_)));
}

#[test]
fn test_cli_parse_simulate_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "simulate",
        "MyContract",
        "--blocks",
        "500",
        "--deployer",
        "0x1234",
        "--mev",
    ])
    .unwrap();

    match cli.command {
        Commands::Simulate(args) => {
            assert_eq!(args.contract, Some("MyContract".into()));
            assert_eq!(args.blocks, 500);
            assert_eq!(args.deployer, Some("0x1234".into()));
            assert!(args.mev);
        }
        _ => panic!("Expected Simulate command"),
    }
}

#[test]
fn test_cli_parse_gas() {
    let cli = Cli::try_parse_from(&["forge-guard", "gas"]).unwrap();
    assert!(matches!(cli.command, Commands::Gas(_)));
}

#[test]
fn test_cli_parse_gas_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "gas",
        "MyContract",
        "--diff",
        "previous.json",
        "--all",
        "--warn-threshold",
        "100000",
    ])
    .unwrap();

    match cli.command {
        Commands::Gas(args) => {
            assert_eq!(args.contract, Some("MyContract".into()));
            assert_eq!(args.diff, Some("previous.json".into()));
            assert!(args.all);
            assert_eq!(args.warn_threshold, 100000);
        }
        _ => panic!("Expected Gas command"),
    }
}

#[test]
fn test_cli_parse_report() {
    let cli = Cli::try_parse_from(&["forge-guard", "report"]).unwrap();
    assert!(matches!(cli.command, Commands::Report(_)));
}

#[test]
fn test_cli_parse_report_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "report",
        "result.json",
        "--format",
        "json",
        "--output",
        "report.json",
        "--exploit-paths",
        "--summary",
    ])
    .unwrap();

    match cli.command {
        Commands::Report(args) => {
            assert_eq!(args.input, Some(std::path::PathBuf::from("result.json")));
            assert_eq!(args.format, "json");
            assert_eq!(args.output, Some(std::path::PathBuf::from("report.json")));
            assert!(args.exploit_paths);
            assert!(args.summary);
        }
        _ => panic!("Expected Report command"),
    }
}

#[test]
fn test_cli_parse_verify() {
    let cli = Cli::try_parse_from(&["forge-guard", "verify"]).unwrap();
    assert!(matches!(cli.command, Commands::Verify(_)));
}

#[test]
fn test_cli_parse_verify_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "verify",
        "0x1234",
        "MyContract",
        "--api-key",
        "test-key",
        "--constructor-args",
        "0xabcdef",
        "--all",
    ])
    .unwrap();

    match cli.command {
        Commands::Verify(args) => {
            assert_eq!(args.address, Some("0x1234".into()));
            assert_eq!(args.name, Some("MyContract".into()));
            assert_eq!(args.api_key, Some("test-key".into()));
            assert_eq!(args.constructor_args, Some("0xabcdef".into()));
            assert!(args.all);
        }
        _ => panic!("Expected Verify command"),
    }
}

#[test]
fn test_cli_parse_doctor() {
    let cli = Cli::try_parse_from(&["forge-guard", "doctor"]).unwrap();
    assert!(matches!(cli.command, Commands::Doctor(_)));
}

#[test]
fn test_cli_parse_doctor_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "doctor",
        "--fix",
        "--verbose",
        "--check",
        "foundry",
    ])
    .unwrap();

    match cli.command {
        Commands::Doctor(args) => {
            assert!(args.fix);
            assert!(args.verbose);
            assert_eq!(args.check, Some("foundry".into()));
        }
        _ => panic!("Expected Doctor command"),
    }
}

#[test]
fn test_cli_parse_watch() {
    let cli = Cli::try_parse_from(&["forge-guard", "watch"]).unwrap();
    assert!(matches!(cli.command, Commands::Watch(_)));
}

#[test]
fn test_cli_parse_watch_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "watch",
        "--dirs",
        "src,contracts",
        "--debounce-ms",
        "1000",
        "--exclude",
        "test",
        "--full",
    ])
    .unwrap();

    match cli.command {
        Commands::Watch(args) => {
            assert_eq!(args.dirs, "src,contracts");
            assert_eq!(args.debounce_ms, 1000);
            assert_eq!(args.exclude, Some("test".into()));
            assert!(args.full);
        }
        _ => panic!("Expected Watch command"),
    }
}

#[test]
fn test_cli_parse_ci() {
    let cli = Cli::try_parse_from(&["forge-guard", "ci"]).unwrap();
    assert!(matches!(cli.command, Commands::Ci(_)));
}

#[test]
fn test_cli_parse_ci_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "ci",
        "--platform",
        "gitlab",
        "--output",
        ".gitlab-ci",
        "--include-deploy",
        "--overwrite",
    ])
    .unwrap();

    match cli.command {
        Commands::Ci(args) => {
            assert_eq!(args.platform, "gitlab");
            assert_eq!(args.output, std::path::PathBuf::from(".gitlab-ci"));
            assert!(args.include_deploy);
            assert!(args.overwrite);
        }
        _ => panic!("Expected Ci command"),
    }
}

#[test]
fn test_cli_parse_ci_defaults() {
    let cli = Cli::try_parse_from(&["forge-guard", "ci"]).unwrap();
    match &cli.command {
        Commands::Ci(args) => {
            assert_eq!(args.platform, "github");
            assert_eq!(args.output, std::path::PathBuf::from(".github/workflows"));
            assert!(!args.include_deploy);
            assert!(!args.overwrite);
            let (c, p, j, m, s, o, pr, r, pl) = parse_shared(&cli);
            assert_shared_defaults(c, p, j, m, s, o, pr, r, pl);
        }
        _ => panic!("Expected Ci command"),
    }
}

#[test]
fn test_cli_parse_benchmark() {
    let cli = Cli::try_parse_from(&["forge-guard", "benchmark"]).unwrap();
    assert!(matches!(cli.command, Commands::Benchmark(_)));
}

#[test]
fn test_cli_parse_benchmark_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "benchmark",
        "--iterations",
        "20",
        "--warmup",
        "5",
        "--compare",
        "baseline.json",
        "--save",
        "results.json",
        "--module",
        "pattern_matching",
    ])
    .unwrap();

    match cli.command {
        Commands::Benchmark(args) => {
            assert_eq!(args.iterations, 20);
            assert_eq!(args.warmup, 5);
            assert_eq!(
                args.compare,
                Some(std::path::PathBuf::from("baseline.json"))
            );
            assert_eq!(args.save, Some(std::path::PathBuf::from("results.json")));
            assert_eq!(args.module, Some("pattern_matching".into()));
        }
        _ => panic!("Expected Benchmark command"),
    }
}

#[test]
fn test_cli_parse_scan() {
    let cli = Cli::try_parse_from(&["forge-guard", "scan"]).unwrap();
    assert!(matches!(cli.command, Commands::Scan(_)));
}

#[test]
fn test_cli_parse_scan_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "scan",
        "--depth",
        "2",
        "--update",
        "--vulnerable-only",
        "--fail-fast",
    ])
    .unwrap();

    match cli.command {
        Commands::Scan(args) => {
            assert_eq!(args.depth, 2);
            assert!(args.update);
            assert!(args.vulnerable_only);
            assert!(args.fail_fast);
        }
        _ => panic!("Expected Scan command"),
    }
}

#[test]
fn test_cli_parse_upgrade_check() {
    let cli = Cli::try_parse_from(&["forge-guard", "upgrade-check"]).unwrap();
    assert!(matches!(cli.command, Commands::UpgradeCheck(_)));
}

#[test]
fn test_cli_parse_upgrade_check_with_flags() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "upgrade-check",
        "0xproxy",
        "0ximpl",
        "--all",
        "--storage-collision",
        "--uups",
    ])
    .unwrap();

    match cli.command {
        Commands::UpgradeCheck(args) => {
            assert_eq!(args.proxy, Some("0xproxy".into()));
            assert_eq!(args.implementation, Some("0ximpl".into()));
            assert!(args.all);
            assert!(args.storage_collision);
            assert!(args.uups);
        }
        _ => panic!("Expected UpgradeCheck command"),
    }
}

#[test]
fn test_cli_parse_plugins_list() {
    let cli = Cli::try_parse_from(&["forge-guard", "plugins", "list"]).unwrap();
    assert!(matches!(cli.command, Commands::Plugins(_)));
}

#[test]
fn test_cli_parse_plugins_install() {
    let cli = Cli::try_parse_from(&["forge-guard", "plugins", "install", "my-plugin"]).unwrap();
    match cli.command {
        Commands::Plugins(args) => {
            assert!(args.action.is_some());
        }
        _ => panic!("Expected Plugins command"),
    }
}

#[test]
fn test_cli_parse_plugins_install_with_source() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "plugins",
        "install",
        "my-plugin",
        "https://github.com/user/plugin.git",
    ])
    .unwrap();
    assert!(matches!(cli.command, Commands::Plugins(_)));
}

#[test]
fn test_cli_parse_plugins_remove() {
    let cli = Cli::try_parse_from(&["forge-guard", "plugins", "remove", "my-plugin"]).unwrap();
    assert!(matches!(cli.command, Commands::Plugins(_)));
}

#[test]
fn test_cli_parse_plugins_enable_disable() {
    let cli_enable =
        Cli::try_parse_from(&["forge-guard", "plugins", "enable", "my-plugin"]).unwrap();
    assert!(matches!(cli_enable.command, Commands::Plugins(_)));

    let cli_disable =
        Cli::try_parse_from(&["forge-guard", "plugins", "disable", "my-plugin"]).unwrap();
    assert!(matches!(cli_disable.command, Commands::Plugins(_)));
}

#[test]
fn test_cli_parse_plugins_new() {
    let cli = Cli::try_parse_from(&["forge-guard", "plugins", "new", "my-awesome-plugin"]).unwrap();
    assert!(matches!(cli.command, Commands::Plugins(_)));
}

#[test]
fn test_cli_parse_chain_list() {
    let cli = Cli::try_parse_from(&["forge-guard", "chain", "list"]).unwrap();
    assert!(matches!(cli.command, Commands::Chain(_)));
}

#[test]
fn test_cli_parse_chain_info() {
    let cli = Cli::try_parse_from(&["forge-guard", "chain", "info", "polygon"]).unwrap();
    assert!(matches!(cli.command, Commands::Chain(_)));
}

#[test]
fn test_cli_parse_chain_add() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "chain",
        "add",
        "my-chain",
        "https://rpc.my-chain.io",
        "99999",
    ])
    .unwrap();
    assert!(matches!(cli.command, Commands::Chain(_)));
}

#[test]
fn test_cli_parse_chain_remove() {
    let cli = Cli::try_parse_from(&["forge-guard", "chain", "remove", "my-chain"]).unwrap();
    assert!(matches!(cli.command, Commands::Chain(_)));
}

#[test]
fn test_cli_parse_chain_test() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "chain",
        "test",
        "polygon",
        "https://polygon-rpc.com",
    ])
    .unwrap();
    assert!(matches!(cli.command, Commands::Chain(_)));
}

#[test]
fn test_cli_parse_security_config() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "config"]).unwrap();
    assert!(matches!(cli.command, Commands::Security(_)));
}

#[test]
fn test_cli_parse_security_threshold() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "threshold", "85"]).unwrap();
    assert!(matches!(cli.command, Commands::Security(_)));
}

#[test]
fn test_cli_parse_security_enable() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "enable", "Reentrancy"]).unwrap();
    assert!(matches!(cli.command, Commands::Security(_)));
}

#[test]
fn test_cli_parse_security_list() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "list"]).unwrap();
    assert!(matches!(cli.command, Commands::Security(_)));
}

#[test]
fn test_cli_parse_security_info() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "info", "Reentrancy"]).unwrap();
    assert!(matches!(cli.command, Commands::Security(_)));
}

// ─────────────────────────────────────────────────────────────
// 2. Shared flags across commands
// ─────────────────────────────────────────────────────────────

#[test]
fn test_shared_flags_on_audit() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "audit",
        "--chain",
        "polygon",
        "--project",
        "/tmp/test",
        "--json",
        "--markdown",
        "--strict",
        "--offline",
        "--production",
        "--report",
        "--parallelism",
        "16",
    ])
    .unwrap();

    match cli.command {
        Commands::Audit(args) => {
            assert_eq!(args.shared.chain, "polygon");
            assert_eq!(args.shared.project, std::path::PathBuf::from("/tmp/test"));
            assert!(args.shared.json);
            assert!(args.shared.markdown);
            assert!(args.shared.strict);
            assert!(args.shared.offline);
            assert!(args.shared.production);
            assert!(args.shared.report);
            assert_eq!(args.shared.parallelism, 16);
        }
        _ => panic!("Expected Audit command"),
    }
}

#[test]
fn test_shared_flags_on_doctor() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "doctor",
        "--chain",
        "optimism",
        "--offline",
        "--json",
    ])
    .unwrap();

    match cli.command {
        Commands::Doctor(args) => {
            assert_eq!(args.shared.chain, "optimism");
            assert!(args.shared.offline);
            assert!(args.shared.json);
        }
        _ => panic!("Expected Doctor command"),
    }
}

#[test]
fn test_shared_flags_on_ci() {
    let cli = Cli::try_parse_from(&[
        "forge-guard",
        "ci",
        "--strict",
        "--production",
        "--parallelism",
        "2",
    ])
    .unwrap();

    match cli.command {
        Commands::Ci(args) => {
            assert!(args.shared.strict);
            assert!(args.shared.production);
            assert_eq!(args.shared.parallelism, 2);
        }
        _ => panic!("Expected Ci command"),
    }
}

// ─────────────────────────────────────────────────────────────
// 3. Error cases
// ─────────────────────────────────────────────────────────────

#[test]
fn test_cli_parse_invalid_subcommand() {
    let result = Cli::try_parse_from(&["forge-guard", "nonexistent"]);
    assert!(result.is_err(), "Expected error for invalid subcommand");
}

#[test]
fn test_cli_parse_invalid_flag() {
    let result = Cli::try_parse_from(&["forge-guard", "audit", "--nonexistent-flag"]);
    assert!(result.is_err(), "Expected error for invalid flag");
}

#[test]
fn test_cli_parse_invalid_parallelism_value() {
    let result = Cli::try_parse_from(&["forge-guard", "audit", "--parallelism", "not-a-number"]);
    assert!(
        result.is_err(),
        "Expected error for non-numeric parallelism"
    );
}

#[test]
fn test_cli_parse_missing_argument() {
    let result = Cli::try_parse_from(&["forge-guard", "plugins", "install"]);
    assert!(result.is_err(), "Expected error for missing plugin name");
}

#[test]
fn test_cli_parse_no_subcommand() {
    let result = Cli::try_parse_from(&["forge-guard"]);
    assert!(result.is_err(), "Expected error when no subcommand given");
}

// ─────────────────────────────────────────────────────────────
// 4. Safe run() tests — commands via Cli::run() that work
//    without a real Foundry project
// ─────────────────────────────────────────────────────────────

#[test]
fn test_run_chain_list() {
    let cli = Cli::try_parse_from(&["forge-guard", "chain", "list"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "chain list should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_list() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "list"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security list should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_config() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "config"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security config should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_threshold() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "threshold", "75"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security threshold should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_enable() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "enable", "Reentrancy"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security enable should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_disable() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "disable", "Reentrancy"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security disable should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_chain_info() {
    let cli = Cli::try_parse_from(&["forge-guard", "chain", "info", "polygon"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "chain info should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_run_security_info() {
    let cli = Cli::try_parse_from(&["forge-guard", "security", "info", "Reentrancy"]).unwrap();
    let result = cli.run();
    assert!(
        result.is_ok(),
        "security info should succeed: {:?}",
        result.err()
    );
}

// ─────────────────────────────────────────────────────────────
// 5. SecurityAction enum — check it's constructable
// ─────────────────────────────────────────────────────────────

#[test]
fn test_security_action_variants() {
    // Verify all variants compile and parse correctly
    let config = Cli::try_parse_from(&["forge-guard", "security", "config"]).unwrap();
    assert!(matches!(config.command, Commands::Security(_)));

    let threshold = Cli::try_parse_from(&["forge-guard", "security", "threshold", "90"]).unwrap();
    let _action = SecurityAction::Threshold { score: 90 };
    assert!(matches!(threshold.command, Commands::Security(_)));

    let enable =
        Cli::try_parse_from(&["forge-guard", "security", "enable", "tx.origin Usage"]).unwrap();
    let _action2 = SecurityAction::Enable {
        check: "tx.origin Usage".into(),
    };
    assert!(matches!(enable.command, Commands::Security(_)));

    let disable =
        Cli::try_parse_from(&["forge-guard", "security", "disable", "Reentrancy"]).unwrap();
    assert!(matches!(disable.command, Commands::Security(_)));

    let list = Cli::try_parse_from(&["forge-guard", "security", "list"]).unwrap();
    assert!(matches!(list.command, Commands::Security(_)));

    let info = Cli::try_parse_from(&["forge-guard", "security", "info", "Reentrancy"]).unwrap();
    assert!(matches!(info.command, Commands::Security(_)));
}

// ─────────────────────────────────────────────────────────────
// 6. PluginAction enum — all variants parse
// ─────────────────────────────────────────────────────────────

#[test]
fn test_plugin_action_variants() {
    // List
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "list"]);
    assert!(r.is_ok());

    // Install
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "install", "p"]);
    assert!(r.is_ok());

    // Install with source
    let r = Cli::try_parse_from(&[
        "forge-guard",
        "plugins",
        "install",
        "p",
        "https://github.com/x/y.git",
    ]);
    assert!(r.is_ok());

    // Remove
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "remove", "p"]);
    assert!(r.is_ok());

    // Enable
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "enable", "p"]);
    assert!(r.is_ok());

    // Disable
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "disable", "p"]);
    assert!(r.is_ok());

    // New
    let r = Cli::try_parse_from(&["forge-guard", "plugins", "new", "my-plugin"]);
    assert!(r.is_ok());
}

// ─────────────────────────────────────────────────────────────
// 7. ChainAction enum — all variants parse
// ─────────────────────────────────────────────────────────────

#[test]
fn test_chain_action_variants() {
    let r = Cli::try_parse_from(&["forge-guard", "chain", "list"]);
    assert!(r.is_ok());

    let r = Cli::try_parse_from(&["forge-guard", "chain", "info", "ethereum"]);
    assert!(r.is_ok());

    let r = Cli::try_parse_from(&["forge-guard", "chain", "add", "c", "http://rpc", "1"]);
    assert!(r.is_ok());

    let r = Cli::try_parse_from(&["forge-guard", "chain", "remove", "c"]);
    assert!(r.is_ok());

    let r = Cli::try_parse_from(&["forge-guard", "chain", "test", "c", "http://rpc"]);
    assert!(r.is_ok());
}

// ─────────────────────────────────────────────────────────────
// 8. Nested subcommand dispatch via Cli::run()
// ─────────────────────────────────────────────────────────────

#[test]
fn test_cli_run_returns_result_ok_for_valid_commands() {
    // These should succeed without a real project
    let cmds = vec![
        vec!["forge-guard", "security", "list"],
        vec!["forge-guard", "security", "config"],
        vec!["forge-guard", "chain", "list"],
        vec!["forge-guard", "chain", "info", "ethereum"],
    ];
    for args in cmds {
        let cli = Cli::try_parse_from(&args).unwrap();
        let result = cli.run();
        assert!(
            result.is_ok(),
            "Command '{:?}' should succeed: {:?}",
            args,
            result.err()
        );
    }
}

// ─────────────────────────────────────────────────────────────
// 9. Audit & Deploy with temp directories and mock contracts
// ─────────────────────────────────────────────────────────────

const CLEAN_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Simple {
    uint256 public value;
    address public owner;

    event ValueChanged(address indexed sender, uint256 newValue);

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    constructor() {
        owner = msg.sender;
    }

    function set(uint256 newValue) external onlyOwner {
        value = newValue;
        emit ValueChanged(msg.sender, newValue);
    }

    function get() external view returns (uint256) {
        return value;
    }
}
"#;

const VULNERABLE_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Vulnerable {
    mapping(address => uint256) public balances;
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    function withdraw(uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
        balances[msg.sender] -= amount;
    }

    function setAdmin(address newAdmin) external {
        admin = newAdmin;
    }

    function kill() external {
        selfdestruct(payable(msg.sender));
    }

    function transfer(address to, uint256 amount) external {
        require(tx.origin == owner);
        balances[to] += amount;
    }

    receive() external payable {}
}
"#;

fn create_temp_project(contracts: &[(&str, &str)]) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("Failed to create temp dir");
    // Project has forge-guard.toml with src_dirs = ["test-contracts/secure/src"]
    let src_dir = dir.path().join("test-contracts").join("secure").join("src");
    std::fs::create_dir_all(&src_dir).expect("Failed to create src dir");

    for (filename, content) in contracts {
        let file_path = src_dir.join(filename);
        std::fs::write(&file_path, content)
            .unwrap_or_else(|e| panic!("Failed to write {}: {}", filename, e));
    }

    let path = dir.path().to_path_buf();
    (dir, path)
}

fn run_audit(project: &std::path::Path, extra_args: &[&str]) -> Result<(), anyhow::Error> {
    let mut args = vec!["forge-guard", "audit", "--offline"];
    args.push("--project");
    args.push(project.to_str().unwrap());
    args.extend_from_slice(extra_args);

    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    cli.run()
}

/// Run the compiled forge-guard binary as a subprocess (true end-to-end).
fn run_binary_in(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
    std::process::Command::new(env!("CARGO_BIN_EXE_forge-guard"))
        .args(args)
        .current_dir(dir)
        .output()
        .expect("Failed to spawn forge-guard binary")
}

#[test]
fn test_audit_clean_contract_succeeds() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &[]);
    assert!(
        result.is_ok(),
        "Audit of clean contract should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_clean_contract_quick_mode() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--quick"]);
    assert!(
        result.is_ok(),
        "Quick audit of clean contract should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_clean_contract_json_output() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--json"]);
    assert!(
        result.is_ok(),
        "Audit with --json should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_clean_contract_strict_mode_passes() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--strict"]);
    // The "clean" contract may still have findings (e.g. Storage Collision from
    // public variable `owner` overlapping with state), so strict may or may not pass.
    // We just verify it runs without panic.
    let _ = result;
}

#[test]
fn test_audit_vulnerable_contract_detects_issues() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let result = run_audit(&project, &[]);
    assert!(
        result.is_ok(),
        "Audit of vulnerable contract should succeed (reports issues): {:?}",
        result.err()
    );
}

#[test]
fn test_audit_vulnerable_contract_strict_fails() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let result = run_audit(&project, &["--strict"]);
    assert!(
        result.is_err(),
        "Strict audit should fail on vulnerable contract with findings"
    );
}

#[test]
fn test_audit_vulnerable_contract_with_exploit() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let result = run_audit(&project, &["--exploit"]);
    assert!(
        result.is_ok(),
        "Audit with exploit analysis should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_vulnerable_contract_with_gas() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let result = run_audit(&project, &["--gas"]);
    assert!(
        result.is_ok(),
        "Audit with gas analysis should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_vulnerable_contract_json_output() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let result = run_audit(&project, &["--json"]);
    assert!(
        result.is_ok(),
        "Audit with --json on vulnerable contract should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_empty_directory_fails() {
    let (_dir, project) = create_temp_project(&[]);
    let result = run_audit(&project, &[]);
    assert!(result.is_err(), "Audit with empty project should fail");
    let err = format!("{:#}", result.unwrap_err());
    assert!(
        err.contains("No Solidity source files found"),
        "Error should mention no source files: {}",
        err
    );
}

#[test]
fn test_audit_multiple_contracts() {
    let (_dir, project) = create_temp_project(&[
        ("Simple.sol", CLEAN_CONTRACT),
        ("Vulnerable.sol", VULNERABLE_CONTRACT),
    ]);
    let result = run_audit(&project, &[]);
    assert!(
        result.is_ok(),
        "Audit of multiple contracts should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_with_report_output() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--report"]);
    assert!(
        result.is_ok(),
        "Audit with --report should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_different_chain() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--chain", "polygon"]);
    assert!(
        result.is_ok(),
        "Audit with different chain should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_with_exclude_pattern() {
    let (_dir, project) = create_temp_project(&[
        ("Simple.sol", CLEAN_CONTRACT),
        ("Vulnerable.sol", VULNERABLE_CONTRACT),
    ]);
    let result = run_audit(&project, &["--exclude", "Vulnerable"]);
    assert!(
        result.is_ok(),
        "Audit with exclude should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_custom_sources() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--sources", "src"]);
    assert!(
        result.is_ok(),
        "Audit with explicit sources should succeed: {:?}",
        result.err()
    );
}

// ─────────────────────────────────────────────────────────────
// 9b. M14 — audit templates & doctor/sbom/hook end-to-end
// ─────────────────────────────────────────────────────────────
#[test]
fn test_audit_with_defi_template_succeeds() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--template", "defi"]);
    assert!(
        result.is_ok(),
        "Audit with --template defi should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_with_template_json_output_succeeds() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--template", "erc20", "--json"]);
    assert!(
        result.is_ok(),
        "Audit with --template erc20 --json should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_audit_with_unknown_template_fails() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--template", "does-not-exist"]);
    assert!(result.is_err(), "Unknown template should error");
    let msg = format!("{:#}", result.unwrap_err());
    assert!(
        msg.contains("Unknown audit template"),
        "Error should mention unknown template: {}",
        msg
    );
}

#[test]
fn test_audit_list_templates_succeeds() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let result = run_audit(&project, &["--list-templates"]);
    assert!(
        result.is_ok(),
        "--list-templates should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_binary_audit_template_min_scores_gate() {
    // End-to-end template scoring: the upgradeable template requires
    // upgradeability >= 90. A UUPS contract without a storage gap scores 70
    // in upgradeability, so production_ready must be false even though the
    // overall score stays above the 70 deployment threshold.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(
        src.join("Upgradeable.sol"),
        "contract Upgradeable is UUPSUpgradeable {\n    uint256 public value;\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("forge-guard.toml"),
        "src_dirs = [\"src\"]\n",
    )
    .unwrap();

    // Without a template, min_scores gate passes trivially.
    let output = run_binary_in(dir.path(), &["audit", "--json"]);
    assert!(
        output.status.success(),
        "audit should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let v: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    assert!(v["production_ready"].as_bool().unwrap());
    assert!(v["overall_score"].as_u64().unwrap() >= 70);

    // With the upgradeable template, min score (upgradeability >= 90) is not
    // met, so production_ready must be false despite a high overall score.
    let output = run_binary_in(
        dir.path(),
        &["audit", "--template", "upgradeable", "--json"],
    );
    assert!(
        output.status.success(),
        "audit with template should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let v: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    assert!(
        v["overall_score"].as_u64().unwrap() >= 70,
        "Overall score should remain above the deployment threshold"
    );
    assert!(
        !v["production_ready"].as_bool().unwrap(),
        "Template min_scores gate should block production_ready"
    );
}

#[test]
fn test_binary_audit_template_focus_areas_weight_score() {
    // defi template focuses exploit_resistance/security/chain_compatibility.
    // A clean contract keeps all 100s, so the template must not crash the
    // scoring pipeline and the JSON must carry the expected fields.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(
        src.join("Clean.sol"),
        "contract Counter {\n    uint256 private count;\n    function increment() external { count += 1; }\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("forge-guard.toml"),
        "src_dirs = [\"src\"]\n",
    )
    .unwrap();

    let output = run_binary_in(dir.path(), &["audit", "--template", "defi", "--json"]);
    assert!(
        output.status.success(),
        "audit with defi template should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let v: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    assert!(v["overall_score"].as_u64().is_some());
    assert!(v["production_ready"].is_boolean());
    assert!(v["deployment_approved"].is_boolean());
    assert!(v["risk_level"].is_string());
}

#[test]
fn test_audit_single_file_sources() {
    // The pre-commit hook audits individual staged files via --sources.
    // Verify auditing a single .sol file path works end-to-end.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let file_path = project
        .join("test-contracts")
        .join("secure")
        .join("src")
        .join("Simple.sol");
    let result = run_audit(&project, &["--sources", file_path.to_str().unwrap()]);
    assert!(
        result.is_ok(),
        "Audit of a single staged file via --sources should succeed: {:?}",
        result.err()
    );
}

#[test]
fn test_binary_doctor_sync_writes_forge_guard_toml() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("foundry.toml"),
        "[profile.default]\n\
         src = 'contracts'\n\
         test = 'tests'\n\
         solc = '0.8.23'\n",
    )
    .unwrap();

    let output = run_binary_in(dir.path(), &["doctor", "--sync"]);
    assert!(
        output.status.success(),
        "doctor --sync should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let written = std::fs::read_to_string(dir.path().join("forge-guard.toml")).unwrap();
    let reparsed: toml::Value = toml::from_str(&written).unwrap();
    assert_eq!(reparsed["src_dirs"][0].as_str(), Some("contracts"));
    assert_eq!(reparsed["solc_version"].as_str(), Some("0.8.23"));
}

#[test]
fn test_binary_doctor_sync_dry_run_does_not_write() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("foundry.toml"),
        "[profile.default]\nsrc = 'contracts'\n",
    )
    .unwrap();

    let output = run_binary_in(dir.path(), &["doctor", "--sync", "--dry-run"]);
    assert!(
        output.status.success(),
        "doctor --sync --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        !dir.path().join("forge-guard.toml").exists(),
        "Dry run must not write forge-guard.toml"
    );
}

#[test]
fn test_binary_sbom_ci_writes_workflow() {
    let dir = tempfile::tempdir().unwrap();

    let output = run_binary_in(dir.path(), &["sbom", "--ci", "--output", "sbom.json"]);
    assert!(
        output.status.success(),
        "sbom --ci should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // SBOM output written
    assert!(dir.path().join("sbom.json").exists());
    let content = std::fs::read_to_string(dir.path().join("sbom.json")).unwrap();
    assert!(content.contains("bomFormat"));

    // CI workflow written to .github/workflows/sbom.yml
    let wf = dir
        .path()
        .join(".github")
        .join("workflows")
        .join("sbom.yml");
    assert!(wf.exists(), "sbom.yml workflow should be written");
    let wf_content = std::fs::read_to_string(&wf).unwrap();
    assert!(wf_content.contains("name: SBOM Generation"));
    assert!(wf_content.contains("forge-guard sbom --format cyclonedx"));
    assert!(wf_content.contains("forge-guard sbom --format spdx"));
}

#[test]
fn test_binary_sbom_without_ci_writes_no_workflow() {
    let dir = tempfile::tempdir().unwrap();

    let output = run_binary_in(dir.path(), &["sbom", "--output", "sbom.json"]);
    assert!(output.status.success());
    assert!(dir.path().join("sbom.json").exists());
    assert!(
        !dir.path().join(".github").exists(),
        "Without --ci, no workflow should be written"
    );
}

#[test]
fn test_binary_install_hook_and_uninstall() {
    let dir = tempfile::tempdir().unwrap();
    let git_dir = dir.path().join(".git");
    std::fs::create_dir_all(git_dir.join("hooks")).unwrap();

    // Install
    let output = run_binary_in(dir.path(), &["install-hook"]);
    assert!(
        output.status.success(),
        "install-hook should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let hook_path = git_dir.join("hooks").join("pre-commit");
    assert!(hook_path.exists(), "pre-commit hook should be created");
    let content = std::fs::read_to_string(&hook_path).unwrap();
    assert!(content.contains("forge-guard pre-commit hook"));
    assert!(content.contains("--sources \"$file\""));

    // Uninstall
    let output = run_binary_in(dir.path(), &["install-hook", "--uninstall"]);
    assert!(output.status.success());
    assert!(
        !hook_path.exists(),
        "pre-commit hook should be removed after uninstall"
    );
}

#[test]
fn test_binary_install_hook_refuses_overwrite_without_force() {
    let dir = tempfile::tempdir().unwrap();
    let git_dir = dir.path().join(".git");
    std::fs::create_dir_all(git_dir.join("hooks")).unwrap();
    std::fs::write(git_dir.join("hooks").join("pre-commit"), "existing hook").unwrap();

    let output = run_binary_in(dir.path(), &["install-hook"]);
    assert!(
        !output.status.success(),
        "install-hook should fail when hook exists without --force"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("already exists"));

    // --force overwrites
    let output = run_binary_in(dir.path(), &["install-hook", "--force"]);
    assert!(output.status.success());
    let content = std::fs::read_to_string(git_dir.join("hooks").join("pre-commit")).unwrap();
    assert!(content.contains("forge-guard pre-commit hook"));
}

#[test]
fn test_binary_install_hook_without_git_fails() {
    let dir = tempfile::tempdir().unwrap();
    let output = run_binary_in(dir.path(), &["install-hook"]);
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("No .git directory"));
}

#[test]
fn test_audit_non_standard_sources_dir() {
    // --sources doesn't override forge-guard.toml's src_dirs
    // so this test just verifies the error message is sensible
    let dir = tempfile::tempdir().expect("Failed to create temp dir");
    // Create the default expected dir so it doesn't error on "no source files"
    let default_src = dir.path().join("test-contracts").join("secure").join("src");
    std::fs::create_dir_all(&default_src).expect("Failed to create dir");
    std::fs::write(default_src.join("Simple.sol"), CLEAN_CONTRACT)
        .expect("Failed to write contract");

    // Also create a contracts dir to verify it's NOT picked up (only src_dirs from config)
    let contracts_dir = dir.path().join("contracts");
    std::fs::create_dir_all(&contracts_dir).expect("Failed to create dir");
    std::fs::write(contracts_dir.join("Other.sol"), CLEAN_CONTRACT)
        .expect("Failed to write contract");

    // This should succeed since files are in the configured src_dirs
    let result = run_audit(dir.path(), &["--quick"]);
    assert!(
        result.is_ok(),
        "Audit should succeed with files in configured src_dirs: {:?}",
        result.err()
    );
}

#[test]
fn test_deploy_vulnerable_contract_blocked() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let args = vec![
        "forge-guard",
        "deploy",
        "Vulnerable",
        "--project",
        project.to_str().unwrap(),
        "--offline",
    ];
    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    let result = cli.run();
    assert!(result.is_err(), "Deploy of vulnerable contract should err");
    let err_msg = format!("{:#}", result.unwrap_err());
    assert!(
        err_msg.contains("blocked")
            || err_msg.contains("forge")
            || err_msg.contains("Failed")
            || err_msg.contains("Deploy failed"),
        "Error should mention blocked or forge: {:#}",
        err_msg
    );
}

#[test]
fn test_deploy_clean_contract_outcome() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let args = vec![
        "forge-guard",
        "deploy",
        "Simple",
        "--project",
        project.to_str().unwrap(),
        "--offline",
    ];
    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    let result = cli.run();
    if let Err(e) = &result {
        let msg = format!("{:#}", e);
        assert!(
            msg.contains("forge") || msg.contains("Failed") || msg.contains("blocked"),
            "If deploy fails, should mention forge or blocked: {:#}",
            msg
        );
    }
}

#[test]
fn test_deploy_force_bypass() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let args = vec![
        "forge-guard",
        "deploy",
        "Simple",
        "--project",
        project.to_str().unwrap(),
        "--offline",
        "--force",
    ];
    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    let result = cli.run();
    if let Err(e) = &result {
        let msg = format!("{:#}", e);
        assert!(
            msg.contains("forge") || msg.contains("Failed"),
            "With --force, error should be forge-related: {:#}",
            msg
        );
    }
}

#[test]
fn test_deploy_safe_blocks_vulnerable() {
    let (_dir, project) = create_temp_project(&[("Vulnerable.sol", VULNERABLE_CONTRACT)]);
    let args = vec![
        "forge-guard",
        "deploy-safe",
        "Vulnerable",
        "--project",
        project.to_str().unwrap(),
        "--offline",
    ];
    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    let result = cli.run();
    assert!(result.is_err(), "deploy-safe should block vulnerable");
    let msg = format!("{:#}", result.unwrap_err());
    assert!(
        msg.contains("blocked") || msg.contains("Security"),
        "Error should mention blocked or security: {:#}",
        msg
    );
}

#[test]
fn test_deploy_empty_project_fails() {
    let (_dir, project) = create_temp_project(&[]);
    let args = vec![
        "forge-guard",
        "deploy",
        "--project",
        project.to_str().unwrap(),
        "--offline",
    ];
    let cli = Cli::try_parse_from(&args).expect("Failed to parse CLI args");
    let result = cli.run();
    assert!(result.is_err(), "Deploy with no contracts should fail");
}

// ─────────────────────────────────────────────────────────────
// 10. M15 — forge-guard import end-to-end (real Slither JSON)
// ─────────────────────────────────────────────────────────────

/// A realistic Slither JSON results file (as produced by
/// `slither . --json out.json`), exercising detector metadata,
/// element source mappings and the `markdown` recommendation field.
const SLITHER_RESULTS_JSON: &str = r#"{
  "success": true,
  "results": {
    "detectors": [
      {
        "check": "reentrancy-eth",
        "impact": "High",
        "confidence": "Medium",
        "description": "Reentrancy in Vault.withdraw (contracts/Vault.sol#42-47)",
        "markdown": "Use checks-effects-interactions or a reentrancy guard.",
        "elements": [
          {
            "type": "function",
            "name": "withdraw",
            "source_mapping": {
              "filename_relative": "contracts/Vault.sol",
              "line": 42,
              "end_line": 47,
              "column": 8,
              "content": "(bool ok, ) = msg.sender.call{value: amount}(\"\");"
            }
          }
        ]
      },
      {
        "check": "uninitialized-state",
        "impact": "Low",
        "confidence": "High",
        "description": "State variable owner is never initialized",
        "markdown": "Initialize the state variable in the constructor.",
        "elements": [
          {
            "type": "state_variable",
            "name": "owner",
            "source_mapping": {
              "filename_relative": "contracts/Vault.sol",
              "line": 12,
              "column": 4,
              "content": "address public owner;"
            }
          }
        ]
      }
    ]
  }
}"#;

#[test]
fn test_import_slither_json_end_to_end() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("slither_out.json"), SLITHER_RESULTS_JSON)
        .expect("write Slither JSON fixture");

    let result = run_binary_in(
        &project,
        &["import", "--from", "slither", "slither_out.json", "--json"],
    );
    assert!(
        result.status.success(),
        "import should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be valid JSON: {e}\n{stdout}"));
    assert_eq!(json["tool"], "Slither");
    assert_eq!(json["merged_with_forge_guard"], false);
    assert_eq!(json["duplicates_removed"], 0);

    let findings = json["findings"].as_array().expect("findings array");
    assert_eq!(
        findings.len(),
        2,
        "two detectors should import as two findings"
    );

    let first = &findings[0];
    assert!(
        first["id"].as_str().unwrap().starts_with("SL-"),
        "imported ids should use the SL- prefix"
    );
    assert_eq!(first["severity"], "high");
    assert_eq!(first["title"], "reentrancy-eth (High)");
    assert_eq!(first["file"], "contracts/Vault.sol");
    assert_eq!(first["line"], 42);
    assert_eq!(first["category"], "slither:reentrancy-eth");
    assert!(
        first["code_snippet"].as_str().unwrap().contains("call"),
        "source snippet should carry the vulnerable code"
    );
    assert_eq!(findings[1]["severity"], "low");
}

#[test]
fn test_import_slither_writes_unified_report_file() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("slither_out.json"), SLITHER_RESULTS_JSON)
        .expect("write Slither JSON fixture");

    let result = run_binary_in(
        &project,
        &[
            "import",
            "--from",
            "slither",
            "slither_out.json",
            "--json",
            "--output",
            "unified.json",
        ],
    );
    assert!(
        result.status.success(),
        "import with --output should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let report = std::fs::read_to_string(project.join("unified.json"))
        .expect("unified report should be written to disk");
    let json: serde_json::Value = serde_json::from_str(&report).expect("report is valid JSON");
    assert_eq!(json["tool"], "Slither");
    assert_eq!(json["findings"].as_array().unwrap().len(), 2);
    assert_eq!(
        json["source_files"],
        serde_json::json!(["contracts/Vault.sol"])
    );
    // The import summary is reported on stderr.
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("Unified report written"),
        "stderr should mention the written report: {stderr}"
    );
}

#[test]
fn test_import_missing_input_file_errors() {
    let (_dir, project) = create_temp_project(&[]);
    let result = run_binary_in(&project, &["import", "--from", "slither", "nope.json"]);
    assert!(
        !result.status.success(),
        "import with a missing input file should fail"
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("Results file not found"),
        "stderr should explain the missing file: {stderr}"
    );
}

// ─────────────────────────────────────────────────────────────
// 10b. M15 — import end-to-end (Mythril & Semgrep JSON)
// ─────────────────────────────────────────────────────────────

/// A realistic Mythril JSON results file (as produced by
/// `myth analyze ... -o mythril_out.json`), exercising the `severity`
/// and `type` fields, source mappings and SWC references.
const MYTHRIL_RESULTS_JSON: &str = r#"{
  "success": true,
  "issues": [
    {
      "title": "The contract executes an external call",
      "description": "The contract executes an external call",
      "severity": "High",
      "swc-id": "107",
      "function": "withdraw",
      "address": 1234,
      "source": {
        "filename": "contracts/Vault.sol",
        "line": 42,
        "source": "msg.sender.call{value: amount}(\"\");"
      }
    },
    {
      "title": "State change after external call",
      "description": "State is written after an external call",
      "type": "Medium",
      "swc-id": "107",
      "function": "withdraw",
      "source": {
        "filename": "contracts/Vault.sol",
        "line": 44,
        "source": "balances[msg.sender] -= amount;"
      }
    }
  ]
}"#;

/// A realistic Semgrep JSON results file (as produced by
/// `semgrep scan --json`), exercising check ids, start locations,
/// severity levels and CWE metadata.
const SEMGREP_RESULTS_JSON: &str = r#"{
  "results": [
    {
      "check_id": "solidity.reentrancy",
      "path": "contracts/Vault.sol",
      "start": { "line": 42, "col": 1 },
      "end": { "line": 42, "col": 30 },
      "extra": {
        "message": "External call before state update",
        "severity": "ERROR",
        "metadata": { "cwe": ["CWE-1077"] },
        "lines": "msg.sender.call{value: amount}(\"\");"
      }
    },
    {
      "check_id": "solidity.avoid-tx-origin",
      "path": "contracts/Vault.sol",
      "start": { "line": 60, "col": 1 },
      "extra": {
        "message": "Use of tx.origin",
        "severity": "WARNING",
        "metadata": { "cwe": "CWE-477" }
      }
    }
  ],
  "errors": []
}"#;

#[test]
fn test_import_mythril_json_end_to_end() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("mythril_out.json"), MYTHRIL_RESULTS_JSON)
        .expect("write Mythril JSON fixture");

    let result = run_binary_in(
        &project,
        &["import", "--from", "mythril", "mythril_out.json", "--json"],
    );
    assert!(
        result.status.success(),
        "import should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be valid JSON: {e}\n{stdout}"));
    assert_eq!(json["tool"], "Mythril");

    let findings = json["findings"].as_array().expect("findings array");
    assert_eq!(
        findings.len(),
        2,
        "two issues should import as two findings"
    );

    let first = &findings[0];
    assert!(
        first["id"].as_str().unwrap().starts_with("MY-"),
        "imported ids should use the MY- prefix"
    );
    assert_eq!(first["severity"], "high");
    assert_eq!(first["title"], "The contract executes an external call");
    assert_eq!(first["file"], "contracts/Vault.sol");
    assert_eq!(first["line"], 42);
    assert_eq!(first["category"], "mythril:withdraw");
    let refs = first["references"].as_array().unwrap();
    assert!(
        refs.iter().any(|r| r == "SWC-107"),
        "Mythril SWC reference should be carried through"
    );
    // The `type` field is honored when `severity` is absent.
    assert_eq!(findings[1]["severity"], "medium");
}

#[test]
fn test_import_semgrep_json_end_to_end() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("semgrep_out.json"), SEMGREP_RESULTS_JSON)
        .expect("write Semgrep JSON fixture");

    let result = run_binary_in(
        &project,
        &["import", "--from", "semgrep", "semgrep_out.json", "--json"],
    );
    assert!(
        result.status.success(),
        "import should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be valid JSON: {e}\n{stdout}"));
    assert_eq!(json["tool"], "Semgrep");

    let findings = json["findings"].as_array().expect("findings array");
    assert_eq!(
        findings.len(),
        2,
        "two results should import as two findings"
    );

    let first = &findings[0];
    assert!(
        first["id"].as_str().unwrap().starts_with("SG-"),
        "imported ids should use the SG- prefix"
    );
    assert_eq!(first["severity"], "high");
    assert_eq!(first["title"], "External call before state update");
    assert_eq!(first["file"], "contracts/Vault.sol");
    assert_eq!(first["line"], 42);
    assert_eq!(first["category"], "semgrep:solidity.reentrancy");
    assert!(
        first["code_snippet"].as_str().unwrap().contains("call"),
        "source lines should be carried as the code snippet"
    );
    let refs = first["references"].as_array().unwrap();
    assert!(
        refs.iter().any(|r| r == "CWE-1077"),
        "Semgrep CWE reference should be carried through"
    );
    // WARNING maps to Medium.
    assert_eq!(findings[1]["severity"], "medium");
    assert!(findings[1]["references"]
        .as_array()
        .unwrap()
        .iter()
        .any(|r| r == "CWE-477"));
}

#[test]
fn test_import_semgrep_writes_unified_report_file() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("semgrep_out.json"), SEMGREP_RESULTS_JSON)
        .expect("write Semgrep JSON fixture");

    let result = run_binary_in(
        &project,
        &[
            "import",
            "--from",
            "semgrep",
            "semgrep_out.json",
            "--json",
            "--output",
            "unified.json",
        ],
    );
    assert!(
        result.status.success(),
        "import with --output should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let report = std::fs::read_to_string(project.join("unified.json"))
        .expect("unified report should be written to disk");
    let json: serde_json::Value = serde_json::from_str(&report).expect("report is valid JSON");
    assert_eq!(json["tool"], "Semgrep");
    assert_eq!(json["findings"].as_array().unwrap().len(), 2);
    assert_eq!(
        json["source_files"],
        serde_json::json!(["contracts/Vault.sol"])
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("Unified report written"),
        "stderr should mention the written report: {stderr}"
    );
}

// ─────────────────────────────────────────────────────────────
// 10c. M15 — import dedup against a forge-guard audit result
// ─────────────────────────────────────────────────────────────

/// A complete forge-guard audit result JSON (as produced by
/// `forge-guard audit --json`). One finding intentionally mirrors the
/// Slither reentrancy detector (same file, line and title) so the
/// dedup path removes exactly one duplicate.
const FORGE_GUARD_AUDIT_JSON: &str = r#"{
  "project_name": "Vault",
  "chain": "ethereum",
  "timestamp": "2026-08-09T12:00:00Z",
  "duration_seconds": 2.5,
  "findings": [
    {
      "id": "FG-H-001",
      "title": "reentrancy-eth (High)",
      "description": "Reentrancy in withdraw (also reported by Slither)",
      "severity": "high",
      "file": "contracts/Vault.sol",
      "line": 42,
      "column": 8,
      "code_snippet": "(bool ok, ) = msg.sender.call{value: amount}(\"\");",
      "recommendation": "Apply checks-effects-interactions",
      "category": "Security",
      "blocks_deployment": true
    },
    {
      "id": "FG-M-002",
      "title": "Unrelated issue",
      "description": "A finding Slither did not report",
      "severity": "medium",
      "file": "contracts/Other.sol",
      "line": 7,
      "recommendation": "Fix it",
      "category": "Security"
    }
  ],
  "scores": {
    "access_control": 85, "security": 55, "fuzzing": 100, "gas": 92,
    "architecture": 75, "upgradeability": 100, "dependencies": 90,
    "deployment": 80, "proxy_safety": 95, "chain_compatibility": 90,
    "production_readiness": 60, "exploit_resistance": 70
  },
  "overall_score": 62,
  "risk_level": "medium",
  "production_ready": false,
  "deployment_approved": false,
  "summary": {
    "total_findings": 2, "critical_count": 0, "high_count": 1, "medium_count": 1,
    "low_count": 0, "info_count": 0, "files_analyzed": 2, "lines_analyzed": 120,
    "contracts_analyzed": 2
  }
}"#;

#[test]
fn test_import_slither_dedups_against_forge_guard_audit() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("slither_out.json"), SLITHER_RESULTS_JSON)
        .expect("write Slither JSON fixture");
    std::fs::write(project.join("audit_result.json"), FORGE_GUARD_AUDIT_JSON)
        .expect("write forge-guard audit fixture");

    let result = run_binary_in(
        &project,
        &[
            "import",
            "--from",
            "slither",
            "slither_out.json",
            "--findings",
            "audit_result.json",
            "--json",
        ],
    );
    assert!(
        result.status.success(),
        "import with --findings should succeed: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be valid JSON: {e}\n{stdout}"));
    assert_eq!(json["tool"], "Slither");
    assert_eq!(json["merged_with_forge_guard"], true);
    assert_eq!(
        json["duplicates_removed"], 1,
        "the Slither reentrancy finding duplicates the forge-guard one"
    );

    let findings = json["findings"].as_array().expect("findings array");
    assert_eq!(
        findings.len(),
        3,
        "2 forge-guard + 2 imported - 1 duplicate"
    );

    // Forge-guard findings are always kept first, with their original ids.
    assert_eq!(findings[0]["id"], "FG-H-001");
    assert_eq!(findings[1]["id"], "FG-M-002");

    // The non-duplicate Slither finding is kept with its imported id.
    let last = &findings[2];
    assert!(
        last["id"].as_str().unwrap().starts_with("SL-"),
        "kept imported finding should use the SL- prefix"
    );
    assert_eq!(last["title"], "uninitialized-state (Low)");
    assert_eq!(last["file"], "contracts/Vault.sol");
    assert_eq!(last["line"], 12);
    assert_eq!(last["severity"], "low");
}

#[test]
fn test_import_missing_findings_file_errors() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("slither_out.json"), SLITHER_RESULTS_JSON)
        .expect("write Slither JSON fixture");

    let result = run_binary_in(
        &project,
        &[
            "import",
            "--from",
            "slither",
            "slither_out.json",
            "--findings",
            "no_such_audit.json",
        ],
    );
    assert!(
        !result.status.success(),
        "import with a missing --findings file should fail"
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("Forge-guard findings file not found"),
        "stderr should explain the missing findings file: {stderr}"
    );
    assert!(
        stderr.contains("no_such_audit.json"),
        "stderr should name the missing file: {stderr}"
    );
}

#[test]
fn test_import_invalid_findings_json_errors() {
    let (_dir, project) = create_temp_project(&[]);
    std::fs::write(project.join("slither_out.json"), SLITHER_RESULTS_JSON)
        .expect("write Slither JSON fixture");
    // File exists but is not a forge-guard AuditResult.
    std::fs::write(project.join("bad_audit.json"), r#"{"foo": "bar"}"#)
        .expect("write invalid audit fixture");

    let result = run_binary_in(
        &project,
        &[
            "import",
            "--from",
            "slither",
            "slither_out.json",
            "--findings",
            "bad_audit.json",
        ],
    );
    assert!(
        !result.status.success(),
        "import with an invalid --findings file should fail"
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("is not a valid forge-guard audit result"),
        "stderr should explain the invalid audit result: {stderr}"
    );
    assert!(
        stderr.contains("bad_audit.json"),
        "stderr should name the offending file: {stderr}"
    );
}

// ─────────────────────────────────────────────────────────────
// 10d. M16 — parallel chain auditing (--all-chains)
// ─────────────────────────────────────────────────────────────

/// Write a forge-guard.toml pointing at the temp project's sources and run the
/// compiled binary with the given audit args.
fn run_binary_audit_in(project: &std::path::Path, args: &[&str]) -> std::process::Output {
    std::fs::write(
        project.join("forge-guard.toml"),
        "src_dirs = [\"test-contracts/secure/src\"]\n",
    )
    .expect("write forge-guard.toml");
    let mut full_args = vec!["audit"];
    full_args.extend_from_slice(args);
    run_binary_in(project, &full_args)
}

#[test]
fn test_audit_all_chains_json_end_to_end() {
    // --all-chains audits every supported EVM chain in parallel and aggregates
    // the results into a single report whose findings are chain-labeled.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(&project, &["--all-chains", "--json"]);
    assert!(
        output.status.success(),
        "audit --all-chains should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be valid JSON: {e}\n{stdout}"));

    assert_eq!(v["chain"], "all", "aggregated result chain should be 'all'");
    let chains = v["chains"].as_array().expect("chains array");
    assert_eq!(
        chains.len(),
        17,
        "all 17 supported EVM chains should be audited"
    );
    let names: Vec<&str> = chains.iter().map(|c| c.as_str().unwrap()).collect();
    assert!(names.contains(&"Ethereum"));
    assert!(names.contains(&"Base"));
    assert!(names.contains(&"Arbitrum"));
    assert!(names.contains(&"Robinhood"));

    // Every finding must be labeled with the chain it was discovered on.
    let findings = v["findings"].as_array().expect("findings array");
    assert!(!findings.is_empty(), "findings should be present");
    for f in findings {
        let chain = f["chain"]
            .as_str()
            .expect("finding should be chain-labeled");
        assert!(
            names.contains(&chain),
            "finding chain '{}' must be one of the audited chains",
            chain
        );
    }
    assert!(v["overall_score"].as_u64().is_some());
    assert!(v["production_ready"].is_boolean());
    assert!(v["deployment_approved"].is_boolean());
}

#[test]
fn test_audit_all_chains_terminal_end_to_end() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(&project, &["--all-chains"]);
    assert!(
        output.status.success(),
        "audit --all-chains (terminal) should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("MULTI-CHAIN REPORT"),
        "terminal output should show the multi-chain report"
    );
    assert!(stdout.contains("Per-Chain Results"));
    assert!(
        stdout.contains("Ethereum"),
        "per-chain table should list Ethereum"
    );
    assert!(stdout.contains("Base"), "per-chain table should list Base");
}

#[test]
fn test_audit_all_chains_max_parallel_flag() {
    // --max-parallel-chains bounds concurrency; the result is unaffected.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(
        &project,
        &["--all-chains", "--max-parallel-chains", "2", "--json"],
    );
    assert!(
        output.status.success(),
        "audit --all-chains --max-parallel-chains 2 should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let v: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    assert_eq!(v["chain"], "all");
    assert_eq!(v["chains"].as_array().unwrap().len(), 17);
}

#[test]
fn test_audit_all_chains_quick_mode() {
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(&project, &["--all-chains", "--quick"]);
    assert!(
        output.status.success(),
        "quick audit --all-chains should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("EXECUTIVE SUMMARY"),
        "quick mode shows the executive summary"
    );
}

#[test]
fn test_audit_all_chains_report_files_written() {
    // --all-chains --report writes the aggregated report files like a
    // single-chain audit does.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(&project, &["--all-chains", "--report"]);
    assert!(
        output.status.success(),
        "audit --all-chains --report should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let report_dir = project.join("reports");
    assert!(report_dir.join("audit.json").exists());
    assert!(report_dir.join("audit.md").exists());
    assert!(report_dir.join("audit.html").exists());

    let md = std::fs::read_to_string(report_dir.join("audit.md")).unwrap();
    assert!(
        md.contains("**Chain:** all"),
        "markdown report should show the aggregate chain"
    );
}

#[test]
fn test_audit_single_chain_json_chains_field() {
    // A regular single-chain audit still reports itself in `chains`.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let output = run_binary_audit_in(&project, &["--chain", "base", "--json"]);
    assert!(
        output.status.success(),
        "audit --chain base should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let v: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    assert_eq!(v["chain"], "base");
    let chains = v["chains"].as_array().unwrap();
    assert_eq!(chains.len(), 1);
    assert_eq!(chains[0], "base");
}

// ─────────────────────────────────────────────────────────────
// 10e. M16 — historical trend tracking (SQLite history db)
// ─────────────────────────────────────────────────────────────

/// Write a forge-guard.toml with a project-local history database so tests
/// never touch the real `~/.forge-guard/history.db`.
fn write_history_config(project: &std::path::Path) {
    std::fs::write(
        project.join("forge-guard.toml"),
        "src_dirs = [\"test-contracts/secure/src\"]\n\
         [history]\n\
         db_path = \"history.db\"\n",
    )
    .expect("write forge-guard.toml");
}

#[test]
fn test_history_record_and_trends_end_to_end() {
    // --enable-history persists the audit; report --history reads it back.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    write_history_config(&project);

    // Record twice so the trend summary (which needs >= 2 entries) shows up.
    for _ in 0..2 {
        let output = run_binary_in(&project, &["audit", "--enable-history"]);
        assert!(
            output.status.success(),
            "audit --enable-history should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("Audit recorded in history database"),
            "stderr should confirm the history write: {stderr}"
        );
    }
    assert!(
        project.join("history.db").exists(),
        "history.db should be created next to the project"
    );

    let output = run_binary_in(&project, &["report", "--history"]);
    assert!(
        output.status.success(),
        "report --history should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("SCORE TREND HISTORY"));
    assert!(
        stdout.contains("ethereum"),
        "trend table should list the chain"
    );
    assert!(stdout.contains("/100"), "trend table should show scores");
    assert!(
        stdout.contains("Score trend"),
        "history report should summarize the trend"
    );
}

#[test]
fn test_history_regression_detects_new_findings() {
    // Record a clean audit, then introduce vulnerabilities WITHOUT recording
    // (default config), so report --regression compares the current audit
    // against the last recorded snapshot and flags the new findings.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    write_history_config(&project);

    let output = run_binary_in(&project, &["audit", "--enable-history"]);
    assert!(output.status.success(), "first audit should succeed");

    // Replace the clean contract with the vulnerable one
    let src = project
        .join("test-contracts")
        .join("secure")
        .join("src")
        .join("Simple.sol");
    std::fs::write(&src, VULNERABLE_CONTRACT).expect("write vulnerable contract");

    let output = run_binary_in(&project, &["audit"]);
    assert!(output.status.success(), "second audit should succeed");

    let output = run_binary_in(&project, &["report", "--regression"]);
    assert!(
        output.status.success(),
        "report --regression should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("REGRESSION REPORT"));
    assert!(
        stdout.contains("New Findings Since Last Audit"),
        "regression report should have a new-findings section"
    );
    assert!(
        stdout.contains("Reentrancy"),
        "new reentrancy finding should be highlighted: {stdout}"
    );
}

#[test]
fn test_history_report_no_history_graceful() {
    // No audits recorded yet → helpful message, not an error.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    write_history_config(&project);

    let output = run_binary_in(&project, &["report", "--history"]);
    assert!(
        output.status.success(),
        "report --history with no data should not fail: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No recorded history"),
        "stderr should explain the empty history: {stderr}"
    );
}

#[test]
fn test_history_regression_no_previous_audit_graceful() {
    // An audit that was never recorded leaves nothing to compare against.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    write_history_config(&project);

    let output = run_binary_in(&project, &["audit"]);
    assert!(output.status.success(), "audit should succeed");

    let output = run_binary_in(&project, &["report", "--regression"]);
    assert!(
        output.status.success(),
        "report --regression with no previous audit should not fail: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No previous audit recorded"),
        "stderr should explain the missing baseline: {stderr}"
    );
}

// ─────────────────────────────────────────────────────────────
// 10f. M16 — dashboard mode (local HTTP server)
// ─────────────────────────────────────────────────────────────

/// Find a free TCP port by binding to port 0 and releasing it.
fn free_port() -> u16 {
    std::net::TcpListener::bind(("127.0.0.1", 0))
        .expect("bind ephemeral port")
        .local_addr()
        .expect("local addr")
        .port()
}

/// Minimal HTTP GET over a raw TCP socket (no extra dependencies).
fn http_get(host: &str, port: u16, path: &str) -> String {
    use std::io::{Read, Write};
    let mut stream =
        std::net::TcpStream::connect((host, port)).expect("connect to dashboard server");
    stream
        .set_read_timeout(Some(std::time::Duration::from_secs(5)))
        .expect("set timeout");
    let req = format!(
        "GET {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n\r\n",
        path, host, port
    );
    stream.write_all(req.as_bytes()).expect("write request");
    let mut buf = String::new();
    stream.read_to_string(&mut buf).expect("read response");
    buf
}

#[test]
fn test_dashboard_serves_page_and_audit_api() {
    // Audit a clean project, then start the dashboard and verify both the
    // HTML page and the /api/audit JSON endpoint respond.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    std::fs::write(
        project.join("forge-guard.toml"),
        "src_dirs = [\"test-contracts/secure/src\"]\n",
    )
    .expect("write forge-guard.toml");
    let output = run_binary_in(&project, &["audit"]);
    assert!(
        output.status.success(),
        "audit should succeed before dashboard: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        project
            .join(".forge-guard-cache")
            .join("last_audit.json")
            .exists(),
        "audit should write last_audit.json"
    );

    let port = free_port();
    let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_forge-guard"))
        .args([
            "dashboard",
            "--port",
            &port.to_string(),
            "--project",
            project.to_str().unwrap(),
        ])
        .spawn()
        .expect("spawn dashboard");

    // Wait for the server to accept connections (max ~5s).
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
            break;
        }
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("dashboard server did not start in time");
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    // The dashboard HTML page.
    let page = http_get("127.0.0.1", port, "/");
    assert!(
        page.contains("200 OK"),
        "dashboard should return HTTP 200: {page}"
    );
    assert!(
        page.contains("Forge Guard") && page.contains("Dashboard"),
        "page should be the dashboard: {}",
        &page[..page.len().min(200)]
    );

    // The audit result JSON.
    let api = http_get("127.0.0.1", port, "/api/audit");
    assert!(
        api.contains("200 OK"),
        "api should return HTTP 200: {}",
        &api[..api.len().min(200)]
    );
    let body = api.split("\r\n\r\n").nth(1).unwrap_or("");
    let v: serde_json::Value =
        serde_json::from_str(body).expect("api body should be valid audit JSON");
    assert_eq!(v["chain"], "ethereum");
    assert!(v["findings"].is_array());

    let _ = child.kill();
    let _ = child.wait();
}

#[test]
fn test_dashboard_api_404_without_audit() {
    // Without a prior audit the API should return 404 with a hint.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    let port = free_port();
    let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_forge-guard"))
        .args([
            "dashboard",
            "--port",
            &port.to_string(),
            "--project",
            project.to_str().unwrap(),
        ])
        .spawn()
        .expect("spawn dashboard");

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
            break;
        }
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("dashboard server did not start in time");
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    let api = http_get("127.0.0.1", port, "/api/audit");
    assert!(
        api.contains("404 Not Found"),
        "api without an audit should be 404: {}",
        &api[..api.len().min(200)]
    );
    assert!(
        api.contains("No audit result"),
        "404 body should hint: {api}"
    );

    let _ = child.kill();
    let _ = child.wait();
}

/// Open a WebSocket connection and read one text frame.
/// Returns `None` if no frame arrives within the timeout.
fn ws_read_first_frame(port: u16, timeout_ms: u64) -> Option<String> {
    use std::io::{Read, Write};
    let mut stream =
        std::net::TcpStream::connect(("127.0.0.1", port)).expect("connect to dashboard");
    stream
        .set_read_timeout(Some(std::time::Duration::from_millis(timeout_ms)))
        .expect("set timeout");

    // Handshake
    let key = "dGhlIHNhbXBsZSBub25jZQ=="; // fixed base64 nonce (RFC 6455 example)
    let req = format!(
        "GET /ws HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {}\r\nSec-WebSocket-Version: 13\r\n\r\n",
        port, key
    );
    stream
        .write_all(req.as_bytes())
        .expect("write ws handshake");

    // Read the HTTP response headers. The first WS frame often arrives in the
    // same TCP segment, so keep any leftover bytes after the header terminator.
    let mut buf = Vec::with_capacity(8192);
    let mut leftover = 0usize;
    loop {
        let mut chunk = [0u8; 4096];
        let n = stream.read(&mut chunk).expect("read ws handshake");
        if n == 0 {
            return None;
        }
        buf.extend_from_slice(&chunk[..n]);
        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
            leftover = pos + 4;
            let headers = String::from_utf8_lossy(&buf[..pos + 4]);
            assert!(
                headers.contains("101 Switching Protocols"),
                "ws upgrade should return 101: {}",
                headers.lines().next().unwrap_or("")
            );
            break;
        }
    }

    // Read one text frame (server-to-client frames are unmasked), consuming
    // any bytes that already arrived after the handshake headers.
    let mut frame = vec![0u8; 2];
    read_ws_bytes(&mut stream, &mut buf, &mut leftover, &mut frame);
    let opcode = frame[0] & 0x0f;
    let len = (frame[1] & 0x7f) as usize;
    let mut payload_len = len;
    if len == 126 {
        let mut ext = [0u8; 2];
        read_ws_bytes(&mut stream, &mut buf, &mut leftover, &mut ext);
        payload_len = u16::from_be_bytes(ext) as usize;
    } else if len == 127 {
        let mut ext = [0u8; 8];
        read_ws_bytes(&mut stream, &mut buf, &mut leftover, &mut ext);
        payload_len = u64::from_be_bytes(ext) as usize;
    }
    let mut payload = vec![0u8; payload_len];
    read_ws_bytes(&mut stream, &mut buf, &mut leftover, &mut payload);

    if opcode == 0x1 {
        Some(String::from_utf8(payload).expect("ws text frame utf8"))
    } else {
        None
    }
}

/// Read `out.len()` bytes from the stream, first consuming any leftover bytes
/// buffered after the handshake headers.
fn read_ws_bytes(
    stream: &mut std::net::TcpStream,
    buf: &mut Vec<u8>,
    leftover: &mut usize,
    out: &mut [u8],
) {
    use std::io::Read;
    let mut filled = 0;
    // Consume buffered leftovers first.
    let from_buf = (*leftover..buf.len()).len().min(out.len());
    out[..from_buf].copy_from_slice(&buf[*leftover..*leftover + from_buf]);
    *leftover += from_buf;
    filled += from_buf;
    while filled < out.len() {
        let n = stream
            .read(&mut out[filled..])
            .expect("read ws frame bytes");
        if n == 0 {
            break;
        }
        filled += n;
    }
}

#[test]
fn test_dashboard_websocket_pushes_audit_result() {
    // After an audit, connecting to /ws should immediately receive the audit
    // result as a JSON text frame (the WebSocket live-update channel).
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    std::fs::write(
        project.join("forge-guard.toml"),
        "src_dirs = [\"test-contracts/secure/src\"]\n",
    )
    .expect("write forge-guard.toml");
    let output = run_binary_in(&project, &["audit"]);
    assert!(
        output.status.success(),
        "audit should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let port = free_port();
    let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_forge-guard"))
        .args([
            "dashboard",
            "--port",
            &port.to_string(),
            "--project",
            project.to_str().unwrap(),
        ])
        .spawn()
        .expect("spawn dashboard");

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
            break;
        }
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("dashboard server did not start in time");
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    let frame = ws_read_first_frame(port, 3000).expect("expected a ws text frame");
    let v: serde_json::Value = serde_json::from_str(&frame).expect("ws frame should be audit JSON");
    assert_eq!(v["chain"], "ethereum");
    assert!(v["findings"].is_array());

    let _ = child.kill();
    let _ = child.wait();
}

#[test]
fn test_dashboard_websocket_broadcasts_reaudit() {
    // With --watch, editing a source file triggers a re-audit, which updates
    // last_audit.json and is broadcast to connected WebSocket clients.
    let (_dir, project) = create_temp_project(&[("Simple.sol", CLEAN_CONTRACT)]);
    std::fs::write(
        project.join("forge-guard.toml"),
        "src_dirs = [\"test-contracts/secure/src\"]\n",
    )
    .expect("write forge-guard.toml");
    let output = run_binary_in(&project, &["audit"]);
    assert!(
        output.status.success(),
        "initial audit should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let port = free_port();
    let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_forge-guard"))
        .args([
            "dashboard",
            "--port",
            &port.to_string(),
            "--project",
            project.to_str().unwrap(),
            "--watch",
            "--dirs",
            "test-contracts/secure/src",
        ])
        .spawn()
        .expect("spawn dashboard with --watch");

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
            break;
        }
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("dashboard server did not start in time");
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    // Connect; receive the initial result.
    let first = ws_read_first_frame(port, 3000).expect("initial ws frame");
    let v: serde_json::Value = serde_json::from_str(&first).expect("initial frame is JSON");
    assert!(v["findings"].is_array());

    // Touch the contract (append a comment) so the watcher re-audits.
    let contract = project
        .join("test-contracts")
        .join("secure")
        .join("src")
        .join("Simple.sol");
    let mut content = std::fs::read_to_string(&contract).expect("read contract");
    content.push_str("\n// dashboard re-audit\n");
    std::fs::write(&contract, content).expect("touch contract");

    // The re-audit writes a fresh last_audit.json; the dashboard broadcasts it.
    let second = ws_read_first_frame(port, 15000).expect("broadcast after re-audit");
    let v2: serde_json::Value = serde_json::from_str(&second).expect("broadcast frame is JSON");
    assert!(v2["findings"].is_array());

    let _ = child.kill();
    let _ = child.wait();
}