rumdl 0.1.51

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

use super::fixtures;

fn setup_test_files() -> tempfile::TempDir {
    let temp_dir = tempfile::tempdir().unwrap();
    fixtures::create_test_files(temp_dir.path(), "basic").unwrap();
    temp_dir
}

fn create_config(dir: &Path, content: &str) {
    fs::write(dir.join(".rumdl.toml"), content).unwrap();
}

#[test]
fn test_cli_include_exclude() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Helper to run command and get stdout/stderr
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(base_path)
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };
    let normalize = |s: &str| s.replace(r"\", "/");

    // Test include via CLI - should only process docs/doc1.md
    println!("--- Running CLI Include Test ---");
    let (success_incl, stdout_incl, _) = run_cmd(&["check", ".", "--include", "docs/doc1.md", "--verbose"]);
    assert!(success_incl, "CLI Include Test failed");
    let norm_stdout_incl = normalize(&stdout_incl);
    assert!(
        norm_stdout_incl.contains("Processing file: docs/doc1.md"),
        "CLI Include: docs/doc1.md missing"
    );
    assert!(
        !norm_stdout_incl.contains("Processing file: README.md"),
        "CLI Include: README.md should be excluded"
    );
    assert!(
        !norm_stdout_incl.contains("Processing file: docs/temp/temp.md"),
        "CLI Include: temp.md should be excluded"
    );

    // Test exclude via CLI - exclude the temp directory
    println!("--- Running CLI Exclude Test ---");
    let (success_excl, stdout_excl, _) = run_cmd(&["check", ".", "--exclude", "docs/temp", "--verbose"]);
    assert!(success_excl, "CLI Exclude Test failed");
    let norm_stdout_excl = normalize(&stdout_excl);
    assert!(
        norm_stdout_excl.contains("Processing file: README.md"),
        "CLI Exclude: README.md missing"
    );
    assert!(
        norm_stdout_excl.contains("Processing file: docs/doc1.md"),
        "CLI Exclude: docs/doc1.md missing"
    );
    assert!(
        norm_stdout_excl.contains("Processing file: src/test.md"),
        "CLI Exclude: src/test.md missing"
    );
    assert!(
        !norm_stdout_excl.contains("Processing file: docs/temp/temp.md"),
        "CLI Exclude: temp.md should be excluded"
    );

    // Test combined include and exclude via CLI - include *.md in docs, exclude temp
    println!("--- Running CLI Include/Exclude Test ---");
    let (success_comb, stdout_comb, _) = run_cmd(&[
        "check",
        ".",
        "--include",
        "docs/*.md",
        "--exclude",
        "docs/temp",
        "--verbose",
    ]);
    assert!(success_comb, "CLI Include/Exclude Test failed");
    let norm_stdout_comb = normalize(&stdout_comb);
    assert!(
        norm_stdout_comb.contains("Processing file: docs/doc1.md"),
        "CLI Combo: docs/doc1.md missing"
    );
    assert!(
        !norm_stdout_comb.contains("Processing file: docs/temp/temp.md"),
        "CLI Combo: temp.md should be excluded"
    );
    assert!(
        !norm_stdout_comb.contains("Processing file: README.md"),
        "CLI Combo: README.md should be excluded"
    );
}

#[test]
fn test_config_include_exclude() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Helper
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(base_path)
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };
    let normalize = |s: &str| s.replace(r"\", "/");

    // Test include via config - only include docs/doc1.md specifically
    println!("--- Running Config Include Test ---");
    let config_incl = r#"
[global]
include = ["docs/doc1.md"]
"#;
    create_config(base_path, config_incl);

    let (success_incl, stdout_incl, _) = run_cmd(&["check", ".", "--verbose"]);
    assert!(success_incl, "Config Include Test failed");
    let norm_stdout_incl = normalize(&stdout_incl);
    assert!(
        norm_stdout_incl.contains("Processing file: docs/doc1.md"),
        "Config Include: docs/doc1.md missing"
    );
    assert!(
        !norm_stdout_incl.contains("Processing file: README.md"),
        "Config Include: README.md should be excluded"
    );
    assert!(
        !norm_stdout_incl.contains("Processing file: docs/temp/temp.md"),
        "Config Include: temp.md should be excluded"
    );

    // Test combined include and exclude via config
    println!("--- Running Config Include/Exclude Test ---");
    let config_comb = r#"
[global]
include = ["docs/**/*.md"] # Include all md in docs recursively
exclude = ["docs/temp"]
"#;
    create_config(base_path, config_comb);

    let (success_comb, stdout_comb, _) = run_cmd(&["check", ".", "--verbose"]);
    assert!(success_comb, "Config Include/Exclude Test failed");
    let norm_stdout_comb = normalize(&stdout_comb);
    assert!(
        norm_stdout_comb.contains("Processing file: docs/doc1.md"),
        "Config Combo: docs/doc1.md missing"
    );
    assert!(
        !norm_stdout_comb.contains("Processing file: docs/temp/temp.md"),
        "Config Combo: temp.md should be excluded"
    );
    assert!(
        !norm_stdout_comb.contains("Processing file: README.md"),
        "Config Combo: README.md should be excluded"
    );
}

#[test]
fn test_cli_override_config() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Helper
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(base_path)
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };
    let normalize = |s: &str| s.replace(r"\", "/");

    // Set up config with one pattern
    let config = r#"
[global]
include = ["src/**/*.md"] # Config includes only src/test.md
"#;
    create_config(base_path, config);

    // Override with CLI pattern - should only process docs/doc1.md
    println!("--- Running CLI Override Config Test ---");
    let (success, stdout, _) = run_cmd(&["check", ".", "--include", "docs/doc1.md", "--verbose"]);
    assert!(success, "CLI Override Config Test failed");
    let norm_stdout = normalize(&stdout);

    assert!(
        norm_stdout.contains("Processing file: docs/doc1.md"),
        "CLI Override: docs/doc1.md missing"
    );
    assert!(
        !norm_stdout.contains("Processing file: src/test.md"),
        "CLI Override: src/test.md should be excluded due to CLI override"
    );
    assert!(
        !norm_stdout.contains("Processing file: README.md"),
        "CLI Override: README.md should be excluded"
    );
}

#[test]
fn test_readme_pattern_scope() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Helper
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(base_path)
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };
    let normalize = |s: &str| s.replace(r"\", "/");

    // Test include pattern for README.md should only match the root README.md file
    println!("--- Running README Pattern Scope Test ---");
    let config = r#"
[global]
include = ["README.md"] # Reverted pattern
"#;
    create_config(base_path, config);

    let (success, stdout, _) = run_cmd(&["check", ".", "--verbose"]);
    assert!(success, "README Pattern Scope Test failed");
    let norm_stdout = normalize(&stdout);

    assert!(
        norm_stdout.contains("Processing file: README.md"),
        "README Scope: Root README.md missing"
    );
    assert!(
        norm_stdout.contains("Processing file: subfolder/README.md"),
        "README Scope: Subfolder README.md ALSO included (known behavior)"
    );
    assert!(
        !norm_stdout.contains("Processing file: docs/doc1.md"),
        "README Scope: docs/doc1.md should be excluded"
    );
}

