cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
// CERT-X-GEN: Advanced Multi-Language Security Scanning Engine
// Copyright (c) 2024 CERT-X-GEN Core Team

use cert_x_gen::pentest_install::{Bundle, Installer};
use cert_x_gen::{
    ai::{AIManager, TemplateValidator},
    config::Config,
    core::CertXGen,
    error::{Error, Result},
    output::OutputManager,
    plugin::{LoggingPlugin, PluginManager},
    progress::{get_progress, init_progress},
    template::{Template, TemplateFilter},
    types::{Protocol, Target, TemplateLanguage},
    utils,
};
use std::io::IsTerminal;
use std::sync::Arc;
use std::{
    collections::HashSet,
    fs,
    path::{Path, PathBuf},
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

mod cli;
mod scan_probes;
use cli::{Cli, Commands};

fn main() {
    // Clap's full command tree can exceed the native Windows main-thread stack
    // in debug builds. Give parsing and dispatch the same stack on every platform.
    std::thread::Builder::new()
        .name("cxg".into())
        .stack_size(8 * 1024 * 1024)
        .spawn(|| {
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .expect("build CLI runtime")
                .block_on(cli_main());
        })
        .expect("start CLI thread")
        .join()
        .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
}

async fn cli_main() {
    // Display the banner first (before parsing CLI), but never onto machine-readable
    // stdout. The default rule is a TTY check: suppress the banner whenever stdout is
    // not a terminal (pipes, redirects, CI, JSON-RPC over stdio for `mcp`, etc.).
    // Explicit escapes still force suppression even on a terminal.
    //
    // Related opt-out: CXG_NO_NAG silences the post-scan star request
    // (see `maybe_print_star_nag`); CXG_NO_BANNER silences both.
    let args: Vec<String> = std::env::args().collect();
    let suppress_banner = std::env::var("CXG_NO_BANNER").is_ok()
        || args.iter().any(|arg| arg == "--quiet" || arg == "-q")
        || args
            .iter()
            .any(|arg| arg == "--version" || arg == "-V" || arg == "--json")
        || !std::io::stdout().is_terminal();

    if !suppress_banner {
        cert_x_gen::banner::display_banner();
    }

    // Parse CLI arguments
    let cli = Cli::parse();

    // Initialize logging
    if let Err(e) = init_logging(&cli) {
        eprintln!("Failed to initialize logging: {}", e);
        std::process::exit(1);
    }

    // Check if we should auto-enter a Docker sandbox
    if let Err(e) = check_and_enter_sandbox(&cli).await {
        tracing::error!("Sandbox error: {}", e);
        eprintln!("Sandbox error: {}", e);
        std::process::exit(1);
    }

    // Run the command
    if let Err(e) = run(cli).await {
        tracing::error!("Error: {}", e);
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}

/// Initialize logging system based on verbosity level
/// - 0: No logging (progress bar mode) - only errors logged internally
/// - 1 (-v): INFO + WARN logs
/// - 2 (-vv): INFO + WARN + TRACE logs  
/// - 3+ (-vvv): INFO + WARN + TRACE + DEBUG logs (everything)
fn init_logging(cli: &Cli) -> Result<()> {
    // Initialize progress tracker (enabled only when verbose=0)
    let progress_enabled = cli.verbose == 0;
    init_progress(progress_enabled);

    // Build filter - for verbose modes, we want cert_x_gen logs at the right level
    // When progress bar is enabled (verbose=0), suppress all logs except errors
    let filter_str = match cli.verbose {
        0 => "error".to_string(),
        1 => "cert_x_gen=info".to_string(),
        2 => "cert_x_gen=trace".to_string(),
        _ => "cert_x_gen=trace,debug".to_string(),
    };

    let env_filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&filter_str));

    let fmt_layer = tracing_subscriber::fmt::layer()
        .with_target(true)
        .with_thread_ids(true)
        .with_writer(std::io::stderr);

    tracing_subscriber::registry()
        .with(env_filter)
        .with(fmt_layer)
        .init();

    Ok(())
}

/// Run the CLI command
async fn run(cli: Cli) -> Result<()> {
    // Handle -ut shorthand (update templates and exit)
    if cli.update_templates {
        use cert_x_gen::template::AutoUpdater;
        let mut updater = AutoUpdater::new()?;
        updater.perform_update()?;

        // Show stats after update
        let stats = updater.get_stats();
        println!();
        println!("Templates: {}", stats.summary());
        return Ok(());
    }

    // Check if command is 'template update' - skip auto-update since command handles it
    let is_template_update = matches!(
        &cli.command,
        Some(Commands::Template(cmd)) if matches!(cmd.action, cli::TemplateAction::Update { .. })
    );

    // Build, pentest and self-update commands need no detection-template
    // updates. Pentest status must stay read-only, pipeline publication must
    // stay offline, and `cxg update` must not clone templates on the way to
    // replacing (or declining to replace) the binary.
    if !is_template_update
        && !matches!(
            &cli.command,
            Some(Commands::Build(_) | Commands::Pentest(_) | Commands::Update(_))
        )
    {
        handle_auto_update(&cli).await?;
    }

    // If no command provided, show help
    let command = match cli.command {
        Some(cmd) => cmd,
        None => {
            // No command and no -ut flag - show help
            use clap::CommandFactory;
            let mut cmd = Cli::command();
            cmd.print_help().ok();
            println!();
            return Ok(());
        }
    };

    match command {
        Commands::Scan(args) => {
            if run_scan(args, cli.config).await? {
                std::process::exit(2);
            }
        }
        Commands::Build(cmd) => {
            run_build_command(cmd)?;
        }
        Commands::Template(cmd) => {
            run_template_command(cmd).await?;
        }
        Commands::Ai(cmd) => {
            run_ai_command(cmd).await?;
        }
        Commands::Search(args) => {
            run_search_command(args).await?;
        }
        Commands::Server(args) => {
            run_server(args).await?;
        }
        Commands::Config(cmd) => {
            run_config_command(cmd)?;
        }
        Commands::Sandbox(cmd) => {
            run_sandbox_command(cmd).await?;
        }
        Commands::Mcp(cmd) => {
            match cmd.action {
                None => {
                    // Default: start MCP server (stdio)
                    cert_x_gen::mcp::run_mcp().await?;
                }
                Some(cli::McpAction::Install { client }) => {
                    cert_x_gen::mcp::installer::run_install(client).await?;
                }
                Some(cli::McpAction::Uninstall { client }) => {
                    cert_x_gen::mcp::installer::run_uninstall(client).await?;
                }
                Some(cli::McpAction::Status) => {
                    cert_x_gen::mcp::installer::run_status().await?;
                }
            }
        }
        Commands::Pentest(cmd) => {
            run_pentest_command(cmd).await?;
        }
        Commands::Update(cmd) => {
            run_update_command(cmd).await?;
        }
        Commands::Version => {
            print_version();
        }
    }

    Ok(())
}

/// Map the current platform to the release-asset suffix used by `release.yml`
/// (e.g. `linux-amd64`, `darwin-arm64`, `windows-amd64`). Returns an error on
/// platforms we don't publish prebuilt binaries for.
// @comment -- "derives the GitHub release asset identifier for the running OS/arch so self-update fetches the correct binary"
fn release_target() -> Result<String> {
    let os = match std::env::consts::OS {
        "macos" => "darwin",
        "linux" => "linux",
        "windows" => "windows",
        other => {
            return Err(Error::config(format!(
                "no prebuilt cxg release for OS '{other}' — build from source"
            )))
        }
    };
    let arch = match std::env::consts::ARCH {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        other => {
            return Err(Error::config(format!(
                "no prebuilt cxg release for architecture '{other}' — build from source"
            )))
        }
    };
    Ok(format!("{os}-{arch}"))
}

/// Handle `cxg build --instrument` — produce an instrumented build, or say
/// honestly why one could not be produced.
///
/// Prints one JSON manifest on stdout and nothing else (or, with `-q`, just
/// the binary's path). The exit status carries the same answer for a shell:
/// **0** the binary exists and was verified, **3** the build was skipped. A
/// skip is not an error -- nothing went wrong, cxg simply refuses to hand back
/// an artefact it could not vouch for -- so it does not take the error path,
/// which is reserved for cxg itself failing.
// @comment -- "drives the target project's own build system, which executes that project's build scripts as the invoking user"
// @g.sink Commands.Build -- "executes `cargo build` in the operator-named project directory"
fn run_build_command(cmd: cli::BuildCommand) -> Result<()> {
    use cert_x_gen::build::{self, InstrumentRequest, Manifest};
    use std::io::Write;

    if !cmd.instrument {
        return Err(Error::config(
            "cxg build needs --instrument: it has no other mode".to_string(),
        ));
    }

    let sanitizers: Vec<String> = cmd
        .sanitizer
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    if sanitizers.is_empty() {
        return Err(Error::config(
            "--sanitizer needs at least one sanitizer, e.g. --sanitizer address".to_string(),
        ));
    }

    let manifest = build::instrument(&InstrumentRequest {
        project: cmd.project.clone(),
        bin: cmd.bin.clone(),
        sanitizers,
        out_dir: cmd.out.clone(),
        build_std: cmd.build_std,
    });

    let rendered =
        serde_json::to_string_pretty(&manifest).map_err(|e| Error::Serialization(e.to_string()))?;
    if let Some(ref path) = cmd.manifest {
        std::fs::write(path, format!("{rendered}\n")).map_err(|e| {
            Error::config(format!("cannot write --manifest '{}': {e}", path.display()))
        })?;
    }

    match &manifest {
        Manifest::Instrumented(built) => {
            if cmd.quiet {
                println!("{}", built.binary.display());
            } else {
                println!("{rendered}");
            }
            Ok(())
        }
        Manifest::Skipped(skipped) => {
            if cmd.quiet {
                // Nothing on stdout: `cli://$(cxg build ... -q)` must not be
                // handed a reason string as if it were a path.
                eprintln!("cxg build: skipped: {}", skipped.reason);
            } else {
                println!("{rendered}");
            }
            let _ = std::io::stdout().flush();
            std::process::exit(3);
        }
    }
}

/// Handle `cxg update` — replace the installed binary with a GitHub release.
///
/// Release assets are plain (non-archived) per-platform binaries named
/// `cxg-<os>-<arch>` (see `.github/workflows/release.yml`), so we match on that
/// suffix rather than the Rust target triple. `cert_x_gen::release_update`
/// explains why the download, the checksum and the replacement happen here
/// rather than in `self_update`.
// @comment -- "downloads an untrusted binary artifact from GitHub over TLS, checks it against the release's SHA256SUMS and atomically overwrites the on-disk cxg executable"
// @g.source (#github_release) -- "release binary fetched from github.com/Bugb-Technologies/cert-x-gen/releases"
// @g.sink Commands.Update -- "writes the downloaded executable over the running cxg binary"
async fn run_update_command(cmd: cli::UpdateCommand) -> Result<()> {
    use cert_x_gen::release_update::{self, CHECKSUMS_ASSET};

    let target = release_target()?;
    let current = env!("CARGO_PKG_VERSION");
    let invoked = std::env::current_exe()?;
    let installed = release_update::installed_executable(&invoked)?;
    let kind = release_update::detect_install(&installed);

    if cmd.check {
        let latest = lookup_release(None).await?;
        if self_update::version::bump_is_greater(current, &latest.version).unwrap_or(false) {
            println!("Update available: v{current} -> v{}", latest.version);
            match kind.upgrade_command() {
                Some(command) => println!("Upgrade it with: {command}"),
                None => println!("Run `cxg update` to install it."),
            }
        } else {
            println!("cxg is up to date (v{current})");
        }
        return Ok(());
    }

    // Decided before any network call, so a managed install is answered offline.
    if let (false, Some(manager), Some(command)) =
        (cmd.force, kind.manager(), kind.upgrade_command())
    {
        eprintln!(
            "cxg at {} is managed by {manager}, so `cxg update` leaves it alone.",
            installed.display()
        );
        eprintln!("Upgrade it with: {command}");
        eprintln!("(Pass --force to replace the file anyway.)");
        std::process::exit(3);
    }

    let release = lookup_release(cmd.version.clone()).await?;
    if cmd.version.is_none()
        && !self_update::version::bump_is_greater(current, &release.version).unwrap_or(false)
    {
        println!("cxg is already up to date (v{current})");
        return Ok(());
    }
    let asset = release.asset_for(&target, None).ok_or_else(|| {
        Error::config(format!(
            "release v{} has no cxg binary for {target}",
            release.version
        ))
    })?;
    let sums_asset = release
        .assets
        .iter()
        .find(|a| a.name == CHECKSUMS_ASSET)
        .ok_or_else(|| {
            Error::config(format!(
                "release v{} has no {CHECKSUMS_ASSET}, so its binary cannot be verified",
                release.version
            ))
        })?;

    println!("Current exe: {}", installed.display());
    if std::fs::symlink_metadata(&invoked).is_ok_and(|m| m.file_type().is_symlink()) {
        println!("  (invoked as {})", invoked.display());
    }
    println!(
        "New release: v{current} -> v{} ({})",
        release.version, asset.name
    );
    if !cmd.yes {
        let proceed = dialoguer::Confirm::new()
            .with_prompt("Replace the installed binary?")
            .default(true)
            .interact()
            .map_err(|e| {
                Error::config(format!("cannot prompt for confirmation ({e}); pass --yes"))
            })?;
        if !proceed {
            println!("Update cancelled.");
            return Ok(());
        }
    }

    let client = reqwest::Client::builder()
        .user_agent(concat!("cxg/", env!("CARGO_PKG_VERSION")))
        .build()?;
    println!("Downloading {}...", asset.name);
    let binary = download_release_asset(&client, &asset.download_url).await?;
    let sums = download_release_asset(&client, &sums_asset.download_url).await?;
    release_update::verify_sha256(&binary, &String::from_utf8_lossy(&sums), &asset.name)
        .map_err(Error::config)?;
    println!("Verified against {CHECKSUMS_ASSET}");

    let staging = tempfile::tempdir()?;
    let new_exe = staging.path().join(&asset.name);
    std::fs::write(&new_exe, &binary)?;
    release_update::replace_executable(&installed, &new_exe).map_err(|e| {
        if e.kind() == std::io::ErrorKind::PermissionDenied {
            Error::config(format!(
                "no permission to replace {} ({e}); re-run with sudo, or reinstall cxg in a \
                 directory you can write",
                installed.display()
            ))
        } else {
            Error::config(format!("cannot replace {}: {e}", installed.display()))
        }
    })?;
    println!("Updated cxg to v{}", release.version);
    Ok(())
}

/// Look up a release of cxg on GitHub: the given tag, or the latest.
async fn lookup_release(tag: Option<String>) -> Result<self_update::update::Release> {
    // self_update's GitHub client is blocking; run it off the async runtime.
    tokio::task::spawn_blocking(move || -> Result<self_update::update::Release> {
        let updater = self_update::backends::github::Update::configure()
            .repo_owner("Bugb-Technologies")
            .repo_name("cert-x-gen")
            .bin_name("cxg")
            .current_version(env!("CARGO_PKG_VERSION"))
            .build()?;
        Ok(match tag {
            Some(tag) => updater.get_release_version(&tag)?,
            None => updater.get_latest_release()?,
        })
    })
    .await
    .map_err(|e| Error::Internal(format!("release lookup task panicked: {e}")))?
}

/// Download one release asset through the GitHub API asset URL.
async fn download_release_asset(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
    let response = client
        .get(url)
        .header(reqwest::header::ACCEPT, "application/octet-stream")
        .send()
        .await?
        .error_for_status()?;
    Ok(response.bytes().await?.to_vec())
}

/// Resolve the pipeline through the existing cross-platform home override.
fn pentest_home() -> PathBuf {
    cert_x_gen::template::PathResolver::user_config_dir().join("pentest")
}

/// Dispatch for `cxg pentest …` — shells out to the Python orchestrator installed under
/// ~/.cert-x-gen/pentest/. The orchestrator is a Python module that handles auth capture,
/// codebase ingest, AI generation, browser execution, scope enforcement, and reporting.
#[derive(Debug, Default)]
struct PentestProcess {
    code: i32,
    error: String,
}

async fn run_pentest_command(cmd: cli::PentestCommand) -> Result<()> {
    let result = run_pentest_process(cmd, false).await?;
    if result.code != 0 {
        std::process::exit(result.code);
    }
    Ok(())
}

