cccc-cli 1.10.0

The unified cccc binary: one CLI that measures cognitive/cyclomatic complexity across every bundled language (ECMAScript/TypeScript, Rust, Go, PHP, Ruby, Python, Perl, Zig, C, C++, Swift, Java, Dart, Scala, C#, Visual Basic .NET, Shell)
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
//! End-to-end tests for the unified `cccc` binary: generic CLI behaviour shared
//! by every language (exercised through the ECMAScript fixture), plus the
//! multi-language dispatch, `--lang` filtering, and `cccc.toml` config features.

use assert_cmd::Command;
use predicates::prelude::PredicateBooleanExt;

fn json(args: &[&str]) -> serde_json::Value {
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .args(args)
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    serde_json::from_str(&stdout).expect("valid JSON")
}

// ----- generic CLI behaviour (via the ECMAScript fixture) --------------------

#[test]
fn version_reports_binary_name() {
    Command::cargo_bin("cccc")
        .unwrap()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicates::str::starts_with("cccc "));
}

#[test]
fn nonexistent_path_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .arg("/no/such/path-xyz")
        .assert()
        .failure()
        .code(2);
}

#[test]
fn existing_dir_with_no_matches_is_ok() {
    let dir = std::env::temp_dir().join("cccc_empty_match_test");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("readme.md"), "# not analyzed").unwrap();
    Command::cargo_bin("cccc")
        .unwrap()
        .arg(&dir)
        .assert()
        .success();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn outputs_json_by_default() {
    let v = json(&["tests/fixtures/sample.ts"]);
    let file = &v["files"][0];
    assert_eq!(file["path"], "tests/fixtures/sample.ts");
    let funcs = file["functions"].as_array().unwrap();
    let sop = funcs.iter().find(|f| f["name"] == "sumOfPrimes").unwrap();
    assert_eq!(sop["cognitive"], 7);
    assert_eq!(sop["cyclomatic"], 4);
}

#[test]
fn jobs_option_produces_same_output() {
    let single = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--jobs", "1", "tests/fixtures/sample.ts"])
        .assert()
        .success();
    let many = Command::cargo_bin("cccc")
        .unwrap()
        .args(["-j", "4", "tests/fixtures/sample.ts"])
        .assert()
        .success();
    assert_eq!(
        single.get_output().stdout,
        many.get_output().stdout,
        "output must not depend on --jobs"
    );
}

#[test]
fn jobs_zero_is_rejected() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--jobs", "0", "tests/fixtures/sample.ts"])
        .assert()
        .failure();
}

#[test]
fn includes_project_summary() {
    let v = json(&["tests/fixtures/sample.ts"]);
    let s = &v["summary"];
    assert_eq!(s["file_count"], 1);
    // sample.ts has sumOfPrimes, getWords, classify.
    assert_eq!(s["function_count"], 3);
    assert_eq!(s["cognitive"]["sum"], 10);
    assert_eq!(s["cognitive"]["max"], 7);
    assert!(s["cognitive"]["median"].is_number());
    assert!(s["cyclomatic"]["p95"].is_number());
}

#[test]
fn top_cognitive_returns_flat_ranking() {
    let v = json(&["--top-cognitive", "2", "tests/fixtures/sample.ts"]);
    assert!(v.get("files").is_none(), "top mode must not emit files");
    assert_eq!(v["metric"], "cognitive");
    let top = v["top"].as_array().unwrap();
    assert_eq!(top.len(), 2);
    assert_eq!(top[0]["name"], "sumOfPrimes");
    assert_eq!(top[0]["cognitive"], 7);
    assert_eq!(top[0]["path"], "tests/fixtures/sample.ts");
    assert_eq!(top[1]["name"], "classify");
    assert_eq!(v["summary"]["function_count"], 3);
}

#[test]
fn top_cyclomatic_orders_by_cyclomatic() {
    let v = json(&["--top-cyclomatic", "1", "tests/fixtures/sample.ts"]);
    assert_eq!(v["metric"], "cyclomatic");
    assert_eq!(v["top"][0]["name"], "sumOfPrimes");
    assert_eq!(v["top"][0]["cyclomatic"], 4);
}

#[test]
fn top_flags_are_mutually_exclusive() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args([
            "--top-cognitive",
            "1",
            "--top-cyclomatic",
            "1",
            "tests/fixtures/sample.ts",
        ])
        .assert()
        .failure();
}

