pretender 0.3.1

Multi-language structural code-quality checks — complexity, duplication, mutation testing, and CI integration
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
use std::path::{Path, PathBuf};
use std::process::Command;

fn git_init(dir: &Path) {
    assert!(Command::new("git")
        .args(["init"])
        .current_dir(dir)
        .output()
        .expect("git init")
        .status
        .success());
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(dir)
        .output()
        .expect("git config email");
    Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(dir)
        .output()
        .expect("git config name");
}

fn git_add(dir: &Path, path: &Path) {
    assert!(Command::new("git")
        .arg("add")
        .arg(path)
        .current_dir(dir)
        .output()
        .expect("git add")
        .status
        .success());
}

fn git_commit(dir: &Path, message: &str) {
    assert!(Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(dir)
        .output()
        .expect("git commit")
        .status
        .success());
}

fn pretender_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/debug/pretender")
}

fn source_fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../tests/fixtures")
        .join(name)
}

// Copy a fixture into a fresh temp dir so role detection treats the file
// as the default `app` role rather than `test` (which would trip the
// stricter test thresholds against simple fixtures).
fn stage_fixture(name: &str) -> (PathBuf, PathBuf) {
    let dir = tempdir();
    let dest = dir.join(name);
    std::fs::copy(source_fixture(name), &dest).expect("copy fixture");
    (dir, dest)
}

fn write_temp_file(relative: &str, source: &str) -> (PathBuf, PathBuf) {
    let dir = tempdir();
    let dest = dir.join(relative);
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent).expect("create parent dirs");
    }
    std::fs::write(&dest, source).expect("write temp source");
    (dir, dest)
}

fn tempdir() -> PathBuf {
    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let dir = std::env::temp_dir().join(format!("pretender-cli-{pid}-{nanos}"));
    std::fs::create_dir_all(&dir).expect("create tempdir");
    dir
}

fn check(path: &Path) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("check").arg(path).env("NO_COLOR", "1");
    cmd
}

fn check_default(dir: &Path) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("check").env("NO_COLOR", "1");
    cmd.current_dir(dir);
    cmd
}

fn check_in(dir: &Path, path: &Path) -> Command {
    let mut cmd = check(path);
    cmd.current_dir(dir);
    cmd
}

fn report_in(dir: &Path) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("report").current_dir(dir).env("NO_COLOR", "1");
    cmd
}

fn ci_generate_in(dir: &Path, provider: &str) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("ci")
        .arg("generate")
        .arg(provider)
        .current_dir(dir)
        .env("NO_COLOR", "1");
    cmd
}

fn hooks_in(dir: &Path, action: &str) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("hooks")
        .arg(action)
        .current_dir(dir)
        .env("NO_COLOR", "1");
    cmd
}

fn init_in(dir: &Path) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("init").current_dir(dir).env("NO_COLOR", "1");
    cmd
}

#[test]
fn test_complexity_command() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("python_simple.py"))
        .output()
        .expect("failed to execute process");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    if !stdout.contains("complex_func: 6") || !stdout.contains("simple: 1") {
        panic!(
            "Output did not contain expected results.\nSTDOUT:\n{}\nSTDERR:\n{}",
            stdout,
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

#[test]
fn test_complexity_multi_path() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("python_simple.py"))
        .arg(source_fixture("rust_simple.rs"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Multi-path mode shows per-file headers
    assert!(
        stdout.contains("python_simple.py:"),
        "should show file header for python file; stdout: {stdout}"
    );
    assert!(
        stdout.contains("rust_simple.rs:"),
        "should show file header for rust file; stdout: {stdout}"
    );
}

#[test]
fn test_complexity_shows_threshold_marker_on_violation() {
    // Write a fixture with a function that exceeds cyclomatic_max=10
    // 11 branches → cyclomatic=12
    let (dir, path) = write_temp_file(
        "high_complexity.py",
        r#"
def very_complex(x):
    if x == 1: return 1
    if x == 2: return 2
    if x == 3: return 3
    if x == 4: return 4
    if x == 5: return 5
    if x == 6: return 6
    if x == 7: return 7
    if x == 8: return 8
    if x == 9: return 9
    if x == 10: return 10
    return 0
"#,
    );
    // No pretender.toml → defaults (app cyclomatic_max=10)
    let _ = dir;

    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(&path)
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("✗"),
        "should mark function exceeding threshold with ✗; stdout: {stdout}"
    );
    assert!(
        stdout.contains("threshold: 10"),
        "should show threshold value; stdout: {stdout}"
    );
}

#[test]
fn test_check_defaults_to_current_dir() {
    let dir = tempdir();
    let src = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../tests/fixtures")
        .join("python_simple.py");
    let dest = dir.join("python_simple.py");
    std::fs::copy(&src, &dest).expect("copy fixture");

    let output = check_default(&dir)
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("python_simple.py"), "stdout: {stdout}");
}

#[test]
fn test_check_command_human_output() {
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged).output().expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("python_simple.py"), "stdout: {stdout}");
    // Default mode hides clean functions; --verbose would show them
    assert!(
        !stdout.contains("cyclomatic="),
        "default should not show per-function metrics for clean files; stdout: {stdout}"
    );
}

#[test]
fn test_check_command_json_output() {
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged)
        .arg("--format")
        .arg("json")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid json");

    assert_eq!(json["files"].as_array().map(Vec::len), Some(1));
    assert_eq!(
        json["files"][0]["path"].as_str(),
        Some(staged.to_string_lossy().as_ref())
    );
    assert_eq!(
        json["files"][0]["units"][0]["name"].as_str(),
        Some("simple")
    );
    assert_eq!(
        json["files"][0]["units"][2]["metrics"]["cyclomatic"].as_u64(),
        Some(6)
    );
}