async fn run_pentest_process(
    cmd: cli::PentestCommand,
    scan_dispatch: bool,
) -> Result<PentestProcess> {
    use std::process::Command as SysCommand;
    let process_log = if scan_dispatch {
        match &cmd.action {
            cli::PentestAction::Run(run) => run
                .probe_inputs
                .session_dir
                .as_ref()
                .map(|dir| dir.join("engine.stderr.log")),
            _ => None,
        }
    } else {
        None
    };
    let home = pentest_home();

    let source_override = std::env::var_os("CXG_SOURCE").is_some();
    let installer = Installer::new(home.parent().unwrap().to_path_buf(), Bundle::embedded());
    let install_error = |e: anyhow::Error| {
        Error::Config(format!("pentest pipeline: {e:#}. No stale pipeline was launched; check writable home/disk space and retry `cxg pentest update`."))
    };
    match &cmd.action {
        cli::PentestAction::Status(cli::PentestStatusArgs { json }) => {
            let status = installer.status();
            if *json {
                println!("{}", serde_json::to_string(&status).unwrap());
            } else {
                println!(
                    "Pentest pipeline: {} at {}",
                    status.freshness,
                    home.display()
                );
            }
            return Ok(PentestProcess::default());
        }
        cli::PentestAction::Update(cli::PentestUpdateArgs {
            json,
            from_embedded,
        }) => {
            let result = installer
                .update(false, *from_embedded, source_override)
                .map_err(install_error)?;
            if *json {
                println!("{}", serde_json::to_string(&result).unwrap());
            }
            return Ok(PentestProcess::default());
        }
        cli::PentestAction::Install { force } => {
            // Source discovery is confined to this explicit development action.
            let bundle = match find_pentest_source() {
                Ok(source) => Bundle::source(&source).map_err(install_error)?,
                Err(e) if source_override => return Err(e),
                Err(_) => Bundle::embedded(),
            };
            Installer::new(home.parent().unwrap().to_path_buf(), bundle)
                .update(*force, false, source_override)
                .map_err(install_error)?;
            // Materialization works before Python or pip is installed.
            if let Err(e) = check_pentest_dependencies(&home) {
                eprintln!("{e}");
            }
            return Ok(PentestProcess::default());
        }
        _ => {}
    }
    let _lease = installer
        .execution_lease(source_override)
        .map_err(install_error)?;
    let orchestrator = home.join("cxg_pentest.py");

    // Build argv for the Python orchestrator.
    let mut args: Vec<String> = vec![orchestrator.to_string_lossy().to_string()];
    match cmd.action {
        cli::PentestAction::Install { .. }
        | cli::PentestAction::Update(_)
        | cli::PentestAction::Status(_) => unreachable!(),
        cli::PentestAction::Capabilities => {
            args.push("capabilities".into());
        }
        cli::PentestAction::Auth {
            target,
            profile,
            auth_numbers,
            creds,
            creds_file,
            login_path,
            label,
            verify_url,
            headers,
            tier,
            persona,
            cohort,
            tags,
            target_type,
            app_cmd,
            app_binary,
            auth_sub,
            auth_dir: parent_auth_dir,
        } => match auth_sub {
            // @comment -- "A subcommand routes to auth.py's browser-free CI paths (import/verify) instead of the interactive `auth login` capture. The capture path's --target/--profile are Option at the clap layer (clap derive won't negate a required parent arg for a subcommand — see cli.rs), and the import/verify subcommands carry their own --profile/--target, so the parent-level bindings are simply unused in these two branches."
            Some(cli::AuthSubcommand::Import {
                profile,
                target,
                storage_state,
                label,
                tier,
                persona,
                cohort,
                tags,
                headers,
                auth_dir,
                liveness_path,
                liveness_status,
                service,
                ci,
            }) => {
                args.extend([
                    "auth".into(),
                    "import".into(),
                    "--profile".into(),
                    profile,
                    "--target".into(),
                    target,
                ]);
                // @g.sink #operator_storage_state -- "hands the operator-supplied storage_state source (a path, '-' for stdin, or omitted for the env-var fallback) to auth.py, which resolves and REDACTS it; cxg never reads or echoes the session contents"
                if let Some(s) = storage_state {
                    args.extend(["--storage-state".into(), s]);
                }
                if let Some(l) = label {
                    args.extend(["--label".into(), l]);
                }
                if let Some(t) = tier {
                    args.extend(["--tier".into(), t]);
                }
                if let Some(p) = persona {
                    args.extend(["--persona".into(), p]);
                }
                if let Some(c) = cohort {
                    args.extend(["--cohort".into(), c]);
                }
                for t in tags {
                    args.extend(["--tag".into(), t]);
                }
                for h in headers {
                    args.extend(["--header".into(), h]);
                }
                if let Some(path) = liveness_path {
                    args.extend(["--liveness-path".into(), path]);
                }
                for status in liveness_status {
                    args.extend(["--liveness-status".into(), status.to_string()]);
                }
                if let Some(name) = service {
                    args.extend(["--service".into(), name]);
                }
                if let Some(d) = auth_dir.or(parent_auth_dir) {
                    args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
                }
                if ci {
                    args.push("--ci".into());
                }
            }
            Some(cli::AuthSubcommand::Verify {
                profile,
                target,
                me_path,
                auth_dir,
            }) => {
                args.extend([
                    "auth".into(),
                    "verify".into(),
                    "--profile".into(),
                    profile,
                    "--me-path".into(),
                    me_path,
                ]);
                if let Some(t) = target {
                    args.extend(["--target".into(), t]);
                }
                if let Some(d) = auth_dir.or(parent_auth_dir) {
                    args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
                }
            }
            None => {
                // @comment -- "--target/--profile are Option at the clap layer (see cli.rs: clap derive won't negate a required parent arg for the import/verify subcommands), so the interactive-capture path enforces them here. This reproduces the pre-change 'required argument' guard for bare `cxg pentest auth` without a subcommand; the happy path is unchanged."
                let (target, profile) = match (target, profile) {
                    (Some(t), Some(p)) => (t, p),
                    _ => {
                        eprintln!(
                            "error: `cxg pentest auth` (interactive capture) requires --target and --profile"
                        );
                        eprintln!("       (use `cxg pentest auth import`/`auth verify` for the non-interactive CI paths)");
                        return Err(Error::Config(
                            "missing --target/--profile for auth capture".to_string(),
                        ));
                    }
                };
                args.extend([
                    "auth".into(),
                    "login".into(),
                    "--target".into(),
                    target,
                    "--profile".into(),
                    profile,
                    "--auth-numbers".into(),
                    auth_numbers.to_string(),
                    "--login-path".into(),
                    login_path,
                ]);
                // The outer Python parser starts its REMAINDER at `login`;
                // capture options must follow that positional subcommand.
                if let Some(d) = parent_auth_dir {
                    args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
                }
                if let Some(c) = creds {
                    args.extend(["--creds".into(), c]);
                }
                if let Some(f) = creds_file {
                    args.extend(["--creds-file".into(), f.to_string_lossy().to_string()]);
                }
                if let Some(l) = label {
                    args.extend(["--label".into(), l]);
                }
                if let Some(v) = verify_url {
                    args.extend(["--verify-url".into(), v]);
                }
                for h in headers {
                    args.extend(["--header".into(), h]);
                }
                // @comment -- "Forward the operator identity-metadata flags to the Python orchestrator so tier/persona/cohort/tags reach the auth capture and are persisted with the profile"
                if let Some(t) = tier {
                    args.extend(["--tier".into(), t]);
                }
                if let Some(p) = persona {
                    args.extend(["--persona".into(), p]);
                }
                if let Some(c) = cohort {
                    args.extend(["--cohort".into(), c]);
                }
                for t in tags {
                    args.extend(["--tag".into(), t]);
                }
                // @comment -- "forwards desktop target selection and launch configuration to the Python orchestrator, which owns substrate construction"
                args.push("--target-type".into());
                args.push(target_type);
                // @g.sink #operator_app_cmd -- "hands the operator-supplied launch command to the Python orchestrator, which splits and executes it as a child process; cxg itself never executes it"
                if let Some(v) = app_cmd {
                    args.push("--app-cmd".into());
                    args.push(v);
                }
                if let Some(v) = app_binary {
                    args.push("--app-binary".into());
                    args.push(v);
                }
            }
        },
        cli::PentestAction::AuthList { auth_dir } => {
            args.extend(["auth".into(), "list".into()]);
            if let Some(d) = auth_dir {
                args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
            }
        }
        cli::PentestAction::ScopeInit { output } => {
            args.extend([
                "scope".into(),
                "init".into(),
                "--output".into(),
                output.to_string_lossy().to_string(),
            ]);
        }
        cli::PentestAction::Run(cli::PentestRunArgs {
            probe_inputs:
                cli::ProbeInputs {
                    codebase,
                    auth,
                    scope_file,
                    session_dir,
                    auth_dir,
                    auth_inputs,
                    no_author,
                },
            target,
            interactive_auth,
            auth_profile,
            auth_numbers,
            creds_file,
            template_lang,
            goal,
            threat_id,
            template_dir,
            max_templates,
            mutation_retries,
            ai_provider,
            ai,
            headed,
            destructive_ok,
            attestation,
            output,
            mitigation_mode,
            me_path,
            generation_timeout,
            skip_health_check,
            insecure_tls,
            proxy,
            client_cert,
            client_key,
            oast,
            oast_interactsh,
            oast_listener,
            oast_listener_dns,
            oast_redirect_location,
            oast_redirect_status,
            oast_dns_rebind_ip,
            target_type,
            app_cmd,
            app_binary,
            host_scan_path,
            tauri_prove,
            tauri_prove_timeout,
            attacker_origin,
            allow_raw_socket,
            capture_http,
            allow_grpc,
            grpc_descriptor_set,
            no_grpc_reflection,
            discover_routes,
            no_code_graph,
            only_routes,
            only_route,
            skills_file,
            enable_chaining,
            batch_size,
            deterministic_templates,
            template_timeout,
            stall_timeout,
            no_restart,
            ci,
        }) => {
            let mutation_retries = if no_author { 0 } else { mutation_retries };
            let ai = ai && !no_author;
            let deterministic_templates = deterministic_templates && !no_author;
            args.push("pentest".into());
            args.extend(["--codebase".into(), codebase.to_string_lossy().to_string()]);
            // @comment -- "Forwarded only when the operator supplied it. --target is optional at clap level so a tauri source-surface map can omit it; a web/electron run with no --target is refused by the Python preflight, not here, so this never silently drops a target a live probe needed."
            if let Some(t) = target {
                args.extend(["--target".into(), t]);
            }
            args.extend(["--auth".into(), auth]);
            args.extend(["--interactive-auth".into(), interactive_auth.to_string()]);
            args.extend(["--auth-profile".into(), auth_profile]);
            if let Some(n) = auth_numbers {
                args.extend(["--auth-numbers".into(), n.to_string()]);
            }
            if let Some(f) = creds_file {
                args.extend(["--creds-file".into(), f.to_string_lossy().to_string()]);
            }
            args.extend(["--template-lang".into(), template_lang]);
            if let Some(g) = goal {
                args.extend(["--goal".into(), g]);
            }
            if let Some(id) = threat_id {
                args.extend(["--threat-id".into(), id]);
            }
            if let Some(d) = template_dir {
                args.extend(["--template-dir".into(), d.to_string_lossy().to_string()]);
            }
            if no_author {
                args.push("--no-author".into());
            }
            args.extend(["--max-templates".into(), max_templates.to_string()]);
            args.extend(["--mutation-retries".into(), mutation_retries.to_string()]);
            args.extend(["--ai-provider".into(), ai_provider]);
            if ai {
                args.push("--ai".into());
            }
            if headed {
                args.push("--headed".into());
            }
            if let Some(s) = scope_file {
                args.extend(["--scope-file".into(), s.to_string_lossy().to_string()]);
            }
            if destructive_ok {
                args.push("--destructive-ok".into());
            }
            if let Some(a) = attestation {
                args.extend(["--attestation".into(), a]);
            }
            if let Some(s) = session_dir {
                args.extend(["--session-dir".into(), s.to_string_lossy().to_string()]);
            }
            if let Some(o) = output {
                args.extend(["--output".into(), o.to_string_lossy().to_string()]);
            }
            args.extend(["--mitigation-mode".into(), mitigation_mode]);
            args.extend(["--me-path".into(), me_path]);
            args.extend([
                "--generation-timeout".into(),
                generation_timeout.to_string(),
            ]);
            if insecure_tls {
                args.push("--insecure-tls".into());
            }
            if let Some(proxy) = proxy {
                args.extend(["--proxy".into(), proxy]);
            }
            if let Some(cert) = client_cert {
                args.extend(["--client-cert".into(), cert.to_string_lossy().to_string()]);
            }
            if let Some(key) = client_key {
                args.extend(["--client-key".into(), key.to_string_lossy().to_string()]);
            }
            if skip_health_check {
                args.push("--skip-health-check".into());
            }
            if let Some(h) = oast {
                args.extend(["--oast".into(), h]);
            }
            // @comment -- "forwards the OAST mode, not a session: which factory in pentest/oast.py builds it (external_session vs interactsh_session) is decided on the Python side, so the two CLIs cannot end up disagreeing about whether a canary is pollable"
            // @g.sink #operator_oast_server -- "hands the operator-supplied interactsh server URL to the Python orchestrator, which registers the session against it; cxg itself opens no connection here"
            // @comment -- "the bare form is forwarded as the flag ALONE, with no argument, because that is precisely what 'use interactsh's defaults' means downstream — passing an empty string as the value would instead register against a server named '' and fail; clap's empty default_missing_value is a marker for this branch, never a value to relay"
            if let Some(server) = oast_interactsh {
                args.push("--oast-interactsh".into());
                if !server.is_empty() {
                    args.push(server);
                }
            }
            // @comment -- "forwards the built-in-listener mode the same way as --oast-interactsh: the bare form is the flag alone (meaning 'bind the docker bridge' downstream), and an empty string as a value would instead be read as an operator address of '' and misparsed, so clap's empty default_missing_value is a branch marker, never a relayed value. pentest/oast_listener.py binds the socket and owns reachability, so the two CLIs cannot disagree about whether this canary is pollable"
            if let Some(bind) = oast_listener {
                args.push("--oast-listener".into());
                if !bind.is_empty() {
                    args.push(bind);
                }
            }
            if oast_listener_dns {
                args.push("--oast-listener-dns".into());
            }
            for (flag, value) in [
                ("--oast-redirect-location", oast_redirect_location),
                ("--oast-redirect-status", oast_redirect_status),
                ("--oast-dns-rebind-ip", oast_dns_rebind_ip),
            ] {
                if let Some(value) = value {
                    args.push(flag.into());
                    args.push(value);
                }
            }
            // @comment -- "forwards desktop target selection and launch configuration to the Python orchestrator, which owns substrate construction"
            args.push("--target-type".into());
            args.push(target_type);
            // @g.sink #operator_app_cmd -- "hands the operator-supplied launch command to the Python orchestrator, which splits and executes it as a child process per identity; cxg itself never executes it"
            if let Some(v) = app_cmd {
                args.push("--app-cmd".into());
                args.push(v);
            }
            if let Some(v) = app_binary {
                args.push("--app-binary".into());
                args.push(v);
            }
            if let Some(v) = host_scan_path {
                args.push("--host-scan-path".into());
                args.push(v);
            }
            // @comment -- "Forwarded only when the operator opted in; a plain tauri run stays a source-surface map. The timeout rides along only when proving is on, so the orchestrator's own default governs every other run."
            if tauri_prove {
                args.push("--tauri-prove".into());
                args.extend([
                    "--tauri-prove-timeout".into(),
                    tauri_prove_timeout.to_string(),
                ]);
            }
            // @comment -- "Both are pushed only when set, matching every other boolean here: an absent flag leaves the orchestrator's own default in force rather than this layer restating it, so the two CLIs cannot drift apart on what 'off' means."
            if attacker_origin {
                args.push("--attacker-origin".into());
            }
            if allow_raw_socket {
                args.push("--allow-raw-socket".into());
            }
            if capture_http {
                args.push("--capture-http".into());
            }
            // @comment -- "Pushed only when set, like every other boolean here, so an absent flag leaves the orchestrator's own default in force rather than this layer restating it. --no-grpc-reflection matters most for that rule: reflection defaults ON in the orchestrator, so forwarding a false here would silently disable a default this layer does not own."
            if allow_grpc {
                args.push("--allow-grpc".into());
            }
            if let Some(v) = grpc_descriptor_set {
                args.push("--grpc-descriptor-set".into());
                args.push(v);
            }
            if no_grpc_reflection {
                args.push("--no-grpc-reflection".into());
            }
            if discover_routes {
                args.push("--discover-routes".into());
            }
            if no_code_graph {
                args.push("--no-code-graph".into());
            }
            if let Some(f) = only_routes {
                args.extend(["--only-routes".into(), f.to_string_lossy().to_string()]);
            }
            for entry in only_route {
                args.extend(["--only-route".into(), entry]);
            }
            if let Some(f) = skills_file {
                args.extend(["--skills-file".into(), f.to_string_lossy().to_string()]);
            }
            if enable_chaining {
                args.push("--enable-chaining".into());
            }
            if let Some(path) = auth_inputs {
                args.push("--auth-inputs".into());
                args.push(path.display().to_string());
            }
            if batch_size > 1 {
                args.push("--batch-size".into());
                args.push(batch_size.to_string());
            }
            if deterministic_templates {
                args.push("--deterministic-templates".into());
            }
            // @comment -- "forwards the two dispatch bounds and the recovery opt-out only when the operator actually set them, so an unset flag leaves the orchestrator's own default in force rather than this layer restating it — one default, in one place, that the two CLIs cannot drift apart on"
            if let Some(v) = template_timeout {
                args.push("--template-timeout".into());
                args.push(v.to_string());
            }
            if let Some(v) = stall_timeout {
                args.push("--stall-timeout".into());
                args.push(v.to_string());
            }
            if no_restart {
                args.push("--no-restart".into());
            }
            // @comment -- "forward the CI auth-store redirect and CI-mode selector only when the operator set them, so an unset flag leaves the orchestrator's ~/.cert-x-gen/auth store and warn-on-dead-session default in force. CXG_CI=1 still reaches the orchestrator through the inherited environment even when --ci is absent."
            if let Some(d) = auth_dir {
                args.push("--auth-dir".into());
                args.push(d.to_string_lossy().to_string());
            }
            if ci {
                args.push("--ci".into());
            }
        }
    }

    let python = check_pentest_dependencies(&home)?;
    let mut process = SysCommand::new(&python);
    process.args(&args);
    if scan_dispatch {
        process.arg("--scan-dispatch");
        let log = process_log
            .ok_or_else(|| Error::config("automatic probes require an engine session directory"))?;
        process.stderr(std::fs::File::create(&log)?);
        process.stdin(std::process::Stdio::inherit());
        let status = process
            .status()
            .map_err(|e| Error::Config(format!("failed to spawn python orchestrator: {e}")))?;
        let error = std::fs::read_to_string(log).unwrap_or_default();
        use std::io::Write;
        std::io::stderr().write_all(error.as_bytes())?;
        return Ok(PentestProcess {
            code: status.code().unwrap_or(1),
            error,
        });
    }
    let status = process
        .status()
        .map_err(|e| Error::Config(format!("failed to spawn python orchestrator: {e}")))?;
    Ok(PentestProcess {
        code: status.code().unwrap_or(1),
        error: String::new(),
    })
}

/// Find a usable python3 binary. Tries CXG_PYTHON env var first.
fn which_python() -> Result<PathBuf> {
    if let Ok(p) = std::env::var("CXG_PYTHON") {
        return Ok(PathBuf::from(p));
    }
    for candidate in &["python3", "python"] {
        if std::process::Command::new(candidate)
            .arg("--version")
            .output()
            .is_ok_and(|out| out.status.success())
        {
            return Ok(PathBuf::from(candidate));
        }
    }
    Err(Error::Config(
        "python3 not found on PATH (set CXG_PYTHON env var to override)".into(),
    ))
}

/// Check imports before any Python dispatch can contact a target. Never installs deps.
fn check_pentest_dependencies(home: &Path) -> Result<PathBuf> {
    let python = which_python()?;
    let check = std::process::Command::new(&python)
        .args(["-c", "import playwright, yaml"])
        .output();
    if !check.is_ok_and(|out| out.status.success()) {
        return Err(Error::Config(format!(
            "Python dependency check failed for {}. Run: \"{}\" -m pip install -r \"{}\"; then \"{}\" -m playwright install chromium. No target was contacted.",
            python.display(), python.display(), home.join("requirements.txt").display(), python.display()
        )));
    }
    Ok(python)
}

fn find_pentest_source() -> Result<PathBuf> {
    if let Ok(s) = std::env::var("CXG_SOURCE") {
        let p = PathBuf::from(s).join("pentest");
        if p.join("cxg_pentest.py").is_file() {
            return Ok(p);
        }
        return Err(Error::Config(format!(
            "CXG_SOURCE has no pentest bundle at {}",
            p.display()
        )));
    }
    // 1) sibling to current_exe (release install layout)
    if let Ok(exe) = std::env::current_exe() {
        if let Some(parent) = exe.parent() {
            for rel in &["pentest", "../pentest", "../share/cert-x-gen/pentest"] {
                let p = parent.join(rel);
                if p.join("cxg_pentest.py").exists() {
                    return Ok(p);
                }
            }
        }
    }
    // 2) source tree (development): cwd/pentest or ./pentest from cargo's manifest dir
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let cwd_p = cwd.join("pentest");
    if cwd_p.join("cxg_pentest.py").exists() {
        return Ok(cwd_p);
    }
    Err(Error::Config(
        "could not locate pentest source dir. Set CXG_SOURCE=<cxg-repo> to override.".into(),
    ))
}

/// Handle auto-update logic based on CLI flags
async fn handle_auto_update(cli: &Cli) -> Result<()> {
    use cert_x_gen::template::AutoUpdater;

    let mut updater = AutoUpdater::new()?;

    // Option 1: Force update on every startup (--update-templates-on-startup)
    if cli.update_templates_on_startup {
        tracing::info!("Forced template update on startup enabled");
        updater.perform_update()?;
        return Ok(());
    }

    // Option 2: Auto-update before running (--auto-update-templates)
    if cli.auto_update_templates {
        tracing::info!("Auto-updating templates before running...");
        updater.perform_update()?;
        return Ok(());
    }

    // Option 3: Disable update checks (--disable-update-check)
    if cli.disable_update_check {
        tracing::debug!("Auto-update checks disabled by user");
        updater.disable_auto_check()?;
        return Ok(());
    }

    // Option 4: Default behavior - check if templates exist (first-run auto-install)
    if updater.needs_initial_install() {
        updater.auto_install()?;
        return Ok(());
    }

    // Option 5: Hourly update check (like Nuclei)
    if updater.should_check_for_updates() {
        tracing::debug!("Checking for template updates...");
        let _ = updater.check_for_updates(); // Don't fail if update check fails
    }

    Ok(())
}

