truent-cli 0.6.0

Truent: multi-chain smart contract security analyzer with static analysis, invariant checking, and vulnerability detection for Solana, EVM, and Move programs.
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
#![deny(unsafe_code)]
#![allow(dead_code)] // Functions used in future feature development
#![allow(missing_docs)] // CLI is self-documenting via clap help

//! Truent CLI: Multi-chain smart contract invariant enforcement tool.
//!
//! Production-grade terminal UI with professional styling and comprehensive
//! analysis capabilities for smart contract security.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::time::Instant;

// UI module
mod ui;
use ui::*;

// Import analyzers
use truent_analyzer_evm::EvmAnalyzer;
use truent_analyzer_move::MoveAnalyzer;
use truent_analyzer_solana::SolanaAnalyzer;
use truent_analyzer_soroban::SorobanAnalyzer;
use truent_core::traits::ChainAnalyzer;
use truent_core::{CodeFuzzer, Finding};
use truent_library::InvariantLibrary;

// ============================================================================
// CLI STRUCTURE
// ============================================================================

/// Truent: Production-grade multi-chain invariant analysis tool.
#[derive(Parser)]
#[command(
    name = "truent",
    about = "Enforce invariants on smart contracts across Solana, EVM, Move, and Soroban",
    version = env!("CARGO_PKG_VERSION"),
    author = "Truent Contributors"
)]
struct Cli {
    /// Enable verbose output.
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Suppress all non-error output.
    #[arg(long, global = true)]
    quiet: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Analyze contracts for invariant violations (recommended: use 'scan' instead).
    Check(CheckArgs),
    /// Scan contracts with full invariant enforcement (primary command).
    Scan(ScanArgs),
    /// Generate a report from analysis results.
    Report(ReportArgs),
    /// Initialize a .truent.toml configuration file.
    Init(InitArgs),
    /// Check that all Truent components are working correctly.
    Doctor(DoctorArgs),
    /// Display exploit registry.
    Registry(RegistryArgs),
    /// Display compiled invariants.
    Invariants(InvariantsArgs),
    /// Run fuzzer on contract invariants.
    Fuzz(FuzzArgs),
}

/// Arguments for the `doctor` subcommand.
#[derive(Parser)]
struct DoctorArgs {
    /// Output format.
    #[arg(long, value_enum, default_value = "text")]
    format: FormatArg,

    /// Output file.
    #[arg(long)]
    output: Option<PathBuf>,
}

/// Arguments for the `check` subcommand.
#[derive(Parser)]
struct CheckArgs {
    /// Path to analyze (file or directory).
    path: PathBuf,

    /// Blockchain to analyze.
    #[arg(long, value_enum, default_value = "evm")]
    chain: ChainArg,

    /// Fail if violations at or above this severity are found.
    #[arg(long, value_enum, default_value = "low")]
    fail_on: SeverityArg,

    /// Also fail on unproven leads, not just results reproduced by execution.
    ///
    /// Off by default: a lead is a pattern match that was never executed, and
    /// blocking a deploy on one trains teams to bypass the gate.
    #[arg(long, default_value_t = false)]
    fail_on_leads: bool,

    /// Output format.
    #[arg(long, value_enum, default_value = "text")]
    format: FormatArg,

    /// Output file (for non-text formats).
    #[arg(long)]
    output: Option<PathBuf>,

    /// Configuration file.
    #[arg(long)]
    config: Option<PathBuf>,

    /// Random seed for reproducible analysis (default: 42).
    #[arg(long)]
    seed: Option<u64>,
}

/// Arguments for the `scan` subcommand (enhanced version of check).
#[derive(Parser)]
struct ScanArgs {
    /// Path to analyze (file or directory).
    path: PathBuf,

    /// Blockchain to analyze.
    #[arg(long, value_enum, default_value = "evm")]
    chain: ChainArg,

    /// Output format.
    #[arg(long, value_enum, default_value = "text")]
    output: FormatArg,

    /// Output file (for non-text formats).
    #[arg(long)]
    file: Option<PathBuf>,

    /// Minimum severity to report.
    #[arg(long, value_enum)]
    severity: Option<SeverityArg>,

    /// Filter by specific invariant ID (can be used multiple times).
    #[arg(long)]
    invariant: Vec<String>,

    /// RPC URL for on-chain verification (e.g., bridge config checks).
    #[arg(long)]
    rpc: Option<String>,

    /// Fail the scan if any issues at or above this severity are found.
    #[arg(long, value_enum, default_value = "critical")]
    fail_on: SeverityArg,

    /// Also fail on unproven leads, not just results reproduced by execution.
    ///
    /// Off by default: a lead is a pattern match that was never executed, and
    /// blocking a deploy on one trains teams to bypass the gate.
    #[arg(long, default_value_t = false)]
    fail_on_leads: bool,

    /// Use parallel scanning with rayon (thread pool).
    #[arg(long)]
    parallel: bool,

    /// Disable ANSI color output.
    #[arg(long)]
    no_color: bool,

    /// Configuration file.
    #[arg(long)]
    config: Option<PathBuf>,
}

/// Arguments for the `registry` subcommand.
#[derive(Parser)]
struct RegistryArgs {
    /// Subcommand for registry operations.
    #[command(subcommand)]
    action: RegistryAction,
}

#[derive(Subcommand)]
enum RegistryAction {
    /// List all known exploits in the registry.
    List {
        /// Filter by chain (evm, solana, move).
        #[arg(long)]
        chain: Option<String>,
        /// Output format.
        #[arg(long, value_enum, default_value = "text")]
        format: FormatArg,
    },
    /// Show details of a specific exploit.
    Show {
        /// Exploit ID (e.g., "euler-finance-2023").
        id: String,
        /// Output format.
        #[arg(long, value_enum, default_value = "text")]
        format: FormatArg,
    },
}

/// Arguments for the `invariants` subcommand.
#[derive(Parser)]
struct InvariantsArgs {
    /// Subcommand for invariants operations.
    #[command(subcommand)]
    action: InvariantsAction,
}

#[derive(Subcommand)]
enum InvariantsAction {
    /// List all compiled invariants.
    List {
        /// Filter by chain (evm, solana, move).
        #[arg(long)]
        chain: Option<String>,
        /// Filter by severity.
        #[arg(long)]
        severity: Option<SeverityArg>,
        /// Output format.
        #[arg(long, value_enum, default_value = "text")]
        format: FormatArg,
    },
    /// Show details of a specific invariant.
    Show {
        /// Invariant ID (e.g., "evm_reentrancy_classic").
        id: String,
        /// Output format.
        #[arg(long, value_enum, default_value = "text")]
        format: FormatArg,
    },
}

/// Arguments for the `fuzz` subcommand.
#[derive(Parser)]
struct FuzzArgs {
    /// Contract file or directory to fuzz. Omit when using --address to
    /// fuzz an already-deployed contract by fetching its bytecode instead
    /// of reading local source.
    path: Option<PathBuf>,

    /// Blockchain to fuzz for.
    #[arg(long, value_enum, default_value = "evm")]
    chain: ChainArg,

    /// Maximum call sequence depth for fuzzer.
    #[arg(long, default_value = "10")]
    depth: usize,

    /// Number of iterations to run.
    #[arg(long, default_value = "10000")]
    iterations: u32,

    /// Random seed for reproducibility.
    #[arg(long)]
    seed: Option<u64>,

    /// Output format.
    #[arg(long, value_enum, default_value = "text")]
    output: FormatArg,

    /// Output file.
    #[arg(long)]
    file: Option<PathBuf>,

    /// Run the dynamic/coverage-guided invariant fuzzer (deploys the
    /// contract in-memory via revm, generates call sequences, and checks
    /// auto-detected invariants after every call) instead of the default
    /// source-mutation crash fuzzer. EVM only for now.
    #[arg(long)]
    dynamic: bool,

    /// Fuzz an already-deployed contract by address instead of local
    /// source: fetches its bytecode via --rpc-url and probes it against
    /// known ERC20/Ownable selectors (no ABI available for an unverified
    /// contract). Only valid with --dynamic; requires --rpc-url. Does not
    /// fork the contract's on-chain storage — only its code.
    #[arg(long, conflicts_with = "path")]
    address: Option<String>,

    /// JSON-RPC endpoint to fetch bytecode from when using --address.
    #[arg(long, requires = "address")]
    rpc_url: Option<String>,

    /// Solana fuzz plan (JSON): the genesis accounts, account pool, pins and
    /// invariants that an IDL cannot express. Required for
    /// `--dynamic --chain solana`, where `path` is the program's Anchor IDL.
    #[arg(long)]
    plan: Option<PathBuf>,

    /// Truent DSL file (`.invar`) of properties to check after every call.
    ///
    /// Auto-detection only recognises shapes it already knows, so the
    /// properties that decide whether a specific protocol is correct — is it
    /// solvent, can a provider always exit — have to be stated. Each free
    /// variable binds to a zero-argument view of the same name on the
    /// contract; a variable that cannot be bound is an error, never a
    /// silently skipped check.
    #[arg(long)]
    invariants: Option<PathBuf>,
}

/// Arguments for the `report` subcommand.
#[derive(Parser)]
struct ReportArgs {
    /// Input results file.
    #[arg(long)]
    input: PathBuf,

    /// Output format.
    #[arg(long, value_enum, default_value = "text")]
    format: FormatArg,

    /// Output file.
    #[arg(long)]
    output: Option<PathBuf>,
}

/// Arguments for the `init` subcommand.
#[derive(Parser)]
struct InitArgs {
    /// Project directory.
    #[arg(default_value = ".")]
    path: PathBuf,
}

/// Supported blockchain networks.
#[derive(ValueEnum, Clone, Debug)]
enum ChainArg {
    /// Ethereum and EVM-compatible chains.
    Evm,
    /// Solana.
    Solana,
    /// Move (Aptos, Sui).
    Move,
    /// Soroban (Stellar).
    Soroban,
}

/// Violation severity levels.
#[derive(ValueEnum, Clone, Debug)]
enum SeverityArg {
    /// Low severity issues.
    Low,
    /// Medium severity issues.
    Medium,
    /// High severity issues.
    High,
    /// Critical severity issues.
    Critical,
}

/// Output format options.
#[derive(ValueEnum, Clone, Debug)]
enum FormatArg {
    /// Human-readable text with colors and boxes.
    Text,
    /// JSON (one object per line).
    Json,
    /// HTML report.
    Html,
}