#[test]
fn test_check_warns_when_no_config() {
    let dir = tempdir();
    let source = dir.join("hello.py");
    std::fs::write(&source, "def hello():\n    pass\n").expect("write source");

    let output = check_in(&dir, &source)
        .output()
        .expect("failed to execute process");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("no pretender.toml found"),
        "expected warning about missing config; stderr: {stderr}"
    );
    assert!(
        stderr.contains("pretender init"),
        "expected suggestion to run pretender init; stderr: {stderr}"
    );
}

#[test]
fn test_check_no_warning_when_config_present() {
    let dir = tempdir();
    let source = dir.join("hello.py");
    std::fs::write(&source, "def hello():\n    pass\n").expect("write source");
    std::fs::write(dir.join("pretender.toml"), "[pretender]\n").expect("write config");

    let output = check_in(&dir, &source)
        .output()
        .expect("failed to execute process");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("no pretender.toml found"),
        "unexpected config warning when toml is present; stderr: {stderr}"
    );
}

#[test]
fn test_check_exits_zero_when_clean() {
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged).output().expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "expected exit 0 on clean fixture; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_check_tiered_mode_exits_zero_on_violation() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged).output().expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "expected exit 0 in default tiered mode; stdout: {} stderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_check_tiered_mode_shows_advisory_not_violation() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("tiered")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("ADVISORY"),
        "tiered mode should show ADVISORY; stdout: {stdout}"
    );
    assert!(
        !stdout.contains("VIOLATION"),
        "tiered mode should not show VIOLATION; stdout: {stdout}"
    );
    assert!(
        !stdout.contains("✗"),
        "tiered mode should not show ✗; stdout: {stdout}"
    );
}

#[test]
fn test_check_gate_mode_shows_violation() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Only assert the label — color codes vary by terminal
    assert!(
        stdout.contains("VIOLATION"),
        "gate mode should show VIOLATION; stdout: {stdout}"
    );
}

#[test]
fn test_check_output_flag_writes_to_file() {
    let (_dir, staged) = stage_fixture("python_simple.py");
    let out_path = staged.with_file_name("report.json");

    let output = check(&staged)
        .arg("--format")
        .arg("json")
        .arg("--output")
        .arg(&out_path)
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        output.stdout.is_empty(),
        "stdout should be empty when --output is set; got: {}",
        String::from_utf8_lossy(&output.stdout)
    );

    let written = std::fs::read_to_string(&out_path).expect("report file should exist");
    let json: serde_json::Value =
        serde_json::from_str(&written).expect("report file should be valid json");
    assert_eq!(json["files"].as_array().map(Vec::len), Some(1));
}

#[test]
fn test_check_human_output_to_file_is_uncolored() {
    let (_dir, staged) = stage_fixture("python_simple.py");
    let out_path = staged.with_file_name("report.txt");

    let output = check(&staged)
        .arg("--output")
        .arg(&out_path)
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let written = std::fs::read_to_string(&out_path).expect("report file should exist");
    assert!(
        !written.contains('\u{1b}'),
        "report written to file must not contain ANSI escape sequences: {written:?}"
    );
}

#[test]
fn test_check_human_output_surfaces_violations() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged).output().expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Default mode is tiered → ⚠ ADVISORY (not ✗ VIOLATION)
    assert!(stdout.contains("⚠"), "stdout: {stdout}");
    assert!(stdout.contains("python_violator.py"), "stdout: {stdout}");
    assert!(
        stdout.contains("ADVISORY"),
        "tiered mode should mark violations as advisory; got: {stdout}"
    );
    assert!(
        stdout.contains("params"),
        "human output should name the violated metric; got: {stdout}"
    );
    assert!(
        !stdout.contains('\u{1b}'),
        "NO_COLOR should suppress ANSI codes; got: {stdout:?}"
    );
}

#[test]
fn test_check_human_output_reports_cognitive_violations() {
    let (_dir, staged) = stage_fixture("python_cognitive.py");

    let output = check(&staged).output().expect("failed to execute process");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("deeply_nested"), "stdout: {stdout}");
    assert!(stdout.contains("cognitive"), "stdout: {stdout}");
}

#[test]
fn test_check_reports_min_assertions_for_test_role() {
    let (_dir, staged) = write_temp_file(
        "tests/test_no_assertions.py",
        "def test_missing_assertion():\n    helper()\n",
    );

    let output = check(&staged).output().expect("failed to execute process");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("test_missing_assertion"),
        "stdout: {stdout}"
    );
    assert!(stdout.contains("min_assertions"), "stdout: {stdout}");
}

#[test]
fn test_check_accepts_test_role_when_assertion_present() {
    let (_dir, staged) = write_temp_file(
        "tests/test_has_assertion.py",
        "def test_has_assertion():\n    assert True\n",
    );

    let output = check(&staged).output().expect("failed to execute process");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.contains("min_assertions"), "stdout: {stdout}");
}

#[test]
fn test_check_guidance_mode_exits_zero_on_violation() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("guidance")
        .output()
        .expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "guidance mode must exit 0 even when violations exist; stdout: {}",
        String::from_utf8_lossy(&output.stdout),
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    // guidance mode uses ⚠ ADVISORY, not ✗ VIOLATION
    assert!(
        stdout.contains("ADVISORY"),
        "guidance mode should surface violations as advisories; got: {stdout}",
    );
}

#[test]
fn test_check_gate_mode_from_config_fails_on_violation() {
    let dir = tempdir();
    let staged = dir.join("python_violator.py");
    std::fs::copy(source_fixture("python_violator.py"), &staged).expect("copy fixture");
    std::fs::write(dir.join("pretender.toml"), "[pretender]\nmode = \"gate\"\n")
        .expect("write config");

    let output = check_in(&dir, &staged)
        .output()
        .expect("failed to execute process");

    assert_eq!(output.status.code(), Some(1));
}