/// Run a security scan
async fn run_scan(args: cli::ScanArgs, config_path: Option<PathBuf>) -> Result<bool> {
    // Load configuration
    let mut config = if let Some(path) = config_path {
        Config::from_file(path)?
    } else {
        Config::default()
    };

    // Override config with CLI arguments
    apply_scan_args_to_config(&mut config, &args);

    tracing::info!("Starting CERT-X-GEN v{}", env!("CARGO_PKG_VERSION"));
    tracing::info!("Configuration loaded and validated");

    // Create CERT-X-GEN engine (template engines are auto-registered)
    let engine = CertXGen::new(config.clone()).await?;

    // Check for direct template file paths in --templates argument
    let (direct_template_paths, filter_ids) = if !args.templates.is_empty() {
        tracing::debug!("Processing --templates argument: {:?}", args.templates);
        separate_template_entries(&args.templates, &config.templates.directories)?
    } else {
        (Vec::new(), Vec::new())
    };

    // Determine loading strategy
    let has_direct_paths = !direct_template_paths.is_empty();
    let has_filter_ids = !filter_ids.is_empty();

    // Load templates based on what user specified
    tracing::info!("Loading templates...");

    let mut discovery_issues = Vec::new();
    let mut selection_error = None;
    let templates: Vec<Box<dyn Template>> = if has_direct_paths {
        // CASE 1: User specified direct file paths - load ONLY those (most efficient)
        tracing::info!(
            "Loading {} template(s) from direct paths",
            direct_template_paths.len()
        );
        let mut direct_templates: Vec<Box<dyn Template>> = Vec::new();

        for path in &direct_template_paths {
            tracing::debug!("Loading template from: {}", path.display());
            match engine.template_loader().load_template(path).await {
                Ok(template) => {
                    tracing::info!(
                        "Loaded template: {} ({}) from {}",
                        template.id(),
                        template.metadata().language,
                        path.display()
                    );
                    direct_templates.push(template);
                }
                Err(e) => {
                    tracing::error!("Failed to load template from {}: {}", path.display(), e);
                    return Err(Error::config(format!(
                        "Failed to load template '{}': {}",
                        path.display(),
                        e
                    )));
                }
            }
        }

        if direct_templates.is_empty() {
            return Err(Error::config(
                "No templates could be loaded from the specified paths.",
            ));
        }

        direct_templates
    } else {
        let mut discovered = engine.load_templates_with_report().await?;
        discovery_issues = discovered.issues;
        if has_filter_ids {
            let mut matched_selectors = HashSet::new();
            discovered.templates.retain(|template| {
                let metadata = template.metadata();
                let mut matched = false;
                for filter_id in &filter_ids {
                    if metadata.id.eq_ignore_ascii_case(filter_id)
                        || metadata.name.eq_ignore_ascii_case(filter_id)
                        || metadata.file_path.to_string_lossy().contains(filter_id)
                        || metadata
                            .file_path
                            .file_stem()
                            .and_then(|s| s.to_str())
                            .is_some_and(|s| s.eq_ignore_ascii_case(filter_id))
                    {
                        matched_selectors.insert(filter_id);
                        matched = true;
                    }
                }
                matched
            });
            for filter_id in &filter_ids {
                if !matched_selectors.contains(filter_id) {
                    tracing::warn!("Template not found: {}", filter_id);
                }
            }
            if discovered.templates.is_empty() {
                selection_error = Some(Error::config(format!(
                    "No templates found matching: {:?}. Use 'cxg template list' to see available templates.",
                    filter_ids
                )));
            }
        }
        discovered.templates
    };

    tracing::info!("Total templates to use: {}", templates.len());

    // Debug: Print all loaded template IDs
    for template in &templates {
        let metadata = template.metadata();
        tracing::debug!(
            "Available template: {} ({})",
            metadata.id,
            metadata.language
        );
    }

    if templates.is_empty() && discovery_issues.is_empty() {
        return Err(selection_error.unwrap_or_else(|| {
            Error::config("No templates loaded. Please add templates to the templates directory.")
        }));
    }
    let no_templates_loaded =
        templates.is_empty() && discovery_issues.iter().any(|issue| issue.error.is_some());

    // Parse targets
    let mut targets = parse_targets(&args)?;
    if targets.is_empty() {
        return Err(Error::config(
            "No scope provided. Use --scope (aliases: --target, --targets, --target-file, --domain, --cidr, etc.).",
        ));
    }
    tracing::info!("Parsed {} targets", targets.len());

    // Expand targets for additional ports
    let mut additional_ports = Vec::new();
    if !args.ports.is_empty() {
        additional_ports = parse_port_entries(&args.ports)?;
        if !additional_ports.is_empty() {
            targets = expand_targets_for_ports(targets, &additional_ports);
            tracing::info!(
                "Expanded to {} targets with additional ports: {:?}",
                targets.len(),
                additional_ports
            );
        }
    }

    let mut top_ports = Vec::new();
    if let Some(count) = args.top_ports {
        top_ports = select_top_ports(count);
        if !top_ports.is_empty() {
            targets = expand_targets_for_ports(targets, &top_ports);
            tracing::info!(
                "Expanded to {} targets with top ports: {:?}",
                targets.len(),
                top_ports
            );
        }
    }

    // Create template filter
    // When we've already done targeted loading (direct paths or filter_ids), skip ID filtering
    let skip_id_filter = has_direct_paths || has_filter_ids;
    let filter = create_template_filter(&args, skip_id_filter)?;

    // Debug: Print filter details
    if !filter.ids.is_empty() {
        tracing::info!("Filtering templates by IDs: {:?}", filter.ids);
    }
    if !filter.tags.is_empty() {
        tracing::info!("Filtering templates by tags: {:?}", filter.tags);
    }
    if !filter.severities.is_empty() {
        tracing::info!("Filtering templates by severities: {:?}", filter.severities);
    }
    if !filter.languages.is_empty() {
        tracing::info!("Filtering templates by languages: {:?}", filter.languages);
    }
    if !filter.exclude_ids.is_empty() {
        tracing::info!("Excluding templates: {:?}", filter.exclude_ids);
    }

    // Create scan job
    let mut job = engine.create_scan_job(targets, templates);
    let templates_before = job.templates.len();
    job.filter_templates(&filter);

    // Apply mode-based template filtering
    if args.safe {
        // Safe mode: Exclude dangerous templates
        let dangerous_tags = [
            "dos",
            "resource-exhaustion",
            "intrusive",
            "destructive",
            "brute-force",
            "exploit",
        ];
        let before_safe = job.templates.len();
        job.templates.retain(|template| {
            let metadata = template.metadata();
            !dangerous_tags
                .iter()
                .any(|tag| metadata.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)))
        });
        let after_safe = job.templates.len();
        if before_safe != after_safe {
            tracing::info!(
                "Safe mode: Excluded {} dangerous templates (DoS, resource-exhaustion, etc.)",
                before_safe - after_safe
            );
        }
    }

    if args.passive {
        // Passive mode: Only include passive templates or exclude active ones
        let active_tags = ["active", "probe", "intrusive", "exploit"];
        let before_passive = job.templates.len();
        job.templates.retain(|template| {
            let metadata = template.metadata();
            // Include if tagged as passive, exclude if tagged as active
            let has_passive_tag = metadata
                .tags
                .iter()
                .any(|t| t.eq_ignore_ascii_case("passive"));
            let has_active_tag = active_tags
                .iter()
                .any(|tag| metadata.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)));
            has_passive_tag || !has_active_tag
        });
        let after_passive = job.templates.len();
        if before_passive != after_passive {
            tracing::info!(
                "Passive mode: Excluded {} active probe templates",
                before_passive - after_passive
            );
        }
    }

    let templates_after = job.templates.len();

    tracing::info!(
        "Templates selected: {} (total available: {})",
        templates_after,
        templates_before
    );

    // List selected templates in verbose mode
    if templates_after > 0 && templates_after <= 10 {
        for template in &job.templates {
            tracing::info!(
                "  - {} ({})",
                template.metadata().id,
                template.metadata().language
            );
        }
    }

    if !additional_ports.is_empty() || !top_ports.is_empty() {
        let mut combined = additional_ports.clone();
        combined.extend(top_ports.iter().copied());
        combined.sort_unstable();
        combined.dedup();
        job.context.additional_ports = combined;
        tracing::info!(
            "Adding {} additional ports to scan (custom + top): {:?}",
            job.context.additional_ports.len(),
            job.context.additional_ports
        );
    }

    if let Some(ref override_ports) = args.override_ports {
        let override_ports = parse_ports(override_ports)?;
        job.context.override_ports = Some(override_ports.clone());
        tracing::info!(
            "Overriding template default ports with: {:?}",
            override_ports
        );
    }

    // Apply --context JSON to template execution context
    if let Some(ref context_json) = args.context {
        match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(context_json) {
            Ok(map) => {
                for (key, value) in map {
                    let str_value = match value {
                        serde_json::Value::String(s) => s,
                        other => other.to_string(),
                    };
                    job.context.variables.insert(key, str_value);
                }
                tracing::info!(
                    "Injected {} context variables from --context flag",
                    job.context.variables.len()
                );
            }
            Err(e) => {
                tracing::warn!(
                    "Failed to parse --context JSON '{}': {}. Context variables not set.",
                    context_json,
                    e
                );
            }
        }
    }

    apply_probe_input(&args, &mut job.context)?;

    let (probe_templates, scanner_templates): (Vec<_>, Vec<_>) = std::mem::take(&mut job.templates)
        .into_iter()
        .partition(|template| template.is_js_probe());
    job.templates = scanner_templates;
    let has_probes = !probe_templates.is_empty();
    if !has_probes
        && (!args.probe_inputs.auth.is_empty()
            || args.probe_inputs.scope_file.is_some()
            || args.probe_inputs.auth_inputs.is_some())
    {
        return Err(Error::config("--auth, --auth-inputs and --scope-file apply to JS probes; no probe-contract templates were selected"));
    }

    tracing::info!(
        "Scan job created: {} targets × {} templates = {} total checks",
        job.targets.len(),
        job.templates.len(),
        job.total_work_units()
    );

    // Initialize plugin system
    let mut plugin_manager = PluginManager::new();
    plugin_manager.register(Arc::new(LoggingPlugin::new()));
    plugin_manager.notify_scan_start(job.id);

    // Initialize progress bar
    if let Some(progress) = get_progress().filter(|_| !job.templates.is_empty()) {
        progress.init(job.targets.len(), job.templates.len());
    }

    // Execute scan
    tracing::info!("Starting scan execution...");
    let start = std::time::Instant::now();
    let mut results = if job.templates.is_empty() {
        let mut results = cert_x_gen::types::ScanResults::new(job.id);
        results.statistics.network_requests = Some(0);
        results.complete();
        results
    } else {
        engine.execute_scan(job).await?
    };
    results.add_discovery_issues(discovery_issues);
    let probe_exit = if has_probes {
        for finding in &mut results.findings {
            finding.verdict_source = Some("template-reported".into());
        }
        let code = scan_probes::execute(&args, probe_templates, &mut results).await?;
        results.complete();
        code
    } else {
        0
    };
    let duration = start.elapsed();

    // Finish progress bar
    if let Some(progress) = get_progress() {
        progress.finish();
    }

    tracing::info!("Scan completed in {:.2}s", duration.as_secs_f64());
    tracing::info!("Found {} total findings", results.findings.len());

    // Notify plugins
    plugin_manager.notify_scan_complete(&results);

    // Output results
    let output_manager = OutputManager::new();
    let mut formats: Vec<String> = args
        .output_format
        .split(',')
        .map(|s| s.trim().to_string())
        .collect();
    if has_probes && !formats.iter().any(|format| format == "json") {
        formats.push("json".into());
    }

    let output_path = PathBuf::from(&args.output);
    output_manager.write_results(&results, &output_path, &formats)?;

    // Print summary
    print_scan_summary(&results);

    // A quiet, infrequent nudge — only after a completed scan on an interactive terminal.
    maybe_print_star_nag(args.quiet);

    if let Some(error) = selection_error {
        return Err(error);
    }

    if probe_exit != 0 {
        use std::io::Write;
        std::io::stdout().flush()?;
        std::process::exit(probe_exit);
    }

    let gate_failed = results.executions.iter().any(|execution| {
        args.fail_on
            .iter()
            .any(|status| status.status() == execution.status)
    });
    if no_templates_loaded && !gate_failed {
        return Err(Error::config(
            "No templates could be loaded from the specified directories.",
        ));
    }
    Ok(gate_failed)
}

/// Apply scan arguments to configuration
fn apply_scan_args_to_config(config: &mut Config, args: &cli::ScanArgs) {
    config.execution.parallel_targets = args.parallel_targets;
    config.execution.parallel_templates = args.parallel_templates;
    config.execution.max_retries = args.retry;
    config.execution.aggressive_mode = args.aggressive;
    config.execution.stealth_mode = args.stealth;

    // Apply mode-specific optimizations
    if args.aggressive {
        // Aggressive mode: Increase concurrency, remove rate limits, increase retries
        config.execution.parallel_targets *= 2;
        config.execution.parallel_templates *= 2;
        config.execution.max_retries *= 2;
        config.network.rate_limit = None; // Remove rate limits
        tracing::info!("Aggressive mode: Increased concurrency and retries, removed rate limits");
    }

    if args.stealth {
        // Stealth mode: Reduce concurrency, enforce rate limits, use browser user agent
        config.execution.parallel_targets = std::cmp::max(1, config.execution.parallel_targets / 3);
        config.execution.parallel_templates =
            std::cmp::max(1, config.execution.parallel_templates / 2);
        // Enforce rate limiting (default to 10 req/s if not set)
        if config.network.rate_limit.is_none() {
            config.network.rate_limit = Some(10);
        }
        // Use browser-like user agent if not already set
        if args.user_agent.is_none() {
            config.network.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36".to_string();
        }
        tracing::info!(
            "Stealth mode: Reduced concurrency, enforced rate limiting, using browser user agent"
        );
    }

    if args.passive {
        // Passive mode: Minimal concurrency
        config.execution.parallel_targets = std::cmp::max(1, config.execution.parallel_targets / 5);
        config.execution.parallel_templates = 1; // Sequential templates
        tracing::info!("Passive mode: Minimal concurrency, sequential template execution");
    }

    if args.safe {
        // Safe mode: Slightly reduce concurrency, keep rate limiting
        config.execution.parallel_targets =
            std::cmp::max(1, (config.execution.parallel_targets * 3) / 4);
        config.execution.parallel_templates =
            std::cmp::max(1, (config.execution.parallel_templates * 3) / 4);
        // Ensure rate limiting is enabled
        if config.network.rate_limit.is_none() {
            config.network.rate_limit = Some(50);
        }
        tracing::info!("Safe mode: Reduced concurrency, rate limiting enabled");
    }

    // Parse and apply timeout
    match utils::parse_duration(&args.timeout) {
        Ok(duration) => {
            config.network.timeout_secs = duration.as_secs();
            // Also apply to template timeout if reasonable
            if duration.as_secs() > 0 {
                config.templates.timeout_secs = duration.as_secs();
            }
        }
        Err(e) => {
            tracing::warn!(
                "Failed to parse timeout '{}': {}. Using default.",
                args.timeout,
                e
            );
        }
    }

    if let Some(proxy) = &args.proxy {
        config.network.proxy = Some(proxy.clone());
    }

    if let Some(user_agent) = &args.user_agent {
        config.network.user_agent = user_agent.clone();
    }

    config.network.follow_redirects = args.follow_redirects;
    config.network.max_redirects = args.max_redirects;

    if let Some(rate_limit) = args.rate_limit {
        config.network.rate_limit = Some(rate_limit);
    }

    // Apply template directory if specified
    if let Some(template_dir) = &args.template_dir {
        config.templates.directories = vec![template_dir.clone()];
    }

    // Apply custom headers
    if let Some(headers) = &args.header {
        for header in headers {
            if let Some((key, value)) = header.split_once(':') {
                config
                    .network
                    .headers
                    .push((key.trim().to_string(), value.trim().to_string()));
            }
        }
    }

    // Apply cookies for authenticated scans
    if let Some(cookies) = &args.cookie {
        for cookie in cookies {
            if let Some((key, value)) = cookie.split_once('=') {
                config
                    .network
                    .cookies
                    .push((key.trim().to_string(), value.trim().to_string()));
            }
        }
        if !config.network.cookies.is_empty() {
            tracing::info!(
                "Using {} cookie(s) for authenticated scanning",
                config.network.cookies.len()
            );
        }
    }
}

/// Expand targets to create one target per port
/// This enables testing multiple ports on the same host
fn expand_targets_for_ports(targets: Vec<Target>, ports: &[u16]) -> Vec<Target> {
    if ports.is_empty() {
        return targets;
    }

    let mut expanded = Vec::new();

    for target in targets {
        // If target already has a port, keep it and add additional ports
        if target.port.is_some() {
            expanded.push(target.clone());
        }

        // Create a target for each additional port
        for &port in ports {
            // Skip if this port is already the target's port
            if target.port == Some(port) {
                continue;
            }

            let mut new_target = target.clone();
            new_target.port = Some(port);
            expanded.push(new_target);
        }
    }

    expanded
}

/// Move the probe-input flags onto the scan context.
///
/// Every one of these is optional and each is delivered to the template as its
/// own environment variable, absent unless the flag was passed. Paths are
/// validated here and canonicalised, so a template never receives a path that
/// does not resolve or that depends on cxg's working directory -- a probe
/// silently reading nothing is exactly the kind of quiet wrong answer the
/// execution ledger exists to prevent.
fn apply_probe_input(args: &cli::ScanArgs, context: &mut cert_x_gen::types::Context) -> Result<()> {
    if !args.arg.is_empty() {
        context.probe_argv = args.arg.clone();
        tracing::info!(
            "Probe argv: {} argument(s) delivered as CERT_X_GEN_ARGV",
            context.probe_argv.len()
        );
    }

    if let Some(ref path) = args.stdin_file {
        if !path.is_file() {
            return Err(Error::config(format!(
                "--stdin-file '{}' is not a readable file",
                path.display()
            )));
        }
        let resolved = path.canonicalize().unwrap_or_else(|_| path.clone());
        tracing::info!("Probe stdin file: {}", resolved.display());
        context.probe_stdin_file = Some(resolved);
    }

    if let Some(ref path) = args.input {
        if !path.is_dir() {
            return Err(Error::config(format!(
                "--input '{}' is not a directory",
                path.display()
            )));
        }
        let resolved = path.canonicalize().unwrap_or_else(|_| path.clone());
        tracing::info!("Probe input dir: {}", resolved.display());
        context.probe_input_dir = Some(resolved);
    }

    for kv in &args.target_env {
        // Only the FIRST '=' separates key from value, so a value that is
        // itself a k=v list (ASAN_OPTIONS=abort_on_error=1) survives intact.
        let Some((key, value)) = kv.split_once('=') else {
            return Err(Error::config(format!(
                "--target-env '{}' is not KEY=VALUE",
                kv
            )));
        };
        if key.is_empty() {
            return Err(Error::config(format!(
                "--target-env '{}' has an empty key",
                kv
            )));
        }
        context.probe_env.push((key.to_string(), value.to_string()));
    }
    if !context.probe_env.is_empty() {
        tracing::info!(
            "Probe target environment: {} variable(s) delivered as CERT_X_GEN_TARGET_ENV",
            context.probe_env.len()
        );
    }

    context.require_instrumentation = args.require_instrumentation;
    if context.require_instrumentation {
        tracing::info!(
            "Instrumentation preflight enabled: against a cli:// target with no detectable \
             instrumentation, a template whose oracles needed it is skipped rather than \
             reported as no-findings"
        );
    }

    for path in &args.instrumented_manifest {
        let (binary, instrumentation) = read_instrumented_manifest(path)?;
        tracing::info!(
            "Instrumentation provenance for {}: {} (from {})",
            binary,
            instrumentation.join(","),
            path.display()
        );
        context
            .instrumentation_provenance
            .insert(binary, instrumentation);
    }

    Ok(())
}

/// Read one `cxg build --instrument` manifest into a (binary, instrumentation)
/// pair.
///
/// A manifest recording a **skipped** build is an error rather than a silent
/// no-op. It names a build that did not happen, so a scan that accepted it and
/// carried on would be inspecting some older artefact while the operator
/// believed they had handed over provenance -- and the reason the build was
/// skipped is exactly what they need to see.
fn read_instrumented_manifest(path: &std::path::Path) -> Result<(String, Vec<String>)> {
    use cert_x_gen::build::Manifest;

    let raw = std::fs::read_to_string(path).map_err(|e| {
        Error::config(format!(
            "--instrumented-manifest '{}' is not readable: {e}",
            path.display()
        ))
    })?;
    let manifest: Manifest = serde_json::from_str(&raw).map_err(|e| {
        Error::config(format!(
            "--instrumented-manifest '{}' is not a cxg build manifest: {e}",
            path.display()
        ))
    })?;

    match manifest {
        Manifest::Instrumented(built) => {
            let binary = built
                .binary
                .canonicalize()
                .unwrap_or_else(|_| built.binary.clone());
            if built.instrumentation.is_empty() {
                return Err(Error::config(format!(
                    "--instrumented-manifest '{}' records no instrumentation for {}",
                    path.display(),
                    built.binary.display()
                )));
            }
            Ok((binary.to_string_lossy().to_string(), built.instrumentation))
        }
        Manifest::Skipped(skipped) => Err(Error::config(format!(
            "--instrumented-manifest '{}' records a build that was SKIPPED ({}); there is no \
             instrumented binary to trust",
            path.display(),
            skipped.reason
        ))),
    }
}