// ============================================================================
// MAIN
// ============================================================================

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Show banner on first launch if TTY
    if is_tty() {
        eprintln!("{}", render_banner(env!("CARGO_PKG_VERSION")));
    }

    match cli.command {
        Commands::Check(args) => cmd_check(args, cli.quiet, cli.verbose)?,
        Commands::Scan(args) => cmd_scan(args, cli.quiet, cli.verbose)?,
        Commands::Report(args) => cmd_report(args, cli.quiet)?,
        Commands::Init(args) => cmd_init(args, cli.quiet)?,
        Commands::Doctor(args) => cmd_doctor(args, cli.quiet)?,
        Commands::Registry(args) => cmd_registry(args, cli.quiet)?,
        Commands::Invariants(args) => cmd_invariants(args, cli.quiet)?,
        Commands::Fuzz(args) => cmd_fuzz(args, cli.quiet, cli.verbose)?,
    }

    Ok(())
}

// ============================================================================
// COMMAND HANDLERS
// ============================================================================

/// Handle the `check` subcommand.
fn cmd_check(args: CheckArgs, quiet: bool, verbose: bool) -> Result<()> {
    let start_time = Instant::now();

    // Set random seed for reproducibility
    let seed = args.seed.unwrap_or(42);
    if verbose && !quiet {
        eprintln!("Setting random seed to: {}", seed);
    }

    let chain_name = match &args.chain {
        ChainArg::Evm => "EVM",
        ChainArg::Solana => "Solana",
        ChainArg::Move => "Move",
        ChainArg::Soroban => "Soroban",
    };

    // Convert config path to String for header
    let config_str = args
        .config
        .as_ref()
        .map(|p| p.to_string_lossy().to_string());
    let config_ref = config_str.as_deref();

    // Display header (only for text format)
    if !quiet && matches!(args.format, FormatArg::Text) {
        println!(
            "{}",
            render_check_header(
                &args.path.display().to_string(),
                chain_name,
                config_ref,
                args.config.as_ref().map(|p| p.exists()).unwrap_or(false)
            )
        );
    }

    // Create spinner (only for text format)
    let spinner = if !quiet && matches!(args.format, FormatArg::Text) {
        Some(Spinner::start(&format!(
            "Analyzing {}...",
            args.path.display()
        )))
    } else {
        None
    };

    // Run actual analysis
    let violations = match run_analysis(&args.path, &args.chain, verbose) {
        Ok(vios) => vios,
        Err(e) => {
            if let Some(s) = spinner {
                s.stop_with_failure(&e.to_string());
            }
            return Err(e);
        }
    };

    let duration_secs = start_time.elapsed().as_secs_f64();

    // Count violations by severity
    let (critical, high, medium, low) = count_violations_by_severity(&violations);
    // Approximate count of live detectors for this chain (a single detector can produce
    // multiple findings, so this is a lower bound, not an exact "checks run" count).
    let detector_count = match args.chain {
        ChainArg::Evm => 44,
        ChainArg::Solana => 11,
        ChainArg::Move => 7,
        ChainArg::Soroban => 9,
    };
    let total_checks = detector_count.max(violations.len());
    let passed = total_checks.saturating_sub(violations.len());

    // Build summary
    let proven = violations.iter().filter(|v| v.evidence.is_proven()).count();
    let leads = violations.len() - proven;

    let summary = AnalysisSummary {
        target: args.path.display().to_string(),
        chain: chain_name.to_string(),
        total_checks,
        violations: violations.len(),
        passed,
        proven,
        leads,
        suppressed: 0,
        duration_secs,
        severity_breakdown: SeverityBreakdown {
            critical,
            high,
            medium,
            low,
        },
    };

    // Stop spinner with success
    if let Some(s) = spinner {
        s.stop_with_success(&format!("{} checks in {:.1}s", total_checks, duration_secs));
    }

    // Handle different output formats
    match args.format {
        FormatArg::Text => {
            // Build text report
            let mut report_text = String::new();

            // Display violations
            if !violations.is_empty() {
                report_text.push_str(&render_violations(&violations));
                report_text.push('\n');
            }

            // Display passed checks (verbose mode)
            if verbose {
                let passed_check_names = vec![
                    "balance_conservation".to_string(),
                    "no_integer_overflow".to_string(),
                    "owner_only_withdraw".to_string(),
                    "access_control_present".to_string(),
                    "arithmetic_overflow".to_string(),
                    "missing_signer_check".to_string(),
                ];
                report_text.push_str(&render_passed_checks(&passed_check_names));
                report_text.push('\n');
            }

            // Display summary
            report_text.push_str(&render_summary(&summary));

            if let Some(output_path) = args.output {
                // Write to file
                std::fs::write(&output_path, &report_text)?;
                if !quiet {
                    eprintln!("✓ Report written to {}", output_path.display());
                }
            } else {
                // Write to stdout
                if !quiet {
                    println!("{}", report_text);
                }
            }
        }
        FormatArg::Json => {
            // Create JSON report
            let report = json!({
                "version": env!("CARGO_PKG_VERSION"),
                "chain": summary.chain,
                "target": summary.target,
                "duration_ms": (summary.duration_secs * 1000.0) as u64,
                "summary": {
                    "total_checks": summary.total_checks,
                    "violations": summary.violations,
                    "critical": summary.severity_breakdown.critical,
                    "high": summary.severity_breakdown.high,
                    "medium": summary.severity_breakdown.medium,
                    "low": summary.severity_breakdown.low,
                    "passed": summary.passed,
                    "suppressed": summary.suppressed,
                },
                "violations": violations,
            });

            let output_json = serde_json::to_string_pretty(&report)?;

            if let Some(output_path) = args.output {
                // Write to file
                std::fs::write(&output_path, &output_json)?;
                if !quiet {
                    eprintln!("✓ Report written to {}", output_path.display());
                }
            } else {
                // Write to stdout
                println!("{}", output_json);
            }
        }
        FormatArg::Html => {
            // Generate HTML report
            let html_report = generate_html_report(&summary, &violations);

            if let Some(output_path) = args.output {
                // Write to file
                std::fs::write(&output_path, &html_report)?;
                if !quiet {
                    eprintln!("✓ HTML report written to {}", output_path.display());
                }
            } else {
                // Write to stdout
                println!("{}", html_report);
            }
        }
    }

    // Exit non-zero only for results that were actually reproduced, at or
    // above --fail-on.
    //
    // A lead is a pattern match nobody executed; failing a build on one asks
    // the team to treat a guess as a defect, and the first false positive
    // teaches them to bypass the gate entirely. Leads are reported and
    // surfaced in the summary, but only a proven violation blocks. Pass
    // --fail-on-leads to gate on unproven results too.
    let fail_rank = severity_arg_rank(&args.fail_on);
    let blocking = violations.iter().any(|v| {
        severity_rank(&v.severity) >= fail_rank && (v.evidence.is_proven() || args.fail_on_leads)
    });
    if blocking {
        std::process::exit(1);
    }

    Ok(())
}