#[test]
fn test_cli_filter_behavior() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let base_path = temp_dir.path();

    // Create test structure using fixtures
    fixtures::create_test_files(base_path, "basic")?;

    // Helper to run command and get stdout/stderr
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
            .current_dir(temp_dir.path())
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };

    // Normalize paths in output for consistent matching
    let normalize = |s: &str| s.replace(r"\", "/");

    // --- Test Case 1: Exclude directory ---
    println!("--- Running Test Case 1: Exclude directory ---");
    let (success1, stdout1, stderr1) = run_cmd(&["check", ".", "--exclude", "docs/temp", "--verbose"]);
    println!("Test Case 1 Stdout:\\n{stdout1}");
    println!("Test Case 1 Stderr:\\n{stderr1}");
    assert!(success1, "Test Case 1 failed");
    let norm_stdout1 = normalize(&stdout1);
    assert!(
        norm_stdout1.contains("Processing file: README.md"),
        "Expected file README.md missing in Test Case 1"
    );
    assert!(
        norm_stdout1.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 1"
    );
    assert!(
        norm_stdout1.contains("Processing file: src/test.md"),
        "Expected file src/test.md missing in Test Case 1"
    );
    assert!(
        norm_stdout1.contains("Processing file: subfolder/README.md"),
        "Expected file subfolder/README.md missing in Test Case 1"
    );

    // --- Test Case 2: Include specific file ---
    println!("--- Running Test Case 2: Include specific file ---");
    let (success2, stdout2, stderr2) = run_cmd(&["check", ".", "--include", "docs/doc1.md", "--verbose"]);
    println!("Test Case 2 Stdout:\\n{stdout2}");
    println!("Test Case 2 Stderr:\\n{stderr2}");
    assert!(success2, "Test Case 2 failed");
    let norm_stdout2 = normalize(&stdout2);
    assert!(
        norm_stdout2.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 2"
    );
    assert!(
        !norm_stdout2.contains("Processing file: README.md"),
        "File README.md should not be processed in Test Case 2"
    );
    assert!(
        !norm_stdout2.contains("Processing file: docs/temp/temp.md"),
        "File docs/temp/temp.md should not be processed in Test Case 2"
    );
    assert!(
        !norm_stdout2.contains("Processing file: src/test.md"),
        "File src/test.md should not be processed in Test Case 2"
    );
    assert!(
        !norm_stdout2.contains("Processing file: subfolder/README.md"),
        "File subfolder/README.md should not be processed in Test Case 2"
    );

    // --- Test Case 3: Exclude glob pattern (original failing case) ---
    // This should exclude README.md in root AND subfolder/README.md
    println!("--- Running Test Case 3: Exclude glob pattern ---");
    let (success3, stdout3, stderr3) = run_cmd(&["check", ".", "--exclude", "**/README.md", "--verbose"]);
    println!("Test Case 3 Stdout:\\n{stdout3}");
    println!("Test Case 3 Stderr:\\n{stderr3}");
    assert!(success3, "Test Case 3 failed");
    let norm_stdout3 = normalize(&stdout3);
    assert!(
        !norm_stdout3.contains("Processing file: README.md"),
        "Root README.md should be excluded in Test Case 3"
    );
    assert!(
        !norm_stdout3.contains("Processing file: subfolder/README.md"),
        "Subfolder README.md should be excluded in Test Case 3"
    );
    assert!(
        norm_stdout3.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 3"
    );
    assert!(
        norm_stdout3.contains("Processing file: docs/temp/temp.md"),
        "Expected file docs/temp/temp.md missing in Test Case 3"
    );
    assert!(
        norm_stdout3.contains("Processing file: src/test.md"),
        "Expected file src/test.md missing in Test Case 3"
    );

    // --- Test Case 4: Include glob pattern ---
    // Should only include docs/doc1.md (not docs/temp/temp.md)
    println!("--- Running Test Case 4: Include glob pattern ---");
    let (success4, stdout4, stderr4) = run_cmd(&["check", ".", "--include", "docs/*.md", "--verbose"]);
    println!("Test Case 4 Stdout:\\n{stdout4}");
    println!("Test Case 4 Stderr:\\n{stderr4}");
    assert!(success4, "Test Case 4 failed");
    let norm_stdout4 = normalize(&stdout4);
    assert!(
        norm_stdout4.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 4"
    );
    assert!(
        !norm_stdout4.contains("Processing file: docs/temp/temp.md"),
        "File docs/temp/temp.md should not be processed in Test Case 4"
    );
    assert!(
        !norm_stdout4.contains("Processing file: README.md"),
        "File README.md should not be processed in Test Case 4"
    );
    assert!(
        !norm_stdout4.contains("Processing file: src/test.md"),
        "File src/test.md should not be processed in Test Case 4"
    );
    assert!(
        !norm_stdout4.contains("Processing file: subfolder/README.md"),
        "File subfolder/README.md should not be processed in Test Case 4"
    );

    // --- Test Case 5: Glob Include + Specific Exclude ---
    // Should include docs/doc1.md but exclude docs/temp/temp.md
    println!("--- Running Test Case 5: Glob Include + Specific Exclude ---");
    let (success5, stdout5, stderr5) = run_cmd(&[
        "check",
        ".",
        "--include",
        "docs/**/*.md",
        "--exclude",
        "docs/temp/temp.md",
        "--verbose",
    ]);
    println!("Test Case 5 Stdout:\\n{stdout5}");
    println!("Test Case 5 Stderr:\\n{stderr5}");
    assert!(success5, "Test Case 5 failed");
    let norm_stdout5 = normalize(&stdout5);
    assert!(
        norm_stdout5.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 5"
    );
    assert!(
        !norm_stdout5.contains("Processing file: docs/temp/temp.md"),
        "File docs/temp/temp.md should be excluded in Test Case 5"
    );
    assert!(
        !norm_stdout5.contains("Processing file: README.md"),
        "File README.md should not be processed in Test Case 5"
    );
    assert!(
        !norm_stdout5.contains("Processing file: src/test.md"),
        "File src/test.md should not be processed in Test Case 5"
    );
    assert!(
        !norm_stdout5.contains("Processing file: subfolder/README.md"),
        "File subfolder/README.md should not be processed in Test Case 5"
    );

    // --- Test Case 6: Specific Exclude Overrides Broader Include ---
    println!("--- Running Test Case 6: Specific Exclude Overrides Broader Include ---");
    let (success6, stdout6, stderr6) = run_cmd(&[
        "check",
        ".",
        "--include",
        "subfolder/*.md",
        "--exclude",
        "subfolder/README.md",
    ]); // Pass only the args slice
    println!("Test Case 6 Stdout:\n{stdout6}");
    println!("Test Case 6 Stderr:{stderr6}");
    assert!(success6, "Case 6: Command failed"); // Use success6
    assert!(
        stdout6.contains("No markdown files found to check."),
        "Case 6: Should find no files"
    );
    assert!(
        !stdout6.contains("Processing file: subfolder/README.md"),
        "File subfolder/README.md should be excluded in Test Case 6"
    );

    // --- Test Case 7: Root Exclude ---
    println!("--- Running Test Case 7: Root Exclude ---");
    let (success7, stdout7, stderr7) = run_cmd(&["check", ".", "--exclude", "README.md", "--verbose"]); // No globstar
    println!("Test Case 7 Stdout:\\n{stdout7}");
    println!("Test Case 7 Stderr:{stderr7}");
    assert!(success7, "Test Case 7 failed");
    let norm_stdout7 = normalize(&stdout7);
    assert!(
        !norm_stdout7.contains("Processing file: README.md"),
        "Root README.md should be excluded in Test Case 7"
    );
    assert!(
        !norm_stdout7.contains("Processing file: subfolder/README.md"),
        "Subfolder README.md should ALSO be excluded in Test Case 7"
    );
    assert!(
        norm_stdout7.contains("Processing file: docs/doc1.md"),
        "File docs/doc1.md should be included in Test Case 7"
    );

    // --- Test Case 8: Deep Glob Exclude ---
    // Should exclude everything
    println!("--- Running Test Case 8: Deep Glob Exclude ---");
    let (success8, stdout8, stderr8) = run_cmd(&["check", ".", "--exclude", "**/*", "--verbose"]);
    println!("Test Case 8 Stdout:\\n{stdout8}");
    println!("Test Case 8 Stderr:\\n{stderr8}");
    assert!(success8, "Test Case 8 failed");
    let norm_stdout8 = normalize(&stdout8);
    // Check that *none* of the files were processed
    assert!(
        !norm_stdout8.contains("Processing file:"),
        "No files should be processed in Test Case 8"
    );

    // --- Test Case 9: Exclude multiple patterns ---
    println!("--- Running Test Case 9: Exclude multiple patterns ---");
    let (success9, stdout9, stderr9) = run_cmd(&["check", ".", "--exclude", "README.md,src/*", "--verbose"]);
    println!("Test Case 9 Stdout:\n{stdout9}");
    println!("Test Case 9 Stderr:{stderr9}\n");
    assert!(success9, "Test Case 9 failed");
    let norm_stdout9 = normalize(&stdout9);
    assert!(
        !norm_stdout9.contains("Processing file: README.md"),
        "Root README.md should be excluded in Test Case 9"
    );
    assert!(
        !norm_stdout9.contains("Processing file: subfolder/README.md"),
        "Subfolder README.md should be excluded in Test Case 9"
    );
    assert!(
        !norm_stdout9.contains("Processing file: src/test.md"),
        "File src/test.md should be excluded in Test Case 9"
    );
    assert!(
        norm_stdout9.contains("Processing file: docs/doc1.md"),
        "Expected file docs/doc1.md missing in Test Case 9"
    );

    // --- Test Case 10: Include multiple patterns ---
    println!("--- Running Test Case 10: Include multiple patterns ---");
    let (success10, stdout10, stderr10) = run_cmd(&["check", ".", "--include", "README.md,src/*", "--verbose"]);
    println!("Test Case 10 Stdout:\n{stdout10}");
    println!("Test Case 10 Stderr:{stderr10}\n");
    assert!(success10, "Test Case 10 failed");
    let norm_stdout10 = normalize(&stdout10);
    assert!(
        norm_stdout10.contains("Processing file: README.md"),
        "Root README.md should be included in Test Case 10"
    );
    assert!(
        norm_stdout10.contains("Processing file: src/test.md"),
        "File src/test.md should be included in Test Case 10"
    );
    assert!(
        !norm_stdout10.contains("Processing file: docs/doc1.md"),
        "File docs/doc1.md should not be processed in Test Case 10"
    );
    assert!(
        norm_stdout10.contains("Processing file: subfolder/README.md"),
        "File subfolder/README.md SHOULD be processed in Test Case 10"
    );

    // --- Test Case 11: Explicit Path (File) Ignores Config Include ---
    println!("--- Running Test Case 11: Explicit Path (File) Ignores Config Include ---");
    let config11 = r#"[global]
include=["src/*.md"]
"#;
    create_config(temp_dir.path(), config11);
    let (success11, stdout11, _) = run_cmd(&["check", "docs/doc1.md", "--verbose"]);
    assert!(success11, "Test Case 11 failed");
    let norm_stdout11 = normalize(&stdout11);
    assert!(
        norm_stdout11.contains("Processing file: docs/doc1.md"),
        "Explicit path docs/doc1.md should be processed in Test Case 11"
    );
    assert!(
        !norm_stdout11.contains("Processing file: src/test.md"),
        "src/test.md should not be processed in Test Case 11"
    );
    fs::remove_file(temp_dir.path().join(".rumdl.toml"))?; // Clean up config

    // --- Test Case 12: Explicit Path (Dir) Ignores Config Include ---
    println!("--- Running Test Case 12: Explicit Path (Dir) Ignores Config Include ---");
    let config12 = r#"[global]
include=["src/*.md"]
"#;
    create_config(temp_dir.path(), config12);
    let (success12, stdout12, _) = run_cmd(&["check", "docs", "--verbose"]); // Process everything in docs/
    assert!(success12, "Test Case 12 failed");
    let norm_stdout12 = normalize(&stdout12);
    assert!(
        norm_stdout12.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md should be processed in Test Case 12"
    );
    assert!(
        norm_stdout12.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should be processed in Test Case 12"
    );
    assert!(
        !norm_stdout12.contains("Processing file: src/test.md"),
        "src/test.md should not be processed in Test Case 12"
    );
    fs::remove_file(temp_dir.path().join(".rumdl.toml"))?; // Clean up config

    // --- Test Case 13: Explicit Path (Dir) Respects Config Exclude ---
    println!("--- Running Test Case 13: Explicit Path (Dir) Respects Config Exclude ---");
    let config13 = r#"[global]
exclude=["docs/temp"]
"#;
    create_config(temp_dir.path(), config13);
    let (success13, stdout13, _) = run_cmd(&["check", "docs", "--verbose"]); // Process docs/, exclude temp via config
    assert!(success13, "Test Case 13 failed");
    let norm_stdout13 = normalize(&stdout13);
    assert!(
        norm_stdout13.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md should be processed in Test Case 13"
    );
    assert!(
        !norm_stdout13.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should be excluded by config in Test Case 13"
    );
    fs::remove_file(temp_dir.path().join(".rumdl.toml"))?; // Clean up config

    // --- Test Case 14: Explicit Path (Dir) Respects CLI Exclude ---
    println!("--- Running Test Case 14: Explicit Path (Dir) Respects CLI Exclude ---");
    let (success14, stdout14, _) = run_cmd(&["check", "docs", "--exclude", "docs/temp", "--verbose"]); // Process docs/, exclude temp via CLI
    assert!(success14, "Test Case 14 failed");
    let norm_stdout14 = normalize(&stdout14);
    assert!(
        norm_stdout14.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md should be processed in Test Case 14"
    );
    assert!(
        !norm_stdout14.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should be excluded by CLI in Test Case 14"
    );

    // --- Test Case 15: Multiple Explicit Paths ---
    println!("--- Running Test Case 15: Multiple Explicit Paths ---");
    let (success15, stdout15, _) = run_cmd(&["check", "docs/doc1.md", "src/test.md", "--verbose"]); // Process specific files
    assert!(success15, "Test Case 15 failed");
    let norm_stdout15 = normalize(&stdout15);
    assert!(
        norm_stdout15.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md was not processed in Test Case 15"
    );
    assert!(
        norm_stdout15.contains("Processing file: src/test.md"),
        "src/test.md was not processed in Test Case 15"
    );
    assert!(
        !norm_stdout15.contains("Processing file: README.md"),
        "README.md should not be processed in Test Case 15"
    );
    assert!(
        !norm_stdout15.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should not be processed in Test Case 15"
    );

    // --- Test Case 16: CLI Exclude Overrides Config Include (Discovery Mode) ---
    println!("--- Running Test Case 16: CLI Exclude Overrides Config Include ---");
    let config16 = r#"[global]
include=["docs/**/*.md"]
"#;
    create_config(temp_dir.path(), config16);
    let (success16, stdout16, _) = run_cmd(&["check", ".", "--exclude", "docs/temp/temp.md", "--verbose"]); // Discover ., exclude specific file via CLI
    assert!(success16, "Test Case 16 failed");
    let norm_stdout16 = normalize(&stdout16);
    assert!(
        norm_stdout16.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md should be included by config in Test Case 16"
    );
    assert!(
        !norm_stdout16.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should be excluded by CLI in Test Case 16"
    );
    assert!(
        !norm_stdout16.contains("Processing file: README.md"),
        "README.md should not be included by config in Test Case 16"
    );
    fs::remove_file(temp_dir.path().join(".rumdl.toml"))?; // Clean up config

    // --- Test Case 17: Exclude wins over include in discovery mode ---
    // This matches the industry-standard model (ruff, eslint, markdownlint-cli):
    // exclude always takes precedence in discovery mode. To lint an excluded file,
    // pass it explicitly or use --no-exclude.
    println!("--- Running Test Case 17: Exclude Wins Over Include in Discovery Mode ---");
    fs::write(
        temp_dir.path().join(".rumdl.toml"),
        r#"
exclude = ["docs/*"]
"#,
    )?;
    let (success17, stdout17, stderr17) = run_cmd(&["check", ".", "--include", "docs/doc1.md", "--verbose"]);
    println!("Test Case 17 Stdout:\n{stdout17}");
    println!("Test Case 17 Stderr:{stderr17}\n");
    assert!(success17, "Test Case 17 failed");
    let norm_stdout17 = normalize(&stdout17);
    // Exclude takes precedence: docs/doc1.md is excluded despite --include
    assert!(
        !norm_stdout17.contains("Processing file: docs/doc1.md"),
        "docs/doc1.md should be excluded by config in Test Case 17 (exclude wins over include)"
    );
    assert!(
        !norm_stdout17.contains("Processing file: docs/temp/temp.md"),
        "docs/temp/temp.md should be excluded by config in Test Case 17"
    );
    assert!(
        !norm_stdout17.contains("Processing file: README.md"),
        "README.md should NOT be included in Test Case 17"
    );
    assert!(
        !norm_stdout17.contains("Processing file: src/test.md"),
        "src/test.md should NOT be included in Test Case 17"
    );
    assert!(
        !norm_stdout17.contains("Processing file: subfolder/README.md"),
        "subfolder/README.md should NOT be included in Test Case 17"
    );

    Ok(())
}