/// Resolve a `cli://` path to its canonical form, falling back to the literal.
///
/// `cli://toy`, `cli://./toy` and `cli:///abs/path/toy` all name the same
/// binary, and without this they would be three distinct targets producing
/// three separate sets of ledger rows for one artifact. A path that does not
/// resolve is kept verbatim, so the operator sees back what they typed --
/// the preflight reports that case as `target-not-found`.
fn canonical_cli_path(path: &str) -> String {
    std::fs::canonicalize(path)
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|_| path.to_string())
}

/// Parse a single target string (supports host:port format)
fn parse_target_string(target_str: &str) -> Target {
    // Local CLI/binary target: `cli://<path>` or `cli:<path>` carries a
    // filesystem path to a locally-built executable, not a network host. Kept
    // ahead of URL parsing so arbitrary paths (leading slash, no authority)
    // survive into `Target::address`.
    if let Some(rest) = target_str
        .strip_prefix("cli://")
        .or_else(|| target_str.strip_prefix("cli:"))
    {
        return Target::new(canonical_cli_path(rest), Protocol::Cli);
    }

    if let Ok(url) = url::Url::parse(target_str) {
        if let Some(host) = url.host_str() {
            let protocol = match url.scheme().to_lowercase().as_str() {
                "http" => Protocol::Http,
                "https" => Protocol::Https,
                "tcp" => Protocol::Tcp,
                "udp" => Protocol::Udp,
                other => Protocol::Custom(other.to_string()),
            };

            let mut target = Target::new(host, protocol);
            if let Some(port) = url.port() {
                target.port = Some(port);
            }
            return target;
        }
    }

    match utils::parse_target(target_str) {
        Ok((host, port)) => {
            if let Some(port) = port {
                let protocol = match port {
                    80 | 8000 | 8080 => Protocol::Http,
                    443 | 8443 => Protocol::Https,
                    _ => Protocol::Https,
                };
                Target::with_port(host, port, protocol)
            } else {
                Target::new(host, Protocol::Https)
            }
        }
        Err(_) => Target::new(target_str, Protocol::Https),
    }
}

/// Parse targets from CLI scope arguments
fn parse_targets(args: &cli::ScanArgs) -> Result<Vec<Target>> {
    let mut expanded_entries = Vec::new();
    let mut in_progress_files = HashSet::new();

    for entry in &args.scope {
        expand_scope_entry(entry, &mut expanded_entries, &mut in_progress_files)?;
    }

    let mut seen = HashSet::new();
    let mut targets = Vec::new();

    for raw in expanded_entries {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            continue;
        }

        if !seen.insert(trimmed.to_string()) {
            continue;
        }

        targets.push(parse_target_string(trimmed));
    }

    Ok(targets)
}

fn expand_scope_entry(
    entry: &str,
    acc: &mut Vec<String>,
    file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
    let trimmed = entry.trim();
    if trimmed.is_empty() {
        return Ok(());
    }

    // A `cli:` entry is a filesystem path, not a list and not a file of
    // targets. Taken verbatim before any of the splitting below, so a binary
    // whose path contains a comma is not cut in half, and one that happens to
    // sit next to a readable file is not read as a target list.
    if trimmed.starts_with("cli://") || trimmed.starts_with("cli:") {
        acc.push(trimmed.to_string());
        return Ok(());
    }

    // Allow comma-separated lists inside scope values (e.g., from files)
    if trimmed.contains(',') {
        for part in trimmed.split(',') {
            expand_scope_entry(part, acc, file_stack)?;
        }
        return Ok(());
    }

    let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file://") {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file:") {
        (rest, true)
    } else {
        (trimmed, false)
    };

    let path = Path::new(candidate);
    if forced_file || path.exists() {
        if !path.exists() {
            return Err(Error::config(format!(
                "Scope file not found: {}",
                candidate
            )));
        }

        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        if !file_stack.insert(canonical.clone()) {
            return Err(Error::config(format!(
                "Recursive scope file reference detected: {}",
                canonical.display()
            )));
        }

        let content = fs::read_to_string(path).map_err(|e| {
            Error::config(format!("Failed to read scope file '{}': {}", candidate, e))
        })?;

        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            expand_scope_entry(line, acc, file_stack)?;
        }

        file_stack.remove(&canonical);
        return Ok(());
    }

    if trimmed.contains('/') && !trimmed.contains("://") {
        if let Ok(addresses) = utils::parse_cidr(trimmed) {
            for ip in addresses {
                acc.push(ip.to_string());
            }
            return Ok(());
        }
    }

    acc.push(trimmed.to_string());
    Ok(())
}

/// Create template filter from CLI arguments
/// When skip_id_filter is true, ID filtering is skipped (used when templates were already loaded by path/ID)
fn create_template_filter(args: &cli::ScanArgs, skip_id_filter: bool) -> Result<TemplateFilter> {
    let mut filter = TemplateFilter::new();

    // Smart template selector entries - skip if we already did targeted loading
    if !skip_id_filter && !args.templates.is_empty() {
        let template_entries = parse_template_entries(&args.templates)?;
        filter.ids.extend(template_entries);
    }

    // Filter by tags
    if let Some(tags) = &args.tags {
        filter.tags = tags.split(',').map(|s| s.trim().to_string()).collect();
    }

    // Filter by severity
    if let Some(severities) = &args.severity {
        filter.severities = severities.iter().map(|s| (*s).into()).collect();
    }

    // Filter by language
    if let Some(languages) = &args.template_language {
        filter.languages = languages.iter().map(|l| (*l).into()).collect();
    }

    // Exclude templates (supports comma-separated patterns)
    if let Some(exclude) = &args.exclude_templates {
        for pattern in exclude.split(',') {
            filter.exclude_ids.push(pattern.trim().to_string());
        }
    }

    // Filter by batch group
    if let Some(bg) = &args.batch_group {
        filter.batch_group = Some(bg.clone());
    }

    Ok(filter)
}

/// Parse port specification string (supports individual ports and ranges)
/// Examples: "80,443,8000-9000" -> [80, 443, 8000, 8001, ..., 9000]
fn parse_ports(port_spec: &str) -> Result<Vec<u16>> {
    let mut ports = Vec::new();

    for part in port_spec.split(',') {
        let part = part.trim();

        if part.contains('-') {
            // Handle range (e.g., "8000-9000")
            let range_parts: Vec<&str> = part.split('-').collect();
            if range_parts.len() != 2 {
                return Err(Error::config(format!("Invalid port range: {}", part)));
            }

            let start: u16 = range_parts[0]
                .trim()
                .parse()
                .map_err(|_| Error::config(format!("Invalid port number: {}", range_parts[0])))?;
            let end: u16 = range_parts[1]
                .trim()
                .parse()
                .map_err(|_| Error::config(format!("Invalid port number: {}", range_parts[1])))?;

            if start > end {
                return Err(Error::config(format!(
                    "Invalid port range: {} > {}",
                    start, end
                )));
            }

            for port in start..=end {
                ports.push(port);
            }
        } else {
            // Handle single port
            let port: u16 = part
                .parse()
                .map_err(|_| Error::config(format!("Invalid port number: {}", part)))?;
            ports.push(port);
        }
    }

    // Remove duplicates and sort
    ports.sort_unstable();
    ports.dedup();

    Ok(ports)
}

fn parse_port_entries(entries: &[String]) -> Result<Vec<u16>> {
    let mut collected = Vec::new();
    let mut file_stack = HashSet::new();

    for entry in entries {
        expand_port_entry(entry, &mut collected, &mut file_stack)?;
    }

    collected.sort_unstable();
    collected.dedup();
    Ok(collected)
}

fn expand_port_entry(
    entry: &str,
    acc: &mut Vec<u16>,
    file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
    let trimmed = entry.trim();
    if trimmed.is_empty() {
        return Ok(());
    }

    if trimmed.contains(',') {
        for part in trimmed.split(',') {
            expand_port_entry(part, acc, file_stack)?;
        }
        return Ok(());
    }

    let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file://") {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file:") {
        (rest, true)
    } else {
        (trimmed, false)
    };

    let path = Path::new(candidate);
    if forced_file || path.exists() {
        if !path.exists() {
            return Err(Error::config(format!("Port file not found: {}", candidate)));
        }

        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        if !file_stack.insert(canonical.clone()) {
            return Err(Error::config(format!(
                "Recursive port file reference detected: {}",
                canonical.display()
            )));
        }

        let content = fs::read_to_string(path).map_err(|e| {
            Error::config(format!("Failed to read port file '{}': {}", candidate, e))
        })?;

        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            expand_port_entry(line, acc, file_stack)?;
        }

        file_stack.remove(&canonical);
        return Ok(());
    }

    acc.extend(parse_ports(trimmed)?);
    Ok(())
}

fn select_top_ports(count: u16) -> Vec<u16> {
    utils::top_ports(count)
}

/// Check if a path is a template source file (actual template, not a list file)
fn is_template_source_file(path: &Path) -> bool {
    match path.extension().and_then(|ext| ext.to_str()) {
        Some(ext) => matches!(
            ext.to_ascii_lowercase().as_str(),
            "yaml" | "yml" |  // YAML templates
            "py" |            // Python
            "js" |            // JavaScript
            "rs" |            // Rust
            "c" |             // C
            "cpp" | "cc" | "cxx" | // C++
            "java" |          // Java
            "go" |            // Go
            "rb" |            // Ruby
            "pl" |            // Perl
            "php" |           // PHP
            "sh" | "bash" // Shell
        ),
        None => false,
    }
}

/// Separate template entries into direct file paths and filter IDs
/// Returns (direct_template_paths, filter_ids)
///
/// When a relative path is provided, it will be resolved against the template directories.
fn separate_template_entries(
    entries: &[String],
    template_dirs: &[PathBuf],
) -> Result<(Vec<PathBuf>, Vec<String>)> {
    let mut direct_paths = Vec::new();
    let mut filter_ids = Vec::new();

    tracing::debug!(
        "Separating {} template entries (template_dirs: {:?})",
        entries.len(),
        template_dirs
    );

    for entry in entries {
        let trimmed = entry.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Handle comma-separated entries
        if trimmed.contains(',') {
            for part in trimmed.split(',') {
                let (mut paths, mut ids) =
                    separate_template_entries(&[part.to_string()], template_dirs)?;
                direct_paths.append(&mut paths);
                filter_ids.append(&mut ids);
            }
            continue;
        }

        let path = Path::new(trimmed);
        let exists = path.exists();
        let is_file = path.is_file();
        let is_template = is_template_source_file(path);
        let is_abs = path.is_absolute();

        tracing::debug!(
            "Entry '{}': exists={}, is_file={}, is_template={}, is_absolute={}",
            trimmed,
            exists,
            is_file,
            is_template,
            is_abs
        );

        // Check if it's a direct path to a template file (absolute or relative that exists)
        if exists && is_file && is_template {
            tracing::info!("Detected direct template path: {}", trimmed);
            direct_paths.push(path.to_path_buf());
        } else if is_abs && is_template && !exists {
            // Absolute path that looks like a template but doesn't exist - report error
            return Err(Error::config(format!(
                "Template file not found: {}",
                trimmed
            )));
        } else if !is_abs && (trimmed.contains('/') || trimmed.contains('\\')) && is_template {
            // Relative path that looks like a template - try resolving against template directories
            let mut found = false;

            for template_dir in template_dirs {
                let resolved_path = template_dir.join(trimmed);
                tracing::debug!(
                    "Trying to resolve relative path: {} -> {}",
                    trimmed,
                    resolved_path.display()
                );

                if resolved_path.exists() && resolved_path.is_file() {
                    tracing::info!(
                        "Resolved relative template path: {} -> {}",
                        trimmed,
                        resolved_path.display()
                    );
                    direct_paths.push(resolved_path);
                    found = true;
                    break;
                }
            }

            if !found {
                // Couldn't find the template in any directory
                let searched_dirs: Vec<String> = template_dirs
                    .iter()
                    .map(|d| d.display().to_string())
                    .collect();
                return Err(Error::config(format!(
                    "Template file not found: {} (searched in: {})",
                    trimmed,
                    if searched_dirs.is_empty() {
                        "current directory".to_string()
                    } else {
                        searched_dirs.join(", ")
                    }
                )));
            }
        } else {
            // Treat as template ID for filtering
            tracing::debug!("Treating as filter ID: {}", trimmed);
            filter_ids.push(trimmed.to_string());
        }
    }

    tracing::info!(
        "Separated template entries: {} direct paths, {} filter IDs",
        direct_paths.len(),
        filter_ids.len()
    );

    Ok((direct_paths, filter_ids))
}

fn parse_template_entries(entries: &[String]) -> Result<Vec<String>> {
    let mut collected = Vec::new();
    let mut file_stack = HashSet::new();

    for entry in entries {
        expand_template_entry(entry, &mut collected, &mut file_stack)?;
    }

    let mut seen = HashSet::new();
    let mut unique = Vec::new();

    for entry in collected {
        if seen.insert(entry.clone()) {
            unique.push(entry);
        }
    }

    Ok(unique)
}

fn expand_template_entry(
    entry: &str,
    acc: &mut Vec<String>,
    file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
    let trimmed = entry.trim();
    if trimmed.is_empty() {
        return Ok(());
    }

    if trimmed.contains(',') {
        for part in trimmed.split(',') {
            expand_template_entry(part, acc, file_stack)?;
        }
        return Ok(());
    }

    let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file://") {
        (rest, true)
    } else if let Some(rest) = trimmed.strip_prefix("file:") {
        (rest, true)
    } else {
        (trimmed, false)
    };

    let path = Path::new(candidate);

    if forced_file || (path.exists() && path.is_file() && is_template_list_file(path)) {
        if !path.exists() {
            return Err(Error::config(format!(
                "Template list file not found: {}",
                candidate
            )));
        }

        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        if !file_stack.insert(canonical.clone()) {
            return Err(Error::config(format!(
                "Recursive template file reference detected: {}",
                canonical.display()
            )));
        }

        let content = fs::read_to_string(path).map_err(|e| {
            Error::config(format!(
                "Failed to read template list '{}': {}",
                candidate, e
            ))
        })?;

        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            expand_template_entry(line, acc, file_stack)?;
        }

        file_stack.remove(&canonical);
        return Ok(());
    }

    acc.push(trimmed.to_string());
    Ok(())
}

fn is_template_list_file(path: &Path) -> bool {
    match path.extension().and_then(|ext| ext.to_str()) {
        Some(ext) => matches!(
            ext.to_ascii_lowercase().as_str(),
            "txt" | "list" | "lst" | "cfg"
        ),
        None => false,
    }
}

/// Run template validation command
async fn run_validate_command(
    path: PathBuf,
    recursive: bool,
    _show_score: bool,
    strict: bool,
    format: String,
    _summary: bool,
    _language: Option<cli::LanguageArg>,
    _min_score: u8,
) -> Result<()> {
    use cert_x_gen::ai::validator::{DiagnosticSeverity, TemplateDiagnostic};
    use console::style;
    use std::fs;

    println!("{}", style("═".repeat(80)).dim());
    println!("{}", style("CERT-X-GEN Template Validator").bold().cyan());
    println!("{}", style("═".repeat(80)).dim());
    println!();

    // Create validator
    let validator = TemplateValidator::new();

    // Collect template files
    let mut template_files = Vec::new();

    if path.is_file() {
        template_files.push(path.clone());
    } else if path.is_dir() {
        if recursive {
            for entry in walkdir::WalkDir::new(&path)
                .into_iter()
                .filter_map(|e| e.ok())
            {
                let entry_path = entry.path();
                if entry_path.is_file() {
                    if let Some(ext) = entry_path.extension() {
                        let ext_str = ext.to_string_lossy();
                        if [
                            "py", "js", "sh", "rb", "pl", "php", "rs", "c", "cpp", "go", "java",
                            "yaml", "yml",
                        ]
                        .contains(&ext_str.as_ref())
                        {
                            template_files.push(entry_path.to_path_buf());
                        }
                    }
                }
            }
        } else if let Ok(entries) = fs::read_dir(&path) {
            for entry in entries.filter_map(|e| e.ok()) {
                let entry_path = entry.path();
                if entry_path.is_file() {
                    if let Some(ext) = entry_path.extension() {
                        let ext_str = ext.to_string_lossy();
                        if [
                            "py", "js", "sh", "rb", "pl", "php", "rs", "c", "cpp", "go", "java",
                            "yaml", "yml",
                        ]
                        .contains(&ext_str.as_ref())
                        {
                            template_files.push(entry_path);
                        }
                    }
                }
            }
        }
    }

    if template_files.is_empty() {
        println!("{}", style("No template files found!").red().bold());
        return Ok(());
    }

    println!(
        "Found {} template(s) to validate",
        style(template_files.len()).cyan().bold()
    );
    println!();

    // Simple validation results
    #[derive(serde::Serialize)]
    struct ValidationResult {
        template_path: String,
        language: Option<TemplateLanguage>,
        passed: bool,
        diagnostics: Vec<TemplateDiagnostic>,
        error: Option<String>,
    }

    // Validate each template
    let mut results = Vec::new();
    let mut passed_count = 0;
    let mut failed_count = 0;

    for template_path in &template_files {
        // Read template content
        let content = match fs::read_to_string(template_path) {
            Ok(c) => c,
            Err(e) => {
                let msg = format!("Failed to read file: {}", e);
                let diag = TemplateDiagnostic {
                    code: "io.read_error".to_string(),
                    message: msg.clone(),
                    severity: DiagnosticSeverity::Error,
                    line: None,
                    column: None,
                };
                let result = ValidationResult {
                    template_path: template_path.display().to_string(),
                    language: None,
                    passed: false,
                    diagnostics: vec![diag],
                    error: Some(msg),
                };
                results.push(result);
                failed_count += 1;
                continue;
            }
        };

        // Determine language from extension
        let language = match template_path.extension().and_then(|e| e.to_str()) {
            Some("py") => TemplateLanguage::Python,
            Some("js") => TemplateLanguage::JavaScript,
            Some("sh") => TemplateLanguage::Shell,
            Some("rb") => TemplateLanguage::Ruby,
            Some("pl") => TemplateLanguage::Perl,
            Some("php") => TemplateLanguage::Php,
            Some("rs") => TemplateLanguage::Rust,
            Some("c") => TemplateLanguage::C,
            Some("cpp") | Some("cc") | Some("cxx") => TemplateLanguage::Cpp,
            Some("go") => TemplateLanguage::Go,
            Some("java") => TemplateLanguage::Java,
            Some("yaml") | Some("yml") => TemplateLanguage::Yaml,
            _ => {
                let msg = "Unknown file extension".to_string();
                let diag = TemplateDiagnostic {
                    code: "template.unknown_extension".to_string(),
                    message: msg.clone(),
                    severity: DiagnosticSeverity::Error,
                    line: None,
                    column: None,
                };
                let result = ValidationResult {
                    template_path: template_path.display().to_string(),
                    language: None,
                    passed: false,
                    diagnostics: vec![diag],
                    error: Some(msg),
                };
                results.push(result);
                failed_count += 1;
                continue;
            }
        };

        // Validate template with structured diagnostics
        let mut diagnostics =
            match validator.validate_with_diagnostics(&content, language, Some(template_path)) {
                Ok(diags) => diags,
                Err(e) => {
                    vec![TemplateDiagnostic {
                        code: "validator.internal_error".to_string(),
                        message: e.to_string(),
                        severity: DiagnosticSeverity::Error,
                        line: None,
                        column: None,
                    }]
                }
            };

        // YAML-specific best-practice: id should match filename stem
        if let TemplateLanguage::Yaml = language {
            if let Ok(yaml_value) = serde_yaml::from_str::<serde_yaml::Value>(&content) {
                if let Some(id_val) = yaml_value.get("id").and_then(|v| v.as_str()) {
                    if let Some(stem) = template_path.file_stem().and_then(|s| s.to_str()) {
                        if id_val != stem {
                            let line = content
                                .lines()
                                .enumerate()
                                .find(|(_, line)| line.contains("id:"))
                                .map(|(idx, _)| idx + 1);

                            diagnostics.push(TemplateDiagnostic {
                                code: "yaml.id_filename_mismatch".to_string(),
                                message: format!(
                                    "YAML template id '{}' does not match filename '{}'. For best results, keep them aligned.",
                                    id_val, stem
                                ),
                                severity: DiagnosticSeverity::Warning,
                                line,
                                column: None,
                            });
                        }
                    }
                }
            }
        }

        let has_error = diagnostics
            .iter()
            .any(|d| matches!(d.severity, DiagnosticSeverity::Error));

        let error_summary = if has_error {
            let messages: Vec<String> = diagnostics
                .iter()
                .filter(|d| matches!(d.severity, DiagnosticSeverity::Error))
                .map(|d| format!("{}: {}", d.code, d.message))
                .collect();
            if messages.is_empty() {
                None
            } else {
                Some(messages.join(" | "))
            }
        } else {
            None
        };

        let result = ValidationResult {
            template_path: template_path.display().to_string(),
            language: Some(language),
            passed: !has_error,
            diagnostics,
            error: error_summary,
        };

        if result.passed {
            passed_count += 1;
        } else {
            failed_count += 1;
        }

        results.push(result);
    }

    // Output results based on format
    match format.as_str() {
        "json" => {
            println!("{}", serde_json::to_string_pretty(&results)?);
        }
        "table" | "text" => {
            for result in &results {
                let filename = PathBuf::from(&result.template_path)
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .to_string();

                if result.passed {
                    println!("{} {}", style("✓").green().bold(), style(&filename).green());
                } else {
                    println!("{} {}", style("✗").red().bold(), style(&filename).red());
                }

                for diag in &result.diagnostics {
                    let sev_label = match diag.severity {
                        DiagnosticSeverity::Error => style("error").red().bold(),
                        DiagnosticSeverity::Warning => style("warning").yellow().bold(),
                        DiagnosticSeverity::Info => style("info").blue().bold(),
                    };

                    let location = match (diag.line, diag.column) {
                        (Some(line), Some(col)) => format!("{}:{}: ", line, col),
                        (Some(line), None) => format!("{}: ", line),
                        _ => String::new(),
                    };

                    println!(
                        "    [{}] {}{}: {}",
                        sev_label, location, diag.code, diag.message
                    );
                }

                if !result.diagnostics.is_empty() {
                    println!();
                }
            }

            println!();

            // Print summary
            println!("{}", style("═".repeat(80)).dim());
            println!("{}", style("Validation Summary").bold().cyan());
            println!("{}", style("═".repeat(80)).dim());
            println!();
            println!("  Total Templates: {}", style(results.len()).bold());
            println!(
                "  {} {}",
                style("✓").green().bold(),
                style(format!("Passed: {}", passed_count)).green()
            );
            println!(
                "  {} {}",
                style("✗").red().bold(),
                style(format!("Failed: {}", failed_count)).red()
            );
            if !results.is_empty() {
                println!(
                    "  Success Rate: {}%",
                    style(passed_count * 100 / results.len()).bold()
                );
            }
            println!();
        }
        _ => {
            eprintln!("Unknown format: {}", format);
            return Err(Error::Validation(format!("Invalid format: {}", format)));
        }
    }

    // Exit with error if any failed and strict mode
    if strict && failed_count > 0 {
        return Err(Error::Validation(format!(
            "{} template(s) failed validation",
            failed_count
        )));
    }

    Ok(())
}