/// Generate an HTML report of the security analysis.
fn generate_html_report(summary: &AnalysisSummary, violations: &[Violation]) -> String {
    let violation_rows = violations
        .iter()
        .map(|v| {
            format!(
                "<tr><td>{}</td><td>{}</td><td>{}</td><td><code>{}</code></td></tr>",
                v.invariant_id,
                v.severity,
                v.location,
                v.message.replace("<", "&lt;").replace(">", "&gt;")
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    #[allow(clippy::useless_vec)]
    let severity_colors = vec![
        format!(
            "<li><strong>Critical:</strong> {} findings</li>",
            summary.severity_breakdown.critical
        ),
        format!(
            "<li><strong>High:</strong> {} findings</li>",
            summary.severity_breakdown.high
        ),
        format!(
            "<li><strong>Medium:</strong> {} findings</li>",
            summary.severity_breakdown.medium
        ),
        format!(
            "<li><strong>Low:</strong> {} findings</li>",
            summary.severity_breakdown.low
        ),
    ];

    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Truent Security Report</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            margin: 20px;
            background-color: #f6f8fb;
            color: #24292e;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #0366d6;
            border-bottom: 2px solid #e1e4e8;
            padding-bottom: 10px;
        }}
        .summary {{
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin: 20px 0;
        }}
        .summary-box {{
            background: #f6f8fa;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #0366d6;
        }}
        .summary-box strong {{
            font-size: 18px;
            color: #0366d6;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }}
        th {{
            background-color: #f6f8fa;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #e1e4e8;
        }}
        td {{
            padding: 12px;
            border-bottom: 1px solid #e1e4e8;
        }}
        tr:hover {{
            background-color: #f6f8fa;
        }}
        .severity-critical {{
            color: #d73a49;
            font-weight: 600;
        }}
        .severity-high {{
            color: #fd7e14;
            font-weight: 600;
        }}
        .severity-medium {{
            color: #ffc107;
            font-weight: 600;
        }}
        .severity-low {{
            color: #6f42c1;
            font-weight: 600;
        }}
        .timestamp {{
            color: #6a737d;
            font-size: 12px;
            margin-top: 20px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 Truent Security Analysis Report</h1>
        
        <div class="summary">
            <div class="summary-box">
                <strong>Target:</strong> {}<br>
                <strong>Chain:</strong> {}<br>
                <strong>Duration:</strong> {:.2}s
            </div>
            <div class="summary-box">
                <strong>Total Checks:</strong> {}<br>
                <strong>Violations Found:</strong> {}<br>
                <strong>Passed:</strong> {}
            </div>
        </div>

        <h2>Severity Breakdown</h2>
        <ul>
            {}
        </ul>

        <h2>Findings</h2>
        {}
        
        <table>
            <thead>
                <tr>
                    <th>Invariant</th>
                    <th>Severity</th>
                    <th>Location</th>
                    <th>Message</th>
                </tr>
            </thead>
            <tbody>
                {}
            </tbody>
        </table>

        <div class="timestamp">
            Generated by Truent v{}
        </div>
    </div>
</body>
</html>"#,
        summary.target,
        summary.chain,
        summary.duration_secs,
        summary.total_checks,
        summary.violations,
        summary.passed,
        severity_colors.join("\n"),
        if violations.is_empty() {
            "<p style=\"color: #28a745; font-weight: 600;\">✓ No security violations found!</p>"
                .to_string()
        } else {
            format!(
                "<p style=\"color: #d73a49;\">⚠️ {} security violations detected</p>",
                violations.len()
            )
        },
        violation_rows,
        env!("CARGO_PKG_VERSION"),
    )
}

/// File extension associated with each chain's source files.
fn chain_extension(chain: &ChainArg) -> &'static str {
    match chain {
        ChainArg::Evm => "sol",
        ChainArg::Solana => "rs",
        ChainArg::Move => "move",
        ChainArg::Soroban => "rs",
    }
}

/// Recursively collect source files matching the chain's extension under `dir`.
fn collect_source_files(dir: &Path, extension: &str, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in std::fs::read_dir(dir)
        .with_context(|| format!("Failed to read directory {}", dir.display()))?
    {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            // Skip common non-source directories to avoid scanning dependency trees.
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if matches!(
                name,
                "node_modules" | "target" | ".git" | "build" | "dist" | "out"
            ) {
                continue;
            }
            collect_source_files(&path, extension, out)?;
        } else if path.extension().and_then(|e| e.to_str()) == Some(extension) {
            out.push(path);
        }
    }
    Ok(())
}

/// Run every live pattern detector for `chain` against a single file's source text.
fn run_detectors_on_file(chain: &ChainArg, path: &Path) -> Result<Vec<Finding>> {
    let source = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    let file_path = path.to_string_lossy().to_string();

    let findings = match chain {
        ChainArg::Evm => truent_analyzer_evm::detectors::run_all_detectors(&source, &file_path),
        ChainArg::Solana => truent_analyzer_solana::run_all_detectors(&source, &file_path),
        ChainArg::Move => truent_analyzer_move::run_all_detectors(&source, &file_path),
        ChainArg::Soroban => truent_analyzer_soroban::run_all_detectors(&source, &file_path),
    };

    Ok(findings)
}

/// Convert a title-cased, human-readable name out of a detector's invariant_id,
/// e.g. "evm_missing_post_state_health_check" -> "Missing Post State Health Check".
fn invariant_id_to_title(invariant_id: &str) -> String {
    let stripped = invariant_id
        .strip_prefix("evm_")
        .or_else(|| invariant_id.strip_prefix("sol_"))
        .or_else(|| invariant_id.strip_prefix("move_"))
        .unwrap_or(invariant_id);

    stripped
        .split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Convert a detector `Finding` into a display/report-ready `Violation`.
fn finding_to_violation(finding: &Finding, index: usize, total: usize) -> Violation {
    let reference = get_vulnerability_reference(&finding.invariant_id);
    Violation {
        index,
        total,
        severity: finding.severity.name().to_lowercase(),
        title: invariant_id_to_title(&finding.invariant_id),
        invariant_id: finding.invariant_id.clone(),
        location: format!("{}:{}", finding.file, finding.line),
        cwe: map_invariant_to_cwe(&finding.invariant_id),
        message: finding.message.clone(),
        recommendation: format!(
            "Review this finding and apply the recommended fix. Details: {}",
            reference
        ),
        reference,
        code_snippet: finding
            .source_fragment
            .clone()
            .unwrap_or_else(|| finding.snippet.clone()),
        evidence: finding.evidence,
    }
}

/// Run actual analysis on the source file or directory, returning display-ready violations.
fn run_analysis(source_path: &Path, chain: &ChainArg, verbose: bool) -> Result<Vec<Violation>> {
    // Check if path exists
    if !source_path.exists() {
        return Err(anyhow::anyhow!("Path not found: {}", source_path.display()));
    }

    let extension = chain_extension(chain);
    let files = if source_path.is_dir() {
        let mut files = Vec::new();
        collect_source_files(source_path, extension, &mut files)?;
        files
    } else {
        vec![source_path.to_path_buf()]
    };

    if files.is_empty() {
        if verbose {
            eprintln!(
                "⚠ No .{} files found under {}",
                extension,
                source_path.display()
            );
        }
        return Ok(Vec::new());
    }

    let mut findings = Vec::new();
    for file in &files {
        findings.extend(run_detectors_on_file(chain, file)?);
    }

    if verbose {
        eprintln!(
            "✓ Scanned {} file(s), {} findings from pattern detectors",
            files.len(),
            findings.len()
        );
    }

    // Best-effort structural analysis (function/state-var counts) for diagnostics only.
    // This requires solc (EVM) to be installed; never let its absence block detection,
    // since the detectors above operate on raw source text and don't need it.
    if verbose {
        if let Some(first_file) = files.first() {
            let structural = match chain {
                ChainArg::Evm => EvmAnalyzer.analyze(first_file),
                ChainArg::Solana => SolanaAnalyzer.analyze(first_file),
                ChainArg::Move => MoveAnalyzer.analyze(first_file),
                ChainArg::Soroban => SorobanAnalyzer.analyze(first_file),
            };
            match structural {
                Ok(program) => eprintln!(
                    "✓ Structural analysis: {} functions in {}",
                    program.functions.len(),
                    first_file.display()
                ),
                Err(e) => eprintln!("⚠ Structural analysis unavailable ({e}); detectors still ran"),
            }
        }

        // Load real built-in invariants for this chain (informational for now; the
        // invariant library's default expressions aren't yet wired into detection).
        let chain_name = match chain {
            ChainArg::Evm => "evm",
            ChainArg::Solana => "solana",
            ChainArg::Move => "move",
            ChainArg::Soroban => "soroban",
        };
        let lib = InvariantLibrary::with_defaults(chain_name);
        eprintln!(
            "✓ Loaded {} built-in invariant definitions for {}",
            lib.all().len(),
            chain_name
        );
    }

    let total = findings.len();
    let violations: Vec<Violation> = findings
        .iter()
        .enumerate()
        .map(|(i, f)| finding_to_violation(f, i + 1, total))
        .collect();

    Ok(violations)
}

/// Generate detailed violation information with actionable recommendations.
fn generate_detailed_violation_info(
    program: &truent_core::model::ProgramModel,
    invariant: &truent_core::model::Invariant,
    confidence: f64,
) -> (String, String) {
    let invariant_lower = invariant.name.to_lowercase();
    let is_solana = program.chain.to_lowercase().contains("solana");

    // Solana-specific violation details
    if is_solana {
        if invariant_lower.contains("lamport") {
            let message = format!(
                "Detected unsafe lamport manipulation with {:.0}% confidence. Direct arithmetic on account lamports without validation or safety checks detected.",
                confidence * 100.0
            );
            let recommendation =
                "CRITICAL: Never directly manipulate lamports without proper validation.\n\
                 Fix: Use checked arithmetic and validate account signer status before modifying lamports:\n\
                 ✓ Require account to be a signer: #[account(mut, signer)]\n\
                 ✓ Use checked_add/checked_sub instead of saturating_add/sub\n\
                 ✓ Validate minimum balance after transfer\n\
                 ✓ Consider using Solana's system program for transfers\n\
                 Reference: https://docs.solana.com/developing/programming-model/transactions"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("overflow") || invariant_lower.contains("integer_overflow") {
            let message = format!(
                "Detected unchecked arithmetic operation with {:.0}% confidence. Potential integer overflow/underflow risk found.",
                confidence * 100.0
            );
            let recommendation =
                "Use overflow-checked arithmetic for all calculations:\n\
                 Available options:\n\
                 1. Use checked_add/checked_sub/checked_mul/checked_div that return Option<T>\n\
                 2. Use wrapping_add/wrapping_sub for intentional wrapping behavior (rare, always document)\n\
                 3. For Solana tokens, use SPL Token's u128 multiplication internally\n\
                 4. Add overflow checks with: require!(value <= MAX_ALLOWED, ErrorCode::Overflow)\n\
                 Example fix:\n\
                   let result = amount.checked_add(fee).ok_or(ErrorCode::Overflow)?;\n\
                 Reference: https://github.com/solana-labs/spl-token/blob/master/program/src/instruction.rs"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("signer") {
            let message = format!(
                "Detected missing signer verification with {:.0}% confidence. Function may accept unauthorized callers.",
                confidence * 100.0
            );
            let recommendation =
                "Ensure all sensitive operations require proper signer verification:\n\
                 Required fixes:\n\
                 1. Mark sensitive account parameters as signers: #[account(mut, signer)]\n\
                 2. Add explicit checks: require!(account.is_signer, ErrorCode::MissingSigner)\n\
                 3. For specific authorities, validate: require!(authority.key == EXPECTED_AUTH, ...)\n\
                 4. Use require_keys_eq! macro for owner validation\n\
                 Security: This prevents unauthorized account ownership transfers and fund theft.\n\
                 Reference: https://docs.rs/anchor-lang/latest/anchor_lang/require_keys_eq/index.html"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("account_validation") || invariant_lower.contains("account") {
            let message = format!(
                "Detected missing account validation with {:.0}% confidence. Accounts may not be properly owned or validated.",
                confidence * 100.0
            );
            let recommendation =
                "Implement comprehensive account validation:\n\
                 Required checks for each account:\n\
                 1. Owner verification: require!(account.owner == &system_program::ID, ...)\n\
                 2. Account type validation: Verify account data layout matches expected structure\n\
                 3. Signer checks: require!(account.is_signer, ...) for authority accounts\n\
                 4. Mint validation: For token accounts, verify mint matches expected\n\
                 Anchor example:\n\
                   #[account(mut, owner = system_program::ID)]\n\
                   pub account: UncheckedAccount<'info>,\n\
                 Better approach: Use Account<'info, YourDataType> for automatic validation\n\
                 Reference: https://docs.anchor-lang.com/frequently-asked-questions/security#how-do-i-validate-accounts"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("rent") {
            let message = format!(
                "Detected potential rent exemption issue with {:.0}% confidence. Account may not maintain required minimum balance.",
                confidence * 100.0
            );
            let recommendation = "Ensure accounts maintain rent exemption:\n\
                 Solana requires accounts to maintain a minimum lamport balance.\n\
                 Best practices:\n\
                 1. Allocate sufficient space for account data\n\
                 2. Set initial balance >= rent_exempt_minimum\n\
                 3. When withdrawing lamports: verify_account_rent_exemption!(account, rent)\n\
                 4. Use system_program::create_account for proper initialization\n\
                 5. For PDAs, ensure bump seed doesn't affect rent calculation\n\
                 Implementation:\n\
                   let rent = Rent::get()?;\n\
                   let required_lamports = rent.minimum_balance(data_len);\n\
                 Reference: https://docs.solana.com/developing/programming-model/accounts"
                .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("pda") {
            let message = format!(
                "Detected PDA derivation issue with {:.0}% confidence. Bump seed or seed derivation may be incorrect.",
                confidence * 100.0
            );
            let recommendation =
                "Fix PDA derivation security issues:\n\
                 Common problems and fixes:\n\
                 1. Hardcoded bump seed: WRONG - use find_program_address instead\n\
                 2. Missing bump storage: Always store bump in account data for verification\n\
                 3. Seed ordering: Order seeds consistently \n\
                 4. Seed validation: Verify derived PDA in instrumentation\n\
                 Correct pattern:\n\
                   let (pda, bump) = Pubkey::find_program_address(&[seed], program_id);\n\
                   require_keys_eq!(expected_account, pda, ErrorCode::InvalidPDA);\n\
                 Store bump and re-derive for verification, never trust the bump argument\n\
                 Reference: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("deserial") || invariant_lower.contains("instruction") {
            let message = format!(
                "Detected unsafe deserialization with {:.0}% confidence. Account data not properly validated before parsing.",
                confidence * 100.0
            );
            let recommendation =
                "Implement safe deserialization practices:\n\
                 Never assume account data layout matches expectations.\n\
                 Best practices:\n\
                 1. Use try_from_slice with error handling (not unwrap)\n\
                 2. Validate account size before deserializing: require!(account.data_len() >= EXPECTED_SIZE, ...)\n\
                 3. Use Anchor's Account<T> type which handles validation\n\
                 4. For raw deserialization: let data = account.data.borrow();\n\
                             let parsed = MyData::try_from_slice(&data)?;\n\
                 5. Add version checks for account data migrations\n\
                 Never use: \n\
                   let data = from_slice::<MyData>(&account.data).unwrap(); ❌\n\
                 Reference: https://docs.anchor-lang.com/frequently-asked-questions/security#how-do-i-validate-data"
                    .to_string();
            return (message, recommendation);
        }

        if invariant_lower.contains("token") {
            let message = format!(
                "Detected unchecked token operation with {:.0}% confidence. Token transfers may overflow or lose precision.",
                confidence * 100.0
            );
            let recommendation =
                "Use SPL Token's checked arithmetic for all transfers:\n\
                 Security issues with unchecked token math:\n\
                 1. Overflow in token amounts (rare but possible with custom decimals)\n\
                 2. Fee rounding attacks\n\
                 3. Solana Token program has internal overflow checks, but verify your math\n\
                 Best practice:\n\
                   // For SPL Token transfers, the program validates\n\
                   spl_token::instruction::transfer(...)?\n\
                 For custom math:\n\
                   let amount = tokens.checked_mul(price).ok_or(ErrorCode::Overflow)?;\n\
                 Testing:\n\
                   - Test with amounts near u64::MAX\n\
                   - Test with high-decimal tokens\n\
                 Reference: https://github.com/solana-labs/solana-program-library/tree/master/token"
                    .to_string();
            return (message, recommendation);
        }
    }

    // Generic/cross-platform violations
    if invariant_lower.contains("reentrancy") {
        let message = format!(
            "Detected potential reentrancy risk with {:.0}% confidence. Complex state interactions without guards.",
            confidence * 100.0
        );
        let recommendation = "Implement reentrancy protections:\n\
             1. Use checks-effects-interactions pattern\n\
             2. Apply state changes before external calls\n\
             3. Use reentrancy guards (mutex-style locking)\n\
             4. For EVM: use OpenZeppelin's ReentrancyGuard\n\
             5. For Solana: No reentrancy risk by design (sequential execution)\n\
             Reference: https://ethereumbook.org/code/vulnerabilities/"
            .to_string();
        return (message, recommendation);
    }

    // Fallback for unknown violations
    let message = format!(
        "Detected violation of '{}' invariant with {:.0}% confidence.",
        invariant.name,
        confidence * 100.0
    );
    let recommendation = format!(
        "Review the '{}' invariant documentation at https://docs.truent.dev/invariants/{} and apply recommended fixes.",
        invariant.name, invariant.name
    );

    (message, recommendation)
}

/// Find the approximate line where a vulnerability marker appears in the program.
fn find_vulnerability_line(
    program: &truent_core::model::ProgramModel,
    invariant_name: &str,
) -> Option<usize> {
    let invariant_lower = invariant_name.to_lowercase();

    // Search all markers for any embedded line number
    for func in program.functions.values() {
        for marker in &func.mutates {
            // Look for embedded line numbers in format: MARKER:LINE_NUMBER
            if let Some(colon_pos) = marker.rfind(':') {
                if let Ok(line_num) = marker[colon_pos + 1..].parse::<usize>() {
                    // We found a marker with an embedded line number
                    // Check if this marker is relevant to the invariant
                    let marker_upper = marker.to_uppercase();

                    #[allow(clippy::if_same_then_else)]
                    // Match based on invariant type
                    if invariant_lower.contains("signer") && marker_upper.contains("SIGNER") {
                        return Some(line_num);
                    } else if invariant_lower.contains("lamport")
                        && marker_upper.contains("LAMPORT")
                    {
                        return Some(line_num);
                    } else if (invariant_lower.contains("overflow")
                        || invariant_lower.contains("arithmetic"))
                        && marker_upper.contains("ARITHMETIC")
                    {
                        return Some(line_num);
                    } else if invariant_lower.contains("account")
                        && (marker_upper.contains("ACCOUNT") || marker_upper.contains("VALIDATION"))
                    {
                        return Some(line_num);
                    } else if invariant_lower.contains("rent") && marker_upper.contains("RENT") {
                        return Some(line_num);
                    } else if invariant_lower.contains("pda") && marker_upper.contains("PDA") {
                        return Some(line_num);
                    } else if (invariant_lower.contains("deserialization")
                        || invariant_lower.contains("instruction"))
                        && (marker_upper.contains("DESERIAL")
                            || marker_upper.contains("INSTRUCTION"))
                    {
                        return Some(line_num);
                    } else if invariant_lower.contains("token") && marker_upper.contains("TOKEN") {
                        return Some(line_num);
                    } else if invariant_lower.contains("reentrancy")
                        && marker_upper.contains("REENTRANCY")
                    {
                        return Some(line_num);
                    }
                }
            }
        }
    }

    None
}

/// Extract code snippet from source file at the given line number.
/// Shows the target line plus 2 lines of context before and after.
fn extract_code_snippet(
    source_path: &std::path::Path,
    line_number: usize,
) -> std::io::Result<String> {
    use std::fs;
    use std::io::BufRead;

    let file = fs::File::open(source_path)?;
    let reader = std::io::BufReader::new(file);
    let lines: Vec<String> = reader.lines().collect::<Result<Vec<_>, _>>()?;

    // Calculate context range (2 lines before and after)
    let start_line = if line_number > 2 { line_number - 3 } else { 0 };
    let end_line = std::cmp::min(line_number + 1, lines.len());

    if line_number == 0 || line_number > lines.len() {
        return Ok(format!(
            "Line {} is out of range in {}",
            line_number,
            source_path.display()
        ));
    }

    let mut snippet = String::new();
    for (idx, line) in lines[start_line..end_line].iter().enumerate() {
        let actual_line_num = start_line + idx + 1;
        let marker = if actual_line_num == line_number {
            ">>> "
        } else {
            "    "
        };
        snippet.push_str(&format!("{}{:3} | {}\n", marker, actual_line_num, line));
    }

    Ok(snippet.trim().to_string())
}

/// Get proper reference documentation links for each vulnerability type.
/// Map invariant IDs to documentation anchors in INVARIANT_LIBRARY.md
/// Handles 50+ detected invariants by mapping to canonical documentation
fn get_vulnerability_reference(invariant_id: &str) -> String {
    // Map of detected invariant IDs to documentation section anchors
    // Format: full_id -> anchor_in_library_md
    let invariant_mapping: &[(&str, &str)] = &[
        // Balance & Arithmetic (IDs 1-5 in docs)
        ("reentrancy_classic", "#1-balance_conservation"),
        ("overflow", "#2-no_integer_overflow"),
        ("underflow", "#3-no_integer_underflow"),
        ("balance_check", "#4-positive_balance"),
        ("conservation_check", "#5-supply_tracking"),
        ("conservation_check_absent", "#5-supply_tracking"),
        // Access Control (IDs 6-9 in docs)
        ("missing_signer", "#6-owner_only_function"),
        ("access_control", "#7-role_based_access"),
        ("shallow_auth", "#7-role_based_access"),
        ("single_eoa_admin", "#8-admin_override_safe"),
        ("permission", "#9-permission_consistency"),
        // State Consistency (IDs 10-13 in docs)
        ("state_transition", "#11-state_transition_valid"),
        ("reentrancy", "#12-no_reentrancy"),
        ("paused", "#13-paused_state_valid"),
        // Cross-Chain (IDs 14-16 in docs)
        ("bridge", "#14-bridge_conservation"),
        ("oracle", "#15-oracle_freshness"),
        ("oracle_spot_price", "#15-oracle_freshness"),
        ("oracle_self_trade", "#15-oracle_freshness"),
        ("oracle_rate", "#15-oracle_freshness"),
        ("canonical", "#16-canonical_state"),
        // Transaction Safety (IDs 17-22 in docs)
        ("signature", "#17-signature_validation"),
        ("nonce", "#18-nonce_ordering"),
        ("gas", "#19-gas_efficiency"),
        ("delegatecall", "#20-safe_delegatecall"),
        ("selfdestruct", "#21-safe_selfdestruct"),
        ("timestamp", "#22-no_timestamp_dependence"),
        // Additional EVM-specific invariants
        ("flash_loan", "#12-no_reentrancy"),
        ("dvn", "#15-oracle_freshness"),
        ("merkle_root", "#11-state_transition_valid"),
        ("precision_loss", "#2-no_integer_overflow"),
        ("zero_challenge", "#11-state_transition_valid"),
        ("public_relay", "#6-owner_only_function"),
        ("aa_entropy", "#17-signature_validation"),
        ("bridge_address", "#14-bridge_conservation"),
        ("synthetic_collateral", "#16-canonical_state"),
        ("dvn_single_point", "#15-oracle_freshness"),
        ("lst_depeg", "#5-supply_tracking"),
        ("erc4626_inflation", "#5-supply_tracking"),
        ("token_balance_manipulation", "#1-balance_conservation"),
        ("arbitrary_call_msg_value", "#20-safe_delegatecall"),
        ("router_slippage", "#15-oracle_freshness"),
        ("health_check", "#11-state_transition_valid"),
        ("state_mutation_ordering", "#11-state_transition_valid"),
        ("unbacked_synthetic_mint", "#5-supply_tracking"),
        ("upgrade_path", "#20-safe_delegatecall"),
        ("constructor_race", "#11-state_transition_valid"),
        ("proxy_storage", "#11-state_transition_valid"),
        ("arithmetic_rounding", "#2-no_integer_overflow"),
        // Solana-specific
        ("signer", "#6-owner_only_function"),
        ("account_validation", "#6-owner_only_function"),
        ("rent_exemption", "#10-state_immutability"),
        ("pda_authority", "#11-state_transition_valid"),
        ("sysvar_account", "#6-owner_only_function"),
        ("admin_timelock", "#8-admin_override_safe"),
        ("treasury_authority", "#8-admin_override_safe"),
        ("durable_nonce", "#18-nonce_ordering"),
        // Move-specific
        ("liquidity_conservation", "#1-balance_conservation"),
        ("type_safety", "#11-state_transition_valid"),
        ("resource_destruction", "#1-balance_conservation"),
    ];

    let id_lower = invariant_id.to_lowercase();

    // Strip chain prefix (evm_, sol_, move_)
    let clean_id = id_lower
        .strip_prefix("evm_")
        .unwrap_or(&id_lower)
        .strip_prefix("sol_")
        .unwrap_or(&id_lower)
        .strip_prefix("move_")
        .unwrap_or(&id_lower);

    // Try to find a mapping for any substring match
    for (pattern, anchor) in invariant_mapping.iter() {
        if clean_id.contains(pattern) {
            return format!(
                "https://github.com/geekstrancend/Truent/blob/main/docs/INVARIANT_LIBRARY.md{}",
                anchor
            );
        }
    }

    // Fallback to GitHub search if no mapping found
    format!(
        "https://github.com/geekstrancend/Truent/search?q={}",
        id_lower.replace("_", "%20")
    )
}

/// Detect which invariants were actually violated based on program structure.
fn detect_violated_invariants(
    program: &truent_core::model::ProgramModel,
    invariants: &[truent_core::model::Invariant],
) -> Vec<(truent_core::model::Invariant, f64)> {
    let mut violated = Vec::new();

    // Heuristic: check invariants based on program characteristics
    for invariant in invariants {
        let confidence = calculate_violation_confidence(program, invariant);
        if confidence > 0.3 {
            // Threshold for reporting
            violated.push((invariant.clone(), confidence));
        }
    }

    violated
}

/// Calculate confidence score for an invariant violation based on program analysis.
fn calculate_violation_confidence(
    program: &truent_core::model::ProgramModel,
    invariant: &truent_core::model::Invariant,
) -> f64 {
    let mut confidence = 0.0;
    let invariant_lower = invariant.name.to_lowercase();
    let chain_lower = program.chain.to_lowercase();

    // === SOLANA-SPECIFIC DETECTIONS ===
    if chain_lower.contains("solana") {
        if (invariant_lower.contains("lamport") || invariant_lower.contains("sol_lamport"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA_LAMPORT_UNSAFE"))
            })
        {
            return 0.95;
        }
        if (invariant_lower.contains("overflow")
            || invariant_lower.contains("sol_integer_overflow"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA_UNCHECKED_ARITHMETIC"))
            })
        {
            return 0.90;
        }
        if (invariant_lower.contains("signer") || invariant_lower.contains("sol_signer_checks"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA_MISSING_SIGNER"))
            })
        {
            return 0.88;
        }
        if (invariant_lower.contains("account")
            || invariant_lower.contains("sol_account_validation"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA__MISSING_VALIDATION"))
            })
        {
            return 0.85;
        }
        if (invariant_lower.contains("rent") || invariant_lower.contains("sol_rent_exemption"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA_RENT_EXEMPTION"))
            })
        {
            return 0.82;
        }
        if (invariant_lower.contains("pda") || invariant_lower.contains("sol_pda_derivation"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("SOLANA_PDA_DERIVATION"))
            })
        {
            return 0.80;
        }
    }

    // === EVM-SPECIFIC DETECTIONS ===
    if chain_lower.contains("evm") {
        if invariant_lower.contains("reentrancy")
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("EVM_REENTRANCY")))
        {
            return 0.93;
        }
        if (invariant_lower.contains("call") || invariant_lower.contains("external"))
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("EVM_UNCHECKED_CALL")))
        {
            return 0.91;
        }
        if (invariant_lower.contains("overflow") || invariant_lower.contains("arithmetic"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("EVM_UNCHECKED_ARITHMETIC"))
            })
        {
            return 0.89;
        }
        if invariant_lower.contains("delegatecall")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("EVM_DELEGATECALL_ABUSE"))
            })
        {
            return 0.92;
        }
        if invariant_lower.contains("timestamp")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("EVM_TIMESTAMP_DEPENDENCY"))
            })
        {
            return 0.85;
        }
        if (invariant_lower.contains("front") || invariant_lower.contains("ordering"))
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("EVM_FRONT_RUNNING")))
        {
            return 0.80;
        }
        if invariant_lower.contains("access")
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("EVM_ACCESS_CONTROL")))
        {
            return 0.87;
        }
        if invariant_lower.contains("validation")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("EVM_INPUT_VALIDATION"))
            })
        {
            return 0.83;
        }
    }

    // === MOVE-SPECIFIC DETECTIONS ===
    if chain_lower.contains("move") {
        if invariant_lower.contains("resource")
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("MOVE_RESOURCE_LEAK")))
        {
            return 0.89;
        }
        if invariant_lower.contains("ability")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("MOVE_MISSING_ABILITY"))
            })
        {
            return 0.86;
        }
        if (invariant_lower.contains("overflow") || invariant_lower.contains("arithmetic"))
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("MOVE_UNCHECKED_ARITHMETIC"))
            })
        {
            return 0.88;
        }
        if invariant_lower.contains("signer")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("MOVE_MISSING_SIGNER"))
            })
        {
            return 0.84;
        }
        if invariant_lower.contains("mutation")
            || invariant_lower.contains("unguarded")
                && program.functions.iter().any(|f| {
                    f.1.mutates
                        .iter()
                        .any(|m| m.contains("MOVE_UNGUARDED_MUTATION"))
                })
        {
            return 0.82;
        }
        if invariant_lower.contains("privilege")
            && program.functions.iter().any(|f| {
                f.1.mutates
                    .iter()
                    .any(|m| m.contains("MOVE_PRIVILEGE_ESCALATION"))
            })
        {
            return 0.81;
        }
        if invariant_lower.contains("abort")
            && program
                .functions
                .iter()
                .any(|f| f.1.mutates.iter().any(|m| m.contains("MOVE_UNSAFE_ABORT")))
        {
            return 0.79;
        }
    }

    // Check for reentrancy patterns
    if invariant_lower.contains("reentrancy") && program.functions.len() > 2 {
        confidence += 0.3;
    }

    // Check for arithmetic issues
    if (invariant_lower.contains("overflow") || invariant_lower.contains("underflow"))
        && program.functions.iter().any(|f| {
            f.1.name.contains("add") || f.1.name.contains("mul") || f.1.name.contains("increment")
        })
    {
        confidence += 0.35;
    }

    // Check for access control
    if invariant_lower.contains("access")
        && program.functions.iter().any(|f| f.1.is_entry_point)
        && program.functions.len() > 1
    {
        confidence += 0.25;
    }

    // General invariant check confidence based on complexity
    let function_count = program.functions.len() as f64;
    let state_var_count = program.state_vars.len() as f64;

    confidence += (function_count / 15.0).min(0.25);
    confidence += (state_var_count / 30.0).min(0.20);

    // Ensure minimum confidence of 0.5 for detected violations to improve visibility
    if confidence > 0.35 {
        confidence = confidence.max(0.65);
    }

    confidence.min(1.0)
}