#[test]
fn test_force_exclude() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempfile::tempdir()?;
    let dir_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Create test files
    fs::create_dir_all(dir_path.join("excluded"))?;
    fs::write(dir_path.join("included.md"), "# Included\n")?;
    fs::write(dir_path.join("excluded.md"), "# Should be excluded\n")?;
    fs::write(dir_path.join("excluded/test.md"), "# In excluded dir\n")?;

    // Helper to run command
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(dir_path)
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };
    let normalize = |s: &str| s.replace(r"\", "/");

    // Create config with exclude pattern
    let config = r#"[global]
exclude = ["excluded.md", "excluded/**"]
"#;
    fs::write(dir_path.join(".rumdl.toml"), config)?;

    // Test 1: Default behavior - explicitly provided files ARE excluded (new behavior as of v0.0.156)
    println!("--- Test 1: Default behavior (always respect excludes) ---");
    let (success1, stdout1, stderr1) = run_cmd(&["check", "excluded.md", "--verbose"]);
    assert!(success1, "Test 1 failed");
    let norm_stdout1 = normalize(&stdout1);
    let norm_stderr1 = normalize(&stderr1);
    assert!(
        norm_stderr1.contains("warning:")
            && norm_stderr1.contains("excluded.md")
            && norm_stderr1.contains("ignored because of exclude pattern"),
        "Default behavior: excluded.md should show warning about exclusion. stderr: {norm_stderr1}"
    );
    assert!(
        !norm_stdout1.contains("Processing file: excluded.md"),
        "Default behavior: excluded.md should NOT be processed"
    );

    // Test 2: included.md should still be processed
    println!("--- Test 2: Non-excluded files are processed ---");
    let (success2, stdout2, _) = run_cmd(&["check", "included.md", "--verbose"]);
    assert!(success2, "Test 2 failed");
    let norm_stdout2 = normalize(&stdout2);
    assert!(
        norm_stdout2.contains("Processing file: included.md"),
        "included.md should be processed"
    );

    // Test 3: Multiple files - only non-excluded are processed
    println!("--- Test 3: Multiple files with excludes ---");
    let (success3, stdout3, stderr3) = run_cmd(&["check", "included.md", "excluded.md", "--verbose"]);
    assert!(success3, "Test 3 failed");
    let norm_stdout3 = normalize(&stdout3);
    let norm_stderr3 = normalize(&stderr3);
    assert!(
        norm_stdout3.contains("Processing file: included.md"),
        "included.md should be processed"
    );
    assert!(
        norm_stderr3.contains("warning:")
            && norm_stderr3.contains("excluded.md")
            && norm_stderr3.contains("ignored because of exclude pattern"),
        "excluded.md should show warning about exclusion"
    );
    assert!(
        !norm_stdout3.contains("Processing file: excluded.md"),
        "excluded.md should NOT be processed"
    );

    // Test 4: Directory patterns work
    println!("--- Test 4: Directory patterns with excludes ---");
    let (success4, stdout4, stderr4) = run_cmd(&["check", "excluded/test.md", "--verbose"]);
    assert!(success4, "Test 4 failed");
    let norm_stdout4 = normalize(&stdout4);
    let norm_stderr4 = normalize(&stderr4);
    assert!(
        norm_stderr4.contains("warning:")
            && norm_stderr4.contains("excluded/test.md")
            && norm_stderr4.contains("ignored because of exclude pattern"),
        "Files in excluded dir should show warning about exclusion"
    );
    assert!(
        !norm_stdout4.contains("Processing file: excluded/test.md"),
        "excluded/test.md should NOT be processed"
    );

    Ok(())
}

#[test]
fn test_default_discovery_includes_only_markdown() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempfile::tempdir()?;
    let dir_path = temp_dir.path();

    // Create a markdown file
    fs::write(dir_path.join("test.md"), "# Valid Markdown\n")?;
    // Create a non-markdown file
    fs::write(dir_path.join("test.txt"), "This is a text file.")?;

    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check")
        .arg(".")
        .arg("--verbose") // Need verbose to see "Processing file:" messages
        .current_dir(dir_path);

    cmd.assert()
        .success() // Should succeed as test.md is valid
        .stdout(predicates::str::contains("Processing file: test.md"))
        .stdout(predicates::str::contains("Processing file: test.txt").not());

    Ok(())
}

#[test]
fn test_markdown_extension_handling() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let dir_path = temp_dir.path();

    // Create files with both extensions
    fs::write(dir_path.join("test.md"), "# MD File\n")?;
    fs::write(dir_path.join("test.markdown"), "# MARKDOWN File\n")?;
    fs::write(dir_path.join("other.txt"), "Text file")?;

    // Test 1: Default discovery should find both .md and .markdown
    let mut cmd1 = cargo_bin_cmd!("rumdl");
    cmd1.arg("check").arg(".").arg("--verbose").current_dir(dir_path);
    cmd1.assert()
        .success()
        .stdout(predicates::str::contains("Processing file: test.md"))
        .stdout(predicates::str::contains("Processing file: test.markdown"))
        .stdout(predicates::str::contains("Processing file: other.txt").not());

    // Test 2: Explicit include for .markdown should only find that file
    let mut cmd2 = cargo_bin_cmd!("rumdl");
    cmd2.arg("check")
        .arg(".")
        .arg("--include")
        .arg("*.markdown")
        .arg("--verbose")
        .current_dir(dir_path);
    cmd2.assert()
        .success()
        .stdout(predicates::str::contains("Processing file: test.markdown"))
        .stdout(predicates::str::contains("Processing file: test.md").not());

    Ok(())
}

#[test]
fn test_type_filter_precedence() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let dir_path = temp_dir.path();

    // Create files
    fs::write(dir_path.join("test.md"), "# MD File\n")?;
    fs::write(dir_path.join("test.txt"), "Text file")?;

    // Test 1: --include allows checking non-markdown files (e.g., .txt)
    let mut cmd1 = cargo_bin_cmd!("rumdl");
    cmd1.arg("check")
        .arg(".")
        .arg("--include")
        .arg("*.txt")
        .arg("--verbose")
        .current_dir(dir_path);
    cmd1.assert()
        .code(1) // Should fail because test.txt has linting issues
        .stdout(predicates::str::contains("Processing file: test.txt"))
        .stdout(predicates::str::contains("MD041")) // First line should be heading
        .stdout(predicates::str::contains("MD047")); // Should end with newline

    // Test 2: Excluding all .md files when only .md files exist
    let mut cmd2 = cargo_bin_cmd!("rumdl");
    cmd2.arg("check")
        .arg(".")
        .arg("--exclude")
        .arg("*.md")
        .arg("--verbose")
        .current_dir(dir_path);
    cmd2.assert()
        .success()
        .stdout(predicates::str::contains("No markdown files found to check."))
        .stdout(predicates::str::contains("Processing file:").not());

    // Test 3: Excluding both markdown types
    fs::write(dir_path.join("test.markdown"), "# MARKDOWN File\n")?;
    let mut cmd3 = cargo_bin_cmd!("rumdl");
    cmd3.arg("check")
        .arg(".")
        .arg("--exclude")
        .arg("*.md,*.markdown")
        .arg("--verbose")
        .current_dir(dir_path);
    cmd3.assert()
        .success()
        .stdout(predicates::str::contains("No markdown files found to check."))
        .stdout(predicates::str::contains("Processing file:").not());

    Ok(())
}