#[test]
fn test_check_tiered_human_output_highlights_yellow_band() {
    let dir = tempdir();
    let staged = dir.join("yellow.py");
    std::fs::write(
        dir.join("pretender.toml"),
        "[thresholds]\ncyclomatic_max = 99\ncognitive_max = 99\n",
    )
    .expect("write config");
    std::fs::write(
        &staged,
        "def yellow_band(value):\n    if value > 0:\n        pass\n    if value > 1:\n        pass\n    if value > 2:\n        pass\n    if value > 3:\n        pass\n    if value > 4:\n        pass\n    if value > 5:\n        pass\n    if value > 6:\n        pass\n    if value > 7:\n        pass\n    if value > 8:\n        pass\n    if value > 9:\n        pass\n    if value > 10:\n        pass\n    return value\n",
    )
    .expect("write source");

    let output = check_in(&dir, &staged)
        .output()
        .expect("failed to execute process");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("⚠"), "stdout: {stdout}");
    assert!(
        stdout.contains("yellow_band(): cyclomatic 12 (yellow)"),
        "stdout: {stdout}"
    );
}

#[test]
fn test_check_gate_mode_fails_on_violation() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("failed to execute process");

    assert_eq!(output.status.code(), Some(1));
}

#[test]
fn test_check_sarif_output_structure() {
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--format")
        .arg("sarif")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success() || output.status.code() == Some(1),
        "sarif format should not exit with error 2; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let sarif: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid SARIF JSON");

    assert_eq!(
        sarif["version"].as_str(),
        Some("2.1.0"),
        "version must be 2.1.0"
    );
    assert!(sarif["$schema"].as_str().is_some(), "must have $schema");

    let runs = sarif["runs"].as_array().expect("must have runs array");
    assert_eq!(runs.len(), 1, "must have exactly one run");

    let run = &runs[0];
    assert_eq!(
        run["tool"]["driver"]["name"].as_str(),
        Some("pretender"),
        "tool.driver.name must be 'pretender'"
    );

    let rules = run["tool"]["driver"]["rules"]
        .as_array()
        .expect("must have rules array");
    assert!(
        !rules.is_empty(),
        "rules must not be empty when violations exist"
    );
    for rule in rules {
        assert!(rule["id"].as_str().is_some(), "each rule must have an id");
    }

    let results = run["results"].as_array().expect("must have results array");
    assert!(
        !results.is_empty(),
        "results must not be empty for a file with violations"
    );
    for result in results {
        assert!(
            result["ruleId"].as_str().is_some(),
            "each result must have ruleId"
        );
        assert!(
            result["message"]["text"].as_str().is_some(),
            "each result must have message.text"
        );
        let locations = result["locations"]
            .as_array()
            .expect("each result must have locations");
        assert!(
            !locations.is_empty(),
            "each result must have at least one location"
        );
        let phys = &locations[0]["physicalLocation"];
        assert!(
            phys["artifactLocation"]["uri"].as_str().is_some(),
            "must have uri"
        );
        assert!(
            phys["region"]["startLine"].as_i64().is_some(),
            "must have startLine"
        );
    }
}

#[test]
fn test_mutation_dry_run_python() {
    let output = Command::new(pretender_bin())
        .args([
            "mutation",
            "--dry-run",
            source_fixture("python_simple.py").to_str().unwrap(),
        ])
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "dry-run should exit 0; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("mutmut"),
        "dry-run should name the tool; got: {stdout}"
    );
    assert!(
        stdout.contains("Planned mutants") || stdout.contains("No mutation sites"),
        "dry-run should list planned mutants; got: {stdout}"
    );
}

#[test]
fn test_stub_subcommands_exit_two() {
    let cmd = vec!["plugins", "list"];
    let output = Command::new(pretender_bin())
        .args(&cmd)
        .output()
        .expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(2),
        "{cmd:?} should exit 2 (not yet implemented); stderr: {}",
        String::from_utf8_lossy(&output.stderr),
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("not yet implemented"),
        "{cmd:?} stderr should explain status; got: {stderr}",
    );
}

#[test]
fn test_explain_known_metric_prints_doc() {
    let output = Command::new(pretender_bin())
        .args(["explain", "cyclomatic"])
        .output()
        .expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "explain cyclomatic should succeed"
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("cyclomatic"),
        "output should include metric name"
    );
    assert!(stdout.contains("McCabe"), "output should cite McCabe");
    assert!(
        stdout.contains("10"),
        "output should mention default threshold"
    );
}

#[test]
fn test_explain_unknown_metric_exits_nonzero() {
    let output = Command::new(pretender_bin())
        .args(["explain", "not_a_real_metric"])
        .output()
        .expect("failed to execute process");

    assert_ne!(output.status.code(), Some(0), "unknown metric should fail");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unknown metric") || stderr.contains("cyclomatic"),
        "stderr should name the error and list available metrics; got: {stderr}",
    );
}

#[test]
fn test_rust_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("rust_simple.rs"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_javascript_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("js_simple.js"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("withBranch: 2"),
        "expected withBranch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complexFunc: 5"),
        "expected complexFunc: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_typescript_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("ts_sample.ts"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("greet: 1"),
        "expected greet: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("withBranch: 2"),
        "expected withBranch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complexFunc: 5"),
        "expected complexFunc: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_check_parallel_results_are_deterministic() {
    let dir = tempdir();
    for name in ["python_simple.py", "python_violator.py"] {
        std::fs::copy(source_fixture(name), dir.join(name)).expect("copy fixture");
    }

    let run = || {
        let output = Command::new(pretender_bin())
            .arg("check")
            .arg(&dir)
            .arg("--format")
            .arg("json")
            .env("NO_COLOR", "1")
            .output()
            .expect("failed to execute process");
        assert!(
            output.status.code().is_some(),
            "process must exit normally; stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).expect("stdout is utf-8")
    };

    let first = run();
    let second = run();
    assert_eq!(
        first, second,
        "json output must be deterministic across runs"
    );
}