#[test]
fn exclude_glob_drops_matching_files() {
    let dir = std::env::temp_dir().join("cccc_exclude_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("src")).unwrap();
    std::fs::write(dir.join("src/app.ts"), "function a() { return 1; }").unwrap();
    std::fs::write(dir.join("src/app.test.ts"), "function b() { return 2; }").unwrap();

    let out = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--exclude", "*.test.ts"])
        .arg(&dir)
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "the *.test.ts file must be excluded");
    assert!(files[0]["path"].as_str().unwrap().ends_with("app.ts"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn exclude_glob_prunes_a_directory_subtree() {
    let dir = std::env::temp_dir().join("cccc_exclude_dir_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("dist/nested")).unwrap();
    std::fs::create_dir_all(dir.join("src")).unwrap();
    std::fs::write(dir.join("src/app.ts"), "function a() { return 1; }").unwrap();
    std::fs::write(dir.join("dist/bundle.ts"), "function b() { return 2; }").unwrap();
    std::fs::write(dir.join("dist/nested/x.ts"), "function c() { return 3; }").unwrap();

    let out = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--exclude", "dist/**"])
        .arg(&dir)
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "everything under dist/ must be excluded");
    assert!(files[0]["path"].as_str().unwrap().ends_with("app.ts"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn report_files_are_sorted_by_path_despite_parallel_walk() {
    let dir = std::env::temp_dir().join("cccc_sorted_output_test");
    let _ = std::fs::remove_dir_all(&dir);
    // Enough files spread over subdirectories that an unsorted parallel walk
    // would almost surely surface out of order.
    for sub in ["a", "b", "c", "d", "e"] {
        std::fs::create_dir_all(dir.join(sub)).unwrap();
        for name in ["m.ts", "n.ts", "o.ts", "p.ts"] {
            std::fs::write(dir.join(sub).join(name), "function f() { return 1; }").unwrap();
        }
    }

    let out = Command::cargo_bin("cccc")
        .unwrap()
        .arg(&dir)
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let paths: Vec<&str> = v["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| f["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths.len(), 20);
    let mut sorted = paths.clone();
    sorted.sort_unstable();
    assert_eq!(paths, sorted, "files must be ordered by path");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn exclude_applies_to_explicit_file_argument() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--exclude", "*.ts", "tests/fixtures/sample.ts"])
        .assert()
        .success()
        .stderr(predicates::str::contains("no matching files"));
}

#[test]
fn invalid_exclude_pattern_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--exclude", "a[b", "tests/fixtures/sample.ts"])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn max_cognitive_threshold_fails() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--max-cognitive", "5", "tests/fixtures/sample.ts"])
        .assert()
        .failure()
        .code(1);
}

#[test]
fn max_cognitive_threshold_passes_when_under() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--max-cognitive", "100", "tests/fixtures/sample.ts"])
        .assert()
        .success();
}

#[test]
fn table_output_renders() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--format", "table", "tests/fixtures/sample.ts"])
        .assert()
        .success()
        .stdout(predicates::str::contains("sumOfPrimes"))
        .stdout(predicates::str::contains("file total"))
        .stdout(predicates::str::contains("summary"));
}

/// Two files: `hot.ts` has a function with cognitive 3, `cold.ts` only trivial ones.
fn write_hot_and_cold(dir_name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(dir_name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("hot.ts"),
        "function hot(a, b) {\n  if (a) {\n    if (b) {\n      return 1;\n    }\n  }\n  return 0;\n}\n",
    )
    .unwrap();
    std::fs::write(dir.join("cold.ts"), "function cold() {\n  return 0;\n}\n").unwrap();
    dir
}

#[test]
fn table_min_skips_files_with_no_remaining_functions() {
    let dir = write_hot_and_cold("cccc_table_min_skip_test");
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--format", "table", "--min", "3"])
        .arg(&dir)
        .assert()
        .success()
        .stdout(predicates::str::contains("hot.ts"))
        .stdout(predicates::str::contains("cold.ts").not())
        .stdout(predicates::str::contains("(no functions)").not())
        // The summary still counts every analyzed file.
        .stdout(predicates::str::contains("summary (2 files"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn table_without_min_still_lists_every_file() {
    let dir = write_hot_and_cold("cccc_table_no_min_test");
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--format", "table"])
        .arg(&dir)
        .assert()
        .success()
        .stdout(predicates::str::contains("hot.ts"))
        .stdout(predicates::str::contains("cold.ts"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn json_min_keeps_files_with_no_remaining_functions() {
    let dir = write_hot_and_cold("cccc_json_min_keep_test");
    let v = json(&["--min", "3", dir.to_str().unwrap()]);
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 2);
    let cold = files
        .iter()
        .find(|f| f["path"].as_str().unwrap().ends_with("cold.ts"))
        .unwrap();
    assert!(cold["functions"].as_array().unwrap().is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

// ----- parse-error reporting --------------------------------------------------

/// Create `broken.py` (one valid function, one syntax error) in a fresh temp
/// dir. Python goes through tree-sitter, which recovers from the error, so the
/// valid function is still measured and the error is reported alongside.
fn write_broken_py(dir_name: &str) -> (std::path::PathBuf, std::path::PathBuf) {
    let dir = std::env::temp_dir().join(dir_name);
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("broken.py");
    std::fs::write(
        &path,
        "def ok(a):\n    if a:\n        return 1\n    return 0\n\ndef broken(:\n    pass\n",
    )
    .unwrap();
    (dir, path)
}

#[test]
fn json_summary_counts_parse_errors() {
    let (dir, path) = write_broken_py("cccc_parse_error_json_test");
    let v = json(&[path.to_str().unwrap()]);
    let s = &v["summary"];
    assert!(s["parse_error_count"].as_u64().unwrap() >= 1);
    assert_eq!(s["parse_error_file_count"], 1);
    let error_files = s["parse_error_files"].as_array().unwrap();
    assert_eq!(error_files.len(), 1);
    assert!(error_files[0].as_str().unwrap().ends_with("broken.py"));
    let file = &v["files"][0];
    assert!(!file["parse_errors"].as_array().unwrap().is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn json_summary_reports_zero_parse_errors_for_clean_input() {
    let v = json(&["tests/fixtures/sample.ts"]);
    assert_eq!(v["summary"]["parse_error_count"], 0);
    assert_eq!(v["summary"]["parse_error_file_count"], 0);
    assert!(v["summary"].get("parse_error_files").is_none());
}

#[test]
fn table_mode_warns_about_parse_errors_on_stderr() {
    let (dir, path) = write_broken_py("cccc_parse_error_table_test");
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--format", "table", path.to_str().unwrap()])
        .assert()
        .success()
        .stderr(predicates::str::contains("cccc: warning:"))
        .stderr(predicates::str::contains("parse error"))
        .stderr(predicates::str::contains("broken.py"))
        .stdout(predicates::str::contains("parse errors:"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn json_mode_reports_parse_errors_in_output_not_stderr() {
    let (dir, path) = write_broken_py("cccc_parse_error_json_stderr_test");
    Command::cargo_bin("cccc")
        .unwrap()
        .arg(path.to_str().unwrap())
        .assert()
        .success()
        .stderr(predicates::str::is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

// ----- multi-language dispatch & --lang -------------------------------------

/// Kotlin's entry in a comma-separated `--lang`/`--exclude-lang` list: it is only
/// compiled in with the (default) `kotlin` feature, and naming an unknown
/// language is an error.
const KOTLIN: &str = if cfg!(feature = "kotlin") {
    ",kotlin"
} else {
    ""
};

#[test]
fn analyzes_all_languages_in_one_run() {
    // The fixtures dir holds one file per language; a single run dispatches each
    // by extension and reports them all together.
    let v = json(&["tests/fixtures"]);
    let expected_files = if cfg!(feature = "kotlin") { 22 } else { 21 };
    assert_eq!(v["summary"]["file_count"], expected_files);
    let paths: Vec<String> = v["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| f["path"].as_str().unwrap().to_string())
        .collect();
    let mut samples = vec![
        "sample.ts",
        "sample.rs",
        "sample.go",
        "sample.php",
        "sample.rb",
        "sample.scm",
        "sample.lisp",
        "sample.el",
        "sample.clj",
        "sample.py",
        "sample.zig",
        "sample.c",
        "sample.cpp",
        "sample.pl",
        "sample.swift",
        "sample.java",
        "sample.dart",
        "sample.scala",
        "sample.cs",
        "sample.vb",
        "sample.sh",
    ];
    if cfg!(feature = "kotlin") {
        samples.push("sample.kt");
    }
    for ext in samples {
        assert!(paths.iter().any(|p| p.ends_with(ext)), "missing {ext}");
    }
}

#[test]
fn lang_filter_restricts_to_selected_languages() {
    let v = json(&["--lang", "go", "tests/fixtures"]);
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "only the Go file should be analyzed");
    assert!(files[0]["path"].as_str().unwrap().ends_with("sample.go"));
}

#[test]
fn lang_filter_accepts_aliases_and_multiple() {
    let v = json(&["--lang", "rs,typescript", "tests/fixtures"]);
    assert_eq!(v["summary"]["file_count"], 2);
}

#[test]
fn unknown_lang_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--lang", "cobol", "tests/fixtures"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains("unknown language"));
}

#[test]
fn exclude_lang_drops_a_language() {
    // Excluding every language except ES and Rust leaves the .ts and .rs fixtures.
    let excluded = format!(
        "go,php,ruby,scheme,commonlisp,emacslisp,clojure{KOTLIN},python,perl,zig,c,cpp,swift,java,dart,scala,csharp,vbnet,shell"
    );
    let v = json(&["--exclude-lang", &excluded, "tests/fixtures"]);
    let mut exts: Vec<String> = v["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| {
            f["path"]
                .as_str()
                .unwrap()
                .rsplit('.')
                .next()
                .unwrap()
                .to_string()
        })
        .collect();
    exts.sort();
    assert_eq!(exts, vec!["rs", "ts"]);
}

#[test]
fn exclude_lang_combines_with_lang() {
    // Start from {es, go, rust}, then drop go → {es, rust}.
    let v = json(&[
        "--lang",
        "es,go,rust",
        "--exclude-lang",
        "go",
        "tests/fixtures",
    ]);
    assert_eq!(v["summary"]["file_count"], 2);
    let has_go = v["files"]
        .as_array()
        .unwrap()
        .iter()
        .any(|f| f["path"].as_str().unwrap().ends_with(".go"));
    assert!(!has_go, "Go must be excluded");
}

#[test]
fn excluding_every_language_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args([
            "--exclude-lang",
            &format!(
                "es,rust,go,php,ruby,scheme,commonlisp,emacslisp,clojure{KOTLIN},python,perl,zig,c,cpp,swift,java,dart,scala,csharp,vbnet,shell"
            ),
            "tests/fixtures",
        ])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains("no languages selected"));
}

#[test]
fn unknown_exclude_lang_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--exclude-lang", "cobol", "tests/fixtures"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains("unknown language"));
}

// ----- cccc.toml config ------------------------------------------------------

/// Create a temp project dir containing `cccc.toml` and a high-complexity
/// `sample.ts` (sumOfPrimes, cognitive 6).
fn config_project(name: &str, toml: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cccc.toml"), toml).unwrap();
    std::fs::write(
        dir.join("sample.ts"),
        "function sumOfPrimes(max) {\n  for (let i = 2; i <= max; ++i) {\n    for (let j = 2; j < i; ++j) {\n      if (i % j === 0) { return i; }\n    }\n  }\n  return 0;\n}\n",
    )
    .unwrap();
    dir
}

#[test]
fn config_is_discovered_by_walking_up_from_cwd() {
    let dir = config_project("cccc_cfg_discover", "max-cognitive = 5\n");
    // Running from inside the project picks up cccc.toml; the threshold fails.
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg("sample.ts")
        .assert()
        .failure()
        .code(1);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cli_flag_overrides_config() {
    let dir = config_project("cccc_cfg_override", "max-cognitive = 5\n");
    // The CLI flag wins over the config's stricter threshold.
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--max-cognitive", "100", "sample.ts"])
        .assert()
        .success();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn no_config_ignores_discovered_file() {
    let dir = config_project("cccc_cfg_no_config", "max-cognitive = 5\n");
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--no-config", "sample.ts"])
        .assert()
        .success();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn explicit_config_path_is_loaded() {
    let dir = config_project("cccc_cfg_explicit", "max-cognitive = 5\n");
    let cfg = dir.join("cccc.toml");
    // Run from elsewhere (the crate dir) but point --config at the file: it
    // applies, so the strict threshold fails.
    Command::cargo_bin("cccc")
        .unwrap()
        .arg("--config")
        .arg(&cfg)
        .arg(dir.join("sample.ts"))
        .assert()
        .failure()
        .code(1);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn missing_explicit_config_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--config", "/no/such/cccc.toml", "tests/fixtures/sample.ts"])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn invalid_config_is_an_error() {
    let dir = config_project("cccc_cfg_invalid", "totally = not valid =\n");
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg("sample.ts")
        .assert()
        .failure()
        .code(2);
    let _ = std::fs::remove_dir_all(&dir);
}

// ----- per-language [ext] config --------------------------------------------

#[test]
fn per_language_ext_override_restricts_extensions() {
    // Restricting ES to `.ts` means a sibling `.js` file is no longer analyzed.
    let dir = std::env::temp_dir().join("cccc_cfg_ext_restrict");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cccc.toml"), "[ext]\nes = [\"ts\"]\n").unwrap();
    std::fs::write(dir.join("a.ts"), "function a() { return 1; }").unwrap();
    std::fs::write(dir.join("b.js"), "function b() { return 2; }").unwrap();

    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg(".")
        .assert()
        .success();
    let v: serde_json::Value =
        serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "only the .ts file should be analyzed");
    assert!(files[0]["path"].as_str().unwrap().ends_with("a.ts"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn per_language_ext_override_routes_custom_extension() {
    // A custom extension assigned to ES is parsed by the ES front-end.
    let dir = std::env::temp_dir().join("cccc_cfg_ext_custom");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cccc.toml"), "[ext]\nes = [\"ts\", \"myts\"]\n").unwrap();
    std::fs::write(dir.join("c.myts"), "const f = (a, b) => (a && b ? 1 : 0);").unwrap();

    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg(".")
        .assert()
        .success();
    let v: serde_json::Value =
        serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "the .myts file should be routed to ES");
    assert!(files[0]["path"].as_str().unwrap().ends_with("c.myts"));
    // `a && b ? .. : ..` scores cognitive 2 (ternary + &&) — proof ES parsed it.
    assert_eq!(files[0]["cognitive"], 2);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn unknown_language_in_ext_config_is_an_error() {
    let dir = std::env::temp_dir().join("cccc_cfg_ext_unknown");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cccc.toml"), "[ext]\ncobol = [\"cbl\"]\n").unwrap();
    std::fs::write(dir.join("a.ts"), "function a() { return 1; }").unwrap();

    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg(".")
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains("unknown language"));
    let _ = std::fs::remove_dir_all(&dir);
}

// ----- per-language --ext CLI flag ------------------------------------------

/// A temp dir with `a.ts`, `a.tsx`, and `b.js` (all analyzable as ECMAScript).
fn es_ext_project(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.ts"), "function a() { return 1; }").unwrap();
    std::fs::write(dir.join("a.tsx"), "function b() { return 2; }").unwrap();
    std::fs::write(dir.join("b.js"), "function c() { return 3; }").unwrap();
    dir
}

fn analyzed_names(v: &serde_json::Value) -> Vec<String> {
    v["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| {
            std::path::Path::new(f["path"].as_str().unwrap())
                .file_name()
                .unwrap()
                .to_string_lossy()
                .into_owned()
        })
        .collect()
}

#[test]
fn cli_per_language_ext_restricts_extensions() {
    let dir = es_ext_project("cccc_cli_ext_restrict");
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--ext", "es=ts"])
        .arg(&dir)
        .assert()
        .success();
    let v: serde_json::Value =
        serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
    assert_eq!(analyzed_names(&v), vec!["a.ts"], "only .ts analyzed");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cli_per_language_ext_accepts_alias_and_list() {
    let dir = es_ext_project("cccc_cli_ext_alias");
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--ext", "typescript=ts,tsx"])
        .arg(&dir)
        .assert()
        .success();
    let v: serde_json::Value =
        serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
    let mut names = analyzed_names(&v);
    names.sort();
    assert_eq!(names, vec!["a.ts", "a.tsx"], ".js excluded, .ts/.tsx kept");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cli_global_ext_still_filters_across_languages() {
    // The bare (no `=`) form is the original global filter.
    let v = json(&["--ext", "ts", "tests/fixtures"]);
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1);
    assert!(files[0]["path"].as_str().unwrap().ends_with("sample.ts"));
}

#[test]
fn cli_ext_overrides_config_ext() {
    // Config says es = [ts, tsx]; the CLI narrows es to ts only — CLI wins.
    let dir = es_ext_project("cccc_cli_ext_over_config");
    std::fs::write(dir.join("cccc.toml"), "[ext]\nes = [\"ts\", \"tsx\"]\n").unwrap();
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--ext", "es=ts", "."])
        .assert()
        .success();
    let v: serde_json::Value =
        serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
    assert_eq!(
        analyzed_names(&v),
        vec!["a.ts"],
        "CLI override wins over config"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cli_unknown_language_in_ext_is_an_error() {
    Command::cargo_bin("cccc")
        .unwrap()
        .args(["--ext", "cobol=cbl", "tests/fixtures/sample.ts"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicates::str::contains("unknown language"));
}

// ----- results cache ---------------------------------------------------------

#[test]
fn cache_reuses_unchanged_files_and_reanalyzes_edits() {
    let dir = std::env::temp_dir().join("cccc_cache_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let src = dir.join("sample.ts");
    std::fs::copy("tests/fixtures/sample.ts", &src).unwrap();
    let cache = dir.join("cache.bin");

    let run = || {
        let out = Command::cargo_bin("cccc")
            .unwrap()
            .args(["--no-config", "--cache-file"])
            .arg(&cache)
            .arg(&dir)
            .assert()
            .success();
        String::from_utf8(out.get_output().stdout.clone()).unwrap()
    };

    let cold = run();
    assert!(cache.is_file(), "cache file is created");
    let warm = run();
    assert_eq!(cold, warm, "an all-hit run must not change the output");

    // Editing the file must invalidate its entry.
    let orig = std::fs::read_to_string(&src).unwrap();
    std::fs::write(
        &src,
        format!("{orig}\nfunction extraFn(x: number) {{ return x ? 1 : 2; }}\n"),
    )
    .unwrap();
    let edited = run();
    assert!(edited.contains("extraFn"), "changed file is re-analyzed");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cache_prunes_deleted_files() {
    let dir = std::env::temp_dir().join("cccc_cache_delete_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("keep.ts"), "function keep() { return 1; }").unwrap();
    std::fs::write(dir.join("gone.ts"), "function gone() { return 2; }").unwrap();
    let cache = dir.join("cache.bin");

    let run = || {
        let out = Command::cargo_bin("cccc")
            .unwrap()
            .args(["--no-config", "--cache-file"])
            .arg(&cache)
            .arg(&dir)
            .assert()
            .success();
        let v: serde_json::Value =
            serde_json::from_slice(&out.get_output().stdout).expect("valid JSON");
        analyzed_names(&v)
    };

    let mut cold = run();
    cold.sort();
    assert_eq!(cold, vec!["gone.ts", "keep.ts"]);

    // Delete one file; nothing else changes, so every surviving file is a
    // cache hit — the deleted file must vanish from the output anyway.
    std::fs::remove_file(dir.join("gone.ts")).unwrap();
    assert_eq!(run(), vec!["keep.ts"], "deleted file must not resurface");

    // And its stale entry must be pruned from the cache file, not left behind
    // by the "all hits, skip the write" fast path. (Cached paths are stored as
    // plain strings, so a byte search is a valid containment check.)
    let bytes = std::fs::read(&cache).unwrap();
    let needle = b"gone.ts";
    let contains = bytes.windows(needle.len()).any(|w| w == needle);
    assert!(!contains, "cache must no longer reference the deleted file");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cache_survives_mtime_only_changes() {
    let dir = std::env::temp_dir().join("cccc_cache_touch_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let src = dir.join("sample.ts");
    std::fs::copy("tests/fixtures/sample.ts", &src).unwrap();
    let cache = dir.join("cache.bin");

    let run = || {
        let out = Command::cargo_bin("cccc")
            .unwrap()
            .args(["--no-config", "--cache-file"])
            .arg(&cache)
            .arg(&dir)
            .assert()
            .success();
        String::from_utf8(out.get_output().stdout.clone()).unwrap()
    };
    // Same bytes, new mtime — what a fresh checkout does to every file in CI.
    let touch = |offset: u64| {
        std::fs::File::options()
            .write(true)
            .open(&src)
            .unwrap()
            .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(offset))
            .unwrap();
    };

    let cold = run();
    touch(10);
    assert_eq!(run(), cold, "an mtime-only change must still hit");

    // That hit went through the content hash; the run must persist the
    // refreshed mtime so the next run is back to stat-only validation…
    let rewritten = std::fs::read(&cache).unwrap();
    let stable = run();
    assert_eq!(stable, cold);
    // …and an untouched all-hit run must take the skip-the-write fast path.
    assert_eq!(
        std::fs::read(&cache).unwrap(),
        rewritten,
        "an all-stat-hit run must not rewrite the cache"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cache_git_index_skips_revalidation() {
    let dir = std::env::temp_dir().join("cccc_cache_git_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    // git resolves symlinks in --show-toplevel (macOS /tmp); agree with it.
    let dir = dir.canonicalize().unwrap();
    let src = dir.join("sample.ts");
    std::fs::copy("tests/fixtures/sample.ts", &src).unwrap();
    let git = |args: &[&str]| {
        assert!(
            std::process::Command::new("git")
                .arg("-C")
                .arg(&dir)
                .args(args)
                .output()
                .unwrap()
                .status
                .success()
        );
    };
    git(&["init", "-q"]);
    git(&["add", "sample.ts"]);
    git(&[
        "-c",
        "user.name=t",
        "-c",
        "user.email=t@t",
        "commit",
        "-q",
        "-m",
        "x",
    ]);
    let cache = dir.join("cache.bin");

    let run = || {
        let out = Command::cargo_bin("cccc")
            .unwrap()
            .args(["--no-config", "--cache-file"])
            .arg(&cache)
            .arg(&dir)
            .assert()
            .success();
        String::from_utf8(out.get_output().stdout.clone()).unwrap()
    };

    let cold = run();
    // Same bytes, new mtime — a fresh checkout. With a clean git index the
    // entry is validated off the index's blob SHA (no re-read), the fresh
    // mtime is persisted, and the following run is back to pure stat hits.
    std::fs::File::options()
        .write(true)
        .open(&src)
        .unwrap()
        .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(10))
        .unwrap();
    assert_eq!(run(), cold, "a git-vouched file must still hit");
    let converged = std::fs::read(&cache).unwrap();
    assert_eq!(run(), cold);
    assert_eq!(
        std::fs::read(&cache).unwrap(),
        converged,
        "once the mtime is persisted, an all-stat-hit run must not rewrite"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

/// End-to-end pin of the git-index path: after an mtime-only change, the run
/// must produce the cold output even when the source file is unreadable.
/// Neither the content-hash fallback nor re-analysis can open the file, so a
/// successful, identical run proves the entry was validated off git's blob
/// SHA alone — i.e. cccc's own blob-SHA computation agrees with git's.
#[cfg(unix)]
#[test]
fn cache_git_index_validates_unreadable_file() {
    use std::os::unix::fs::PermissionsExt;

    let dir = std::env::temp_dir().join("cccc_cache_git_unreadable_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    // git resolves symlinks in --show-toplevel (macOS /tmp); agree with it.
    let dir = dir.canonicalize().unwrap();
    let src = dir.join("sample.ts");
    std::fs::copy("tests/fixtures/sample.ts", &src).unwrap();
    let git = |args: &[&str]| {
        assert!(
            std::process::Command::new("git")
                .arg("-C")
                .arg(&dir)
                .args(args)
                .output()
                .unwrap()
                .status
                .success()
        );
    };
    git(&["init", "-q"]);
    // Making the file unreadable below bumps its ctime, and git compares
    // ctime at one-second granularity: a chmod landing in a later second
    // than the index refresh would make `git status` re-read the file, fail,
    // and report it dirty. Only mode changes are in play here, so ignore ctime.
    git(&["config", "core.trustctime", "false"]);
    git(&["add", "sample.ts"]);
    git(&[
        "-c",
        "user.name=t",
        "-c",
        "user.email=t@t",
        "commit",
        "-q",
        "-m",
        "x",
    ]);
    let cache = dir.join("cache.bin");

    let run = || {
        let out = Command::cargo_bin("cccc")
            .unwrap()
            .args(["--no-config", "--cache-file"])
            .arg(&cache)
            .arg(&dir)
            .assert()
            .success();
        String::from_utf8(out.get_output().stdout.clone()).unwrap()
    };

    let cold = run();
    // The CI shape: mtime moved (into the past — a future mtime trips git's
    // racy-clean re-read), content untouched, index stat-clean.
    std::fs::File::options()
        .write(true)
        .open(&src)
        .unwrap()
        .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(3600))
        .unwrap();
    git(&["update-index", "--refresh"]);
    let perms = std::fs::metadata(&src).unwrap().permissions();
    std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).unwrap();

    assert_eq!(
        run(),
        cold,
        "an unreadable, git-clean file must be served from the cache via the index"
    );

    std::fs::set_permissions(&src, perms).unwrap();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn print_cache_file_reports_the_resolved_path() {
    let dir = std::env::temp_dir().join("cccc_print_cache_file_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cccc.toml"), "cache = true\n").unwrap();

    // Config-enabled cache: the default file next to the config.
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--print-cache-file"])
        .assert()
        .success();
    let printed = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let printed = printed.trim_end();
    assert!(
        std::path::Path::new(printed).is_absolute() && printed.ends_with("/.cccc.cache"),
        "expected an absolute default path, got {printed:?}"
    );

    // An explicit --cache-file wins.
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--print-cache-file", "--cache-file", "elsewhere.bin"])
        .assert()
        .success();
    let printed = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert_eq!(printed.trim_end(), "elsewhere.bin");

    // Disabled (--no-cache, or no config at all): prints nothing.
    for args in [
        vec!["--print-cache-file", "--no-cache"],
        vec!["--print-cache-file", "--no-config"],
    ] {
        Command::cargo_bin("cccc")
            .unwrap()
            .current_dir(&dir)
            .args(&args)
            .assert()
            .success()
            .stdout(predicates::str::is_empty());
    }

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn no_cache_flag_disables_config_enabled_cache() {
    let dir = std::env::temp_dir().join("cccc_no_cache_cli_test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::copy("tests/fixtures/sample.ts", dir.join("sample.ts")).unwrap();
    std::fs::write(dir.join("cccc.toml"), "cache = true\n").unwrap();

    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--no-cache", "."])
        .assert()
        .success();
    assert!(
        !dir.join(".cccc.cache").exists(),
        "--no-cache must not write a cache file"
    );

    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg(".")
        .assert()
        .success();
    assert!(
        dir.join(".cccc.cache").is_file(),
        "config-enabled cache defaults to .cccc.cache beside the config"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

// ----- JSON formatting -------------------------------------------------------

#[test]
fn default_json_is_compact_and_pretty_expands_it() {
    let compact_out = Command::cargo_bin("cccc")
        .unwrap()
        .arg("tests/fixtures/sample.ts")
        .assert()
        .success();
    let compact = String::from_utf8(compact_out.get_output().stdout.clone()).unwrap();
    assert_eq!(compact.trim_end().lines().count(), 1, "one line of JSON");

    let pretty_out = Command::cargo_bin("cccc")
        .unwrap()
        .args(["--pretty", "tests/fixtures/sample.ts"])
        .assert()
        .success();
    let pretty = String::from_utf8(pretty_out.get_output().stdout.clone()).unwrap();
    assert!(pretty.trim_end().lines().count() > 1, "indented JSON");

    let a: serde_json::Value = serde_json::from_str(&compact).expect("valid JSON");
    let b: serde_json::Value = serde_json::from_str(&pretty).expect("valid JSON");
    assert_eq!(a, b, "--pretty must not change the content");
}

// ----- --format / --violations ----------------------------------------------

/// A temp dir with `a.ts` (`outer`: cognitive 1 / cyclomatic 2, holding the
/// nested arrow `inner`: 3 / 3) and `b.ts` (`cold`: 0 / 1).
fn simple_project(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("a.ts"),
        "function outer(a) {\n  const inner = (b) => {\n    if (b) { if (a) { return 1; } }\n    return 0;\n  };\n  if (a) { return inner(a); }\n  return 0;\n}\n",
    )
    .unwrap();
    std::fs::write(dir.join("b.ts"), "function cold() {\n  return 0;\n}\n").unwrap();
    dir
}

fn run_in(dir: &std::path::Path, args: &[&str]) -> assert_cmd::assert::Assert {
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(dir)
        .arg("--no-config")
        .args(args)
        .assert()
}

fn stdout_of(a: &assert_cmd::assert::Assert) -> String {
    String::from_utf8(a.get_output().stdout.clone()).unwrap()
}

#[test]
fn simple_lists_every_function_on_one_line() {
    let dir = simple_project("cccc_simple_all");
    run_in(&dir, &["--format", "simple", "."]).success().stdout(
        "./a.ts:1: outer (function) cognitive 1, cyclomatic 2\n\
         ./a.ts:2: inner (arrow) cognitive 3, cyclomatic 3\n\
         ./b.ts:1: cold (function) cognitive 0, cyclomatic 1\n",
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn simple_with_min_prints_only_selected_functions() {
    let dir = simple_project("cccc_simple_min");
    // `outer` is kept in the tree as `inner`'s ancestor but is below --min.
    run_in(&dir, &["--format", "simple", "--min", "3", "."])
        .success()
        .stdout("./a.ts:2: inner (arrow) cognitive 3, cyclomatic 3\n");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn simple_with_top_prints_the_ranking() {
    let dir = simple_project("cccc_simple_top");
    run_in(&dir, &["--format", "simple", "--top-cognitive", "2", "."])
        .success()
        .stdout(
            "./a.ts:2: inner (arrow) cognitive 3, cyclomatic 3\n\
             ./a.ts:1: outer (function) cognitive 1, cyclomatic 2\n",
        );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn simple_violations_marks_exceeded_metrics() {
    let dir = simple_project("cccc_simple_violations");
    let out = run_in(
        &dir,
        &[
            "--format",
            "simple",
            "--violations",
            "--max-cognitive",
            "0",
            "--max-cyclomatic",
            "2",
            ".",
        ],
    )
    .failure()
    .code(1);
    // Nested functions are flattened in line order; within-limit ones are
    // absent; only the exceeded metric gets `(max N)` (strictly greater).
    assert_eq!(
        stdout_of(&out),
        "./a.ts:1: outer (function) cognitive 1 (max 0), cyclomatic 2\n\
         ./a.ts:2: inner (arrow) cognitive 3 (max 0), cyclomatic 3 (max 2)\n"
    );
    assert_eq!(
        String::from_utf8(out.get_output().stderr.clone()).unwrap(),
        "cccc: 2 functions over the limits in 1 file\n"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn simple_violations_is_silent_when_clean() {
    let dir = simple_project("cccc_simple_violations_clean");
    run_in(
        &dir,
        &[
            "--format",
            "simple",
            "--violations",
            "--max-cognitive",
            "3",
            ".",
        ],
    )
    .success()
    .stdout("")
    .stderr("");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn json_violations_keeps_offenders_and_drops_clean_files() {
    let dir = simple_project("cccc_json_violations");
    let out = run_in(&dir, &["--violations", "--max-cognitive", "2", "."])
        .failure()
        .code(1);
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let files = v["files"].as_array().unwrap();
    assert_eq!(files.len(), 1, "b.ts has no offender");
    // `outer` stays as the parent of the offending `inner`.
    let outer = &files[0]["functions"][0];
    assert_eq!(outer["name"], "outer");
    assert_eq!(outer["children"][0]["name"], "inner");
    // The summary still covers every function.
    assert_eq!(v["summary"]["function_count"], 3);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn json_violations_when_clean_is_an_empty_report() {
    let dir = simple_project("cccc_json_violations_clean");
    let out = run_in(&dir, &["--violations", "--max-cognitive", "3", "."]).success();
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    assert!(v["files"].as_array().unwrap().is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn table_violations_omits_clean_files() {
    let dir = simple_project("cccc_table_violations");
    let out = run_in(
        &dir,
        &[
            "--format",
            "table",
            "--violations",
            "--max-cognitive",
            "2",
            ".",
        ],
    )
    .failure()
    .code(1);
    let stdout = stdout_of(&out);
    assert!(stdout.contains("inner [arrow]"));
    assert!(!stdout.contains("b.ts"));
    assert!(stdout.contains("summary (2 files"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn violations_requires_a_threshold() {
    let dir = simple_project("cccc_violations_no_limit");
    run_in(&dir, &["--violations", "."])
        .failure()
        .code(2)
        .stderr(predicates::str::contains("--max-cognitive"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn violations_rejects_min_and_top() {
    let dir = simple_project("cccc_violations_conflicts");
    for extra in [
        ["--min", "1"],
        ["--top-cognitive", "1"],
        ["--top-cyclomatic", "1"],
    ] {
        let mut args = vec!["--violations", "--max-cognitive", "0"];
        args.extend(extra);
        args.push(".");
        run_in(&dir, &args)
            .failure()
            .code(2)
            .stderr(predicates::str::contains(extra[0]));
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn format_and_table_flags_conflict() {
    let dir = simple_project("cccc_format_table_conflict");
    run_in(&dir, &["--format", "json", "--table", "."])
        .failure()
        .code(2);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn format_table_matches_table_flag() {
    let dir = simple_project("cccc_format_table_alias");
    let a = run_in(&dir, &["--format", "table", "."]).success();
    let b = run_in(&dir, &["--table", "."]).success();
    assert_eq!(a.get_output().stdout, b.get_output().stdout);
    // The deprecated alias still works but says what to use instead.
    assert_eq!(
        String::from_utf8(b.get_output().stderr.clone()).unwrap(),
        "cccc: warning: --table is deprecated; use --format table\n"
    );
    assert!(a.get_output().stderr.is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn config_simple_violations_applies_and_ignores_config_min() {
    let dir = config_project(
        "cccc_cfg_simple_violations",
        "format = \"simple\"\nviolations = true\nmax-cognitive = 5\nmin = 100\n",
    );
    Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg("sample.ts")
        .assert()
        .failure()
        .code(1)
        .stdout("sample.ts:1: sumOfPrimes (function) cognitive 6 (max 5), cyclomatic 4\n");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn config_format_beats_config_table() {
    let dir = config_project(
        "cccc_cfg_format_vs_table",
        "table = true\nformat = \"json\"\n",
    );
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .arg("sample.ts")
        .assert()
        .success();
    serde_json::from_str::<serde_json::Value>(&stdout_of(&out)).expect("valid JSON");
    assert!(
        String::from_utf8(out.get_output().stderr.clone())
            .unwrap()
            .contains("`table` in the config file is deprecated"),
        "the deprecated config key is reported"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn format_json_flag_overrides_config_table() {
    let dir = config_project("cccc_cfg_table_override", "table = true\n");
    let out = Command::cargo_bin("cccc")
        .unwrap()
        .current_dir(&dir)
        .args(["--format", "json", "sample.ts"])
        .assert()
        .success();
    serde_json::from_str::<serde_json::Value>(&stdout_of(&out)).expect("valid JSON");
    let _ = std::fs::remove_dir_all(&dir);
}