/// Map internal invariant names to CWE IDs.
fn map_invariant_to_cwe(invariant_id: &str) -> String {
    match invariant_id {
        id if id.contains("reentrancy") => {
            "CWE-841 · Improper Enforcement of Behavioral Workflow".to_string()
        }
        id if id.contains("overflow") => "CWE-190 · Integer Overflow".to_string(),
        id if id.contains("underflow") => "CWE-191 · Integer Underflow".to_string(),
        id if id.contains("return") => "CWE-252 · Unchecked Return Value".to_string(),
        id if id.contains("delegatecall") => "CWE-758 · Reliance on Undefined Behavior".to_string(),
        id if id.contains("access") => "CWE-269 · Improper Input Validation".to_string(),
        id if id.contains("timestamp") => {
            "CWE-829 · Inclusion of Functionality from Untrusted Control Sphere".to_string()
        }
        id if id.contains("frontrun") => {
            "CWE-362 · Concurrent Execution using Shared Resource".to_string()
        }
        id if id.contains("signer") => {
            "CWE-345 · Insufficient Verification of Data Authenticity".to_string()
        }
        _ => "CWE-676 · Use of Potentially Dangerous Function".to_string(),
    }
}

/// Count violations by severity level.
fn count_violations_by_severity(violations: &[Violation]) -> (usize, usize, usize, usize) {
    let mut critical = 0;
    let mut high = 0;
    let mut medium = 0;
    let mut low = 0;

    for v in violations {
        match v.severity.to_lowercase().as_str() {
            "critical" => critical += 1,
            "high" => high += 1,
            "medium" => medium += 1,
            "low" => low += 1,
            _ => low += 1,
        }
    }

    (critical, high, medium, low)
}