#[test]
fn test_init_defaults_flag_is_rejected() {
    let dir = tempdir();

    let output = init_in(&dir).arg("--defaults").output().expect("run init");

    assert!(
        !output.status.success(),
        "expected failure for removed --defaults flag"
    );
}

#[test]
fn test_init_non_interactive_writes_config_with_mode_override() {
    let dir = tempdir();

    let output = init_in(&dir)
        .arg("--non-interactive")
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("run init");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let config = std::fs::read_to_string(dir.join("pretender.toml")).expect("config exists");
    assert!(config.contains("mode = \"gate\""), "config: {config}");
    assert!(
        config.contains("languages = [\"auto\"]"),
        "config: {config}"
    );
    assert!(config.contains("[roles.test]"), "config: {config}");
}

#[test]
fn test_init_interactive_can_install_hook_and_ci() {
    let dir = tempdir();
    std::fs::create_dir_all(dir.join(".git/hooks")).expect("git hooks dir");

    let output = init_in(&dir)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write as _;
            child
                .stdin
                .as_mut()
                .expect("stdin")
                .write_all(b"guidance\npython,rust\ny\ny\n")?;
            child.wait_with_output()
        })
        .expect("run init interactively");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let config = std::fs::read_to_string(dir.join("pretender.toml")).expect("config exists");
    assert!(config.contains("mode = \"guidance\""), "config: {config}");
    assert!(
        config.contains("languages = [\"python\", \"rust\"]"),
        "config: {config}"
    );

    let hook = std::fs::read_to_string(dir.join(".git/hooks/pre-commit")).expect("hook exists");
    assert!(hook.contains("Installed by Pretender"), "hook: {hook}");
    assert!(
        hook.contains("exec pretender check . --staged"),
        "hook: {hook}"
    );

    let workflow = std::fs::read_to_string(dir.join(".github/workflows/pretender.yml"))
        .expect("workflow exists");
    assert!(
        workflow
            .contains("cargo install --git https://github.com/charly/pretender --locked pretender"),
        "workflow: {workflow}"
    );
}

#[test]
fn test_ci_generate_github_writes_workflow() {
    let dir = tempdir();

    let output = ci_generate_in(&dir, "github")
        .output()
        .expect("run ci generator");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let workflow = std::fs::read_to_string(dir.join(".github/workflows/pretender.yml"))
        .expect("workflow exists");
    assert!(
        workflow.starts_with("name: Pretender"),
        "workflow: {workflow}"
    );
    assert!(
        workflow.contains("uses: actions/checkout@v4"),
        "workflow: {workflow}"
    );
    assert!(
        workflow.contains("uses: dtolnay/rust-toolchain@stable"),
        "workflow: {workflow}"
    );
    assert!(
        workflow
            .contains("cargo install --git https://github.com/charly/pretender --locked pretender"),
        "workflow: {workflow}"
    );
    assert!(
        workflow.contains("pretender check . --format=sarif --output=pretender.sarif"),
        "workflow: {workflow}"
    );
    assert!(
        workflow.contains("uses: github/codeql-action/upload-sarif@v3"),
        "workflow: {workflow}"
    );
    assert!(
        workflow.contains("pretender report --format=markdown >> $GITHUB_STEP_SUMMARY"),
        "workflow: {workflow}"
    );
}

#[test]
fn test_ci_generate_non_github_stays_stubbed() {
    let dir = tempdir();

    let output = ci_generate_in(&dir, "gitlab")
        .output()
        .expect("run ci generator");

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("not yet implemented"), "stderr: {stderr}");
}

#[test]
fn test_hooks_install_and_uninstall_manage_pretender_shim() {
    let dir = tempdir();
    std::fs::create_dir_all(dir.join(".git/hooks")).expect("git hooks dir");

    let install = hooks_in(&dir, "install")
        .output()
        .expect("run hooks install");
    assert!(
        install.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&install.stderr)
    );

    let hook_path = dir.join(".git/hooks/pre-commit");
    let hook = std::fs::read_to_string(&hook_path).expect("hook exists");
    assert!(hook.contains("Installed by Pretender"), "hook: {hook}");
    assert!(
        hook.contains("exec pretender check . --staged"),
        "hook: {hook}"
    );

    let uninstall = hooks_in(&dir, "uninstall")
        .output()
        .expect("run hooks uninstall");
    assert!(
        uninstall.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&uninstall.stderr)
    );
    assert!(!hook_path.exists(), "hook should be removed");
}

#[test]
fn test_hooks_install_creates_hooks_dir_when_absent() {
    let dir = tempdir();
    std::fs::create_dir_all(dir.join(".git")).expect("git dir");
    // .git/hooks does NOT exist

    let install = hooks_in(&dir, "install")
        .output()
        .expect("run hooks install");
    assert!(
        install.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&install.stderr)
    );
    assert!(
        dir.join(".git/hooks/pre-commit").exists(),
        "hook should exist even when .git/hooks was absent"
    );
}

#[test]
fn test_hooks_uninstall_is_noop_when_no_hook() {
    let dir = tempdir();
    std::fs::create_dir_all(dir.join(".git/hooks")).expect("git hooks dir");
    // no hook file present

    let uninstall = hooks_in(&dir, "uninstall")
        .output()
        .expect("run hooks uninstall");
    assert!(
        uninstall.status.success(),
        "uninstall with no hook should succeed silently; stderr: {}",
        String::from_utf8_lossy(&uninstall.stderr)
    );
}