/// Run template management commands
async fn run_template_command(cmd: cli::TemplateCommand) -> Result<()> {
    use cli::TemplateAction;

    match cmd.action {
        TemplateAction::List {
            language,
            severity,
            tags,
            batch_group,
        } => {
            // Load configuration
            let config = Config::default();

            // Create CERT-X-GEN engine
            let engine = CertXGen::new(config).await?;

            // Load all templates
            let templates = engine.load_templates().await?;

            // Filter templates based on criteria
            let mut filtered_templates = templates;

            if let Some(lang) = language {
                let target_language: cert_x_gen::types::TemplateLanguage = lang.into();
                filtered_templates
                    .retain(|template| template.metadata().language == target_language);
            }

            if let Some(sev) = severity {
                let target_severity: cert_x_gen::types::Severity = sev.into();
                filtered_templates
                    .retain(|template| template.metadata().severity == target_severity);
            }

            if let Some(tag_filter) = tags {
                let target_tags: Vec<String> = tag_filter
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .collect();
                filtered_templates.retain(|template| {
                    target_tags
                        .iter()
                        .any(|tag| template.metadata().tags.contains(tag))
                });
            }

            if let Some(bg) = batch_group {
                filtered_templates.retain(|template| {
                    template
                        .metadata()
                        .batch_group
                        .as_deref()
                        .map(|g| g.eq_ignore_ascii_case(&bg))
                        .unwrap_or(false)
                });
            }

            // Display templates
            println!("Found {} templates:", filtered_templates.len());
            println!();

            for template in filtered_templates {
                let metadata = template.metadata();
                println!("ID: {}", metadata.id);
                println!("Name: {}", metadata.name);
                println!("Language: {:?}", metadata.language);
                println!("Severity: {:?}", metadata.severity);
                println!("Author: {}", metadata.author.name);
                println!("Description: {}", metadata.description);
                println!("Tags: {}", metadata.tags.join(", "));
                println!("File: {}", metadata.file_path.display());
                println!("---");
            }

            Ok(())
        }
        TemplateAction::Validate {
            path,
            recursive,
            json,
        } => {
            // Call the validation function with default parameters
            let format = if json {
                "json".to_string()
            } else {
                "text".to_string()
            };
            run_validate_command(
                path, recursive, false,  // show_score
                true,   // strict
                format, // format
                false,  // summary
                None,   // language
                0,      // min_score
            )
            .await?;
            Ok(())
        }
        TemplateAction::Update { force: _ } => {
            use cert_x_gen::template::AutoUpdater;

            let mut updater = AutoUpdater::new()
                .map_err(|e| Error::config(format!("Failed to initialize updater: {}", e)))?;

            // Check if this is first run (no templates)
            if updater.needs_initial_install() {
                updater
                    .auto_install()
                    .map_err(|e| Error::config(format!("Failed to install templates: {}", e)))?;
            } else {
                // Regular update
                updater
                    .perform_update()
                    .map_err(|e| Error::config(format!("Failed to update templates: {}", e)))?;

                // Show stats
                let stats = updater.get_stats();
                println!();
                println!("✅ Templates ready: {}", stats.summary());
            }

            Ok(())
        }
        TemplateAction::Info { template_id } => {
            // Use the same template loading as search command
            let config = Config::default();
            let engine = CertXGen::new(config).await?;
            let templates = engine.load_templates().await?;

            // Find template by ID (case-insensitive partial match)
            let matching: Vec<_> = templates
                .iter()
                .filter(|t| t.id().to_lowercase().contains(&template_id.to_lowercase()))
                .collect();

            if matching.is_empty() {
                println!("❌ No template found matching: {}", template_id);
                println!("\nTry: cxg search --query \"{}\"", template_id);
                return Ok(());
            }

            if matching.len() > 1 {
                println!(
                    "Found {} templates matching '{}':\n",
                    matching.len(),
                    template_id
                );
                for t in &matching {
                    println!("  • {} ({:?})", t.id(), t.metadata().language);
                }
                println!("\nPlease specify a more exact template ID.");
                return Ok(());
            }

            // Show detailed info for the single match
            let template = matching[0];
            let meta = template.metadata();

            println!("\n╔════════════════════════════════════════════════════════════════╗");
            println!("║  Template Information                                          ║");
            println!("╚════════════════════════════════════════════════════════════════╝\n");

            println!("  ID:          {}", template.id());
            println!("  Name:        {}", meta.name);
            println!("  Language:    {:?}", meta.language);
            println!("  Severity:    {:?}", meta.severity);
            println!("  Author:      {}", meta.author.name);
            println!("  Description: {}", meta.description);

            if !meta.tags.is_empty() {
                println!("  Tags:        {}", meta.tags.join(", "));
            }

            if let Some(ref vc) = meta.vuln_class {
                println!("  Vuln Class:  {}", vc);
            }

            if !meta.hypothesis_tags.is_empty() {
                println!("  Hyp. Tags:   {}", meta.hypothesis_tags.join(", "));
            }

            if let Some(ref bg) = meta.batch_group {
                println!("  Batch Group: {}", bg);
            }

            if meta.auto_probe {
                println!("  Auto-Probe:  yes (template can self-acquire missing context)");
            }

            if !meta.context_vars.is_empty() {
                println!("\n  Context Variables:");
                for cv_str in &meta.context_vars {
                    // cv_str format: "name:required" or "name[]:optional"
                    let parts: Vec<&str> = cv_str.splitn(2, ':').collect();
                    let (name, qualifier) = if parts.len() == 2 {
                        (parts[0], parts[1])
                    } else {
                        (cv_str.as_str(), "optional")
                    };
                    let marker = if qualifier == "required" {
                        "✓"
                    } else {
                        "○"
                    };
                    println!("    {} {:<30} [{}]", marker, name, qualifier);
                }
            }

            if !meta.file_path.as_os_str().is_empty() {
                println!("  File:        {}", meta.file_path.display());

                // Show file size
                if let Ok(file_meta) = std::fs::metadata(&meta.file_path) {
                    let size = file_meta.len();
                    if size > 1024 {
                        println!("  Size:        {:.1} KB", size as f64 / 1024.0);
                    } else {
                        println!("  Size:        {} bytes", size);
                    }
                }
            }

            println!();
            Ok(())
        }
        TemplateAction::Create {
            id,
            language,
            name,
            output,
        } => {
            use cli::LanguageArg;

            // Map language to file extension and skeleton name
            let (ext, skeleton_name) = match language {
                LanguageArg::Python => ("py", "python-template-skeleton.py"),
                LanguageArg::Rust => ("rs", "rust-template-skeleton.rs"),
                LanguageArg::C => ("c", "c-template-skeleton.c"),
                LanguageArg::Cpp => ("cpp", "cpp-template-skeleton.cpp"),
                LanguageArg::Java => ("java", "java-template-skeleton.java"),
                LanguageArg::Go => ("go", "go-template-skeleton.go"),
                LanguageArg::JavaScript => ("js", "javascript-template-skeleton.js"),
                LanguageArg::Ruby => ("rb", "ruby-template-skeleton.rb"),
                LanguageArg::Perl => ("pl", "perl-template-skeleton.pl"),
                LanguageArg::Php => ("php", "php-template-skeleton.php"),
                LanguageArg::Shell => ("sh", "shell-template-skeleton.sh"),
                LanguageArg::Yaml => ("yaml", "yaml-template-skeleton.yaml"),
            };

            // Try to find skeleton in multiple locations
            let skeleton_paths = vec![
                // Local dev path
                std::path::PathBuf::from("templates/skeleton").join(skeleton_name),
                // Installed user path
                dirs::home_dir()
                    .unwrap_or_default()
                    .join(".cert-x-gen/templates/official/templates/skeleton")
                    .join(skeleton_name),
            ];

            let skeleton_content = skeleton_paths
                .iter()
                .find_map(|p| std::fs::read_to_string(p).ok())
                .ok_or_else(|| {
                    Error::config(format!(
                        "Skeleton template '{}' not found. Run 'cxg --ut' to download templates.",
                        skeleton_name
                    ))
                })?;

            // Replace placeholders
            let template_name = if name.is_empty() {
                // Convert kebab-case to Title Case
                id.split('-')
                    .map(|word| {
                        let mut chars = word.chars();
                        match chars.next() {
                            Some(c) => c.to_uppercase().chain(chars).collect(),
                            None => String::new(),
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(" ")
            } else {
                name.clone()
            };

            let content = skeleton_content
                .replace("template-skeleton", &id)
                .replace("Template Skeleton", &template_name);

            // Determine output path
            let output_path = output.join(format!("{}.{}", id, ext));

            // Write template
            std::fs::write(&output_path, &content)
                .map_err(|e| Error::config(format!("Failed to write template: {}", e)))?;

            println!("✅ Created template: {}", output_path.display());
            println!("   Language: {:?}", language);
            println!("   ID: {}", id);
            println!("\nNext steps:");
            println!("   1. Edit the template to add your detection logic");
            println!(
                "   2. Validate: cxg template validate {}",
                output_path.display()
            );
            println!(
                "   3. Test: cxg scan --scope <target> --templates {}",
                output_path.display()
            );

            Ok(())
        }
        TemplateAction::Test {
            template,
            target,
            debug: _,
        } => {
            println!("Testing template {} against {}", template.display(), target);
            // TODO: Implement template testing
            Ok(())
        }

        // @comment -- "Delegates `cxg template search <query>` to the existing search engine"
        TemplateAction::Search {
            query,
            language,
            severity,
            tags,
            content,
            detailed,
            limit,
        } => {
            use cert_x_gen::search::{
                SearchArgs as LibSearchArgs, SearchFormat, SearchResultFormatter, SearchSort,
                TemplateSearchEngine,
            };

            let config = Config::default();
            let engine = CertXGen::new(config).await?;
            let templates = engine.load_templates().await?;

            let search_args = LibSearchArgs {
                query: Some(query),
                language: language.map(|l| l.into()),
                severity: severity.map(|s| s.into()),
                tags,
                author: None,
                cwe: None,
                content,
                case_sensitive: false,
                regex: false,
                limit,
                format: SearchFormat::Table,
                detailed,
                sort: SearchSort::Relevance,
                reverse: false,
                ids_only: false,
                stats: false,
            };

            let search_engine = TemplateSearchEngine::new(templates);
            let (results, stats) = search_engine.search(&search_args);

            let output = SearchResultFormatter::format_results(
                &results,
                &stats,
                search_args.format,
                detailed,
                false,
            );
            print!("{}", output);

            Ok(())
        }

        // @comment -- "Prints all template directory paths with existence status"
        TemplateAction::Pwd => {
            use cert_x_gen::template::PathResolver;

            println!("\n📂 Template Directories (priority order):\n");

            let dirs = vec![
                ("Local (project)", PathResolver::local_template_dir()),
                ("User", PathResolver::user_template_dir()),
                ("System", PathResolver::system_template_dir()),
            ];

            for (label, dir) in &dirs {
                let exists = dir.exists();
                let marker = if exists { "✓" } else { "✗" };
                let abs_path = if dir.is_relative() {
                    let stripped = dir.strip_prefix("./").unwrap_or(dir);
                    let joined = std::env::current_dir()
                        .map(|cwd| cwd.join(stripped))
                        .unwrap_or_else(|_| dir.clone());
                    joined.canonicalize().unwrap_or(joined)
                } else {
                    dir.clone()
                };
                println!("  [{}] {:<18} {}", marker, label, abs_path.display());
            }

            println!();
            Ok(())
        }

        // @comment -- "Reads and prints the skeleton scaffold file for a given language"
        TemplateAction::Skeleton { language } => {
            use cli::LanguageArg;

            let skeleton_name = match language {
                LanguageArg::Python => "python-template-skeleton.py",
                LanguageArg::Rust => "rust-template-skeleton.rs",
                LanguageArg::C => "c-template-skeleton.c",
                LanguageArg::Cpp => "cpp-template-skeleton.cpp",
                LanguageArg::Java => "java-template-skeleton.java",
                LanguageArg::Go => "go-template-skeleton.go",
                LanguageArg::JavaScript => "javascript-template-skeleton.js",
                LanguageArg::Ruby => "ruby-template-skeleton.rb",
                LanguageArg::Perl => "perl-template-skeleton.pl",
                LanguageArg::Php => "php-template-skeleton.php",
                LanguageArg::Shell => "shell-template-skeleton.sh",
                LanguageArg::Yaml => "yaml-template-skeleton.yaml",
            };

            let skeleton_paths = vec![
                std::path::PathBuf::from("templates/skeleton").join(skeleton_name),
                dirs::home_dir()
                    .unwrap_or_default()
                    .join(".cert-x-gen/templates/official/templates/skeleton")
                    .join(skeleton_name),
            ];

            match skeleton_paths.iter().find_map(|p| {
                std::fs::read_to_string(p)
                    .ok()
                    .map(|content| (p.clone(), content))
            }) {
                Some((path, content)) => {
                    println!(
                        "📄 Skeleton template for {:?} ({})\n",
                        language,
                        path.display()
                    );
                    println!("{}", content);
                }
                None => {
                    eprintln!("❌ Skeleton template '{}' not found.", skeleton_name);
                    eprintln!("   Run 'cxg template update' to download templates.");
                }
            }

            Ok(())
        }

        // @comment -- "Copies a researcher-authored template file into the user template directory"
        TemplateAction::Add { file, dest } => {
            use cert_x_gen::template::PathResolver;

            if !file.exists() {
                eprintln!("❌ File not found: {}", file.display());
                return Err(Error::config(format!(
                    "Template file does not exist: {}",
                    file.display()
                )));
            }

            let file_name = file
                .file_name()
                .ok_or_else(|| Error::config("Invalid file path".to_string()))?;

            let user_dir = PathResolver::user_template_dir();
            let target_dir = match &dest {
                Some(sub) => user_dir.join(sub),
                None => user_dir.clone(),
            };

            std::fs::create_dir_all(&target_dir).map_err(|e| {
                Error::config(format!(
                    "Failed to create directory {}: {}",
                    target_dir.display(),
                    e
                ))
            })?;

            let target_path = target_dir.join(file_name);

            if target_path.exists() {
                println!("⚠️  File already exists: {}", target_path.display());
                println!("   Overwriting...");
            }

            std::fs::copy(&file, &target_path).map_err(|e| {
                Error::config(format!(
                    "Failed to copy {} → {}: {}",
                    file.display(),
                    target_path.display(),
                    e
                ))
            })?;

            println!("✅ Template added: {}", target_path.display());
            println!("   Source: {}", file.display());
            println!("\nNext steps:");
            println!(
                "   1. Validate: cxg template validate {}",
                target_path.display()
            );
            println!("   2. List:     cxg template list");

            Ok(())
        }
    }
}

/// Run search command
async fn run_search_command(args: cli::SearchArgs) -> Result<()> {
    use cert_x_gen::search::{
        SearchArgs as LibSearchArgs, SearchFormat, SearchResultFormatter, SearchSort,
        TemplateSearchEngine,
    };
    use std::fs;

    tracing::info!("Starting template search...");

    // Load configuration
    let config = Config::default();

    // Create CERT-X-GEN engine
    let engine = CertXGen::new(config).await?;

    // Load all templates
    let templates = engine.load_templates().await?;
    tracing::info!("Loaded {} templates", templates.len());

    // Convert CLI args to library args
    let search_args = LibSearchArgs {
        query: args.query,
        language: args.language.map(|l| l.into()),
        severity: args.severity.map(|s| s.into()),
        tags: args.tags,
        author: args.author,
        cwe: args.cwe,
        content: args.content,
        case_sensitive: args.case_sensitive,
        regex: args.regex,
        limit: args.limit,
        format: match args.format {
            cli::SearchFormat::Table => SearchFormat::Table,
            cli::SearchFormat::Json => SearchFormat::Json,
            cli::SearchFormat::Yaml => SearchFormat::Yaml,
            cli::SearchFormat::Csv => SearchFormat::Csv,
            cli::SearchFormat::List => SearchFormat::List,
            cli::SearchFormat::Detailed => SearchFormat::Detailed,
        },
        detailed: args.detailed,
        sort: match args.sort {
            cli::SearchSort::Relevance => SearchSort::Relevance,
            cli::SearchSort::Name => SearchSort::Name,
            cli::SearchSort::Language => SearchSort::Language,
            cli::SearchSort::Severity => SearchSort::Severity,
            cli::SearchSort::Author => SearchSort::Author,
            cli::SearchSort::Date => SearchSort::Date,
            cli::SearchSort::Popularity => SearchSort::Popularity,
        },
        reverse: args.reverse,
        ids_only: args.ids_only,
        stats: args.stats,
    };

    // Create search engine
    let search_engine = TemplateSearchEngine::new(templates);

    // Perform search
    let (results, stats) = search_engine.search(&search_args);

    // Format and output results
    let output = SearchResultFormatter::format_results(
        &results,
        &stats,
        search_args.format,
        args.detailed,
        args.ids_only,
    );

    // Output results
    if let Some(output_file) = args.output {
        fs::write(&output_file, &output)?;
        println!("Search results written to: {}", output_file.display());
    } else {
        print!("{}", output);
    }

    // Show statistics if requested
    if args.stats {
        println!("\nSearch Statistics:");
        println!("  Total templates: {}", stats.total_templates);
        println!("  Matching templates: {}", stats.matching_templates);
        println!("  Search time: {}ms", stats.search_time_ms);

        if !stats.languages.is_empty() {
            println!("  Languages:");
            for (language, count) in &stats.languages {
                println!("    {:?}: {}", language, count);
            }
        }

        if !stats.severities.is_empty() {
            println!("  Severities:");
            for (severity, count) in &stats.severities {
                println!("    {:?}: {}", severity, count);
            }
        }
    }

    Ok(())
}

/// Run API server
async fn run_server(args: cli::ServerArgs) -> Result<()> {
    tracing::info!("Starting API server on {}:{}", args.bind, args.port);
    // TODO: Implement API server
    Err(Error::NotImplemented(
        "API server not yet implemented".to_string(),
    ))
}

/// Run configuration commands
fn run_config_command(cmd: cli::ConfigCommand) -> Result<()> {
    use cli::ConfigAction;

    match cmd.action {
        ConfigAction::Generate { output, format: _ } => {
            let config = Config::default();
            config.save(&output)?;
            println!("Configuration generated: {}", output.display());
            Ok(())
        }
        ConfigAction::Validate { config } => {
            // `from_file_reporting_obsolete` prints the detail for each obsolete
            // section; a file carrying one must not come back as simply valid.
            let (cfg, obsolete) = Config::from_file_reporting_obsolete(&config)?;
            cfg.validate()?;

            if obsolete.is_empty() {
                println!("Configuration is valid");
            } else {
                println!(
                    "Configuration is loadable, but contains {} obsolete section(s) with no \
                     effect: {}. See the warning above; remove them.",
                    obsolete.len(),
                    obsolete.join(", ")
                );
            }
            Ok(())
        }
        ConfigAction::Show => {
            let config = Config::default();
            let yaml =
                serde_yaml::to_string(&config).map_err(|e| Error::Serialization(e.to_string()))?;
            println!("{}", yaml);
            Ok(())
        }
    }
}

/// Run sandbox commands
async fn run_sandbox_command(cmd: cli::SandboxCommand) -> Result<()> {
    use cert_x_gen::sandbox::{Sandbox, SandboxConfig};
    use cli::SandboxAction;
    use console::{style, Term};

    let term = Term::stdout();

    match cmd.action {
        SandboxAction::Init {
            force,
            languages,
            directory,
        } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::{
                current_sandbox_name, inside_sandbox, DockerSandbox,
            };
            use cert_x_gen::sandbox::Sandbox;

            // Check if we're inside a Docker sandbox
            if inside_sandbox() {
                if let Some(sandbox_name) = current_sandbox_name() {
                    term.write_line(&format!(
                        "\n{} Running inside Docker sandbox: {}",
                        style("🐳").cyan(),
                        style(&sandbox_name).yellow()
                    ))?;
                    term.write_line(
                        &"  Initializing package environment inside the container...".to_string(),
                    )?;
                    term.write_line("")?;
                }
            } else {
                // Check if there's a default Docker sandbox
                if let Ok(cfg) = SandboxConfigFile::load() {
                    if let Some((name, config)) = cfg.get_default_sandbox() {
                        if config.auto_start {
                            term.write_line(&format!(
                                "\n{} Default Docker sandbox detected: {}",
                                style("🐳").cyan(),
                                style(name).yellow()
                            ))?;
                            term.write_line(
                                &"  This command will run INSIDE the Docker container.".to_string(),
                            )?;
                            term.write_line(
                                &"  You'll stay on your host, but init happens in the sandbox."
                                    .to_string(),
                            )?;
                            term.write_line("")?;
                        }
                    }
                }

                // Check if Docker is available and recommend it (only if no default sandbox)
                if DockerSandbox::docker_available()
                    && DockerSandbox::docker_running()
                    && SandboxConfigFile::load()
                        .ok()
                        .and_then(|c| c.default_sandbox)
                        .is_none()
                {
                    term.write_line(&format!("\n{} Docker detected!", style("ℹ").blue()))?;
                    term.write_line(
                        &"  For fresh runtimes instead of your host's, consider a Docker environment:"
                            .to_string(),
                    )?;
                    term.write_line(&format!(
                        "  {}",
                        style("cxg sandbox create my-env").yellow()
                    ))?;
                    term.write_line(&format!(
                        "  {}",
                        style("cxg sandbox set-default my-env").yellow()
                    ))?;
                    term.write_line("")?;
                    term.write_line(&"  This command (init) creates package directories using your host's language runtimes.".to_string())?;
                    term.write_line(&"  A Docker environment gives you fresh runtimes inside a container you can 'enter'.".to_string())?;
                    term.write_line(&"  Neither confines template execution: templates run as ordinary child processes".to_string())?;
                    term.write_line(&"  with your privileges and full network and filesystem access. Review templates first.".to_string())?;
                    term.write_line("")?;
                    term.write_line(&format!(
                        "  Run {} for more info.",
                        style("cxg sandbox info").cyan()
                    ))?;
                    term.write_line("")?;
                }
            }

            let mut config = SandboxConfig::default();

            if let Some(dir) = directory {
                config.root_dir = dir;
            }

            // Parse language filter
            if let Some(langs) = languages {
                config.enable_python = langs.contains("python");
                config.enable_javascript = langs.contains("javascript") || langs.contains("js");
                config.enable_ruby = langs.contains("ruby");
                config.enable_perl = langs.contains("perl");
                config.enable_php = langs.contains("php");
                config.enable_rust = langs.contains("rust");
                config.enable_go = langs.contains("go");
                config.enable_java = langs.contains("java");
            }

            let mut sandbox = Sandbox::with_config(config.clone());

            // Check if sandbox is already initialized
            let already_initialized = sandbox.is_initialized();

            if already_initialized && !force {
                term.write_line(&format!(
                    "{} Sandbox already initialized at: {}",
                    style("✓").green(),
                    sandbox.root_dir().display()
                ))?;

                // Check current status to see what's already there
                let status = sandbox.status();
                let mut existing_langs = Vec::new();
                if status.python_ready {
                    existing_langs.push("Python");
                }
                if status.javascript_ready {
                    existing_langs.push("JavaScript");
                }
                if status.ruby_ready {
                    existing_langs.push("Ruby");
                }
                if status.perl_ready {
                    existing_langs.push("Perl");
                }
                if status.php_ready {
                    existing_langs.push("PHP");
                }
                if status.rust_ready {
                    existing_langs.push("Rust");
                }
                if status.go_ready {
                    existing_langs.push("Go");
                }
                if status.java_ready {
                    existing_langs.push("Java");
                }

                term.write_line(&format!(
                    "  Existing languages: {}",
                    if existing_langs.is_empty() {
                        "None".to_string()
                    } else {
                        existing_langs.join(", ")
                    }
                ))?;

                // Check if user requested new languages
                let mut languages_to_add = Vec::new();
                if config.enable_python && !status.python_ready {
                    languages_to_add.push("Python");
                }
                if config.enable_javascript && !status.javascript_ready {
                    languages_to_add.push("JavaScript");
                }
                if config.enable_ruby && !status.ruby_ready {
                    languages_to_add.push("Ruby");
                }
                if config.enable_perl && !status.perl_ready {
                    languages_to_add.push("Perl");
                }
                if config.enable_php && !status.php_ready {
                    languages_to_add.push("PHP");
                }
                if config.enable_rust && !status.rust_ready {
                    languages_to_add.push("Rust");
                }
                if config.enable_go && !status.go_ready {
                    languages_to_add.push("Go");
                }
                if config.enable_java && !status.java_ready {
                    languages_to_add.push("Java");
                }

                if languages_to_add.is_empty() {
                    term.write_line(&format!(
                        "\n{} All requested languages are already initialized!",
                        style("✓").green()
                    ))?;
                    term.write_line(&format!(
                        "  Nothing to do. Use {} to rebuild everything.",
                        style("--force").yellow()
                    ))?;
                    return Ok(());
                } else {
                    term.write_line(&format!(
                        "\n{} Adding new languages: {}",
                        style("→").cyan(),
                        style(languages_to_add.join(", ")).yellow()
                    ))?;
                    // Continue to init only the new ones
                }
            } else if force {
                term.write_line(&format!(
                    "{} Force re-initialization requested",
                    style("→").cyan()
                ))?;
                term.write_line(
                    &"  Rebuilding all language environments from scratch...".to_string(),
                )?;
            }

            term.write_line(&format!(
                "{} Initializing sandbox environment...",
                style("→").cyan()
            ))?;
            sandbox.init().await?;

            // Show summary of what was initialized
            let status = sandbox.status();
            let mut initialized_langs = Vec::new();
            if status.python_ready {
                initialized_langs.push("Python");
            }
            if status.javascript_ready {
                initialized_langs.push("JavaScript");
            }
            if status.ruby_ready {
                initialized_langs.push("Ruby");
            }
            if status.perl_ready {
                initialized_langs.push("Perl");
            }
            if status.php_ready {
                initialized_langs.push("PHP");
            }
            if status.rust_ready {
                initialized_langs.push("Rust");
            }
            if status.go_ready {
                initialized_langs.push("Go");
            }
            if status.java_ready {
                initialized_langs.push("Java");
            }

            if !initialized_langs.is_empty() {
                term.write_line(&format!(
                    "{} Sandbox initialized successfully!",
                    style("✓").green()
                ))?;
                term.write_line(&format!(
                    "  Initialized languages: {}",
                    style(initialized_langs.join(", ")).cyan()
                ))?;
            } else {
                term.write_line(&format!(
                    "{} Sandbox initialization completed with warnings",
                    style("⚠").yellow()
                ))?;
                term.write_line(
                    &"  No language environments were successfully initialized".to_string(),
                )?;
                term.write_line(&"  Check logs above for details on what failed".to_string())?;
            }

            term.write_line("")?;
            term.write_line(&format!(
                "{} Note: Some packages may have failed to install due to:",
                style("ℹ").blue()
            ))?;
            term.write_line("  - Missing system dependencies (build tools, compilers)")?;
            term.write_line("  - Outdated runtime versions (e.g., Ruby < 3.0)")?;
            term.write_line("  - Package incompatibilities")?;
            term.write_line("")?;
            term.write_line(&format!(
                "{} The sandbox will continue to work with successfully installed packages.",
                style("ℹ").blue()
            ))?;
            term.write_line(&format!(
                "{} You can install missing packages manually if needed.",
                style("ℹ").blue()
            ))?;
            term.write_line(&format!("  Location: {}", sandbox.root_dir().display()))?;

            Ok(())
        }

        SandboxAction::Status => {
            let sandbox = Sandbox::new();
            let status = sandbox.status();

            term.write_line(&format!("\n{}", style("Sandbox Status").bold().cyan()))?;
            term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;

            term.write_line(&format!("Location: {}", status.root_dir.display()))?;
            term.write_line(&format!(
                "Initialized: {}",
                if status.initialized {
                    style("Yes").green()
                } else {
                    style("No").red()
                }
            ))?;

            term.write_line(&format!("\n{}", style("Language Runtimes:").bold()))?;
            term.write_line(&format!(
                "  Python:     {}",
                if status.python_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  JavaScript: {}",
                if status.javascript_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  Ruby:       {}",
                if status.ruby_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  Perl:       {}",
                if status.perl_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  PHP:        {}",
                if status.php_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  Rust:       {}",
                if status.rust_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  Go:         {}",
                if status.go_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;
            term.write_line(&format!(
                "  Java:       {}",
                if status.java_ready {
                    style("✓").green()
                } else {
                    style("✗").red()
                }
            ))?;

            term.write_line("")?;

            Ok(())
        }

        SandboxAction::Install { language, packages } => {
            let sandbox = Sandbox::new();

            if !sandbox.is_initialized() {
                return Err(Error::config(
                    "Sandbox not initialized. Run 'cxg sandbox init' first.",
                ));
            }

            term.write_line(&format!(
                "{} Installing {} packages for {}...",
                style("→").cyan(),
                packages.len(),
                style(&language).yellow()
            ))?;

            let packages_str: Vec<&str> = packages.iter().map(|s| s.as_str()).collect();

            match language.as_str() {
                "python" | "py" => {
                    cert_x_gen::sandbox::python::install_packages(&sandbox, &packages_str).await?;
                }
                "javascript" | "js" | "node" => {
                    cert_x_gen::sandbox::javascript::install_packages(&sandbox, &packages_str)
                        .await?;
                }
                "ruby" | "rb" => {
                    cert_x_gen::sandbox::ruby::install_gems(&sandbox, &packages_str).await?;
                }
                "perl" | "pl" => {
                    cert_x_gen::sandbox::perl::install_modules(&sandbox, &packages_str).await?;
                }
                "php" => {
                    cert_x_gen::sandbox::php::install_packages(&sandbox, &packages_str).await?;
                }
                _ => {
                    return Err(Error::config(format!("Unsupported language: {}", language)));
                }
            }

            term.write_line(&format!(
                "{} Packages installed successfully!",
                style("✓").green()
            ))?;

            Ok(())
        }

        SandboxAction::Clean { language: _, force } => {
            let sandbox = Sandbox::new();

            if !force {
                term.write_line(&format!(
                    "{} This will delete the sandbox environment.",
                    style("⚠").yellow()
                ))?;
                term.write_line("Use --force to confirm.")?;
                return Ok(());
            }

            term.write_line(&format!("{} Cleaning sandbox...", style("→").cyan()))?;
            sandbox.clean()?;
            term.write_line(&format!(
                "{} Sandbox cleaned successfully!",
                style("✓").green()
            ))?;

            Ok(())
        }

        SandboxAction::Shell { language } => {
            let sandbox = Sandbox::new();

            if !sandbox.is_initialized() {
                return Err(Error::config(
                    "Sandbox not initialized. Run 'cxg sandbox init' first.",
                ));
            }

            term.write_line(&format!(
                "{} Opening {} shell in sandbox...",
                style("→").cyan(),
                style(&language).yellow()
            ))?;
            term.write_line(&format!("Location: {}", sandbox.root_dir().display()))?;
            term.write_line("Type 'exit' to return.\n")?;

            let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
            std::process::Command::new(shell)
                .current_dir(sandbox.root_dir())
                .envs(sandbox.get_env_vars())
                .status()
                .map_err(|e| Error::command(format!("Failed to open shell: {}", e)))?;

            Ok(())
        }

        SandboxAction::Path => {
            let sandbox = Sandbox::new();
            println!("{}", sandbox.root_dir().display());
            Ok(())
        }

        SandboxAction::Update { language: _ } => {
            term.write_line(&format!("{} Updating packages...", style("→").cyan()))?;

            // Implement update logic here
            term.write_line(&format!("{} Update complete!", style("✓").green()))?;

            Ok(())
        }

        SandboxAction::Export {
            output,
            description,
            author,
        } => {
            let sandbox = Sandbox::new();

            if !sandbox.is_initialized() {
                return Err(Error::config(
                    "Sandbox not initialized. Run 'cxg sandbox init' first.",
                ));
            }

            term.write_line(&format!(
                "{} Exporting sandbox configuration...",
                style("→").cyan()
            ))?;

            let mut export =
                cert_x_gen::sandbox::import_export::SandboxExport::from_sandbox(&sandbox)?;

            if let Some(desc) = description {
                export.metadata.description = Some(desc);
            }
            if let Some(auth) = author {
                export.metadata.author = Some(auth);
            }

            export.save(&output)?;

            term.write_line(&format!(
                "{} Sandbox exported to: {}",
                style("✓").green(),
                output.display()
            ))?;
            term.write_line(&format!(
                "  Python packages: {}",
                export.python_packages.len()
            ))?;
            term.write_line(&format!(
                "  JavaScript packages: {}",
                export.javascript_packages.len()
            ))?;
            term.write_line(&format!("  Ruby gems: {}", export.ruby_gems.len()))?;

            Ok(())
        }

        SandboxAction::Import { file, force } => {
            term.write_line(&format!(
                "{} Importing sandbox configuration from: {}",
                style("→").cyan(),
                file.display()
            ))?;

            let export = cert_x_gen::sandbox::import_export::SandboxExport::load(&file)?;

            term.write_line(&format!("  Version: {}", export.metadata.version))?;
            term.write_line(&format!("  Exported: {}", export.metadata.exported_at))?;
            if let Some(desc) = &export.metadata.description {
                term.write_line(&format!("  Description: {}", desc))?;
            }

            if !force {
                term.write_line(&format!(
                    "\n{} This will replace your current sandbox. Use --force to confirm.",
                    style("⚠").yellow()
                ))?;
                return Ok(());
            }

            let mut sandbox = Sandbox::new();
            export.apply_to_sandbox(&mut sandbox).await?;

            term.write_line(&format!(
                "{} Sandbox imported successfully!",
                style("✓").green()
            ))?;

            Ok(())
        }

        SandboxAction::Templates => {
            term.write_line(&format!(
                "\n{}",
                style("Available Sandbox Templates").bold().cyan()
            ))?;
            term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;

            let templates = vec![
                cert_x_gen::sandbox::import_export::SandboxTemplate::web_security(),
                cert_x_gen::sandbox::import_export::SandboxTemplate::network_security(),
                cert_x_gen::sandbox::import_export::SandboxTemplate::api_testing(),
            ];

            for template in templates {
                term.write_line(&format!("\n{}", style(&template.name).yellow().bold()))?;
                term.write_line(&format!("  {}", template.description))?;
                term.write_line(&format!(
                    "  Python: {} packages",
                    template.export.python_packages.len()
                ))?;
                term.write_line(&format!(
                    "  JavaScript: {} packages",
                    template.export.javascript_packages.len()
                ))?;
                term.write_line(&format!(
                    "  Usage: cxg sandbox use-template {}",
                    template.name
                ))?;
            }

            term.write_line("")?;

            Ok(())
        }

        SandboxAction::UseTemplate { template } => {
            term.write_line(&format!(
                "{} Loading template: {}",
                style("→").cyan(),
                style(&template).yellow()
            ))?;

            let sandbox_template = match template.as_str() {
                "web-security" => {
                    cert_x_gen::sandbox::import_export::SandboxTemplate::web_security()
                }
                "network-security" => {
                    cert_x_gen::sandbox::import_export::SandboxTemplate::network_security()
                }
                "api-testing" => cert_x_gen::sandbox::import_export::SandboxTemplate::api_testing(),
                _ => {
                    return Err(Error::config(format!("Unknown template: {}. Use 'cxg sandbox templates' to list available templates.", template)));
                }
            };

            let mut sandbox = Sandbox::new();
            sandbox_template
                .export
                .apply_to_sandbox(&mut sandbox)
                .await?;

            term.write_line(&format!(
                "{} Template applied successfully!",
                style("✓").green()
            ))?;

            Ok(())
        }

        SandboxAction::List { language } => {
            let sandbox = Sandbox::new();

            if !sandbox.is_initialized() {
                return Err(Error::config(
                    "Sandbox not initialized. Run 'cxg sandbox init' first.",
                ));
            }

            term.write_line(&format!(
                "\n{} Installed Packages",
                style(&language).bold().cyan()
            ))?;
            term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;

            let export = cert_x_gen::sandbox::import_export::SandboxExport::from_sandbox(&sandbox)?;

            let packages = match language.as_str() {
                "python" | "py" => export.python_packages,
                "javascript" | "js" | "node" => export.javascript_packages,
                "ruby" | "rb" => export.ruby_gems,
                "perl" | "pl" => export.perl_modules,
                "php" => export.php_packages,
                _ => {
                    return Err(Error::config(format!("Unsupported language: {}", language)));
                }
            };

            for (i, package) in packages.iter().enumerate() {
                term.write_line(&format!("{}. {}", i + 1, package))?;
            }

            term.write_line(&format!(
                "\n{} Total: {} packages",
                style("✓").green(),
                packages.len()
            ))?;

            Ok(())
        }

        SandboxAction::Create {
            name,
            languages,
            persist,
            auto_start,
        } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::{DockerConfig, DockerSandbox, ResourceLimits};

            // Check if Docker is available
            if !DockerSandbox::docker_available() {
                term.write_line(&format!(
                    "{} Docker is not installed or not available",
                    style("✗").red()
                ))?;
                term.write_line(&"\nTo use Docker sandboxes, please install Docker:".to_string())?;
                term.write_line(
                    &"  macOS: https://docs.docker.com/desktop/install/mac-install/".to_string(),
                )?;
                term.write_line(&"  Linux: https://docs.docker.com/engine/install/".to_string())?;
                term.write_line(
                    &"  Windows: https://docs.docker.com/desktop/install/windows-install/"
                        .to_string(),
                )?;
                return Ok(());
            }

            if !DockerSandbox::docker_running() {
                term.write_line(&format!(
                    "{} Docker is installed but not running",
                    style("⚠").yellow()
                ))?;
                term.write_line(&"  Please start Docker Desktop and try again".to_string())?;
                return Ok(());
            }

            term.write_line(&format!(
                "{} Creating Docker sandbox: {}",
                style("→").cyan(),
                style(&name).yellow()
            ))?;

            // Prepare config
            let selected_languages = languages.unwrap_or_else(|| {
                vec![
                    "python".to_string(),
                    "ruby".to_string(),
                    "node".to_string(),
                    "go".to_string(),
                    "java".to_string(),
                    "perl".to_string(),
                    "php".to_string(),
                    "rust".to_string(),
                ]
            });

            // Get current directory and templates directory
            let current_dir = std::env::current_dir()?;
            let templates_dir = current_dir.join("templates");

            let mut volumes = std::collections::HashMap::new();
            if templates_dir.exists() {
                volumes.insert(
                    templates_dir.to_str().unwrap().to_string(),
                    "/workspace/templates".to_string(),
                );
            }

            let config = DockerConfig {
                name: name.clone(),
                image: format!("cert-x-gen/sandbox:{}", name),
                languages: selected_languages.clone(),
                persist,
                auto_start,
                resources: ResourceLimits {
                    memory: "4g".to_string(),
                    cpus: "2".to_string(),
                },
                volumes,
                environment: std::collections::HashMap::new(),
                network_mode: "bridge".to_string(), // Allow network access
            };

            let mut sandbox = DockerSandbox::new(config.clone());

            term.write_line(&format!(
                "  Building Docker image with languages: {}",
                selected_languages.join(", ")
            ))?;
            sandbox.build_image(None).await?;

            term.write_line(&"  Creating container...".to_string())?;
            sandbox.create().await?;

            // Save to config file
            let mut cfg = SandboxConfigFile::load()?;
            cfg.set_sandbox(name.clone(), config);
            cfg.save()?;

            term.write_line(&format!(
                "{} Sandbox '{}' created successfully!",
                style("✓").green(),
                name
            ))?;
            term.write_line(&format!(
                "  Set as default: cxg sandbox set-default {}",
                name
            ))?;
            term.write_line(&format!("  Enter sandbox: cxg sandbox enter {}", name))?;

            Ok(())
        }

        SandboxAction::Delete { name, force } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::DockerSandbox;

            if !force {
                term.write_line(&format!(
                    "{} This will delete the sandbox '{}'",
                    style("⚠").yellow(),
                    name
                ))?;
                term.write_line(&"  Use --force to confirm deletion".to_string())?;
                return Ok(());
            }

            term.write_line(&format!("{} Deleting sandbox: {}", style("→").cyan(), name))?;

            // Load and delete container
            match DockerSandbox::load(&name) {
                Ok(mut sandbox) => {
                    sandbox.delete().await?;
                    term.write_line(&"  Container deleted".to_string())?;
                }
                Err(_) => {
                    term.write_line(&format!(
                        "  {} Container not found (may already be deleted)",
                        style("⚠").yellow()
                    ))?;
                }
            }

            // Remove from config
            let mut cfg = SandboxConfigFile::load()?;
            cfg.remove_sandbox(&name);
            cfg.save()?;

            term.write_line(&format!(
                "{} Sandbox '{}' deleted",
                style("✓").green(),
                name
            ))?;

            Ok(())
        }

        SandboxAction::Enter { name } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::DockerSandbox;

            let cfg = SandboxConfigFile::load()?;

            let sandbox_name = name.or_else(|| cfg.default_sandbox.clone())
                .ok_or_else(|| Error::config("No sandbox specified and no default set. Use: cxg sandbox set-default <name>"))?;

            term.write_line(&format!(
                "{} Entering sandbox: {}",
                style("→").cyan(),
                sandbox_name
            ))?;

            let mut sandbox = DockerSandbox::load(&sandbox_name)?;

            if !sandbox.is_running() {
                term.write_line(&"  Starting container...".to_string())?;
                sandbox.start().await?;
            }

            sandbox.shell().await?;

            Ok(())
        }

        SandboxAction::SetDefault { name } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;

            let mut cfg = SandboxConfigFile::load()?;

            if let Some(sandbox_name) = name {
                // Verify sandbox exists
                if !cfg.sandboxes.contains_key(&sandbox_name) {
                    return Err(Error::config(format!(
                        "Sandbox '{}' not found",
                        sandbox_name
                    )));
                }

                cfg.set_default(Some(sandbox_name.clone()));
                cfg.save()?;

                term.write_line(&format!(
                    "{} Default sandbox set to: {}",
                    style("✓").green(),
                    sandbox_name
                ))?;
            } else {
                cfg.set_default(None);
                cfg.save()?;

                term.write_line(&format!("{} Default sandbox cleared", style("✓").green()))?;
            }

            Ok(())
        }

        SandboxAction::Info => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::DockerSandbox;

            term.write_line(&format!(
                "\n{}",
                style("Docker Sandbox Information").bold().cyan()
            ))?;
            term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;

            // Check Docker status
            if DockerSandbox::docker_available() {
                term.write_line(&format!("{} Docker: Installed", style("✓").green()))?;
                if let Some(version) = DockerSandbox::docker_version() {
                    term.write_line(&format!("  Version: {}", version))?;
                }

                if DockerSandbox::docker_running() {
                    term.write_line(&format!("{} Docker Daemon: Running", style("✓").green()))?;
                } else {
                    term.write_line(&format!(
                        "{} Docker Daemon: Not running",
                        style("⚠").yellow()
                    ))?;
                    term.write_line(&"  Please start Docker Desktop".to_string())?;
                }
            } else {
                term.write_line(&format!("{} Docker: Not installed", style("✗").red()))?;
                term.write_line(&"\nInstallation:".to_string())?;
                term.write_line(
                    &"  macOS: https://docs.docker.com/desktop/install/mac-install/".to_string(),
                )?;
                term.write_line(&"  Linux: https://docs.docker.com/engine/install/".to_string())?;
                term.write_line(
                    &"  Windows: https://docs.docker.com/desktop/install/windows-install/"
                        .to_string(),
                )?;
            }

            // Show configured sandboxes
            let cfg = SandboxConfigFile::load()?;

            term.write_line(&format!(
                "\n{}",
                style("Configured Sandboxes").bold().cyan()
            ))?;
            term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;

            if cfg.sandboxes.is_empty() {
                term.write_line(&"  No sandboxes configured".to_string())?;
                term.write_line(&"\nCreate one: cxg sandbox create my-sandbox".to_string())?;
            } else {
                for (name, config) in &cfg.sandboxes {
                    let is_default = cfg.default_sandbox.as_ref() == Some(name);
                    let marker = if is_default { "* " } else { "  " };

                    term.write_line(&format!("{}{}", marker, style(name).yellow().bold()))?;
                    term.write_line(&format!("    Image: {}", config.image))?;
                    term.write_line(&format!("    Languages: {}", config.languages.join(", ")))?;
                    term.write_line(&format!("    Persist: {}", config.persist))?;
                    term.write_line(&format!("    Auto-start: {}", config.auto_start))?;

                    // Check if container running
                    if let Ok(sandbox) = DockerSandbox::load(name) {
                        if sandbox.is_running() {
                            term.write_line(&format!("    Status: {}", style("Running").green()))?;
                        } else {
                            term.write_line(&format!("    Status: {}", style("Stopped").dim()))?;
                        }
                    }

                    term.write_line("")?;
                }

                if let Some(default) = &cfg.default_sandbox {
                    term.write_line(&format!("* Default sandbox: {}", style(default).cyan()))?;
                }
            }

            Ok(())
        }

        SandboxAction::Build { dockerfile } => {
            use cert_x_gen::sandbox::config::SandboxConfigFile;
            use cert_x_gen::sandbox::docker::DockerSandbox;

            term.write_line(&format!("{} Building Docker image...", style("→").cyan()))?;

            let cfg = SandboxConfigFile::load()?;
            let (_name, config) = cfg.get_default_sandbox().ok_or_else(|| {
                Error::config("No default sandbox set. Use: cxg sandbox set-default <name>")
            })?;

            let sandbox = DockerSandbox::new(config.clone());

            sandbox.build_image(dockerfile.as_deref()).await?;

            term.write_line(&format!("{} Image built successfully!", style("✓").green()))?;

            Ok(())
        }
    }
}