#[test]
fn test_check_subcommand_works() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    let output = std::process::Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "README.md"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    assert!(output.status.success(), "check subcommand failed: {stderr}");
    assert!(
        stdout.contains("Success:") || stdout.contains("Issues:"),
        "Output missing summary"
    );
    assert!(
        !stderr.contains("Deprecation warning"),
        "Should not print deprecation warning for subcommand"
    );
}

#[test]
fn test_legacy_cli_works_and_warns() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that direct file path doesn't work anymore
    let output = std::process::Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["README.md"])
        .output()
        .expect("Failed to execute command");
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    // Should fail and show help because "README.md" is not a valid subcommand
    assert!(!output.status.success(), "legacy CLI should fail");
    assert!(
        stderr.contains("error:") || stderr.contains("Usage:"),
        "Should show error or usage for invalid subcommand"
    );

    // Test that new syntax with 'check' works
    let output = std::process::Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "README.md"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(output.status.success(), "new CLI with check should work");
    assert!(
        stdout.contains("Success:") || stdout.contains("Issues:"),
        "Output missing summary"
    );
}

#[test]
fn test_rule_command_lists_all_rules() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .arg("rule")
        .output()
        .expect("Failed to execute 'rumdl rule'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(output.status.success(), "'rumdl rule' did not exit successfully");
    assert!(stdout.contains("Available rules:"), "Output missing 'Available rules:'");
    assert!(stdout.contains("MD013"), "Output missing rule MD013");
}

#[test]
fn test_rule_command_shows_specific_rule() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "MD013"])
        .output()
        .expect("Failed to execute 'rumdl rule MD013'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(output.status.success(), "'rumdl rule MD013' did not exit successfully");
    assert!(stdout.contains("MD013"), "Output missing rule name MD013");
    // Updated to match new output format
    assert!(
        stdout.contains("Name:") || stdout.contains("Description"),
        "Output missing expected field"
    );
}

#[test]
fn test_rule_command_json_output_all_rules() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule --output-format json'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(
        output.status.success(),
        "'rumdl rule --output-format json' did not exit successfully"
    );

    // Parse the JSON output
    let rules: serde_json::Value = serde_json::from_str(&stdout).expect("Failed to parse JSON output");
    assert!(rules.is_array(), "Expected JSON array");
    let rules_array = rules.as_array().unwrap();
    assert!(!rules_array.is_empty(), "Expected at least one rule");

    // Check structure of first rule
    let first_rule = &rules_array[0];
    assert!(first_rule.get("code").is_some(), "Missing 'code' field");
    assert!(first_rule.get("name").is_some(), "Missing 'name' field");
    assert!(first_rule.get("aliases").is_some(), "Missing 'aliases' field");
    assert!(first_rule.get("summary").is_some(), "Missing 'summary' field");
    assert!(first_rule.get("category").is_some(), "Missing 'category' field");
    assert!(first_rule.get("fix").is_some(), "Missing 'fix' field");
    assert!(
        first_rule.get("fix_availability").is_some(),
        "Missing 'fix_availability' field"
    );
    assert!(first_rule.get("url").is_some(), "Missing 'url' field");

    // Verify MD001 is present
    let md001 = rules_array
        .iter()
        .find(|r| r.get("code").and_then(|c| c.as_str()) == Some("MD001"));
    assert!(md001.is_some(), "MD001 not found in rules");
    let md001 = md001.unwrap();
    assert_eq!(md001.get("name").and_then(|n| n.as_str()), Some("heading-increment"));
    assert_eq!(md001.get("category").and_then(|c| c.as_str()), Some("heading"));
    assert!(
        md001.get("url").and_then(|u| u.as_str()).unwrap().contains("rumdl.dev"),
        "URL should contain rumdl.dev"
    );
}

#[test]
fn test_rule_command_json_output_single_rule() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "MD041", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule MD041 --output-format json'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(
        output.status.success(),
        "'rumdl rule MD041 --output-format json' did not exit successfully"
    );

    // Parse the JSON output (single object, not array)
    let rule: serde_json::Value = serde_json::from_str(&stdout).expect("Failed to parse JSON output");
    assert!(rule.is_object(), "Expected JSON object for single rule");

    assert_eq!(rule.get("code").and_then(|c| c.as_str()), Some("MD041"));
    assert_eq!(rule.get("name").and_then(|n| n.as_str()), Some("first-line-h1"));
    // MD041 has "first-line-heading" as an alias
    let aliases = rule.get("aliases").and_then(|a| a.as_array()).unwrap();
    assert!(aliases.iter().any(|a| a.as_str() == Some("first-line-heading")));
    assert_eq!(
        rule.get("url").and_then(|u| u.as_str()),
        Some("https://rumdl.dev/md041/")
    );
}

#[test]
fn test_rule_command_json_fix_availability_values() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule --output-format json'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rules: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    // Verify fix_availability values are one of the expected values
    for rule in &rules {
        let fix_avail = rule.get("fix_availability").and_then(|f| f.as_str()).unwrap();
        assert!(
            matches!(fix_avail, "Always" | "Sometimes" | "None"),
            "Unexpected fix_availability value: {} for rule {}",
            fix_avail,
            rule.get("code").and_then(|c| c.as_str()).unwrap_or("unknown")
        );
    }

    // Verify at least one unfixable rule exists (MD033 - no-inline-html)
    let md033 = rules
        .iter()
        .find(|r| r.get("code").and_then(|c| c.as_str()) == Some("MD033"));
    assert!(md033.is_some(), "MD033 not found");
    assert_eq!(
        md033.unwrap().get("fix_availability").and_then(|f| f.as_str()),
        Some("None")
    );
}

#[test]
fn test_rule_command_fixable_filter() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--fixable", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule --fixable'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rules: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    // All returned rules should be fixable (Always or Sometimes)
    for rule in &rules {
        let fix_avail = rule.get("fix_availability").and_then(|f| f.as_str()).unwrap();
        assert!(
            matches!(fix_avail, "Always" | "Sometimes"),
            "Non-fixable rule {} returned with --fixable filter",
            rule.get("code").and_then(|c| c.as_str()).unwrap_or("unknown")
        );
    }

    // Should not include MD033 (no-inline-html) which has fix_availability = None
    let has_md033 = rules
        .iter()
        .any(|r| r.get("code").and_then(|c| c.as_str()) == Some("MD033"));
    assert!(!has_md033, "MD033 should not be included with --fixable filter");
}

#[test]
fn test_rule_command_category_filter() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--category", "heading", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule --category heading'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rules: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    assert!(!rules.is_empty(), "Should return at least one heading rule");

    // All returned rules should have category "heading"
    for rule in &rules {
        let category = rule.get("category").and_then(|c| c.as_str()).unwrap();
        assert_eq!(
            category,
            "heading",
            "Rule {} has category {} instead of heading",
            rule.get("code").and_then(|c| c.as_str()).unwrap_or("unknown"),
            category
        );
    }

    // Should include MD001 (heading-increment)
    let has_md001 = rules
        .iter()
        .any(|r| r.get("code").and_then(|c| c.as_str()) == Some("MD001"));
    assert!(has_md001, "MD001 should be included with --category heading");
}

#[test]
fn test_rule_command_combined_filters() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--fixable", "--category", "heading", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule --fixable --category heading'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rules: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    assert!(!rules.is_empty(), "Should return at least one fixable heading rule");

    // All returned rules should be fixable AND have category heading
    for rule in &rules {
        let fix_avail = rule.get("fix_availability").and_then(|f| f.as_str()).unwrap();
        let category = rule.get("category").and_then(|c| c.as_str()).unwrap();

        assert!(
            matches!(fix_avail, "Always" | "Sometimes"),
            "Rule {} should be fixable",
            rule.get("code").and_then(|c| c.as_str()).unwrap_or("unknown")
        );
        assert_eq!(
            category,
            "heading",
            "Rule {} should have category heading",
            rule.get("code").and_then(|c| c.as_str()).unwrap_or("unknown")
        );
    }
}

#[test]
fn test_rule_command_json_lines_format() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--output-format", "json-lines"])
        .output()
        .expect("Failed to execute 'rumdl rule --output-format json-lines'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Each line should be valid JSON
    let lines: Vec<&str> = stdout.lines().collect();
    assert!(!lines.is_empty(), "Should output at least one line");

    for (i, line) in lines.iter().enumerate() {
        let rule: serde_json::Value =
            serde_json::from_str(line).unwrap_or_else(|e| panic!("Line {i} is not valid JSON: {e}"));
        assert!(rule.get("code").is_some(), "Line {i} missing 'code' field");
        assert!(rule.get("name").is_some(), "Line {i} missing 'name' field");
    }

    // First line should be MD001
    let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(
        first.get("code").and_then(|c| c.as_str()),
        Some("MD001"),
        "First line should be MD001"
    );
}