#[test]
fn test_hooks_uninstall_refuses_foreign_hook() {
    let dir = tempdir();
    let hooks_dir = dir.join(".git/hooks");
    std::fs::create_dir_all(&hooks_dir).expect("git hooks dir");
    std::fs::write(
        hooks_dir.join("pre-commit"),
        "#!/bin/sh\necho 'custom hook'\n",
    )
    .expect("write foreign hook");

    let uninstall = hooks_in(&dir, "uninstall")
        .output()
        .expect("run hooks uninstall");
    assert!(
        !uninstall.status.success(),
        "should refuse to remove a hook not installed by Pretender"
    );
    let stderr = String::from_utf8_lossy(&uninstall.stderr);
    assert!(
        stderr.contains("refusing to remove hook not installed by Pretender"),
        "stderr: {stderr}"
    );
    assert!(
        hooks_dir.join("pre-commit").exists(),
        "foreign hook should be left intact"
    );
}

#[test]
fn test_hooks_install_refuses_foreign_hook() {
    let dir = tempdir();
    let hooks_dir = dir.join(".git/hooks");
    std::fs::create_dir_all(&hooks_dir).expect("git hooks dir");
    std::fs::write(
        hooks_dir.join("pre-commit"),
        "#!/bin/sh\necho 'custom hook'\n",
    )
    .expect("write foreign hook");

    let install = hooks_in(&dir, "install")
        .output()
        .expect("run hooks install");
    assert!(
        !install.status.success(),
        "should refuse to overwrite a hook not installed by Pretender"
    );
    let stderr = String::from_utf8_lossy(&install.stderr);
    assert!(
        stderr.contains("refusing to overwrite hook not installed by Pretender"),
        "stderr: {stderr}"
    );
    let hook = std::fs::read_to_string(hooks_dir.join("pre-commit")).expect("hook still exists");
    assert!(
        hook.contains("custom hook"),
        "foreign hook should be left intact: {hook}"
    );
}

#[test]
fn test_hooks_install_is_idempotent() {
    let dir = tempdir();
    std::fs::create_dir_all(dir.join(".git/hooks")).expect("git hooks dir");

    let first = hooks_in(&dir, "install").output().expect("first install");
    assert!(
        first.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&first.stderr)
    );

    let second = hooks_in(&dir, "install").output().expect("second install");
    assert!(
        second.status.success(),
        "reinstall over Pretender-owned hook should succeed; stderr: {}",
        String::from_utf8_lossy(&second.stderr)
    );

    let hook = std::fs::read_to_string(dir.join(".git/hooks/pre-commit")).expect("hook exists");
    assert!(
        hook.contains("exec pretender check . --staged"),
        "hook: {hook}"
    );
}

#[test]
fn test_report_markdown_reads_last_json_check() {
    let dir = tempdir();
    let staged = dir.join("python_violator.py");
    std::fs::copy(source_fixture("python_violator.py"), &staged).expect("copy fixture");

    let check_output = check_in(&dir, &staged)
        .arg("--format")
        .arg("json")
        .output()
        .expect("run json check");
    assert!(
        check_output.status.success(),
        "json check failed: {}",
        String::from_utf8_lossy(&check_output.stderr)
    );

    let output = report_in(&dir)
        .arg("--format")
        .arg("markdown")
        .output()
        .expect("run report");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("# Pretender report"), "stdout: {stdout}");
    assert!(stdout.contains("python_violator.py"), "stdout: {stdout}");
    assert!(stdout.contains("too_many_params"), "stdout: {stdout}");
    assert!(stdout.contains("cyclomatic"), "stdout: {stdout}");
}

#[test]
fn test_report_html_writes_output_file() {
    let dir = tempdir();
    let staged = dir.join("python_violator.py");
    let out_path = dir.join("pretender-report.html");
    std::fs::copy(source_fixture("python_violator.py"), &staged).expect("copy fixture");

    let check_output = check_in(&dir, &staged)
        .arg("--format")
        .arg("json")
        .output()
        .expect("run json check");
    assert!(
        check_output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&check_output.stderr)
    );

    let output = report_in(&dir)
        .arg("--format")
        .arg("html")
        .arg("--output")
        .arg(&out_path)
        .output()
        .expect("run report");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        output.stdout.is_empty(),
        "stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    let html = std::fs::read_to_string(&out_path).expect("html report exists");
    assert!(html.contains("<!doctype html>"), "html: {html}");
    assert!(html.contains("python_violator.py"), "html: {html}");
    assert!(html.contains("too_many_params"), "html: {html}");
}

#[test]
fn test_report_markdown_reads_last_human_check() {
    let dir = tempdir();
    let staged = dir.join("python_violator.py");
    std::fs::copy(source_fixture("python_violator.py"), &staged).expect("copy fixture");

    let check_output = check_in(&dir, &staged).output().expect("run human check");
    assert!(
        check_output.status.success(),
        "human check failed: {}",
        String::from_utf8_lossy(&check_output.stderr)
    );

    let output = report_in(&dir)
        .arg("--format")
        .arg("markdown")
        .output()
        .expect("run report");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("# Pretender report"), "stdout: {stdout}");
    assert!(stdout.contains("python_violator.py"), "stdout: {stdout}");
}

#[test]
fn test_report_fails_without_cached_report() {
    let dir = tempdir();

    let output = report_in(&dir).output().expect("run report");

    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout: {} stderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("failed to read last check report"),
        "stderr: {stderr}"
    );
}