/// Check if we should auto-enter a Docker sandbox
async fn check_and_enter_sandbox(cli: &Cli) -> Result<()> {
    use cert_x_gen::sandbox::config::SandboxConfigFile;
    use cert_x_gen::sandbox::docker::{inside_sandbox, DockerSandbox};

    // Don't auto-enter if we're already inside a sandbox
    if inside_sandbox() {
        tracing::debug!("Already inside sandbox, skipping auto-enter");
        return Ok(());
    }

    // Don't auto-enter for sandbox management commands (except init, which should run in sandbox)
    if matches!(cli.command, Some(Commands::Sandbox(_))) {
        // Allow 'sandbox init' to run in Docker if default sandbox is set
        if !matches!(cli.command, Some(Commands::Sandbox(ref cmd)) if matches!(cmd.action, cli::SandboxAction::Init { .. }))
        {
            return Ok(());
        }
    }

    // Check if Docker is available
    if !DockerSandbox::docker_available() {
        tracing::debug!("Docker not available, skipping sandbox auto-enter");
        return Ok(());
    }

    if !DockerSandbox::docker_running() {
        tracing::debug!("Docker not running, skipping sandbox auto-enter");
        return Ok(());
    }

    // Load config and check for default sandbox
    let cfg = match SandboxConfigFile::load() {
        Ok(c) => c,
        Err(_) => {
            tracing::debug!("No sandbox config found, skipping auto-enter");
            return Ok(());
        }
    };

    // Check if there's a default sandbox with auto_start enabled
    if let Some((name, config)) = cfg.get_default_sandbox() {
        if config.auto_start {
            tracing::info!("Auto-entering sandbox: {}", name);

            // Load sandbox
            let mut sandbox = match DockerSandbox::load(name) {
                Ok(s) => s,
                Err(e) => {
                    tracing::warn!("Failed to load default sandbox '{}': {}", name, e);
                    return Ok(()); // Don't fail, just skip
                }
            };

            // Start if not running
            if !sandbox.is_running() {
                tracing::info!("Starting sandbox container...");
                if let Err(e) = sandbox.start().await {
                    tracing::warn!("Failed to start sandbox: {}", e);
                    return Ok(()); // Don't fail, just skip
                }
            }

            // Verify container is ready.
            sandbox
                .exec_cli(&std::env::args().collect::<Vec<_>>())
                .await?;

            // The container is started, but this command is NOT relocated into it —
            // `exec_cli` only checks readiness, and nothing downstream routes execution
            // through `docker exec`. Say so, rather than let the started container imply
            // the scan about to run is contained by it.
            tracing::info!(
                "Started Docker environment '{}'; this command still runs on the host",
                name
            );
            eprintln!(
                "note: Docker environment '{}' is running, but this command executes on the \
                 host, not inside it. Templates run as ordinary child processes with your \
                 privileges and full network and filesystem access. To run inside the \
                 container, use `cxg sandbox enter {}`.",
                name, name
            );
        }
    }

    Ok(())
}