#[test]
fn test_rule_command_explain_flag() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "MD001", "--output-format", "json", "--explain"])
        .output()
        .expect("Failed to execute 'rumdl rule MD001 --explain'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rule: serde_json::Value = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    // Should have explanation field
    let explanation = rule.get("explanation").and_then(|e| e.as_str());
    assert!(explanation.is_some(), "Should have explanation field with --explain");
    assert!(
        explanation.unwrap().contains("heading"),
        "Explanation should contain 'heading'"
    );

    // Without --explain, should not have explanation field
    let output_no_explain = Command::new(rumdl_exe)
        .args(["rule", "MD001", "--output-format", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule MD001'");
    let stdout_no_explain = String::from_utf8_lossy(&output_no_explain.stdout).to_string();
    let rule_no_explain: serde_json::Value = serde_json::from_str(&stdout_no_explain).expect("Failed to parse JSON");

    assert!(
        rule_no_explain.get("explanation").is_none(),
        "Should not have explanation field without --explain"
    );
}

#[test]
fn test_rule_command_text_output_with_filters() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--fixable", "--category", "heading"])
        .output()
        .expect("Failed to execute 'rumdl rule --fixable --category heading'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should show filter info in header
    assert!(stdout.contains("fixable"), "Output should mention fixable filter");
    assert!(stdout.contains("heading"), "Output should mention category filter");

    // Should show total count
    assert!(stdout.contains("Total:"), "Output should show total count");

    // Should include MD001
    assert!(stdout.contains("MD001"), "Should include MD001 in output");
}

#[test]
fn test_rule_command_list_categories() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--list-categories"])
        .output()
        .expect("Failed to execute 'rumdl rule --list-categories'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(output.status.success(), "Should exit successfully");
    assert!(stdout.contains("Available categories:"), "Should show header");
    assert!(stdout.contains("heading"), "Should list heading category");
    assert!(stdout.contains("whitespace"), "Should list whitespace category");
    assert!(stdout.contains("rules)"), "Should show rule counts");
}

#[test]
fn test_rule_command_invalid_category_error() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .args(["rule", "--category", "nonexistent"])
        .output()
        .expect("Failed to execute 'rumdl rule --category nonexistent'");
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    assert!(!output.status.success(), "Should exit with error");
    assert!(stderr.contains("Invalid category"), "Should mention invalid category");
    assert!(stderr.contains("Valid categories:"), "Should list valid categories");
    assert!(stderr.contains("heading"), "Should show heading as valid option");
}

#[test]
fn test_rule_command_short_flags() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test -f (fixable) and -c (category) short flags
    let output = Command::new(rumdl_exe)
        .args(["rule", "-f", "-c", "heading", "-o", "json"])
        .output()
        .expect("Failed to execute 'rumdl rule -f -c heading -o json'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let rules: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("Failed to parse JSON");

    assert!(!rules.is_empty(), "Should return at least one rule");

    // All rules should be fixable and in heading category
    for rule in &rules {
        let fix_avail = rule.get("fix_availability").and_then(|f| f.as_str()).unwrap();
        let category = rule.get("category").and_then(|c| c.as_str()).unwrap();

        assert!(matches!(fix_avail, "Always" | "Sometimes"), "Rule should be fixable");
        assert_eq!(category, "heading", "Rule should be in heading category");
    }
}

#[test]
fn test_config_command_lists_options() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .arg("config")
        .output()
        .expect("Failed to execute 'rumdl config'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(output.status.success(), "'rumdl config' did not exit successfully");
    assert!(stdout.contains("[global]"), "Output missing [global] section");
    assert!(
        stdout.contains("enable =") || stdout.contains("disable =") || stdout.contains("exclude ="),
        "Output missing expected config keys"
    );
}

#[test]
fn test_version_command_prints_version() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let output = Command::new(rumdl_exe)
        .arg("version")
        .output()
        .expect("Failed to execute 'rumdl version'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    assert!(output.status.success(), "'rumdl version' did not exit successfully");
    assert!(stdout.contains("rumdl"), "Output missing 'rumdl' in version output");
    assert!(stdout.contains("."), "Output missing version number");
}

#[test]
fn test_config_get_subcommand() {
    use std::fs;
    use std::process::Command;
    use tempfile::tempdir;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
exclude = ["docs/temp", "node_modules"]

[MD013]
line_length = 123
"#;
    fs::write(&config_path, config_content).unwrap();

    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");
    let run_cmd = |args: &[&str]| -> (bool, String, String) {
        let output = Command::new(rumdl_exe)
            .current_dir(temp_dir.path())
            .args(args)
            .output()
            .expect("Failed to execute command");
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        (output.status.success(), stdout, stderr)
    };

    // Test global.exclude
    let (success, stdout, stderr) = run_cmd(&["config", "get", "global.exclude"]);
    assert!(success, "config get global.exclude should succeed, stderr: {stderr}");
    assert!(
        stdout.contains("global.exclude = [\"docs/temp\", \"node_modules\"] [from project config]"),
        "Unexpected output: {stdout}. Stderr: {stderr}"
    );

    // Test MD013.line_length
    let (success, stdout, stderr) = run_cmd(&["config", "get", "MD013.line_length"]);
    assert!(success, "config get MD013.line_length should succeed, stderr: {stderr}");
    assert!(
        stdout.contains("MD013.line-length = 123 [from project config]"),
        "Unexpected output: {stdout}. Stderr: {stderr}"
    );

    // Test unknown key
    let (success, _stdout, stderr) = run_cmd(&["config", "get", "global.unknown"]);
    assert!(!success, "config get global.unknown should fail");
    assert!(
        stderr.contains("Unknown global key: unknown"),
        "Unexpected stderr: {stderr}"
    );

    let (success, _stdout, stderr) = run_cmd(&["config", "get", "MD999.line_length"]);
    assert!(!success, "config get MD999.line_length should fail");
    assert!(
        stderr.contains("Unknown config key: MD999.line-length"),
        "Unexpected stderr: {stderr}"
    );

    let (success, _stdout, stderr) = run_cmd(&["config", "get", "notavalidkey"]);
    assert!(!success, "config get notavalidkey should fail");
    assert!(
        stderr.contains("Key must be in the form global.key or MDxxx.key"),
        "Unexpected stderr: {stderr}"
    );
}

#[test]
fn test_config_command_defaults_prints_only_defaults() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Write a .rumdl.toml with non-defaults to ensure it is ignored
    let config_content = r#"
[global]
enable = ["MD013"]
exclude = ["docs/temp"]
"#;
    create_config(base_path, config_content);

    // Run 'rumdl config --defaults' (should ignore .rumdl.toml)
    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["config", "--defaults"])
        .output()
        .expect("Failed to execute 'rumdl config --defaults'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    assert!(
        output.status.success(),
        "'rumdl config --defaults' did not exit successfully: {stderr}"
    );
    // [global] should be at the top
    assert!(
        stdout.trim_start().starts_with("[global]"),
        "Output should start with [global], got: {}",
        &stdout[..stdout.find('\n').unwrap_or(stdout.len())]
    );
    // Should contain provenance annotation [from default]
    assert!(
        stdout.contains("[from default]"),
        "Output should contain provenance annotation [from default]"
    );
    // Should not mention .rumdl.toml
    assert!(!stdout.contains(".rumdl.toml"), "Output should not mention .rumdl.toml");
    // Should contain a known default (e.g., enable = [])
    assert!(
        stdout.contains("enable = ["),
        "Output should contain default enable = []"
    );
    // Should NOT contain the custom value from .rumdl.toml
    assert!(
        !stdout.contains("enable = [\"MD013\"]"),
        "Output should not contain custom config values from .rumdl.toml"
    );
    // Output is NOT valid TOML (annotated), so do not parse as TOML
}

#[test]
fn test_config_command_defaults_output_toml_is_valid() {
    use toml::Value;
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Write a .rumdl.toml with non-defaults to ensure it is ignored
    let config_content = r#"
[global]
enable = ["MD013"]
exclude = ["docs/temp"]
"#;
    create_config(base_path, config_content);

    // Run 'rumdl config --defaults --output toml' (should ignore .rumdl.toml)
    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["config", "--defaults", "--output", "toml"])
        .output()
        .expect("Failed to execute 'rumdl config --defaults --output toml'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    assert!(
        output.status.success(),
        "'rumdl config --defaults --output toml' did not exit successfully: {stderr}"
    );
    // [global] should be at the top
    assert!(
        stdout.trim_start().starts_with("[global]"),
        "Output should start with [global], got: {}",
        &stdout[..stdout.find('\n').unwrap_or(stdout.len())]
    );
    // Should NOT contain provenance annotation [from default]
    assert!(
        !stdout.contains("[from default]"),
        "Output should NOT contain provenance annotation [from default] in TOML output"
    );
    // Should not mention .rumdl.toml
    assert!(!stdout.contains(".rumdl.toml"), "Output should not mention .rumdl.toml");
    // Should contain a known default (e.g., enable = [])
    assert!(
        stdout.contains("enable = ["),
        "Output should contain default enable = []"
    );
    // Should NOT contain the custom value from .rumdl.toml
    assert!(
        !stdout.contains("enable = [\"MD013\"]"),
        "Output should not contain custom config values from .rumdl.toml"
    );
    // Output should be valid TOML (parse all [section] blocks)
    let mut current = String::new();
    for line in stdout.lines() {
        if line.starts_with('[') && !current.is_empty() {
            toml::from_str::<Value>(&current).expect("Section is not valid TOML");
            current.clear();
        }
        current.push_str(line);
        current.push('\n');
    }
    if !current.trim().is_empty() {
        toml::from_str::<Value>(&current).expect("Section is not valid TOML");
    }
}

#[test]
fn test_config_command_defaults_provenance_annotation_colored() {
    let temp_dir = setup_test_files();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Write a .rumdl.toml with non-defaults to ensure it is ignored
    let config_content = r#"
[global]
enable = ["MD013"]
exclude = ["docs/temp"]
"#;
    create_config(base_path, config_content);

    // Run 'rumdl config --defaults --color always'
    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["config", "--defaults", "--color", "always"])
        .output()
        .expect("Failed to execute 'rumdl config --defaults --color always'");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    assert!(
        output.status.success(),
        "'rumdl config --defaults --color always' did not exit successfully: {stderr}"
    );
    // Should contain provenance annotation [from default]
    assert!(
        stdout.contains("[from default]"),
        "Output should contain provenance annotation [from default]"
    );
    // Should contain ANSI color codes for provenance annotation (e.g., dim/gray: \x1b[2m...\x1b[0m)
    let provenance_colored = "\x1b[2m[from default]\x1b[0m";
    assert!(
        stdout.contains(provenance_colored),
        "Provenance annotation [from default] should be colored dim/gray (found: {stdout:?})"
    );
}

#[test]
fn test_stdin_formatting() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test case 1: Format markdown with trailing spaces
    let input = "# Test   \n\nTest paragraph   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin").arg("--fix").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Fixed content should be on stdout
    // Note: MD009 removes all trailing spaces from headings, but preserves 2 spaces
    // for line breaks in regular text (br_spaces: 2)
    // Note: Output will have a trailing newline even if input doesn't
    assert_eq!(stdout, "# Test\n\nTest paragraph\n");
    // No errors should be on stderr in quiet mode
    assert_eq!(stderr, "");
    assert!(output.status.success());
}

#[test]
fn test_stdin_formatting_with_remaining_issues() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test case with fixable issues (trailing spaces) and unfixable issues (duplicate heading)
    let input = "# Test   \n## Test\n# Test";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin").arg("--fix");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Fixed content should be on stdout
    // Note: MD009 removes all trailing spaces from headings
    // MD001 and MD003 add blank lines around headings
    // Note: Output will have a trailing newline even if input doesn't
    assert_eq!(stdout, "# Test\n\n## Test\n\n## Test\n");
    // Stderr should show [fixed] labels for fixed issues in text mode
    assert!(
        stderr.contains("[fixed]"),
        "Stdin text fix mode must show [fixed] labels on stderr. stderr: {stderr}"
    );
    // Should report remaining issues on stderr
    assert!(stderr.contains("MD024"));
    assert!(stderr.contains("remaining"));
    // Should exit with error due to remaining issues
    assert!(!output.status.success());
}