#[test]
fn test_smell_call_weights_elevate_abc() {
    let (_dir, path) = stage_fixture("python_smell_calls.py");
    let output = Command::new(pretender_bin())
        .arg("check")
        .arg(&path)
        .arg("--format")
        .arg("json")
        .env("NO_COLOR", "1")
        .output()
        .expect("run pretender");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("invalid json: {e}\nstdout: {stdout}"));
    let units = json["files"][0]["units"].as_array().expect("units array");
    let abc_for = |name: &str| -> f64 {
        units
            .iter()
            .find(|u| u["name"] == name)
            .unwrap_or_else(|| panic!("unit {name} not found"))["metrics"]["abc"]
            .as_f64()
            .unwrap_or_else(|| panic!("abc metric for {name}"))
    };
    // smell_eval: A=1, B=0, C=5 (eval weight=5.0) → sqrt(26) ≈ 5.099
    let eval_abc = abc_for("smell_eval");
    assert!(
        (eval_abc - 5.099).abs() < 0.01,
        "smell_eval abc={eval_abc}, expected ≈5.099 (sqrt(26))"
    );
    // smell_exec: A=0, B=0, C=5 (exec weight=5.0) → 5.0
    let exec_abc = abc_for("smell_exec");
    assert!(
        (exec_abc - 5.0).abs() < 0.01,
        "smell_exec abc={exec_abc}, expected 5.0"
    );
    // smell_compile: A=1, B=0, C=3 (compile weight=3.0) → sqrt(10) ≈ 3.162
    let compile_abc = abc_for("smell_compile");
    assert!(
        (compile_abc - 3.162).abs() < 0.01,
        "smell_compile abc={compile_abc}, expected ≈3.162 (sqrt(10))"
    );
}

#[test]
fn test_go_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("go_sample.go"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_java_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("java_sample.java"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("withBranch: 2"),
        "expected withBranch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complexFunc: 5"),
        "expected complexFunc: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_ruby_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("ruby_sample.rb"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_c_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("c_sample.c"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_check_staged_only_scans_staged_files() {
    let dir = tempdir();
    git_init(&dir);

    // Commit a baseline file so HEAD exists
    let baseline = dir.join("baseline.py");
    std::fs::write(&baseline, "def baseline(): pass\n").unwrap();
    git_add(&dir, &baseline);
    git_commit(&dir, "baseline");

    // Stage file_a.py
    let file_a = dir.join("file_a.py");
    std::fs::write(&file_a, "def func_a(): pass\n").unwrap();
    git_add(&dir, &file_a);

    // Write file_b.py but do NOT stage it
    let file_b = dir.join("file_b.py");
    std::fs::write(&file_b, "def func_b(): pass\n").unwrap();

    let output = Command::new(pretender_bin())
        .args(["check", ".", "--staged"])
        .current_dir(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("file_a.py"),
        "expected file_a.py in stdout: {stdout}"
    );
    assert!(
        !stdout.contains("file_b.py"),
        "unexpected file_b.py in stdout (not staged): {stdout}"
    );
}

#[test]
fn test_check_staged_empty_staging_area_exits_success() {
    let dir = tempdir();
    git_init(&dir);

    // Commit a file so HEAD exists
    let f = dir.join("committed.py");
    std::fs::write(&f, "def f(): pass\n").unwrap();
    git_add(&dir, &f);
    git_commit(&dir, "init");

    // Nothing staged — check should succeed with no file output
    let output = Command::new(pretender_bin())
        .args(["check", ".", "--staged"])
        .current_dir(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_check_staged_first_commit_no_head() {
    let dir = tempdir();
    git_init(&dir);

    // No prior commits — stage one file
    let f = dir.join("first.py");
    std::fs::write(&f, "def first(): pass\n").unwrap();
    git_add(&dir, &f);

    let output = Command::new(pretender_bin())
        .args(["check", ".", "--staged"])
        .current_dir(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("first.py"),
        "expected first.py in stdout: {stdout}"
    );
}

#[test]
fn test_check_diff_only_filters_to_changed_files() {
    let dir = tempdir();
    git_init(&dir);

    // First commit: file_old.py
    let file_old = dir.join("file_old.py");
    std::fs::write(&file_old, "def old(): pass\n").unwrap();
    git_add(&dir, &file_old);
    git_commit(&dir, "first commit");

    // Second commit (HEAD): add file_new.py
    let file_new = dir.join("file_new.py");
    std::fs::write(&file_new, "def new_func(): pass\n").unwrap();
    git_add(&dir, &file_new);
    git_commit(&dir, "second commit");

    // --diff-only --diff-base=HEAD~1 should only show file_new.py
    let output = Command::new(pretender_bin())
        .args(["check", ".", "--diff-only", "--diff-base=HEAD~1"])
        .current_dir(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("file_new.py"),
        "expected file_new.py in stdout: {stdout}"
    );
    assert!(
        !stdout.contains("file_old.py"),
        "unexpected file_old.py in stdout (unchanged): {stdout}"
    );
}

#[test]
fn test_cpp_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("cpp_sample.cpp"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

const RUFF_PLUGIN_TOML: &str = r#"
name = "ruff"
extensions = [".py"]
command = ["ruff", "check", "--output-format=json", "--select=E501", "{files}"]
parser = "json"

[mapping]
path = "filename"
line = "location.row"
message = "message"
code = "code"
"#;

/// The python_simple.py fixture has a 112-char comment on line 1, which triggers
/// E501 (line too long > 79) when ruff is run with --select=E501.
#[test]
fn test_external_plugin_ruff_json_findings() {
    if std::process::Command::new("ruff")
        .arg("--version")
        .output()
        .is_err()
    {
        eprintln!("skipping: ruff not in PATH");
        return;
    }

    let metrics_dir = tempdir();
    std::fs::write(metrics_dir.join("ruff.toml"), RUFF_PLUGIN_TOML).expect("write ruff.toml");

    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged)
        .arg("--format")
        .arg("json")
        .env("PRETENDER_METRICS_DIR", &metrics_dir)
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("valid json output");

    let files = json["files"].as_array().expect("files array");
    assert_eq!(files.len(), 1);
    let external = files[0]["external_findings"]
        .as_array()
        .expect("external_findings present when ruff fires");
    assert!(
        !external.is_empty(),
        "expected at least one ruff finding; full output: {json}"
    );
    assert_eq!(
        external[0]["source"].as_str(),
        Some("ruff"),
        "finding source should be 'ruff'"
    );
    assert_eq!(
        external[0]["code"].as_str(),
        Some("E501"),
        "finding code should be 'E501'"
    );
}

#[test]
fn test_check_format_junit_is_rejected() {
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged)
        .arg("--format")
        .arg("junit")
        .output()
        .expect("failed to execute process");

    assert!(
        !output.status.success(),
        "junit format should be rejected (removed until implemented)"
    );
}

#[test]
fn test_check_staged_no_files_prints_message() {
    let dir = tempdir();
    git_init(&dir);
    // No staged files — just an empty git repo with a source file not added
    std::fs::write(dir.join("hello.py"), "def hello():\n    pass\n").expect("write file");

    let output = check_in(&dir, &dir)
        .arg("--staged")
        .output()
        .expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "should exit 0 with no staged files; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("No staged files to check"),
        "should print message when no staged files; stdout: {stdout}"
    );
}