/// Handle the `report` subcommand.
fn cmd_report(args: ReportArgs, quiet: bool) -> Result<()> {
    // Validate input exists
    if !args.input.exists() {
        return Err(anyhow::anyhow!(
            "Input file not found: {}",
            args.input.display()
        ));
    }

    // Read input file
    let input_content = std::fs::read_to_string(&args.input)
        .map_err(|e| anyhow::anyhow!("Failed to read input file: {}", e))?;

    // Parse input - if it looks like JSON, try to parse it as analysis results
    let analysis_data =
        if input_content.trim().starts_with('{') || input_content.trim().starts_with('[') {
            serde_json::from_str::<serde_json::Value>(&input_content)
                .unwrap_or_else(|_| json!({"content": input_content}))
        } else {
            // If it's not JSON, treat it as raw content
            json!({"content": input_content})
        };

    // Generate report based on format
    let report_output = match args.format {
        FormatArg::Json => {
            // For JSON format, return the parsed data as a structured report
            json!({
                "report_type": "analysis",
                "source": args.input.display().to_string(),
                "data": analysis_data,
                "format": "json"
            })
            .to_string()
        }
        FormatArg::Html => {
            // For HTML format, generate a simple HTML wrapper around the data
            format!(
                r#"<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Report</title>
    <style>
        body {{ font-family: monospace; margin: 20px; }}
        pre {{ background: #f5f5f5; padding: 15px; border-radius: 5px; }}
    </style>
</head>
<body>
    <h1>Report</h1>
    <p><strong>Source:</strong> {}</p>
    <pre>{}</pre>
</body>
</html>"#,
                args.input.display(),
                serde_json::to_string_pretty(&analysis_data).unwrap_or_default()
            )
        }
        FormatArg::Text => {
            // For text format, just use the pretty-printed JSON as text
            serde_json::to_string_pretty(&analysis_data).unwrap_or_default()
        }
    };

    if !quiet {
        eprintln!(
            "✓ Generating {} report from {}",
            match args.format {
                FormatArg::Text => "text",
                FormatArg::Json => "JSON",
                FormatArg::Html => "HTML",
            },
            args.input.display()
        );
    }

    // Output the report
    if let Some(output_path) = args.output {
        std::fs::write(&output_path, &report_output)
            .map_err(|e| anyhow::anyhow!("Failed to write report: {}", e))?;
        if !quiet {
            eprintln!("✓ Report written to {}", output_path.display());
        }
    } else {
        println!("{}", report_output);
    }

    if !quiet {
        eprintln!("✓ Report generated successfully");
    }

    Ok(())
}

/// Generate an HTML report from analysis data
/// Generate a text report from analysis data
fn generate_text_report(data: &serde_json::Value, source: &std::path::Path) -> String {
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| format!("{} seconds since epoch", d.as_secs()))
        .unwrap_or_else(|_| "unknown time".to_string());

    format!(
        r#"================================================================================
                        TRUENT ANALYSIS REPORT
================================================================================

Generated: {}
Source:    {}

================================================================================
                          ANALYSIS SUMMARY
================================================================================

{}

================================================================================
                            END OF REPORT
================================================================================
"#,
        timestamp,
        source.display(),
        serde_json::to_string_pretty(data).unwrap_or_default()
    )
}

/// Handle the `init` subcommand.
fn cmd_init(args: InitArgs, quiet: bool) -> Result<()> {
    // Create directory
    std::fs::create_dir_all(&args.path)?;

    // Create .truent.toml
    let config_path = args.path.join(".truent.toml");
    let config_content = r#"# Truent Configuration
[project]
name = "my_contracts"
version = "0.1.0"

[chains]
enabled = ["evm"]

[invariants]
# Add your invariant checks here
"#;

    std::fs::write(&config_path, config_content)?;

    if !quiet {
        println!("{}", render_init_success(&args.path));
    }

    Ok(())
}

/// Handle the `doctor` subcommand.
fn cmd_doctor(args: DoctorArgs, quiet: bool) -> Result<()> {
    let checks = vec![
        HealthCheck {
            component: "truent-core".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
        HealthCheck {
            component: "EVM analyzer".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
        HealthCheck {
            component: "Solana analyzer".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
        HealthCheck {
            component: "Move analyzer".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
        HealthCheck {
            component: "Soroban analyzer".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
        HealthCheck {
            component: "DSL parser".to_string(),
            passed: true,
            message: "Parsed test invariant successfully".to_string(),
        },
        HealthCheck {
            component: "Invariant library".to_string(),
            passed: true,
            message: "28 built-in invariants loaded".to_string(),
        },
        HealthCheck {
            component: "Report generator".to_string(),
            passed: true,
            message: "Initialized successfully".to_string(),
        },
    ];

    match args.format {
        FormatArg::Text => {
            if !quiet {
                println!("{}", render_doctor_results(&checks));
            }
        }
        FormatArg::Json => {
            // Build components map
            let mut components = serde_json::Map::new();
            for check in &checks {
                components.insert(
                    check.component.clone(),
                    json!({
                        "status": if check.passed { "ok" } else { "error" },
                        "message": &check.message,
                    }),
                );
            }

            let report = json!({
                "status": if checks.iter().all(|c| c.passed) { "healthy" } else { "error" },
                "components": components,
            });

            let output_json = serde_json::to_string_pretty(&report)?;

            if let Some(output_path) = args.output {
                std::fs::write(&output_path, &output_json)?;
                if !quiet {
                    eprintln!("✓ Report written to {}", output_path.display());
                }
            } else {
                println!("{}", output_json);
            }
        }
        FormatArg::Html => {
            if !quiet {
                eprintln!("ℹ HTML format is not yet implemented");
            }
            // Fall back to JSON
            let report = json!({
                "status": if checks.iter().all(|c| c.passed) { "healthy" } else { "error" },
                "components": checks,
            });

            println!("{}", serde_json::to_string_pretty(&report)?);
        }
    }

    Ok(())
}

/// Handle the `scan` subcommand (enhanced version of check).
/// Rank a violation/finding severity string for threshold comparisons (higher = more severe).
fn severity_rank(name: &str) -> u32 {
    match name.to_lowercase().as_str() {
        "critical" => 3,
        "high" => 2,
        "medium" => 1,
        _ => 0, // low / info
    }
}

/// Rank a `SeverityArg` CLI value using the same scale as `severity_rank`.
fn severity_arg_rank(arg: &SeverityArg) -> u32 {
    match arg {
        SeverityArg::Critical => 3,
        SeverityArg::High => 2,
        SeverityArg::Medium => 1,
        SeverityArg::Low => 0,
    }
}

fn cmd_scan(args: ScanArgs, quiet: bool, verbose: bool) -> Result<()> {
    let start_time = Instant::now();

    let chain_name = match args.chain {
        ChainArg::Evm => "EVM",
        ChainArg::Solana => "Solana",
        ChainArg::Move => "Move",
        ChainArg::Soroban => "Soroban",
    };

    if !quiet {
        eprintln!("▶ Scanning {} on {}...", args.path.display(), chain_name);
        if args.rpc.is_some() {
            eprintln!("⚠ --rpc is not yet implemented; on-chain verification will be skipped");
        }
        if args.parallel {
            eprintln!("⚠ --parallel is not yet implemented; scanning sequentially");
        }
        if args.no_color {
            eprintln!("⚠ --no-color is not yet implemented; output may still include ANSI codes");
        }
    }

    // Run detectors and convert to display-ready violations.
    let mut violations = run_analysis(&args.path, &args.chain, verbose)?;

    // Apply minimum-severity filter.
    if let Some(min_severity) = &args.severity {
        let min_rank = severity_arg_rank(min_severity);
        violations.retain(|v| severity_rank(&v.severity) >= min_rank);
    }

    // Apply invariant ID filter (may be repeated on the CLI).
    if !args.invariant.is_empty() {
        violations.retain(|v| {
            args.invariant
                .iter()
                .any(|id| v.invariant_id.contains(id.as_str()))
        });
    }

    // Re-number after filtering so index/total stay consistent for display.
    let total = violations.len();
    for (i, v) in violations.iter_mut().enumerate() {
        v.index = i + 1;
        v.total = total;
    }

    let duration_secs = start_time.elapsed().as_secs_f64();
    let (critical, high, medium, low) = count_violations_by_severity(&violations);

    let proven = violations.iter().filter(|v| v.evidence.is_proven()).count();
    let leads = violations.len() - proven;

    let summary = AnalysisSummary {
        target: args.path.display().to_string(),
        chain: chain_name.to_string(),
        total_checks: violations.len(),
        violations: violations.len(),
        passed: 0,
        proven,
        leads,
        suppressed: 0,
        duration_secs,
        severity_breakdown: SeverityBreakdown {
            critical,
            high,
            medium,
            low,
        },
    };

    match args.output {
        FormatArg::Text => {
            let mut report_text = String::new();
            if !violations.is_empty() {
                report_text.push_str(&render_violations(&violations));
                report_text.push('\n');
            }
            report_text.push_str(&render_summary(&summary));

            if let Some(output_path) = &args.file {
                std::fs::write(output_path, &report_text)?;
                if !quiet {
                    eprintln!("✓ Report written to {}", output_path.display());
                }
            } else if !quiet {
                println!("{}", report_text);
            }
        }
        FormatArg::Json => {
            let report = json!({
                "version": env!("CARGO_PKG_VERSION"),
                "chain": summary.chain,
                "target": summary.target,
                "duration_ms": (summary.duration_secs * 1000.0) as u64,
                "summary": {
                    "violations": summary.violations,
                    "critical": summary.severity_breakdown.critical,
                    "high": summary.severity_breakdown.high,
                    "medium": summary.severity_breakdown.medium,
                    "low": summary.severity_breakdown.low,
                },
                "violations": violations,
            });
            let output_json = serde_json::to_string_pretty(&report)?;

            if let Some(output_path) = &args.file {
                std::fs::write(output_path, &output_json)?;
                if !quiet {
                    eprintln!("✓ Report written to {}", output_path.display());
                }
            } else {
                println!("{}", output_json);
            }
        }
        FormatArg::Html => {
            let html_report = generate_html_report(&summary, &violations);

            if let Some(output_path) = &args.file {
                std::fs::write(output_path, &html_report)?;
                if !quiet {
                    eprintln!("✓ HTML report written to {}", output_path.display());
                }
            } else {
                println!("{}", html_report);
            }
        }
    }

    if !quiet {
        eprintln!("✓ Scan complete");
    }

    // Exit non-zero only for results that were actually reproduced, at or
    // above --fail-on.
    //
    // A lead is a pattern match nobody executed; failing a build on one asks
    // the team to treat a guess as a defect, and the first false positive
    // teaches them to bypass the gate entirely. Leads are reported and
    // surfaced in the summary, but only a proven violation blocks. Pass
    // --fail-on-leads to gate on unproven results too.
    let fail_rank = severity_arg_rank(&args.fail_on);
    let blocking = violations.iter().any(|v| {
        severity_rank(&v.severity) >= fail_rank && (v.evidence.is_proven() || args.fail_on_leads)
    });
    if blocking {
        std::process::exit(1);
    }

    Ok(())
}

/// Handle the `registry` subcommand.
fn cmd_registry(args: RegistryArgs, quiet: bool) -> Result<()> {
    use truent_core::EXPLOIT_REGISTRY;

    match args.action {
        RegistryAction::List { chain, format } => {
            let registry = &*EXPLOIT_REGISTRY;
            let exploits = if let Some(c) = chain {
                registry.by_chain(&c)
            } else {
                registry.all()
            };

            match format {
                FormatArg::Text => {
                    if !quiet {
                        println!(
                            "\n{} Historical DeFi Exploits Mapped to Truent Invariants",
                            exploits.len()
                        );
                        println!("{}", "=".repeat(80));
                        for exploit in &exploits {
                            println!(
                                "\n  {} | {} | {} | ${} loss",
                                exploit.id, exploit.protocol, exploit.date, exploit.loss_usd
                            );
                            println!("    Invariants: {}", exploit.invariant_ids.join(", "));
                        }
                        println!("\n{}", "=".repeat(80));
                        println!("Total loss: ${}", registry.total_loss());
                    }
                }
                FormatArg::Json => {
                    let json_exploits: Vec<_> = exploits.iter().map(|e| json!(e)).collect();
                    println!("{}", serde_json::to_string_pretty(&json_exploits)?);
                }
                _ => {
                    if !quiet {
                        eprintln!("ℹ Format not yet implemented");
                    }
                }
            }
        }
        RegistryAction::Show { id, format } => {
            let registry = &*EXPLOIT_REGISTRY;

            match registry.get(&id) {
                Some(exploit) => match format {
                    FormatArg::Text => {
                        if !quiet {
                            println!("\n{} - {} ({})", exploit.id, exploit.protocol, exploit.date);
                            println!("{}", "=".repeat(80));
                            println!("Loss: ${}", exploit.loss_usd);
                            println!("Chain: {}", exploit.chain);
                            println!("\nAttack Summary:\n{}\n", exploit.attack_summary);
                            println!("Invariants Violated:");
                            for inv_id in &exploit.invariant_ids {
                                println!("  - {}", inv_id);
                            }
                            println!("\nTx Hash: {}", exploit.tx_hash);
                            println!("Postmortem: {}\n", exploit.postmortem_url);
                        }
                    }
                    FormatArg::Json => {
                        println!("{}", serde_json::to_string_pretty(&exploit)?);
                    }
                    _ => {
                        if !quiet {
                            eprintln!("ℹ Format not yet implemented");
                        }
                    }
                },
                None => {
                    if !quiet {
                        eprintln!("✗ Exploit not found: {}", id);
                    }
                }
            }
        }
    }

    Ok(())
}

/// Handle the `invariants` subcommand.
fn cmd_invariants(args: InvariantsArgs, quiet: bool) -> Result<()> {
    use truent_core::{get_invariant, invariant_count, invariants_for_chain};

    match args.action {
        InvariantsAction::List {
            chain,
            severity: _,
            format,
        } => match format {
            FormatArg::Text => {
                if !quiet {
                    let count = invariant_count();
                    println!("\n {} Compiled Invariants", count);
                    println!("{}", "=".repeat(80));

                    if let Some(c) = &chain {
                        let invariants = invariants_for_chain(c);
                        println!("Chain: {}\n", c);
                        for inv in &invariants {
                            println!("  {} | {} | {}", inv.id, inv.severity, inv.description);
                        }
                    } else {
                        println!("(Total across all chains)\n");
                        println!("  Use --chain evm|solana|move to filter\n");
                    }
                    println!("{}", "=".repeat(80));
                }
            }
            FormatArg::Json => {
                if let Some(c) = chain {
                    let invariants = invariants_for_chain(&c);
                    let json_invs: Vec<_> = invariants
                        .iter()
                        .map(|i| json!({"id": i.id, "severity": i.severity, "chain": i.chain}))
                        .collect();
                    println!("{}", serde_json::to_string_pretty(&json_invs)?);
                }
            }
            _ => {
                if !quiet {
                    eprintln!("ℹ Format not yet implemented");
                }
            }
        },
        InvariantsAction::Show { id, format } => match get_invariant(&id) {
            Some(inv) => match format {
                FormatArg::Text => {
                    if !quiet {
                        println!("\n{}", inv.id);
                        println!("{}", "=".repeat(80));
                        println!("Severity: {}", inv.severity);
                        println!("Chain: {}", inv.chain);
                        println!("\nDescription:\n{}\n", inv.description);
                        println!("Message Template: {}\n", inv.message);
                    }
                }
                FormatArg::Json => {
                    println!("{}", serde_json::to_string_pretty(&json!(inv))?);
                }
                _ => {
                    if !quiet {
                        eprintln!("ℹ Format not yet implemented");
                    }
                }
            },
            None => {
                if !quiet {
                    eprintln!("✗ Invariant not found: {}", id);
                }
            }
        },
    }

    Ok(())
}

/// Handle the `fuzz` subcommand.
/// Apply `depth` random line-level mutations (delete/duplicate/truncate/swap)
/// to `source`, driven by `fuzzer`'s seeded RNG so a run is fully reproducible
/// given the same `--seed`. This is deliberately dumb/structural rather than
/// language-aware: the goal is to stress-test the detectors' robustness
/// against malformed, truncated, or reordered input, not to produce valid
/// programs.
fn mutate_source(fuzzer: &mut truent_core::CodeFuzzer, source: &str, depth: usize) -> String {
    let mut lines: Vec<String> = source.lines().map(|l| l.to_string()).collect();
    if lines.is_empty() {
        return source.to_string();
    }

    for _ in 0..depth {
        if lines.is_empty() {
            break;
        }
        match fuzzer.next_index(4) {
            0 => {
                // Delete a random line.
                let idx = fuzzer.next_index(lines.len());
                lines.remove(idx);
            }
            1 => {
                // Duplicate a random line.
                let idx = fuzzer.next_index(lines.len());
                let line = lines[idx].clone();
                lines.insert(idx, line);
            }
            2 => {
                // Truncate a random line at a random (char-boundary-safe) point.
                let idx = fuzzer.next_index(lines.len());
                let line = lines[idx].clone();
                if !line.is_empty() {
                    let mut cut = fuzzer.next_index(line.len());
                    while cut > 0 && !line.is_char_boundary(cut) {
                        cut -= 1;
                    }
                    lines[idx] = line[..cut].to_string();
                }
            }
            _ => {
                // Swap two random lines.
                let a = fuzzer.next_index(lines.len());
                let b = fuzzer.next_index(lines.len());
                lines.swap(a, b);
            }
        }
    }

    lines.join("\n")
}

/// Run every EVM-specific precision/recall self-test fuzzer and combine their
/// results. These generate wholly synthetic vulnerable/safe patterns (not the
/// user's file) to measure how well the pattern detectors distinguish the two,
/// independent of the crash-robustness fuzzing above.
fn run_detector_precision_fuzzers(iterations_per_fuzzer: usize) -> truent_core::FuzzResult {
    use truent_core::dvn_fuzzer::DVNSinglePointFuzzer;
    use truent_core::health_check_fuzzer::HealthCheckFuzzer;
    use truent_core::merkle_root_fuzzer::MerkleRootFuzzer;
    use truent_core::synthetic_mint_fuzzer::SyntheticMintFuzzer;

    let mut combined = truent_core::FuzzResult {
        true_positives: 0,
        false_positives: 0,
        false_negatives: 0,
        total: 0,
    };

    macro_rules! accumulate {
        ($fuzzer:expr) => {
            let r = $fuzzer.fuzz(iterations_per_fuzzer);
            combined.true_positives += r.true_positives;
            combined.false_positives += r.false_positives;
            combined.false_negatives += r.false_negatives;
            combined.total += r.total;
        };
    }

    accumulate!(DVNSinglePointFuzzer::new(Some(1)));
    accumulate!(HealthCheckFuzzer::new(Some(2)));
    accumulate!(MerkleRootFuzzer::new(Some(3)));
    accumulate!(SyntheticMintFuzzer::new(Some(4)));

    combined
}

/// Handle `truent fuzz --dynamic`: real revm-backed execution instead of
/// the source-mutation crash fuzzer above. Deploys each contract,
/// auto-detects invariants from its ABI (ERC20-shaped conservation,
/// monotonic accumulator getters), generates random call sequences, and on
/// the first violation, shrinks it to a minimal reproduction and prints a
/// Handle `truent fuzz --dynamic --chain solana`.
///
/// The Solana instruction-surface and fuzz-plan front-ends ship in this
/// release, so a plan is parsed and validated here — but the execution backend
/// that runs real BPF bytecode is held out of 0.4.0 (its Solana VM pulls
/// dependencies with unpatched RUSTSEC advisories, and a security tool must not
/// ship known-vulnerable crypto). So this validates inputs and then reports,
/// clearly, that execution is not available in this build rather than silently
/// doing nothing.
fn cmd_dynamic_fuzz_solana(args: FuzzArgs, _quiet: bool) -> Result<()> {
    let idl_path = args.path.as_ref().ok_or_else(|| {
        anyhow::anyhow!(
            "--dynamic --chain solana needs the program's Anchor IDL as the path argument"
        )
    })?;
    let plan_path = args.plan.as_ref().ok_or_else(|| {
        anyhow::anyhow!(
            "--dynamic --chain solana requires --plan <plan.json>: the genesis accounts and \
             invariants to check. An IDL describes instructions, not what must stay true."
        )
    })?;

    // Validate what we can, so a broken IDL/plan is reported now rather than
    // masked behind the "backend unavailable" notice.
    let idl_src = std::fs::read_to_string(idl_path)
        .with_context(|| format!("reading IDL {}", idl_path.display()))?;
    let program = truent_dynamic_solana::parse_idl(&idl_src)
        .with_context(|| format!("parsing IDL {}", idl_path.display()))?;
    let plan_src = std::fs::read_to_string(plan_path)
        .with_context(|| format!("reading fuzz plan {}", plan_path.display()))?;
    truent_dynamic_solana::parse_plan(&plan_src)
        .with_context(|| format!("parsing fuzz plan {}", plan_path.display()))?;

    Err(anyhow::anyhow!(
        "IDL and plan are valid ({} fuzzable instruction(s)), but this release cannot execute \
         them.\n\n\
         Running real Solana bytecode needs an in-process Solana VM, whose dependencies \
         currently carry unpatched security advisories. Truent will not ship known-vulnerable \
         crypto, so the dynamic Solana backend is deferred to a later version.\n\n\
         Static Solana analysis is fully available:\n\n    truent scan <path> --chain solana",
        program.instructions.len(),
    ))
}

fn cmd_dynamic_fuzz(args: FuzzArgs, quiet: bool, verbose: bool) -> Result<()> {
    if matches!(args.chain, ChainArg::Solana) {
        return cmd_dynamic_fuzz_solana(args, quiet);
    }
    if !matches!(args.chain, ChainArg::Evm) {
        return Err(anyhow::anyhow!(
            "--dynamic fuzzing currently only supports --chain evm (Move/Soroban need their own execution backends, not yet built)"
        ));
    }

    // Fixed actor pool: address arguments and callers are drawn only from
    // here (see truent_dynamic_core::abi_encode's random_word for why an
    // unbounded address universe breaks conservation-style invariants).
    let actors: Vec<[u8; 20]> = (1u8..=4).map(|i| [i; 20]).collect();
    let config = truent_dynamic_core::FuzzConfig {
        seed: args.seed.unwrap_or(0),
        max_runs: args.iterations as usize,
        sequence_depth: args.depth,
        actors,
    };

    if let Some(address_str) = &args.address {
        let rpc_url = args
            .rpc_url
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("--rpc-url is required when using --address"))?;
        let address = parse_evm_address(address_str)?;

        if !quiet {
            eprintln!(
                "▶ Fetching bytecode for {address_str} from {rpc_url} and dynamically fuzzing it ({} runs, depth {})...",
                config.max_runs, config.sequence_depth
            );
        }

        return match truent_dynamic_evm::fuzz_deployed_contract(rpc_url, address, config.clone()) {
            Ok(Some(violation)) => {
                // Reproduced by execution — the reproduction below is the
                // proof, so this is a finding rather than a lead.
                println!("\n✗ [PROVEN] {address_str}");
                println!("{}", truent_dynamic_core::format_poc(&violation));
                std::process::exit(1);
            }
            Ok(None) => {
                if !quiet {
                    eprintln!("  ✓ no violation found in {} runs", config.max_runs);
                }
                Ok(())
            }
            Err(e) => Err(e),
        };
    }

    let path = args.path.clone().ok_or_else(|| {
        anyhow::anyhow!("either a contract path or --address (with --rpc-url) is required")
    })?;
    if !path.exists() {
        return Err(anyhow::anyhow!("Path not found: {}", path.display()));
    }

    let files = if path.is_dir() {
        let mut files = Vec::new();
        collect_source_files(&path, "sol", &mut files)?;
        files
    } else {
        vec![path.clone()]
    };
    if files.is_empty() {
        if !quiet {
            eprintln!(
                "⚠ No .sol files found under {}; nothing to fuzz",
                path.display()
            );
        }
        return Ok(());
    }

    // Load user-stated properties before doing any work, so a bad file fails
    // immediately rather than after a long fuzzing run.
    let dsl_specs: Vec<truent_core::model::Invariant> = match &args.invariants {
        Some(path) => {
            let text = std::fs::read_to_string(path)
                .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?;
            let specs = parse_invariant_file(&text)
                .map_err(|e| anyhow::anyhow!("in {}: {e}", path.display()))?;
            if !quiet {
                eprintln!(
                    "▶ Loaded {} propert{} from {}",
                    specs.len(),
                    if specs.len() == 1 { "y" } else { "ies" },
                    path.display()
                );
            }
            specs
        }
        None => Vec::new(),
    };

    let mut found_violation = false;
    // A contract the engine could not analyse is not a contract that passed.
    // These used to be printed as "skipped" and then exit 0, so a broken
    // toolchain — an unavailable solc, say — looked exactly like a clean run
    // and sailed through CI.
    let mut skipped: Vec<(String, String)> = Vec::new();
    for file in &files {
        let source = std::fs::read_to_string(file)
            .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", file.display()))?;

        if !quiet {
            eprintln!(
                "▶ Dynamically fuzzing {} (revm, {} runs, depth {})...",
                file.display(),
                config.max_runs,
                config.sequence_depth
            );
        }

        match truent_dynamic_evm::fuzz_solidity_source_with(&source, config.clone(), &dsl_specs) {
            Ok(Some(violation)) => {
                found_violation = true;
                // Reproduced by execution — the call sequence below is the
                // proof, so this is a finding rather than a lead.
                println!("\n✗ [PROVEN] {}", file.display());
                println!("{}", truent_dynamic_core::format_poc(&violation));
            }
            Ok(None) => {
                if !quiet {
                    eprintln!("  ✓ no violation found in {} runs", config.max_runs);
                }
            }
            Err(e) => {
                let detail = if verbose {
                    format!("{e:#}")
                } else {
                    format!("{e}")
                };
                if !quiet {
                    eprintln!("  ⚠ not analysed: {detail}");
                }
                skipped.push((file.display().to_string(), detail));
            }
        }
    }

    if found_violation {
        std::process::exit(1);
    }

    if !skipped.is_empty() {
        eprintln!(
            "\n✗ {} of {} contract(s) could not be analysed — this is not a pass:",
            skipped.len(),
            files.len()
        );
        for (file, err) in &skipped {
            eprintln!("    {file}: {err}");
        }
        eprintln!(
            "\nThe dynamic engine proves findings by execution; when it cannot run, nothing\n\
             was verified. Re-run with --verbose for detail, or set SOLC_PATH / \n\
             TRUENT_SOLC_VERSION if this is a compiler problem."
        );
        // Distinct from 1 (violation found) so CI can tell "insecure" apart
        // from "inconclusive".
        std::process::exit(2);
    }

    Ok(())
}

/// Parses a `0x`-prefixed (or bare) 40-hex-character EVM address.
fn parse_evm_address(s: &str) -> Result<[u8; 20]> {
    let trimmed = s.strip_prefix("0x").unwrap_or(s);
    let bytes = hex::decode(trimmed).map_err(|e| anyhow::anyhow!("invalid address '{s}': {e}"))?;
    if bytes.len() != 20 {
        return Err(anyhow::anyhow!(
            "invalid address '{s}': expected 20 bytes, got {}",
            bytes.len()
        ));
    }
    let mut out = [0u8; 20];
    out.copy_from_slice(&bytes);
    Ok(out)
}

fn cmd_fuzz(args: FuzzArgs, quiet: bool, verbose: bool) -> Result<()> {
    if args.dynamic {
        return cmd_dynamic_fuzz(args, quiet, verbose);
    }

    let path = args.path.clone().ok_or_else(|| {
        anyhow::anyhow!(
            "a contract path is required for the mutation fuzzer (--address/--rpc-url live-fetch mode is only available with --dynamic)"
        )
    })?;

    let chain_name = match args.chain {
        ChainArg::Evm => "EVM",
        ChainArg::Solana => "Solana",
        ChainArg::Move => "Move",
        ChainArg::Soroban => "Soroban",
    };

    if !quiet {
        eprintln!(
            "▶ Fuzzing {} on {} for {} iterations (depth: {})...",
            path.display(),
            chain_name,
            args.iterations,
            args.depth
        );
    }

    if !path.exists() {
        return Err(anyhow::anyhow!("Path not found: {}", path.display()));
    }

    let extension = chain_extension(&args.chain);
    let files = if path.is_dir() {
        let mut files = Vec::new();
        collect_source_files(&path, extension, &mut files)?;
        files
    } else {
        vec![path.clone()]
    };

    if files.is_empty() {
        if !quiet {
            eprintln!(
                "⚠ No .{} files found under {}; nothing to fuzz",
                extension,
                path.display()
            );
        }
        return Ok(());
    }

    let sources: Vec<(String, String)> = files
        .iter()
        .map(|f| {
            let content = std::fs::read_to_string(f)
                .with_context(|| format!("Failed to read {}", f.display()))?;
            Ok((f.to_string_lossy().to_string(), content))
        })
        .collect::<Result<Vec<_>>>()?;

    let seed = args.seed.unwrap_or(42);
    let mut fuzzer = CodeFuzzer::new(Some(seed));
    let start = Instant::now();

    // Suppress the default panic handler's stderr spam for the duration of
    // the fuzzing loop - a caught panic is an expected, reported outcome
    // here, not an unhandled crash the user needs a backtrace for.
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));

    let mut crashes: Vec<(u32, String, String)> = Vec::new();
    let mut finding_counts: Vec<usize> = Vec::new();

    for i in 0..args.iterations {
        let (file_path, source) = &sources[i as usize % sources.len()];
        let mutated = mutate_source(&mut fuzzer, source, args.depth);

        let chain = args.chain.clone();
        let result = std::panic::catch_unwind(|| match chain {
            ChainArg::Evm => truent_analyzer_evm::detectors::run_all_detectors(&mutated, file_path),
            ChainArg::Solana => truent_analyzer_solana::run_all_detectors(&mutated, file_path),
            ChainArg::Move => truent_analyzer_move::run_all_detectors(&mutated, file_path),
            ChainArg::Soroban => truent_analyzer_soroban::run_all_detectors(&mutated, file_path),
        });

        match result {
            Ok(findings) => finding_counts.push(findings.len()),
            Err(panic_payload) => {
                let msg = panic_payload
                    .downcast_ref::<&str>()
                    .map(|s| s.to_string())
                    .or_else(|| panic_payload.downcast_ref::<String>().cloned())
                    .unwrap_or_else(|| "<non-string panic payload>".to_string());
                crashes.push((i, file_path.clone(), msg));
            }
        }
    }

    std::panic::set_hook(original_hook);

    let duration_secs = start.elapsed().as_secs_f64();

    if !quiet {
        eprintln!(
            "✓ Ran {} iterations across {} file(s) in {:.2}s",
            args.iterations,
            sources.len(),
            duration_secs
        );

        if !finding_counts.is_empty() {
            let min = finding_counts.iter().min().copied().unwrap_or(0);
            let max = finding_counts.iter().max().copied().unwrap_or(0);
            let avg = finding_counts.iter().sum::<usize>() as f64 / finding_counts.len() as f64;
            eprintln!("  Findings per mutated variant: min {min}, max {max}, avg {avg:.1}");
        }

        if crashes.is_empty() {
            eprintln!("✓ No crashes found - detectors held up across all mutated inputs");
        } else {
            eprintln!(
                "✗ {} crash(es) found - detectors panicked on mutated input:",
                crashes.len()
            );
            for (iter, file, msg) in crashes.iter().take(10) {
                eprintln!("  iteration {iter} ({file}): {msg}");
            }
            if crashes.len() > 10 {
                eprintln!("  ... and {} more", crashes.len() - 10);
            }
        }

        // Bonus: EVM-specific detector precision/recall self-test, reusing
        // the existing synthetic-pattern fuzzers rather than leaving them
        // permanently disconnected from the CLI.
        if matches!(args.chain, ChainArg::Evm) && verbose {
            let precision_result = run_detector_precision_fuzzers(args.iterations as usize / 4);
            eprintln!(
                "  Detector precision self-test: precision {:.2}, recall {:.2}, F1 {:.2} ({} synthetic cases)",
                precision_result.precision(),
                precision_result.recall(),
                precision_result.f1_score(),
                precision_result.total,
            );
        }
    }

    if !crashes.is_empty() {
        std::process::exit(1);
    }

    Ok(())
}

/// Parse a `.invar` file into individual invariant specs.
///
/// Blocks are split by brace depth rather than by blank lines so a property
/// may span as many lines as it needs, and `//` comments are stripped.
fn parse_invariant_file(text: &str) -> anyhow::Result<Vec<truent_core::model::Invariant>> {
    let mut specs = Vec::new();
    let mut current = String::new();
    let mut depth = 0usize;

    for line in text.lines() {
        let code = line.split("//").next().unwrap_or("");
        if current.is_empty() && !code.trim_start().starts_with("invariant") {
            continue;
        }
        current.push_str(code);
        current.push('\n');
        depth += code.matches('{').count();
        depth -= code.matches('}').count().min(depth);
        if depth == 0 && !current.trim().is_empty() {
            let block = current.trim().to_string();
            let spec = truent_dsl_parser::parse_invariant(&block)
                .map_err(|e| anyhow::anyhow!("could not parse:\n{block}\n  {e}"))?;
            specs.push(spec);
            current.clear();
        }
    }

    if depth != 0 {
        anyhow::bail!("unbalanced braces — an invariant block is not closed");
    }
    if specs.is_empty() {
        anyhow::bail!("no `invariant NAME {{ ... }}` blocks found");
    }
    Ok(specs)
}