#[test]
fn test_stdin_fix_with_json_output_format() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Stdin with fixable (MD009 trailing spaces) and unfixable (MD024 duplicate heading) issues
    let input = "# Test   \n## Test\n# Test";
    let mut cmd = Command::new(rumdl_exe);
    cmd.args(["check", "--stdin", "--fix", "--output-format", "json"]);
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Fixed content on stdout (not JSON — stdout is the fixed document)
    assert!(!stdout.is_empty(), "Fixed content should appear on stdout");
    assert!(
        !stdout.starts_with('['),
        "Stdout should be fixed markdown, not JSON. Got: {stdout}"
    );

    // Remaining warnings on stderr should be valid JSON array
    // Parse just the JSON portion (ignore the summary line)
    let json_part = stderr
        .lines()
        .take_while(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join("\n");
    if !json_part.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&json_part);
        assert!(
            parsed.is_ok(),
            "Remaining warnings on stderr should be valid JSON. Got: {stderr}"
        );
        let arr = parsed.unwrap();
        assert!(arr.is_array(), "JSON output should be an array");
        // Only remaining (unfixable) warnings should appear
        let warnings = arr.as_array().unwrap();
        for w in warnings {
            let rule = w["rule"].as_str().unwrap_or("");
            assert_ne!(
                rule, "MD009",
                "Fixed rule MD009 should not appear in remaining JSON output"
            );
        }
    }

    // Should exit with error due to remaining issues
    assert!(!output.status.success());
}

#[test]
fn test_stdin_check_without_fix() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that check mode without --fix reports issues but doesn't output fixed content
    let input = "# Test   \n\nTest   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should not output content to stdout in check mode
    assert_eq!(stdout, "");
    // Should report issues on stderr
    assert!(stderr.contains("MD009"));
    assert!(stderr.contains("trailing spaces"));
    // MD047 is also triggered since input doesn't end with newline
    assert!(stderr.contains("Found 3 issue(s)"));
    // Should exit with error due to issues
    assert!(!output.status.success());
}

#[test]
fn test_stdin_formatting_no_issues() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that formatting mode outputs the original content when there are no issues
    // This was a bug where it would output "No issues found in stdin" instead
    let input = "# Clean Markdown\n\nThis markdown has no issues.\n";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("fmt").arg("-").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should output the original content unchanged
    assert_eq!(stdout, input, "fmt should output original content when no issues found");
    // No errors should be on stderr in quiet mode
    assert_eq!(stderr, "");
    assert!(output.status.success());
}

#[test]
fn test_stdin_dash_syntax() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that '-' works as stdin indicator
    let input = "# Test   \n\nTest   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("-");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should not output content to stdout in check mode
    assert_eq!(stdout, "");
    // Should report issues on stderr
    assert!(stderr.contains("MD009"));
    assert!(stderr.contains("trailing spaces"));
    assert!(stderr.contains("Found 3 issue(s)"));
}

#[test]
fn test_stdin_filename_flag() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that --stdin-filename changes the displayed filename in error messages
    let input = "# Test   \n\nTest paragraph   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("-").arg("--stdin-filename").arg("test-file.md");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should not output content to stdout in check mode
    assert_eq!(stdout, "");
    // Should show the custom filename in error messages
    assert!(
        stderr.contains("test-file.md:1:"),
        "Error message should contain custom filename"
    );
    assert!(
        stderr.contains("test-file.md:3:"),
        "Error message should contain custom filename for line 3"
    );
    assert!(stderr.contains("in test-file.md"), "Summary should use custom filename");
    // Should still detect the issues
    assert!(stderr.contains("MD009"));
}

#[test]
fn test_stdin_filename_in_fmt_mode() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that --stdin-filename also works in fmt mode
    let input = "# Clean Markdown\n\nNo issues here.\n";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("fmt")
        .arg("-")
        .arg("--stdin-filename")
        .arg("custom-file.md")
        .arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // In fmt mode with no issues, should output the original content
    assert_eq!(stdout, input, "Should output original content");
    // No errors should be on stderr in quiet mode
    assert_eq!(stderr, "");
    assert!(output.status.success());
}

#[test]
fn test_fmt_dash_syntax() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that 'fmt -' works for formatting
    let input = "# Test   \n\nTest   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("fmt").arg("-");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should output formatted content
    assert_eq!(stdout, "# Test\n\nTest\n");
    // Should exit successfully
    assert!(output.status.success());
}

#[test]
fn test_fmt_command() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test that fmt command works as an alias for check --fix
    let input = "# Test   \n\nTest paragraph   ";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("fmt").arg("--stdin").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    // Write input to stdin
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should output formatted content to stdout (same as check --fix)
    assert_eq!(stdout, "# Test\n\nTest paragraph\n");
    // No errors in quiet mode
    assert_eq!(stderr, "");
    assert!(output.status.success());
}

#[test]
fn test_fmt_vs_check_fix_exit_codes() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Test content with an unfixable violation (MD041 - first line heading)
    // and fixable violations (missing blank line before heading - MD022)
    let input = "Some text\n# Title\n";

    // Test 1: fmt should exit 0 even if unfixable violations remain
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("fmt").arg("-").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn fmt command");
    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for fmt command");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should output formatted content (blank line added before heading)
    assert_eq!(stdout, "Some text\n\n# Title\n");
    // fmt should exit 0 even though MD041 violation remains
    assert!(output.status.success(), "fmt should exit 0 on successful formatting");

    // Test 2: check --fix should exit 1 if unfixable violations remain
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--fix").arg("-").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn check --fix command");
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child
        .wait_with_output()
        .expect("Failed to wait for check --fix command");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should output formatted content (same as fmt)
    assert_eq!(stdout, "Some text\n\n# Title\n");
    // check --fix should exit 1 because MD041 violation remains
    assert!(
        !output.status.success(),
        "check --fix should exit 1 when unfixable violations remain"
    );
    assert_eq!(output.status.code(), Some(1), "check --fix should exit with code 1");
}

/// Test that --include allows checking files with non-standard extensions (issue #127)
#[test]
fn test_include_nonstandard_extensions() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let dir_path = temp_dir.path();

    // Create files with both standard and non-standard extensions
    fs::write(
        dir_path.join("template.md.jinja"),
        "# Template\n\nThis is a Jinja2 template.\n",
    )?;
    fs::write(
        dir_path.join("regular.md"),
        "# Regular\n\nThis is a regular markdown file.\n",
    )?;
    fs::write(dir_path.join("config.yml.j2"), "# Not markdown\n\nThis is YAML.\n")?;

    // Test 1: Default behavior should only find regular.md
    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check").arg(".").arg("--verbose").current_dir(dir_path);

    cmd.assert()
        .success()
        .stdout(predicates::str::contains("Processing file: regular.md"))
        .stdout(predicates::str::contains("template.md.jinja").not())
        .stdout(predicates::str::contains("config.yml.j2").not());

    // Test 2: --include with *.md.jinja should find template.md.jinja
    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check")
        .arg(".")
        .arg("--include")
        .arg("**/*.md.jinja")
        .arg("--verbose")
        .current_dir(dir_path);

    cmd.assert()
        .success()
        .stdout(predicates::str::contains("Processing file: template.md.jinja"));

    // Test 3: --include should still respect patterns (not find yml.j2)
    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check")
        .arg(".")
        .arg("--include")
        .arg("**/*.md.jinja")
        .arg("--verbose")
        .current_dir(dir_path);

    cmd.assert()
        .success()
        .stdout(predicates::str::contains("config.yml.j2").not());

    Ok(())
}

/// Test that explicit file paths work with non-standard extensions (issue #127)
#[test]
fn test_explicit_path_nonstandard_extensions() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let dir_path = temp_dir.path();

    // Create a file with non-standard extension
    let jinja_file = dir_path.join("template.md.jinja");
    fs::write(&jinja_file, "# Jinja Template\n\nThis should be checked.\n")?;

    // Test: Explicitly providing the file path should work
    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check").arg(&jinja_file).arg("--verbose");

    cmd.assert()
        .success()
        .stdout(predicates::str::contains("Processing file:"))
        .stdout(predicates::str::contains("template.md.jinja"));

    Ok(())
}

/// Test that --include works with multiple non-standard extensions
#[test]
fn test_include_multiple_nonstandard_extensions() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = tempdir()?;
    let dir_path = temp_dir.path();

    // Create files with various extensions
    fs::write(dir_path.join("template.md.jinja"), "# Jinja\n")?;
    fs::write(dir_path.join("readme.md.tmpl"), "# Template\n")?;
    fs::write(dir_path.join("doc.md.erb"), "# ERB\n")?;
    fs::write(dir_path.join("regular.md"), "# Regular\n")?;

    // Test: Include multiple non-standard extensions
    let mut cmd = cargo_bin_cmd!("rumdl");
    cmd.arg("check")
        .arg(".")
        .arg("--include")
        .arg("**/*.md.jinja,**/*.md.tmpl,**/*.md.erb")
        .arg("--verbose")
        .current_dir(dir_path);

    let output = cmd.output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should find all three non-standard extension files
    assert!(stdout.contains("template.md.jinja"), "Should find .md.jinja file");
    assert!(stdout.contains("readme.md.tmpl"), "Should find .md.tmpl file");
    assert!(stdout.contains("doc.md.erb"), "Should find .md.erb file");
    // Should NOT find regular.md (not in include pattern)
    assert!(
        !stdout.contains("regular.md"),
        "Should not find regular.md when using specific --include"
    );

    Ok(())
}

// Tests for Issue #197: Exit code behavior with --fix
// These tests verify that rumdl check --fix returns the correct exit code
mod issue197_exit_code {
    use std::fs;
    use std::process::Command;
    use tempfile::tempdir;

    #[test]
    fn test_exit_code_after_all_fixes() {
        let temp_dir = tempdir().unwrap();
        let test_file = temp_dir.path().join("test.md");

        // Create a file with a fixable issue (MD007 - list indentation)
        // This will be fixed by --fix
        fs::write(
            &test_file,
            "# Heading\n\n- list item\n    - nested item (4 spaces, should be 2)\n",
        )
        .unwrap();

        // Create config to set MD007 indent to 2
        let config_file = temp_dir.path().join(".rumdl.toml");
        fs::write(&config_file, "[MD007]\nindent = 2\n").unwrap();

        // Run rumdl check --fix
        let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
            .arg("check")
            .arg("--fix")
            .arg(test_file.to_str().unwrap())
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to execute rumdl");

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(-1);

        // Verify the fix was applied
        assert!(
            stdout.contains("[fixed]") || stdout.contains("Fixed:"),
            "Should show that issues were fixed. stdout: {stdout}\nstderr: {stderr}"
        );

        // Verify exit code is 0 when all issues are fixed
        assert_eq!(
            exit_code, 0,
            "Exit code should be 0 when all issues are fixed. stdout: {stdout}\nstderr: {stderr}\nexit_code: {exit_code}"
        );

        // Verify the message shows all issues were fixed
        assert!(
            stdout.contains("Fixed:") && (stdout.contains("Fixed 1/1") || stdout.contains("Fixed: 1/1")),
            "Should show 'Fixed: Fixed 1/1 issues' message. stdout: {stdout}"
        );
    }