#[test]
fn test_check_default_hides_clean_functions() {
    // python_simple has passing functions — default output should not list them
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // No per-function metric lines should appear for a clean file
    assert!(
        !stdout
            .lines()
            .any(|l| l.starts_with("  ") && l.contains("cyclomatic=")),
        "clean functions should be hidden by default; stdout: {stdout}"
    );
}

#[test]
fn test_check_verbose_shows_all_functions() {
    let (_dir, staged) = stage_fixture("python_simple.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("gate")
        .arg("--verbose")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.lines().any(|l| l.contains("cyclomatic=")),
        "--verbose should show per-function metrics; stdout: {stdout}"
    );
}

#[test]
fn test_check_human_output_rounds_violation_values() {
    // python_violator triggers integer violations; ensure they display without decimals
    let (_dir, staged) = stage_fixture("python_violator.py");

    let output = check(&staged)
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Integer violations should display without trailing .00 (default app params_max = 4)
    assert!(
        stdout.contains("params 6 > 4"),
        "integer violation should display without decimals; stdout: {stdout}"
    );
}

#[test]
fn test_check_human_output_abc_rounds_to_two_decimal_places() {
    // Write a fixture that reliably triggers a fractional ABC violation
    // A function with assignments + branches + calls produces a non-integer ABC score
    let (dir, path) = write_temp_file(
        "abc_fixture.py",
        r#"
def complex_function(x, y, z):
    a = x + 1
    b = y * 2
    c = z - 1
    if a > 0:
        result = some_call(a, b)
        result2 = other_call(b, c)
        result3 = third_call(a, c)
        return result + result2 + result3
    elif b > 0:
        return another_call(a, b, c)
    else:
        return fallback(x, y, z)
"#,
    );
    // Write a config that sets a very low abc threshold to force a violation
    std::fs::write(dir.join("pretender.toml"), "[thresholds]\nabc_max = 1\n")
        .expect("write config");

    let output = check_in(&dir, &path)
        .arg("--mode")
        .arg("gate")
        .output()
        .expect("failed to execute process");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Violation line must exist and must not contain a long float
    let abc_violation = stdout
        .lines()
        .find(|l| l.contains("VIOLATION") && l.contains("abc"));
    assert!(
        abc_violation.is_some(),
        "expected abc violation; stdout: {stdout}"
    );
    let line = abc_violation.unwrap();
    let has_long_float = line.split_whitespace().any(|tok| {
        if let Some(idx) = tok.find('.') {
            tok[idx + 1..].len() > 2
        } else {
            false
        }
    });
    assert!(
        !has_long_float,
        "abc violation line has excessive decimal places: {line}"
    );
}

#[test]
fn test_check_skips_binary_files() {
    let dir = tempdir();
    // Write a binary file (null bytes are not valid UTF-8)
    let binary = dir.join("artifact.bin");
    std::fs::write(&binary, b"\x00\x01\x02\x03\xff\xfe").expect("write binary file");

    let output = check(&binary).output().expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "check should exit 0 when given a binary file; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_check_skips_binary_files_in_directory() {
    let dir = tempdir();
    // Write a source file alongside a binary file
    let source = dir.join("hello.py");
    std::fs::write(&source, "def hello():\n    pass\n").expect("write source");
    let binary = dir.join("artifact.bin");
    std::fs::write(&binary, b"\x00\x01\x02\x03\xff\xfe").expect("write binary file");

    let output = check(&dir).output().expect("failed to execute process");

    assert_eq!(
        output.status.code(),
        Some(0),
        "check should exit 0 when directory contains binary files; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// No clap version set yet; move to a version-based test once #[command(version)] is added
#[test]
fn test_version_flag_works() {
    let output = Command::new(pretender_bin())
        .arg("--version")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "--version should exit 0; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("pretender"),
        "--version should print 'pretender'; got: {stdout}"
    );
    assert!(
        stdout.contains("0.3."),
        "--version should include version number; got: {stdout}"
    );
}

#[test]
fn test_version_short_flag_works() {
    let output = Command::new(pretender_bin())
        .arg("-V")
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "-V should exit 0; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("pretender"),
        "-V should print 'pretender'; got: {stdout}"
    );
}