/// Print version information
fn print_version() {
    println!("CERT-X-GEN v{}", env!("CARGO_PKG_VERSION"));
    println!("Advanced Multi-Language Security Scanning Engine");
    println!();
    println!("Build Information:");
    println!("  Version: {}", env!("CARGO_PKG_VERSION"));
    println!(
        "  Target:  {}-{}",
        std::env::consts::ARCH,
        std::env::consts::OS
    );
    println!();
    println!("Links:");
    println!("  Repository:    https://github.com/Bugb-Technologies/cert-x-gen");
    println!("  Documentation: https://docs.bugb.io/cxg/");
    println!("  Issues:        https://github.com/Bugb-Technologies/cert-x-gen/issues");
}

/// Print a one-line GitHub star request at the end of a completed scan.
///
/// Deliberately unobtrusive. It prints only when the user just received findings
/// on an interactive terminal, and at most once a week — a nag on every scan is
/// worse than no nag. Gating (all must hold):
///   - stdout is a terminal (same `IsTerminal` check the banner uses)
///   - `CXG_NO_BANNER` is unset, `CXG_NO_NAG` is unset
///   - `--quiet`/`-q` was not passed
///   - (call site) the scan completed without error
///
/// Frequency is tracked by a timestamp file at `~/.cert-x-gen/.star-nag`. Weekly
/// is chosen so it reaches active users at most a handful of times a year while
/// never competing with day-to-day scan output. If the timestamp cannot be read
/// or written, the nag is skipped rather than shown — better silent than repeated.
fn maybe_print_star_nag(quiet: bool) {
    // At most once per this interval.
    const NAG_INTERVAL_SECS: u64 = 7 * 24 * 60 * 60; // one week

    if quiet
        || std::env::var("CXG_NO_BANNER").is_ok()
        || std::env::var("CXG_NO_NAG").is_ok()
        || !std::io::stdout().is_terminal()
    {
        return;
    }

    let Some(stamp) = dirs::home_dir().map(|h| h.join(".cert-x-gen").join(".star-nag")) else {
        return;
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    // Shown recently? Stay quiet.
    if let Ok(contents) = std::fs::read_to_string(&stamp) {
        if let Ok(last) = contents.trim().parse::<u64>() {
            if now.saturating_sub(last) < NAG_INTERVAL_SECS {
                return;
            }
        }
    }

    // Record the timestamp before printing; if we can't persist it, skip the nag so
    // an un-writable home dir doesn't turn into a nag on every single run.
    if let Some(parent) = stamp.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if std::fs::write(&stamp, now.to_string()).is_err() {
        return;
    }

    println!(
        "{}",
        console::style(
            "★ Enjoying cxg? A star helps others find it: https://github.com/Bugb-Technologies/cert-x-gen"
        )
        .dim()
    );
}

/// Print scan summary
fn print_scan_summary(results: &cert_x_gen::types::ScanResults) {
    use console::{style, Term};

    let _term = Term::stdout();

    println!();
    println!("{}", style("═".repeat(80)).dim());
    println!("{}", style("Scan Summary").bold().cyan());
    println!("{}", style("═".repeat(80)).dim());
    println!();

    println!("  Scan ID: {}", style(&results.scan_id).yellow());
    println!(
        "  Duration: {:.2}s",
        results.statistics.duration.as_secs_f64()
    );
    println!("  Targets Scanned: {}", results.statistics.targets_scanned);
    println!(
        "  Templates Executed: {}",
        results.statistics.templates_executed
    );
    println!();

    println!("{}", style("Findings by Severity:").bold());

    let critical = results
        .statistics
        .findings_by_severity
        .get(&cert_x_gen::types::Severity::Critical)
        .unwrap_or(&0);
    let high = results
        .statistics
        .findings_by_severity
        .get(&cert_x_gen::types::Severity::High)
        .unwrap_or(&0);
    let medium = results
        .statistics
        .findings_by_severity
        .get(&cert_x_gen::types::Severity::Medium)
        .unwrap_or(&0);
    let low = results
        .statistics
        .findings_by_severity
        .get(&cert_x_gen::types::Severity::Low)
        .unwrap_or(&0);
    let info = results
        .statistics
        .findings_by_severity
        .get(&cert_x_gen::types::Severity::Info)
        .unwrap_or(&0);

    println!(
        "  {} {}",
        style("CRITICAL:").red().bold(),
        style(critical).red().bold()
    );
    println!("  {} {}", style("HIGH:    ").red(), style(high).red());
    println!(
        "  {} {}",
        style("MEDIUM:  ").yellow(),
        style(medium).yellow()
    );
    println!("  {} {}", style("LOW:     ").blue(), style(low).blue());
    println!("  {} {}", style("INFO:    ").cyan(), style(info).cyan());
    println!();

    println!(
        "  {} {}",
        style("TOTAL:").bold(),
        style(results.findings.len()).bold()
    );
    println!();

    print_execution_ledger(results);

    println!("{}", style("═".repeat(80)).dim());
}

/// Rows of the execution ledger printed under the summary before it is elided.
const LEDGER_ROW_LIMIT: usize = 25;

fn execution_verdict_source(record: &cert_x_gen::types::ExecutionRecord) -> &'static str {
    if record.declared_by_template {
        "template-declared"
    } else if record
        .detail
        .as_deref()
        .is_some_and(|detail| detail.starts_with("engine-adjudicated:"))
    {
        "engine-adjudicated"
    } else {
        "cxg-inferred"
    }
}

/// Print the per-(template, target) execution ledger.
///
/// Findings tell you what was confirmed. This tells you what was *refuted*,
/// *skipped* or *errored* -- distinctions a scan reporting zero findings
/// otherwise cannot express. The full ledger is always in the JSON output;
/// the terminal shows counts plus a bounded sample of the rows.
fn print_execution_ledger(results: &cert_x_gen::types::ScanResults) {
    use cert_x_gen::types::ExecutionStatus;
    use console::style;

    if results.executions.is_empty() {
        return;
    }

    println!("{}", style("Execution Status:").bold());
    for status in ExecutionStatus::ALL {
        let count = results
            .executions
            .iter()
            .filter(|e| e.status == status)
            .count();
        let declared = results
            .executions
            .iter()
            .filter(|e| e.status == status && e.declared_by_template)
            .count();
        let engine = results
            .executions
            .iter()
            .filter(|e| e.status == status && execution_verdict_source(e) == "engine-adjudicated")
            .count();
        let mut value = format!(
            "{} ({} declared, {} inferred)",
            count,
            declared,
            count - declared - engine
        );
        if engine > 0 {
            value.pop();
            value.push_str(&format!(", {} engine-adjudicated)", engine));
        }
        let label = format!("{}:", status.to_string().to_uppercase());
        let styled = match status {
            ExecutionStatus::Confirmed => style(format!("{:<11}{}", label, value)).red(),
            ExecutionStatus::Refuted => style(format!("{:<11}{}", label, value)).green(),
            ExecutionStatus::Skipped => style(format!("{:<11}{}", label, value)).yellow(),
            ExecutionStatus::Errored | ExecutionStatus::TimedOut => {
                style(format!("{:<11}{}", label, value)).magenta()
            }
        };
        println!("  {}", styled);
    }
    println!();

    for e in results.executions.iter().take(LEDGER_ROW_LIMIT) {
        println!(
            "  {:<10} {} → {}{}{}",
            style(e.status.to_string()).bold(),
            e.template_id,
            e.target,
            e.detail
                .as_ref()
                .map(|d| format!("  [{}]", d))
                .unwrap_or_default(),
            style(format!("  ({})", execution_verdict_source(e))).dim()
        );
    }
    if results.executions.len() > LEDGER_ROW_LIMIT {
        println!(
            "  {}",
            style(format!(
                "… and {} more execution(s); the full ledger is in the JSON output",
                results.executions.len() - LEDGER_ROW_LIMIT
            ))
            .dim()
        );
    }
    println!();
}

/// Run AI command
async fn run_ai_command(cmd: cli::AiCommand) -> Result<()> {
    use cli::AiAction;

    match cmd.action {
        AiAction::Generate {
            prompt,
            language,
            provider,
            model,
            output,
            test,
            test_target,
            force,
            estimate_cost,
            api_key,
        } => {
            handle_ai_generate(
                prompt,
                language,
                provider,
                model,
                output,
                test,
                test_target,
                force,
                estimate_cost,
                api_key,
            )
            .await?;
        }
        AiAction::Providers { action } => {
            handle_providers_command(action).await?;
        }
    }

    Ok(())
}