    #[test]
    fn test_exit_code_with_remaining_issues() {
        let temp_dir = tempdir().unwrap();
        let test_file = temp_dir.path().join("test.md");

        // Create a file with both fixable and unfixable issues
        // MD007 (fixable) and MD041 (unfixable - first line must be heading)
        fs::write(
            &test_file,
            "This is not a heading (MD041 violation - unfixable)\n\n- list item\n    - nested item (MD007 violation - fixable)\n",
        )
        .unwrap();

        // Create config to set MD007 indent to 2
        let config_file = temp_dir.path().join(".rumdl.toml");
        fs::write(&config_file, "[MD007]\nindent = 2\n").unwrap();

        // Run rumdl check --fix
        let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
            .arg("check")
            .arg("--fix")
            .arg(test_file.to_str().unwrap())
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to execute rumdl");

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(-1);

        // Verify exit code is 1 when some issues remain (unfixable)
        assert_eq!(
            exit_code, 1,
            "Exit code should be 1 when unfixable issues remain. stdout: {stdout}\nstderr: {stderr}\nexit_code: {exit_code}"
        );
    }

    /// Test that verifies the fix implementation re-lints after applying fixes.
    ///
    /// This addresses a concern raised by @martimlobao on issue #197:
    /// If --fix creates NEW issues while fixing existing ones (e.g., MD005/MD007 conflict),
    /// the exit code should still be 1.
    ///
    /// The implementation in file_processor.rs:668-740 handles this by:
    /// 1. Applying all fixes to the content
    /// 2. Re-linting the fixed content with all rules
    /// 3. Returning exit code based on remaining_warnings (which includes ANY issues, new or old)
    ///
    /// This test verifies that behavior by checking that:
    /// - The fix is applied (issue count decreases)
    /// - But exit code is 1 if ANY issues remain after fixing
    #[test]
    fn test_relint_after_fix_catches_remaining_issues() {
        let temp_dir = tempdir().unwrap();
        let test_file = temp_dir.path().join("test.md");

        // Create a file where:
        // - MD007 will fix the indentation
        // - But MD041 (first line not heading) remains unfixable
        // This verifies the re-lint catches issues that weren't part of the original fix
        fs::write(&test_file, "Not a heading\n\n- item\n    - nested\n").unwrap();

        let config_file = temp_dir.path().join(".rumdl.toml");
        fs::write(&config_file, "[MD007]\nindent = 2\n").unwrap();

        // First, verify the file has multiple issues
        let check_output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
            .arg("check")
            .arg(test_file.to_str().unwrap())
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to execute rumdl");

        let check_stdout = String::from_utf8_lossy(&check_output.stdout);
        assert!(
            check_stdout.contains("MD007") && check_stdout.contains("MD041"),
            "File should have both MD007 and MD041 issues. stdout: {check_stdout}"
        );

        // Now run --fix
        let fix_output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
            .arg("check")
            .arg("--fix")
            .arg(test_file.to_str().unwrap())
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to execute rumdl");

        let fix_stdout = String::from_utf8_lossy(&fix_output.stdout);
        let fix_stderr = String::from_utf8_lossy(&fix_output.stderr);
        let exit_code = fix_output.status.code().unwrap_or(-1);

        // MD007 should be shown with [fixed] label (it was fixed)
        assert!(
            fix_stdout.contains("MD007"),
            "MD007 should appear in output. stdout: {fix_stdout}"
        );
        if let Some(md007_line) = fix_stdout.lines().find(|l| l.contains("MD007")) {
            assert!(
                md007_line.contains("[fixed]"),
                "MD007 should have [fixed] label. line: {md007_line}"
            );
        }
        // MD041 should remain without [fixed] (unfixable)
        assert!(
            fix_stdout.contains("MD041"),
            "MD041 should remain in output (unfixable). stdout: {fix_stdout}"
        );
        if let Some(md041_line) = fix_stdout.lines().find(|l| l.contains("MD041")) {
            assert!(
                !md041_line.contains("[fixed]"),
                "MD041 should NOT have [fixed] label. line: {md041_line}"
            );
        }

        // Verify exit code is 1 because MD041 still remains
        // This proves the implementation re-lints after fixing and catches remaining issues
        assert_eq!(
            exit_code, 1,
            "Exit code should be 1 when issues remain after fix (re-lint catches them). \
             stdout: {fix_stdout}\nstderr: {fix_stderr}"
        );

        // Verify the content was actually modified (fix was applied)
        let fixed_content = fs::read_to_string(&test_file).unwrap();
        assert!(
            fixed_content.contains("  - nested"),
            "Content should be fixed (2 spaces). Got: {fixed_content}"
        );
    }
}

/// Test that `rumdl fmt` correctly reports the number of files that were actually fixed
/// (GitHub issue #347: summary underreported changed files)
///
/// This test verifies that when all issues in a file are fixed (leaving no remaining issues),
/// the file is still counted in the "Fixed X issues in Y files" summary.
#[test]
fn test_fmt_files_fixed_count_reports_actual_modified_files() {
    let temp_dir = tempdir().unwrap();

    // Create file A with fixable issues (no space after # in heading)
    let file_a = temp_dir.path().join("file_a.md");
    fs::write(
        &file_a,
        r#"# Heading A

#Bad heading A1

#Bad heading A2
"#,
    )
    .unwrap();

    // Create file B with fixable issues
    let file_b = temp_dir.path().join("file_b.md");
    fs::write(
        &file_b,
        r#"# Heading B

#Bad heading B1
"#,
    )
    .unwrap();

    // Create file C with NO issues (clean file)
    let file_c = temp_dir.path().join("file_c.md");
    fs::write(
        &file_c,
        r#"# Clean file

This file has no issues.
"#,
    )
    .unwrap();

    // Create file D with fixable issues
    let file_d = temp_dir.path().join("file_d.md");
    fs::write(
        &file_d,
        r#"# Heading D

#Bad heading D1

#Bad heading D2

#Bad heading D3
"#,
    )
    .unwrap();

    // Run rumdl fmt
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["fmt", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // The summary should report 3 files fixed (A, B, D), NOT 0 or 4
    // Before the fix, it would show "in 0 files" because no remaining issues
    assert!(
        stdout.contains("in 3 files") || stdout.contains("in 3 file"),
        "Summary should report 3 files fixed (not 0 or 4). Got:\n{stdout}"
    );

    // Verify files were actually modified
    let content_a = fs::read_to_string(&file_a).unwrap();
    assert!(
        content_a.contains("## Bad heading A1"),
        "File A should be modified. Got:\n{content_a}"
    );

    let content_c = fs::read_to_string(&file_c).unwrap();
    assert!(
        content_c.contains("# Clean file"),
        "File C should not be modified. Got:\n{content_c}"
    );
}

/// Test that files_fixed count is correct when some files have unfixable issues
#[test]
fn test_fmt_files_fixed_count_with_unfixable_issues() {
    let temp_dir = tempdir().unwrap();

    // Create file A with fixable issues only
    let file_a = temp_dir.path().join("file_a.md");
    fs::write(
        &file_a,
        r#"# Heading A

#Bad heading A1
"#,
    )
    .unwrap();

    // Create file B with unfixable issue (MD041 - first line should be heading)
    let file_b = temp_dir.path().join("file_b.md");
    fs::write(
        &file_b,
        r#"This file starts with text, not a heading.

# Later heading
"#,
    )
    .unwrap();

    // Create file C with NO issues
    let file_c = temp_dir.path().join("file_c.md");
    fs::write(
        &file_c,
        r#"# Clean file

This file has no issues.
"#,
    )
    .unwrap();

    // Run rumdl fmt
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["fmt", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Only file A should be counted as fixed (file B has unfixable issues)
    assert!(
        stdout.contains("in 1 file"),
        "Summary should report 1 file fixed (only file_a). Got:\n{stdout}"
    );

    // Verify file A was modified
    let content_a = fs::read_to_string(&file_a).unwrap();
    assert!(
        content_a.contains("## Bad heading A1"),
        "File A should be modified. Got:\n{content_a}"
    );
}

/// Test that files_fixed is 0 when no files are actually modified
#[test]
fn test_fmt_files_fixed_count_zero_when_no_changes() {
    let temp_dir = tempdir().unwrap();

    // Create clean files only
    let file_a = temp_dir.path().join("file_a.md");
    fs::write(
        &file_a,
        r#"# Clean file A

This file has no issues.
"#,
    )
    .unwrap();

    let file_b = temp_dir.path().join("file_b.md");
    fs::write(
        &file_b,
        r#"# Clean file B

This file also has no issues.
"#,
    )
    .unwrap();

    // Run rumdl fmt
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["fmt", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should show success with no issues found
    assert!(
        stdout.contains("No issues found") || stdout.contains("Success"),
        "Summary should indicate no issues found. Got:\n{stdout}"
    );
}

/// Test that MD033 warnings are NOT counted as fixable (issue #349)
/// MD033 has LSP-only fixes (for VS Code quick actions) but declares FixCapability::Unfixable
#[test]
fn test_md033_not_counted_as_fixable() {
    let temp_dir = tempdir().unwrap();

    // Create file with MD033 violation (inline HTML)
    let file = temp_dir.path().join("test.md");
    fs::write(
        &file,
        r#"# Test

This has <b>inline HTML</b> which triggers MD033.
"#,
    )
    .unwrap();

    // Run rumdl check - should report issue but NOT as fixable
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["check", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should find MD033 issue
    assert!(
        stdout.contains("MD033") || stderr.contains("MD033"),
        "Should detect MD033 violation. Got stdout:\n{stdout}\nstderr:\n{stderr}"
    );

    // Should NOT show fixable count (MD033 is not CLI-fixable)
    assert!(
        !stdout.contains("fixable"),
        "MD033 should NOT be counted as fixable. Got:\n{stdout}"
    );

    // Run rumdl fmt - should report 0 fixes
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["fmt", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should NOT report any fixes
    assert!(!stdout.contains("Fixed"), "MD033 should NOT be fixed. Got:\n{stdout}");

    // File content should be unchanged
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("<b>inline HTML</b>"),
        "File should not be modified. Got:\n{content}"
    );
}

/// Test that capability-based fix counting works correctly with mixed rule types
/// Tests that only truly CLI-fixable rules are counted as fixable
#[test]
fn test_capability_based_fixable_count() {
    let temp_dir = tempdir().unwrap();

    // Create file with both fixable (MD018) and unfixable (MD033) issues
    let file = temp_dir.path().join("test.md");
    fs::write(
        &file,
        r#"#Missing space after hash

This has <b>inline HTML</b> which triggers MD033.
"#,
    )
    .unwrap();

    // Run rumdl check
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["check", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should detect both issues
    assert!(
        stdout.contains("MD018") || stdout.contains("no-missing-space-atx"),
        "Should detect MD018 violation. Got:\n{stdout}"
    );
    assert!(
        stdout.contains("MD033") || stdout.contains("no-inline-html"),
        "Should detect MD033 violation. Got:\n{stdout}"
    );

    // Should show 1 fixable (MD018 only, not MD033)
    // Output format: "Run `rumdl fmt` to automatically fix 1 of the 2 issues"
    assert!(
        stdout.contains("fix 1 of the 2 issues") || stdout.contains("1 fixable"),
        "Should report 1 fixable issue (MD018 only). Got:\n{stdout}"
    );

    // Run rumdl fmt
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["fmt", "--no-cache", "."])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should report 1 fix (MD018 only)
    // Output format: "Fixed 1/2 issues in 1 file"
    assert!(
        stdout.contains("Fixed 1/2 issues") || stdout.contains("Fixed 1 issue"),
        "Should report 1 issue fixed. Got:\n{stdout}"
    );

    // Verify MD018 was fixed but HTML remains
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("# Missing space"),
        "MD018 should be fixed. Got:\n{content}"
    );
    assert!(
        content.contains("<b>inline HTML</b>"),
        "HTML should remain unchanged. Got:\n{content}"
    );
}

// =============================================================================
// Shell completions tests
// =============================================================================

#[test]
fn test_completions_list_shells() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "--list"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(stdout.contains("bash"), "Should list bash");
    assert!(stdout.contains("zsh"), "Should list zsh");
    assert!(stdout.contains("fish"), "Should list fish");
    assert!(stdout.contains("powershell"), "Should list powershell");
    assert!(stdout.contains("elvish"), "Should list elvish");
}

#[test]
fn test_completions_bash_generates_script() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "bash"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(stdout.contains("_rumdl()"), "Should generate bash completion function");
    assert!(stdout.contains("COMPREPLY"), "Should use COMPREPLY for completions");
}

#[test]
fn test_completions_zsh_generates_script() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "zsh"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(stdout.contains("#compdef rumdl"), "Should have zsh compdef directive");
    assert!(stdout.contains("_rumdl()"), "Should generate zsh completion function");
}