fn doctor_in(dir: &Path, extra_args: &[&str]) -> Command {
    let mut cmd = Command::new(pretender_bin());
    cmd.arg("doctor")
        .args(extra_args)
        .current_dir(dir)
        .env("NO_COLOR", "1");
    cmd
}

fn write_pretender_hook(dir: &Path) {
    let hooks_dir = dir.join(".git/hooks");
    std::fs::create_dir_all(&hooks_dir).expect("create hooks dir");
    let hook = hooks_dir.join("pre-commit");
    std::fs::write(
        &hook,
        "#!/usr/bin/env sh\n# Installed by Pretender.\nexec pretender check . --staged\n",
    )
    .expect("write hook");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755))
            .expect("chmod hook");
    }
}

#[test]
fn test_doctor_all_pass_with_valid_config_and_hook() {
    let dir = tempdir();
    git_init(&dir);
    std::fs::write(dir.join("pretender.toml"), "").expect("write config");
    write_pretender_hook(&dir);

    let output = doctor_in(&dir, &[]).output().expect("run doctor");

    assert_eq!(
        output.status.code(),
        Some(0),
        "doctor should exit 0; stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("6/6 checks passed"),
        "expected summary; got: {stdout}"
    );
}

#[test]
fn test_doctor_missing_config_exits_1_with_correct_skips() {
    let dir = tempdir();
    git_init(&dir);

    let output = doctor_in(&dir, &[]).output().expect("run doctor");

    assert_eq!(output.status.code(), Some(1), "should exit 1");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("✗ Config present"),
        "Config present should fail; got: {stdout}"
    );
    assert!(
        stdout.contains("⚠ Config valid"),
        "Config valid should be skipped; got: {stdout}"
    );
    assert!(
        stdout.contains("⚠ Plugin manifests"),
        "Plugin manifests should be skipped; got: {stdout}"
    );
}

#[test]
fn test_doctor_json_missing_config_exits_1_with_fail_status() {
    let dir = tempdir();
    git_init(&dir);

    let output = doctor_in(&dir, &["--format", "json"])
        .output()
        .expect("run doctor");

    assert_eq!(output.status.code(), Some(1), "should exit 1");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("output should be valid JSON");
    let checks = parsed.as_array().expect("JSON root should be array");
    let config_present = checks
        .iter()
        .find(|c| c["name"] == "Config present")
        .expect("Config present check missing");
    assert_eq!(
        config_present["status"], "fail",
        "Config present should have status=fail"
    );
}

#[test]
fn test_doctor_unmanaged_hook_fails_installed_skips_executable() {
    let dir = tempdir();
    git_init(&dir);
    std::fs::write(dir.join("pretender.toml"), "").expect("write config");
    let hooks_dir = dir.join(".git/hooks");
    std::fs::create_dir_all(&hooks_dir).expect("create hooks dir");
    let hook = hooks_dir.join("pre-commit");
    std::fs::write(&hook, "#!/usr/bin/env sh\necho 'custom hook'\n").expect("write hook");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755))
            .expect("chmod hook");
    }

    let output = doctor_in(&dir, &[]).output().expect("run doctor");

    assert_eq!(output.status.code(), Some(1), "should exit 1");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("✗ Hook installed"),
        "Hook installed should fail; got: {stdout}"
    );
    assert!(
        stdout.contains("⚠ Hook executable"),
        "Hook executable should be skipped; got: {stdout}"
    );
}

#[test]
fn test_check_warns_on_unsupported_language_paths() {
    let dir = tempdir();
    std::fs::write(
        dir.join("main.hs"),
        "module Main where\nmain :: IO ()\nmain = putStrLn \"hi\"\n",
    )
    .expect("write haskell file");

    let output = Command::new(pretender_bin())
        .arg("check")
        .arg(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    // Should still exit 0 (it's a warning, not a hard failure)
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("no files matched a supported grammar"),
        "expected warning about no supported grammar; stderr: {stderr}"
    );
    assert!(
        stderr.contains("warning:"),
        "warning should appear on stderr; stderr: {stderr}"
    );
}

#[test]
fn test_check_no_warning_when_supported_language_found() {
    let dir = tempdir();
    std::fs::write(dir.join("main.clj"), "(ns my-app)\n").expect("write clojure file");
    std::fs::write(dir.join("main.py"), "def hello(): pass\n").expect("write python file");

    let output = Command::new(pretender_bin())
        .arg("check")
        .arg(&dir)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to execute process");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("no files matched a supported grammar"),
        "should not warn when supported files are present; stderr: {stderr}"
    );
}

#[test]
fn test_r_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("r_sample.R"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_julia_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("julia_sample.jl"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with_branch: 2"),
        "expected with_branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex_func: 5"),
        "expected complex_func: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_csharp_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("csharp_sample.cs"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Simple: 1"),
        "expected Simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("WithBranch: 2"),
        "expected WithBranch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("ComplexFunc: 5"),
        "expected ComplexFunc: 5 in stdout: {stdout}"
    );
}

#[test]
fn test_csharp_check() {
    let (_dir, staged) = stage_fixture("csharp_sample.cs");

    let output = check(&staged).output().expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("csharp_sample.cs"),
        "expected csharp_sample.cs in output; stdout: {stdout}"
    );
}

#[test]
fn test_clojure_complexity() {
    let output = Command::new(pretender_bin())
        .arg("complexity")
        .arg(source_fixture("clojure_sample.clj"))
        .output()
        .expect("failed to execute process");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("simple: 1"),
        "expected simple: 1 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("with-branch: 2"),
        "expected with-branch: 2 in stdout: {stdout}"
    );
    assert!(
        stdout.contains("complex-func: 5"),
        "expected complex-func: 5 in stdout: {stdout}"
    );
}