/// Handle AI template generation
async fn handle_ai_generate(
    prompt: String,
    language: cli::LanguageArg,
    provider: Option<String>,
    model: Option<String>,
    output: Option<PathBuf>,
    test: bool,
    test_target: Option<String>,
    force: bool,
    estimate_cost: bool,
    api_key: Option<String>,
) -> Result<()> {
    use console::{style, Term};
    use std::fs;

    // Inject --api-key into the env var for the chosen provider (session-only, not persisted).
    // AIConfig::load() expands ${PROVIDER_API_KEY} from env, so setting here before
    // AIManager::new() is the cleanest override path — mirrors GuardLink's approach.
    if let Some(ref key) = api_key {
        let env_var = match provider.as_deref() {
            Some("anthropic") => "ANTHROPIC_API_KEY",
            Some("openai") => "OPENAI_API_KEY",
            Some("deepseek") => "DEEPSEEK_API_KEY",
            Some("ollama") => "", // ollama doesn't use an API key
            // If no provider specified, try to detect from key prefix
            _ => {
                if key.starts_with("sk-ant-") {
                    "ANTHROPIC_API_KEY"
                } else if key.starts_with("sk-") {
                    "OPENAI_API_KEY"
                } else {
                    "ANTHROPIC_API_KEY" // safe default
                }
            }
        };
        if !env_var.is_empty() {
            std::env::set_var(env_var, key);
            tracing::info!("Injected --api-key into {} for this session", env_var);
        }
    }

    let term = Term::stdout();

    // Convert language argument to TemplateLanguage
    let template_lang: TemplateLanguage = language.into();

    println!();
    println!("{}", style("🤖 AI Template Generation").bold().cyan());
    println!("{}", style("═".repeat(60)).dim());
    println!();
    println!("  {}  {}", style("Prompt:").bold(), prompt);
    println!("  {}  {:?}", style("Language:").bold(), template_lang);
    if let Some(ref p) = provider {
        println!("  {}  {}", style("Provider:").bold(), p);
    }
    if let Some(ref m) = model {
        println!("  {}  {}", style("Model:").bold(), m);
    }
    println!();

    // Create AI manager
    term.write_line(&format!(
        "{} Initializing AI manager...",
        style("[1/5]").dim()
    ))?;
    let manager = AIManager::new()
        .map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;

    // Show cost estimate if requested
    if estimate_cost {
        term.write_line(&format!("{} Estimating cost...", style("[2/5]").dim()))?;
        println!(
            "  {} Cost estimation not yet implemented",
            style("ℹ").blue()
        );
        println!();
    }

    // Generate template
    term.write_line(&format!("{} Generating template...", style("[2/5]").dim()))?;
    term.write_line("  This may take 10-30 seconds depending on the model...")?;

    let template_code = manager
        .generate_template(&prompt, template_lang, provider.as_deref())
        .await
        .map_err(|e| Error::Ai(format!("Template generation failed: {}", e)))?;

    term.write_line(&format!(
        "  {} Template generated successfully!",
        style("✓").green()
    ))?;
    println!();

    // Validate template
    term.write_line(&format!("{} Validating template...", style("[3/5]").dim()))?;
    let validator = TemplateValidator::new();
    validator
        .validate(&template_code, template_lang)
        .map_err(|e| Error::Ai(format!("Template validation failed: {}", e)))?;

    term.write_line(&format!("  {} Template is valid!", style("✓").green()))?;
    println!();

    // Determine output path
    let output_path = if let Some(path) = output {
        path
    } else {
        // Auto-generate filename
        let filename = manager.generate_filename(&prompt, template_lang);
        let ai_templates_dir = dirs::home_dir()
            .ok_or_else(|| Error::Internal("Could not determine home directory".to_string()))?
            .join(".cert-x-gen")
            .join("templates")
            .join("ai-generated");

        ai_templates_dir.join(filename)
    };

    // Check if file exists and force flag
    if output_path.exists() && !force {
        return Err(Error::Internal(format!(
            "File already exists: {}. Use --force to overwrite",
            output_path.display()
        )));
    }

    // Save template
    term.write_line(&format!("{} Saving template...", style("[4/5]").dim()))?;

    // Create directory if it doesn't exist
    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| Error::Internal(format!("Failed to create directory: {}", e)))?;
    }

    fs::write(&output_path, &template_code)
        .map_err(|e| Error::Internal(format!("Failed to write template: {}", e)))?;

    term.write_line(&format!(
        "  {} Template saved to: {}",
        style("✓").green(),
        output_path.display()
    ))?;
    println!();

    // Test template if requested
    if test {
        term.write_line(&format!("{} Testing template...", style("[5/5]").dim()))?;

        if let Some(target) = test_target {
            println!("  Testing against target: {}", target);
            println!(
                "  {} Template testing not yet implemented",
                style("ℹ").blue()
            );
        } else {
            println!(
                "  {} No test target specified, skipping test",
                style("ℹ").yellow()
            );
        }
        println!();
    }

    // Print summary
    println!("{}", style("═".repeat(60)).dim());
    println!(
        "{}",
        style("✓ Template Generation Complete!").bold().green()
    );
    println!("{}", style("═".repeat(60)).dim());
    println!();
    println!("  {} {}", style("Location:").bold(), output_path.display());
    println!(
        "  {} {} lines",
        style("Size:").bold(),
        template_code.lines().count()
    );
    println!("  {} {:?}", style("Language:").bold(), template_lang);
    println!();
    println!("Next steps:");
    println!("  • View template:    cat {}", output_path.display());
    println!(
        "  • Run scan:         cert-x-gen scan --template {} --target <host>",
        output_path.display()
    );
    println!("  • Edit template:    $EDITOR {}", output_path.display());
    println!();

    Ok(())
}

/// Handle providers command
async fn handle_providers_command(action: cli::ProviderAction) -> Result<()> {
    use cert_x_gen::ai::AIManager;
    use cli::ProviderAction;
    use console::style;

    match action {
        ProviderAction::List { detailed } => {
            println!();
            println!("{}", style("Available LLM Providers").bold().cyan());
            println!("{}", style("═".repeat(60)).dim());
            println!();

            let manager = AIManager::new()
                .map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;

            let providers = manager.list_providers();

            if providers.is_empty() {
                println!("  {} No providers configured", style("ℹ").yellow());
                println!();
                println!("To get started:");
                println!("  1. Install Ollama: curl -fsSL https://ollama.com/install.sh | sh");
                println!("  2. Download model: ollama pull codellama:13b");
                println!("  3. Start Ollama: ollama serve");
                println!();
                return Ok(());
            }

            for (provider_name, enabled) in providers {
                let icon = if provider_name == "ollama" && enabled {
                    style("✓").green()
                } else if enabled {
                    style("○").cyan()
                } else {
                    style("○").dim()
                };

                println!("  {} {}", icon, style(&provider_name).bold());

                if detailed {
                    // TODO: Get more detailed info from provider
                    println!(
                        "      Type: {}",
                        if provider_name == "ollama" {
                            "Local"
                        } else {
                            "Cloud"
                        }
                    );
                    println!(
                        "      Status: {}",
                        if enabled { "Enabled" } else { "Disabled" }
                    );
                }
            }

            println!();
            println!("Use 'cxg ai providers test <name>' to test a provider");
            println!();

            Ok(())
        }
        ProviderAction::Test { provider } => {
            println!();
            println!(
                "{}",
                style(format!("Testing Provider: {}", provider))
                    .bold()
                    .cyan()
            );
            println!("{}", style("═".repeat(60)).dim());
            println!();

            let manager = AIManager::new()
                .map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;

            println!("  {} Running health checks...", style("⚙").cyan());
            println!();

            match manager.test_provider(&provider).await {
                Ok(status) => {
                    // Connection status
                    let conn_icon = if status.connection.is_ok() {
                        style("✓").green()
                    } else {
                        style("✗").red()
                    };
                    println!(
                        "  {} Connection: {}",
                        conn_icon,
                        match status.connection {
                            cert_x_gen::ai::providers::ConnectionStatus::Connected =>
                                style("OK").green(),
                            cert_x_gen::ai::providers::ConnectionStatus::Failed =>
                                style("Failed").red(),
                            cert_x_gen::ai::providers::ConnectionStatus::Untested =>
                                style("Not tested").yellow(),
                        }
                    );

                    // Authentication status
                    let auth_icon = if status.authentication.is_ok() {
                        style("✓").green()
                    } else if matches!(
                        status.authentication,
                        cert_x_gen::ai::providers::AuthStatus::NotRequired
                    ) {
                        style("○").dim()
                    } else {
                        style("✗").red()
                    };
                    println!(
                        "  {} Authentication: {}",
                        auth_icon,
                        match status.authentication {
                            cert_x_gen::ai::providers::AuthStatus::Authenticated =>
                                style("Valid").green(),
                            cert_x_gen::ai::providers::AuthStatus::Failed => style("Invalid").red(),
                            cert_x_gen::ai::providers::AuthStatus::NotRequired =>
                                style("Not required").dim(),
                            cert_x_gen::ai::providers::AuthStatus::NotConfigured =>
                                style("Not configured").yellow(),
                            cert_x_gen::ai::providers::AuthStatus::Untested =>
                                style("Not tested").yellow(),
                        }
                    );

                    // Response time
                    if let Some(rt) = status.response_time_ms {
                        let rt_style = if rt < 1000 {
                            style(format!("{}ms", rt)).green()
                        } else if rt < 5000 {
                            style(format!("{}ms", rt)).yellow()
                        } else {
                            style(format!("{}ms", rt)).red()
                        };
                        println!("  {} Response time: {}", style("⚡").cyan(), rt_style);
                    }

                    // Models available
                    if let Some(count) = status.models_available {
                        println!(
                            "  {} Models available: {}",
                            style("📦").cyan(),
                            style(count).bold()
                        );

                        if !status.models.is_empty() {
                            println!();
                            println!("  Available models:");
                            for model in &status.models {
                                let size_info = if let Some(_size) = model.size {
                                    format!(" ({})", model.size_human_readable())
                                } else {
                                    String::new()
                                };
                                println!(
                                    "    • {}{}",
                                    style(&model.name).dim(),
                                    style(size_info).dim()
                                );
                            }
                        }
                    }

                    // Messages
                    if !status.messages.is_empty() {
                        println!();
                        println!("  Messages:");
                        for msg in &status.messages {
                            if msg.starts_with("⚠") || msg.starts_with("Hint:") {
                                println!("    {}", style(msg).yellow());
                            } else if msg.contains("✓") || msg.contains("Success") {
                                println!("    {}", style(msg).green());
                            } else {
                                println!("    {}", style(msg).dim());
                            }
                        }
                    }

                    // Overall status
                    println!();
                    if status.healthy {
                        println!(
                            "  {} Status: {}",
                            style("✓").green().bold(),
                            style("Ready").green().bold()
                        );
                    } else {
                        println!(
                            "  {} Status: {}",
                            style("✗").red().bold(),
                            style("Not Ready").red().bold()
                        );
                    }

                    println!();
                }
                Err(e) => {
                    println!("  {} Error testing provider: {}", style("✗").red(), e);
                    println!();
                }
            }

            Ok(())
        }
        ProviderAction::Status => {
            println!();
            println!("{}", style("Provider Status").bold().cyan());
            println!("{}", style("═".repeat(60)).dim());
            println!();

            let manager = AIManager::new()
                .map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;

            let providers = manager.list_providers();

            if providers.is_empty() {
                println!("  {} No providers configured", style("ℹ").yellow());
                println!();
                return Ok(());
            }

            println!(
                "  {} Testing {} providers...",
                style("⚙").cyan(),
                providers.len()
            );
            println!();

            for (provider_name, enabled) in providers {
                // Provider header
                let icon = if enabled {
                    style("●").green()
                } else {
                    style("○").dim()
                };
                println!("  {} {}", icon, style(&provider_name).bold());
                println!(
                    "    Enabled: {}",
                    if enabled {
                        style("Yes").green()
                    } else {
                        style("No").dim()
                    }
                );

                if enabled {
                    // Test the provider
                    match manager.test_provider(&provider_name).await {
                        Ok(status) => {
                            // Connection
                            let conn_status = match status.connection {
                                cert_x_gen::ai::providers::ConnectionStatus::Connected => {
                                    style("Connected").green()
                                }
                                cert_x_gen::ai::providers::ConnectionStatus::Failed => {
                                    style("Failed").red()
                                }
                                _ => style("Unknown").yellow(),
                            };
                            println!("    Connection: {}", conn_status);

                            // Auth
                            let auth_status = match status.authentication {
                                cert_x_gen::ai::providers::AuthStatus::Authenticated => {
                                    style("Valid").green()
                                }
                                cert_x_gen::ai::providers::AuthStatus::NotRequired => {
                                    style("Not required").dim()
                                }
                                cert_x_gen::ai::providers::AuthStatus::Failed => {
                                    style("Invalid").red()
                                }
                                cert_x_gen::ai::providers::AuthStatus::NotConfigured => {
                                    style("Not configured").yellow()
                                }
                                _ => style("Unknown").yellow(),
                            };
                            println!("    Authentication: {}", auth_status);

                            // Response time
                            if let Some(rt) = status.response_time_ms {
                                println!("    Response time: {}ms", rt);
                            }

                            // Models
                            if let Some(count) = status.models_available {
                                println!("    Models: {}", count);
                            }

                            // Overall
                            let health = if status.healthy {
                                style("✓ Ready").green()
                            } else {
                                style("✗ Not Ready").red()
                            };
                            println!("    Status: {}", health);
                        }
                        Err(e) => {
                            println!("    Status: {} ({})", style("Error").red(), e);
                        }
                    }
                } else {
                    println!("    Status: {}", style("Disabled").dim());
                }

                println!();
            }

            Ok(())
        }
    }
}

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

    #[test]
    fn engine_adjudication_is_not_labelled_as_scanner_inference() {
        let mut record: cert_x_gen::types::ExecutionRecord =
            serde_json::from_value(serde_json::json!({
                "target": "127.0.0.1", "template_id": "probe", "status": "confirmed", "findings": 1,
                "detail": "engine-adjudicated: engine-confirmed finding"
            }))
            .unwrap();
        assert_eq!(execution_verdict_source(&record), "engine-adjudicated");
        record.detail = None;
        assert_eq!(execution_verdict_source(&record), "cxg-inferred");
        record.declared_by_template = true;
        assert_eq!(execution_verdict_source(&record), "template-declared");
    }

    #[test]
    fn parse_target_string_accepts_cli_scheme_with_authority() {
        let target = parse_target_string("cli:///opt/build/toy");
        assert_eq!(target.protocol, Protocol::Cli);
        assert_eq!(target.address, "/opt/build/toy");
        assert_eq!(target.port, None);
    }

    #[test]
    fn parse_target_string_accepts_bare_cli_scheme() {
        let target = parse_target_string("cli:/opt/build/toy");
        assert_eq!(target.protocol, Protocol::Cli);
        assert_eq!(target.address, "/opt/build/toy");
    }

    fn scan_args(extra: &[&str]) -> cli::ScanArgs {
        let mut argv = vec!["scan"];
        argv.extend_from_slice(extra);
        <cli::ScanArgs as clap::Parser>::parse_from(argv)
    }

    /// A probe argument must be able to be the target's own flag, which means
    /// clap has to stop treating a hyphen-leading value as a flag of its own.
    #[test]
    fn probe_arguments_accept_hyphen_leading_values() {
        let args = scan_args(&["--arg", "--label", "--arg", "AAAA"]);
        assert_eq!(args.arg, vec!["--label", "AAAA"]);

        let mut context = cert_x_gen::types::Context::default();
        apply_probe_input(&args, &mut context).unwrap();
        assert_eq!(context.probe_argv, vec!["--label", "AAAA"]);
    }

    /// Only the first '=' separates key from value, so a sanitizer option list
    /// (which is itself k=v) survives intact.
    #[test]
    fn target_env_splits_on_the_first_equals_only() {
        let args = scan_args(&["--target-env", "ASAN_OPTIONS=abort_on_error=1"]);
        let mut context = cert_x_gen::types::Context::default();
        apply_probe_input(&args, &mut context).unwrap();
        assert_eq!(
            context.probe_env,
            vec![("ASAN_OPTIONS".to_string(), "abort_on_error=1".to_string())]
        );
    }

    #[test]
    fn target_env_without_an_equals_is_an_error_not_a_silent_drop() {
        let args = scan_args(&["--target-env", "NOEQUALS"]);
        let mut context = cert_x_gen::types::Context::default();
        let err = apply_probe_input(&args, &mut context)
            .unwrap_err()
            .to_string();
        assert!(err.contains("NOEQUALS"), "error was {err}");
    }

    #[test]
    fn a_missing_stdin_file_is_rejected_before_the_scan_starts() {
        let args = scan_args(&["--stdin-file", "/definitely/not/here.bin"]);
        let mut context = cert_x_gen::types::Context::default();
        let err = apply_probe_input(&args, &mut context)
            .unwrap_err()
            .to_string();
        assert!(err.contains("not a readable file"), "error was {err}");
    }

    #[test]
    fn an_input_path_that_is_not_a_directory_is_rejected() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let args = scan_args(&["--input", file.path().to_str().unwrap()]);
        let mut context = cert_x_gen::types::Context::default();
        let err = apply_probe_input(&args, &mut context)
            .unwrap_err()
            .to_string();
        assert!(err.contains("not a directory"), "error was {err}");
    }

    /// Probe paths are canonicalised so the template never depends on cxg's
    /// working directory to resolve them.
    #[test]
    fn probe_paths_are_canonicalised() {
        let dir = tempfile::tempdir().unwrap();
        let stdin_file = dir.path().join("case.bin");
        std::fs::write(&stdin_file, b"probe").unwrap();
        let indirect = dir.path().join(".").join("case.bin");

        let args = scan_args(&["--stdin-file", indirect.to_str().unwrap()]);
        let mut context = cert_x_gen::types::Context::default();
        apply_probe_input(&args, &mut context).unwrap();

        assert_eq!(
            context.probe_stdin_file.unwrap(),
            stdin_file.canonicalize().unwrap()
        );
    }

    /// With no probe flags the context is untouched, which is what keeps a
    /// network scan's template environment byte-identical to before.
    #[test]
    fn no_probe_flags_leaves_the_context_empty() {
        let args = scan_args(&[]);
        let mut context = cert_x_gen::types::Context::default();
        apply_probe_input(&args, &mut context).unwrap();

        assert!(context.probe_argv.is_empty());
        assert!(context.probe_stdin_file.is_none());
        assert!(context.probe_input_dir.is_none());
        assert!(context.probe_env.is_empty());
    }

    /// A1: three spellings of one binary must be one target, not three.
    #[test]
    fn cli_target_paths_are_canonicalised_so_spellings_deduplicate() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("toy");
        std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
        let canonical = bin.canonicalize().unwrap().to_string_lossy().to_string();

        let dotted = dir.path().join(".").join("toy");
        for spelling in [
            format!("cli://{}", bin.display()),
            format!("cli:{}", bin.display()),
            format!("cli://{}", dotted.display()),
        ] {
            let target = parse_target_string(&spelling);
            assert_eq!(target.protocol, Protocol::Cli);
            assert_eq!(
                target.address, canonical,
                "spelling {spelling} did not canonicalise"
            );
        }
    }

    /// A path that does not resolve is kept verbatim, so the operator sees
    /// back what they typed rather than a rewritten guess.
    #[test]
    fn an_unresolvable_cli_path_is_kept_verbatim() {
        let target = parse_target_string("cli:///definitely/not/here");
        assert_eq!(target.address, "/definitely/not/here");
    }

    /// A2: a `cli:` scope entry is a path, not a comma list and not a file of
    /// targets, so none of the scope splitting may touch it.
    #[test]
    fn a_cli_scope_entry_with_a_comma_is_not_split_in_half() {
        let mut acc = Vec::new();
        let mut stack = HashSet::new();
        expand_scope_entry("cli:///opt/my,build/toy", &mut acc, &mut stack).unwrap();
        assert_eq!(acc, vec!["cli:///opt/my,build/toy".to_string()]);
    }

    /// ...and a `cli:` entry that happens to name a readable file is still a
    /// target, not a list of targets to read.
    #[test]
    fn a_cli_scope_entry_is_never_read_as_a_target_file() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("toy");
        std::fs::write(&bin, b"example.com\nother.example\n").unwrap();

        let mut acc = Vec::new();
        let mut stack = HashSet::new();
        let entry = format!("cli://{}", bin.display());
        expand_scope_entry(&entry, &mut acc, &mut stack).unwrap();
        assert_eq!(acc, vec![entry]);
    }

    /// The exemption is narrow: ordinary scope entries still split.
    #[test]
    fn ordinary_scope_entries_still_split_on_commas() {
        let mut acc = Vec::new();
        let mut stack = HashSet::new();
        expand_scope_entry("example.com,other.example", &mut acc, &mut stack).unwrap();
        assert_eq!(acc, vec!["example.com", "other.example"]);
    }

    #[test]
    fn parse_target_string_leaves_network_targets_alone() {
        let target = parse_target_string("https://example.com:8443");
        assert_eq!(target.protocol, Protocol::Https);
        assert_eq!(target.address, "example.com");
        assert_eq!(target.port, Some(8443));
    }
}