#[test]
fn test_completions_fish_generates_script() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "fish"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(
        stdout.contains("complete -c rumdl"),
        "Should generate fish complete commands"
    );
}

#[test]
fn test_completions_powershell_generates_script() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "powershell"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(
        stdout.contains("Register-ArgumentCompleter"),
        "Should register argument completer"
    );
}

#[test]
fn test_completions_elvish_generates_script() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "elvish"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed");
    assert!(
        stdout.contains("set edit:completion:arg-completer[rumdl]"),
        "Should set elvish completion handler"
    );
}

#[test]
fn test_completions_auto_detect_from_shell_env() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions"])
        .env("SHELL", "/bin/bash")
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed with SHELL=bash");
    assert!(
        stdout.contains("_rumdl()"),
        "Should auto-detect bash and generate bash completions"
    );
}

#[test]
fn test_completions_unknown_shell_error() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions"])
        .env("SHELL", "/bin/unknown")
        .output()
        .expect("Failed to execute rumdl");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success(), "Command should fail with unknown shell");
    assert!(
        stderr.contains("Could not detect shell"),
        "Should show helpful error message"
    );
    assert!(
        stderr.contains("rumdl completions bash"),
        "Should suggest explicit shell argument"
    );
}

#[test]
fn test_completions_short_list_flag() {
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "-l"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Command should succeed with -l flag");
    assert!(stdout.contains("bash"), "Should list shells with short flag");
}

#[test]
fn test_completions_clean_piping_stdout_only_has_script() {
    // Verify stdout contains only the script (no extra output)
    // This ensures `eval "$(rumdl completions zsh)"` works cleanly
    let output = Command::new(env!("CARGO_BIN_EXE_rumdl"))
        .args(["completions", "zsh"])
        .output()
        .expect("Failed to execute rumdl");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // stdout should have the script only
    assert!(
        stdout.contains("#compdef rumdl"),
        "stdout should contain the zsh script"
    );
    assert!(
        !stdout.contains("Installation"),
        "stdout should NOT contain installation instructions"
    );

    // stderr should be empty (no noise for eval usage)
    assert!(stderr.is_empty(), "stderr should be empty for clean eval usage");
}

#[test]
fn test_stdin_inline_disable_suppresses_warnings() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Input with trailing spaces that would trigger MD009, but a rumdl-disable
    // comment disables the rule for the entire document.
    let input = "# Heading\n\n<!-- rumdl-disable MD009 -->\n\nTrailing spaces   \nMore trailing   \n";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        !stderr.contains("MD009"),
        "MD009 should be suppressed by inline disable directive, but got: {stderr}"
    );
}

#[test]
fn test_stdin_inline_disable_next_line_is_scoped() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // disable-next-line suppresses only the immediately following line.
    // Line 4 is suppressed; line 5 still fires.
    let input =
        "# Heading\n\n<!-- rumdl-disable-next-line MD009 -->\nSuppressed trailing   \nUnsuppressed trailing   \n";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stderr = String::from_utf8_lossy(&output.stderr);

    let md009_warnings: Vec<&str> = stderr.lines().filter(|l| l.contains("MD009")).collect();

    assert_eq!(
        md009_warnings.len(),
        1,
        "Expected exactly 1 MD009 warning (line 5 only), got {}: {stderr}",
        md009_warnings.len()
    );
    assert!(
        md009_warnings[0].contains(":5:"),
        "MD009 warning should be for line 5, but got: {}",
        md009_warnings[0]
    );
}

#[test]
fn test_stdin_inline_markdownlint_disable_compat() {
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // rumdl supports markdownlint-disable syntax for compatibility.
    // Verify it suppresses warnings when linting via stdin.
    let input = "# Heading\n\n<!-- markdownlint-disable MD009 -->\n\nTrailing spaces   \n";
    let mut cmd = Command::new(rumdl_exe);
    cmd.arg("check").arg("--stdin").arg("--quiet");
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("Failed to spawn command");

    use std::io::Write;
    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
    drop(stdin);

    let output = child.wait_with_output().expect("Failed to wait for command");
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        !stderr.contains("MD009"),
        "MD009 should be suppressed by markdownlint-disable directive, but got: {stderr}"
    );
}

// ─── Config include discovers non-markdown files ────────────────

#[test]
fn test_config_include_discovers_rs_files() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Create a .rs file with doc comments
    fs::write(
        base_path.join("lib.rs"),
        "/// # Example\n///\n/// Clean doc comment.\npub fn example() {}\n",
    )
    .unwrap();

    // Create a .md file
    fs::write(base_path.join("test.md"), "# Test\n\nSome text.\n").unwrap();

    // Create config that includes both .md and .rs files
    fs::write(
        base_path.join(".rumdl.toml"),
        "[global]\ninclude = [\"**/*.md\", \"**/*.rs\"]\n",
    )
    .unwrap();

    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "--no-cache", ".", "--verbose"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(
        stdout.contains("Processing file: lib.rs"),
        "Config include should discover .rs files, stdout: {stdout}"
    );
    assert!(
        stdout.contains("Processing file: test.md"),
        "Config include should still discover .md files, stdout: {stdout}"
    );
    assert!(stdout.contains("2 file"), "Should process 2 files, stdout: {stdout}");
}

#[test]
fn test_config_include_directory_pattern_does_not_discover_non_lintable_files() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Create a docs directory with mixed file types
    fs::create_dir_all(base_path.join("docs")).unwrap();
    fs::write(base_path.join("docs/guide.md"), "# Guide\n\nSome text.\n").unwrap();
    fs::write(base_path.join("docs/script.py"), "print('hello')\n").unwrap();
    fs::write(base_path.join("docs/image.png"), [0u8; 8]).unwrap();

    // Config with directory pattern (no explicit extension)
    fs::write(base_path.join(".rumdl.toml"), "[global]\ninclude = [\"docs/**\"]\n").unwrap();

    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "--no-cache", ".", "--verbose"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(
        stdout.contains("Processing file: docs/guide.md") || stdout.contains("1 file"),
        "Should discover markdown file in docs/, stdout: {stdout}"
    );
    assert!(
        !stdout.contains("script.py"),
        "Should NOT discover .py files, stdout: {stdout}"
    );
    assert!(
        !stdout.contains("image.png"),
        "Should NOT discover .png files, stdout: {stdout}"
    );
}

#[test]
fn test_config_include_with_rs_and_directory_pattern() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Create files in a src directory
    fs::create_dir_all(base_path.join("src")).unwrap();
    fs::write(
        base_path.join("src/lib.rs"),
        "/// # Example\n///\n/// Clean doc.\npub fn example() {}\n",
    )
    .unwrap();
    fs::write(base_path.join("src/notes.md"), "# Notes\n\nSome notes.\n").unwrap();
    fs::write(base_path.join("src/data.json"), "{}\n").unwrap();

    // Config that includes both .md and .rs explicitly
    fs::write(
        base_path.join(".rumdl.toml"),
        "[global]\ninclude = [\"**/*.md\", \"**/*.rs\"]\n",
    )
    .unwrap();

    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "--no-cache", ".", "--verbose"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(stdout.contains("lib.rs"), "Should discover .rs files, stdout: {stdout}");
    assert!(
        stdout.contains("notes.md"),
        "Should discover .md files, stdout: {stdout}"
    );
    assert!(
        !stdout.contains("data.json"),
        "Should NOT discover .json files, stdout: {stdout}"
    );
    assert!(
        stdout.contains("2 file"),
        "Should process exactly 2 files, stdout: {stdout}"
    );
}

#[test]
fn test_default_discovery_does_not_include_rs_files() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();
    let rumdl_exe = env!("CARGO_BIN_EXE_rumdl");

    // Create a .rs file
    fs::write(base_path.join("lib.rs"), "/// Some doc.\npub fn example() {}\n").unwrap();

    // Create a .md file
    fs::write(base_path.join("test.md"), "# Test\n\nSome text.\n").unwrap();

    // No config — default behavior should only find .md files
    let output = Command::new(rumdl_exe)
        .current_dir(base_path)
        .args(["check", "--no-cache", ".", "--verbose"])
        .output()
        .expect("Failed to execute command");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    assert!(
        !stdout.contains("Processing file: lib.rs"),
        "Default discovery should NOT include .rs files, stdout: {stdout}"
    );
    assert!(
        stdout.contains("Processing file: test.md"),
        "Default discovery should include .md files, stdout: {stdout}"
    );
    assert!(
        stdout.contains("1 file"),
        "Should process only 1 file, stdout: {stdout}"
    );
}