rumdl 0.1.88

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
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
use super::*;
use std::fs;
use tempfile::tempdir;

#[test]
fn test_flavor_loading() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
flavor = "mkdocs"
disable = ["MD001"]
"#;
    fs::write(&config_path, config_content).unwrap();

    // Load the config
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Check that flavor was loaded
    assert_eq!(config.global.flavor, MarkdownFlavor::MkDocs);
    assert!(config.is_mkdocs_flavor());
    assert!(config.is_mkdocs_project()); // Test backwards compatibility
    assert_eq!(config.global.disable, vec!["MD001".to_string()]);
}

#[test]
fn test_pyproject_toml_root_level_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");

    // Create a test pyproject.toml with root-level configuration
    let content = r#"
[tool.rumdl]
line-length = 120
disable = ["MD033"]
enable = ["MD001", "MD004"]
include = ["docs/*.md"]
exclude = ["node_modules"]
respect-gitignore = true
        "#;

    fs::write(&config_path, content).unwrap();

    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into(); // Convert to plain config for assertions

    // Check global settings
    assert_eq!(config.global.disable, vec!["MD033".to_string()]);
    assert_eq!(config.global.enable, vec!["MD001".to_string(), "MD004".to_string()]);
    // Should now contain only the configured pattern since auto-discovery is disabled
    assert_eq!(config.global.include, vec!["docs/*.md".to_string()]);
    assert_eq!(config.global.exclude, vec!["node_modules".to_string()]);
    assert!(config.global.respect_gitignore);

    // Check line-length was correctly added to MD013
    let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(line_length, Some(120));
}

#[test]
fn test_pyproject_toml_snake_case_and_kebab_case() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");

    // Test with both kebab-case and snake_case variants
    let content = r#"
[tool.rumdl]
line-length = 150
respect_gitignore = true
        "#;

    fs::write(&config_path, content).unwrap();

    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into(); // Convert to plain config for assertions

    // Check settings were correctly loaded
    assert!(config.global.respect_gitignore);
    let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(line_length, Some(150));
}

#[test]
fn test_md013_key_normalization_in_rumdl_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[MD013]
line_length = 111
line-length = 222
"#;
    fs::write(&config_path, config_content).unwrap();
    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
    // Now we should only get the explicitly configured key
    let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
    assert_eq!(keys, vec!["line-length"]);
    let val = &rule_cfg.values["line-length"].value;
    assert_eq!(val.as_integer(), Some(222));
    // get_rule_config_value should retrieve the value for both snake_case and kebab-case
    let config: Config = sourced.clone().into_validated_unchecked().into();
    let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
    let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(v1, Some(222));
    assert_eq!(v2, Some(222));
}

#[test]
fn test_md013_section_case_insensitivity() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[md013]
line-length = 101

[Md013]
line-length = 102

[MD013]
line-length = 103
"#;
    fs::write(&config_path, config_content).unwrap();
    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.clone().into_validated_unchecked().into();
    // Only the last section should win, and be present
    let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
    let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
    assert_eq!(keys, vec!["line-length"]);
    let val = &rule_cfg.values["line-length"].value;
    assert_eq!(val.as_integer(), Some(103));
    let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(v, Some(103));
}

#[test]
fn test_md013_key_snake_and_kebab_case() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[MD013]
line_length = 201
line-length = 202
"#;
    fs::write(&config_path, config_content).unwrap();
    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.clone().into_validated_unchecked().into();
    let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
    let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
    assert_eq!(keys, vec!["line-length"]);
    let val = &rule_cfg.values["line-length"].value;
    assert_eq!(val.as_integer(), Some(202));
    let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
    let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(v1, Some(202));
    assert_eq!(v2, Some(202));
}

#[test]
fn test_unknown_rule_section_is_ignored() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[MD999]
foo = 1
bar = 2
[MD013]
line-length = 303
"#;
    fs::write(&config_path, config_content).unwrap();
    // Load the config with skip_auto_discovery to avoid environment config files
    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.clone().into_validated_unchecked().into();
    // MD999 should not be present
    assert!(!sourced.rules.contains_key("MD999"));
    // MD013 should be present and correct
    let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(v, Some(303));
}

#[test]
fn test_invalid_toml_syntax() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // Invalid TOML with unclosed string
    let config_content = r#"
[MD013]
line-length = "unclosed string
"#;
    fs::write(&config_path, config_content).unwrap();

    let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
    assert!(result.is_err());
    match result.unwrap_err() {
        ConfigError::ParseError(msg) => {
            // The actual error message from toml parser might vary
            assert!(msg.contains("expected") || msg.contains("invalid") || msg.contains("unterminated"));
        }
        _ => panic!("Expected ParseError"),
    }
}

#[test]
fn test_wrong_type_for_config_value() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // line-length should be a number, not a string
    let config_content = r#"
[MD013]
line-length = "not a number"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // The value should be loaded as a string, not converted
    let rule_config = config.rules.get("MD013").unwrap();
    let value = rule_config.values.get("line-length").unwrap();
    assert!(matches!(value, toml::Value::String(_)));
}

#[test]
fn test_empty_config_file() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // Empty file
    fs::write(&config_path, "").unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Should have default values
    assert_eq!(config.global.line_length.get(), 80);
    assert!(config.global.respect_gitignore);
    assert!(config.rules.is_empty());
}

#[test]
fn test_malformed_pyproject_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");

    // Missing closing bracket
    let content = r#"
[tool.rumdl
line-length = 120
"#;
    fs::write(&config_path, content).unwrap();

    let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
    assert!(result.is_err());
}

#[test]
fn test_conflicting_config_values() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // Both enable and disable the same rule - these need to be in a global section
    let config_content = r#"
[global]
enable = ["MD013"]
disable = ["MD013"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Conflict resolution: enable wins over disable
    assert!(config.global.enable.contains(&"MD013".to_string()));
    assert!(!config.global.disable.contains(&"MD013".to_string()));
}

#[test]
fn test_invalid_rule_names() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let config_content = r#"
[global]
enable = ["MD001", "NOT_A_RULE", "md002", "12345"]
disable = ["MD-001", "MD_002"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // All values should be preserved as-is
    assert_eq!(config.global.enable.len(), 4);
    assert_eq!(config.global.disable.len(), 2);
}

#[test]
fn test_deeply_nested_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // This should be ignored as we don't support nested tables within rule configs
    let config_content = r#"
[MD013]
line-length = 100
[MD013.nested]
value = 42
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    let rule_config = config.rules.get("MD013").unwrap();
    assert_eq!(
        rule_config.values.get("line-length").unwrap(),
        &toml::Value::Integer(100)
    );
    // Nested table should not be present
    assert!(!rule_config.values.contains_key("nested"));
}

#[test]
fn test_unicode_in_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let config_content = r#"
[global]
include = ["文档/*.md", "ドキュメント/*.md"]
exclude = ["测试/*", "🚀/*"]

[MD013]
line-length = 80
message = "行太长了 🚨"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.include.len(), 2);
    assert_eq!(config.global.exclude.len(), 2);
    assert!(config.global.include[0].contains("文档"));
    assert!(config.global.exclude[1].contains("🚀"));

    let rule_config = config.rules.get("MD013").unwrap();
    let message = rule_config.values.get("message").unwrap();
    if let toml::Value::String(s) = message {
        assert!(s.contains("行太长了"));
        assert!(s.contains("🚨"));
    }
}

#[test]
fn test_extremely_long_values() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let long_string = "a".repeat(10000);
    let config_content = format!(
        r#"
[global]
exclude = ["{long_string}"]

[MD013]
line-length = 999999999
"#
    );

    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.exclude[0].len(), 10000);
    let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(line_length, Some(999999999));
}

#[test]
fn test_config_with_comments() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let config_content = r#"
[global]
# This is a comment
enable = ["MD001"] # Enable MD001
# disable = ["MD002"] # This is commented out

[MD013] # Line length rule
line-length = 100 # Set to 100 characters
# ignored = true # This setting is commented out
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.enable, vec!["MD001"]);
    assert!(config.global.disable.is_empty()); // Commented out

    let rule_config = config.rules.get("MD013").unwrap();
    assert_eq!(rule_config.values.len(), 1); // Only line-length
    assert!(!rule_config.values.contains_key("ignored"));
}

#[test]
fn test_arrays_in_rule_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let config_content = r#"
[MD003]
levels = [1, 2, 3]
tags = ["important", "critical"]
mixed = [1, "two", true]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Arrays should now be properly parsed
    let rule_config = config.rules.get("MD003").expect("MD003 config should exist");

    // Check that arrays are present and correctly parsed
    assert!(rule_config.values.contains_key("levels"));
    assert!(rule_config.values.contains_key("tags"));
    assert!(rule_config.values.contains_key("mixed"));

    // Verify array contents
    if let Some(toml::Value::Array(levels)) = rule_config.values.get("levels") {
        assert_eq!(levels.len(), 3);
        assert_eq!(levels[0], toml::Value::Integer(1));
        assert_eq!(levels[1], toml::Value::Integer(2));
        assert_eq!(levels[2], toml::Value::Integer(3));
    } else {
        panic!("levels should be an array");
    }

    if let Some(toml::Value::Array(tags)) = rule_config.values.get("tags") {
        assert_eq!(tags.len(), 2);
        assert_eq!(tags[0], toml::Value::String("important".to_string()));
        assert_eq!(tags[1], toml::Value::String("critical".to_string()));
    } else {
        panic!("tags should be an array");
    }

    if let Some(toml::Value::Array(mixed)) = rule_config.values.get("mixed") {
        assert_eq!(mixed.len(), 3);
        assert_eq!(mixed[0], toml::Value::Integer(1));
        assert_eq!(mixed[1], toml::Value::String("two".to_string()));
        assert_eq!(mixed[2], toml::Value::Boolean(true));
    } else {
        panic!("mixed should be an array");
    }
}

#[test]
fn test_normalize_key_edge_cases() {
    // Rule names
    assert_eq!(normalize_key("MD001"), "MD001");
    assert_eq!(normalize_key("md001"), "MD001");
    assert_eq!(normalize_key("Md001"), "MD001");
    assert_eq!(normalize_key("mD001"), "MD001");

    // Non-rule names
    assert_eq!(normalize_key("line_length"), "line-length");
    assert_eq!(normalize_key("line-length"), "line-length");
    assert_eq!(normalize_key("LINE_LENGTH"), "line-length");
    assert_eq!(normalize_key("respect_gitignore"), "respect-gitignore");

    // Edge cases
    assert_eq!(normalize_key("MD"), "md"); // Too short to be a rule
    assert_eq!(normalize_key("MD00"), "md00"); // Too short
    assert_eq!(normalize_key("MD0001"), "md0001"); // Too long
    assert_eq!(normalize_key("MDabc"), "mdabc"); // Non-digit
    assert_eq!(normalize_key("MD00a"), "md00a"); // Partial digit
    assert_eq!(normalize_key(""), "");
    assert_eq!(normalize_key("_"), "-");
    assert_eq!(normalize_key("___"), "---");
}

#[test]
fn test_missing_config_file() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("nonexistent.toml");

    let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
    assert!(result.is_err());
    match result.unwrap_err() {
        ConfigError::IoError { .. } => {}
        _ => panic!("Expected IoError for missing file"),
    }
}

#[test]
#[cfg(unix)]
fn test_permission_denied_config() {
    use std::os::unix::fs::PermissionsExt;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    fs::write(&config_path, "enable = [\"MD001\"]").unwrap();

    // Remove read permissions
    let mut perms = fs::metadata(&config_path).unwrap().permissions();
    perms.set_mode(0o000);
    fs::set_permissions(&config_path, perms).unwrap();

    let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);

    // Restore permissions for cleanup
    let mut perms = fs::metadata(&config_path).unwrap().permissions();
    perms.set_mode(0o644);
    fs::set_permissions(&config_path, perms).unwrap();

    assert!(result.is_err());
    match result.unwrap_err() {
        ConfigError::IoError { .. } => {}
        _ => panic!("Expected IoError for permission denied"),
    }
}

#[test]
fn test_circular_reference_detection() {
    // This test is more conceptual since TOML doesn't support circular references
    // But we test that deeply nested structures don't cause stack overflow
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let mut config_content = String::from("[MD001]\n");
    for i in 0..100 {
        config_content.push_str(&format!("key{i} = {i}\n"));
    }

    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    let rule_config = config.rules.get("MD001").unwrap();
    assert_eq!(rule_config.values.len(), 100);
}

#[test]
fn test_special_toml_values() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    let config_content = r#"
[MD001]
infinity = inf
neg_infinity = -inf
not_a_number = nan
datetime = 1979-05-27T07:32:00Z
local_date = 1979-05-27
local_time = 07:32:00
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Some values might not be parsed due to parser limitations
    if let Some(rule_config) = config.rules.get("MD001") {
        // Check special float values if present
        if let Some(toml::Value::Float(f)) = rule_config.values.get("infinity") {
            assert!(f.is_infinite() && f.is_sign_positive());
        }
        if let Some(toml::Value::Float(f)) = rule_config.values.get("neg_infinity") {
            assert!(f.is_infinite() && f.is_sign_negative());
        }
        if let Some(toml::Value::Float(f)) = rule_config.values.get("not_a_number") {
            assert!(f.is_nan());
        }

        // Check datetime values if present
        if let Some(val) = rule_config.values.get("datetime") {
            assert!(matches!(val, toml::Value::Datetime(_)));
        }
        // Note: local_date and local_time might not be parsed by the current implementation
    }
}

#[test]
fn test_default_config_passes_validation() {
    use crate::rules;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_path_str = config_path.to_str().unwrap();

    // Create the default config using the same function that `rumdl init` uses
    create_default_config(config_path_str).unwrap();

    // Load it back as a SourcedConfig
    let sourced = SourcedConfig::load(Some(config_path_str), None).expect("Default config should load successfully");

    // Create the rule registry
    let all_rules = rules::all_rules(&Config::default());
    let registry = RuleRegistry::from_rules(&all_rules);

    // Validate the config
    let warnings = validate_config_sourced(&sourced, &registry);

    // The default config should have no warnings
    if !warnings.is_empty() {
        for warning in &warnings {
            eprintln!("Config validation warning: {}", warning.message);
            if let Some(rule) = &warning.rule {
                eprintln!("  Rule: {rule}");
            }
            if let Some(key) = &warning.key {
                eprintln!("  Key: {key}");
            }
        }
    }
    assert!(
        warnings.is_empty(),
        "Default config from rumdl init should pass validation without warnings"
    );
}

#[test]
fn test_md054_preferred_style_accepts_scalar_form() {
    use crate::rules;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    fs::write(&config_path, "[MD054]\npreferred-style = \"autolink\"\n").unwrap();

    let sourced = SourcedConfig::load(Some(config_path.to_str().unwrap()), None).expect("Config should load");
    let all_rules = rules::all_rules(&Config::default());
    let registry = RuleRegistry::from_rules(&all_rules);
    let warnings = validate_config_sourced(&sourced, &registry);

    let md054_warnings: Vec<_> = warnings.iter().filter(|w| w.rule.as_deref() == Some("MD054")).collect();
    assert!(
        md054_warnings.is_empty(),
        "Scalar preferred-style should pass validation, got: {md054_warnings:?}"
    );
}

#[test]
fn test_md054_preferred_style_accepts_list_form() {
    use crate::rules;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    fs::write(&config_path, "[MD054]\npreferred-style = [\"autolink\", \"full\"]\n").unwrap();

    let sourced = SourcedConfig::load(Some(config_path.to_str().unwrap()), None).expect("Config should load");
    let all_rules = rules::all_rules(&Config::default());
    let registry = RuleRegistry::from_rules(&all_rules);
    let warnings = validate_config_sourced(&sourced, &registry);

    let md054_warnings: Vec<_> = warnings.iter().filter(|w| w.rule.as_deref() == Some("MD054")).collect();
    assert!(
        md054_warnings.is_empty(),
        "List preferred-style should pass validation (polymorphic schema), got: {md054_warnings:?}"
    );
}

#[test]
fn test_md054_preferred_style_unknown_key_still_warns() {
    use crate::rules;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    fs::write(&config_path, "[MD054]\npreferred-styel = \"autolink\"\n").unwrap();

    let sourced = SourcedConfig::load(Some(config_path.to_str().unwrap()), None).expect("Config should load");
    let all_rules = rules::all_rules(&Config::default());
    let registry = RuleRegistry::from_rules(&all_rules);
    let warnings = validate_config_sourced(&sourced, &registry);

    let unknown_key_warnings: Vec<_> = warnings
        .iter()
        .filter(|w| w.rule.as_deref() == Some("MD054") && w.message.contains("Unknown option"))
        .collect();
    assert!(
        !unknown_key_warnings.is_empty(),
        "Polymorphic schema must still detect typos in key names; got warnings: {warnings:?}"
    );
}

#[test]
fn test_enabled_key_valid_for_any_rule() {
    use crate::rules;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // MD070 has no config struct — test that enabled is accepted anyway
    std::fs::write(&config_path, "[MD070]\nenabled = true\n").unwrap();

    let sourced = SourcedConfig::load(Some(config_path.to_str().unwrap()), None).expect("Config should load");
    let all_rules = rules::all_rules(&Config::default());
    let registry = RuleRegistry::from_rules(&all_rules);
    let warnings = validate_config_sourced(&sourced, &registry);

    let enabled_warnings: Vec<_> = warnings
        .iter()
        .filter(|w| w.key.as_deref() == Some("enabled"))
        .collect();
    assert!(
        enabled_warnings.is_empty(),
        "'enabled' should be valid for any rule, got warnings: {enabled_warnings:?}"
    );
}

#[test]
fn test_per_file_ignores_config_parsing() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-ignores]
"README.md" = ["MD033"]
"docs/**/*.md" = ["MD013", "MD033"]
"test/*.md" = ["MD041"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Verify per-file-ignores was loaded
    assert_eq!(config.per_file_ignores.len(), 3);
    assert_eq!(
        config.per_file_ignores.get("README.md"),
        Some(&vec!["MD033".to_string()])
    );
    assert_eq!(
        config.per_file_ignores.get("docs/**/*.md"),
        Some(&vec!["MD013".to_string(), "MD033".to_string()])
    );
    assert_eq!(
        config.per_file_ignores.get("test/*.md"),
        Some(&vec!["MD041".to_string()])
    );
}

#[test]
fn test_per_file_ignores_glob_matching() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-ignores]
"README.md" = ["MD033"]
"docs/**/*.md" = ["MD013"]
"**/test_*.md" = ["MD041"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Test exact match
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
    assert!(ignored.contains("MD033"));
    assert_eq!(ignored.len(), 1);

    // Test glob pattern matching
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
    assert!(ignored.contains("MD013"));
    assert_eq!(ignored.len(), 1);

    // Test recursive glob pattern
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("tests/fixtures/test_example.md"));
    assert!(ignored.contains("MD041"));
    assert_eq!(ignored.len(), 1);

    // Test non-matching path
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("other/file.md"));
    assert!(ignored.is_empty());
}

#[test]
fn test_per_file_ignores_pyproject_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
[tool.rumdl.per-file-ignores]
"README.md" = ["MD033", "MD013"]
"generated/*.md" = ["MD041"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Verify per-file-ignores was loaded from pyproject.toml
    assert_eq!(config.per_file_ignores.len(), 2);
    assert_eq!(
        config.per_file_ignores.get("README.md"),
        Some(&vec!["MD033".to_string(), "MD013".to_string()])
    );
    assert_eq!(
        config.per_file_ignores.get("generated/*.md"),
        Some(&vec!["MD041".to_string()])
    );
}

#[test]
fn test_per_file_ignores_multiple_patterns_match() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-ignores]
"docs/**/*.md" = ["MD013"]
"**/api/*.md" = ["MD033"]
"docs/api/overview.md" = ["MD041"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // File matches multiple patterns - should get union of all rules
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
    assert_eq!(ignored.len(), 3);
    assert!(ignored.contains("MD013"));
    assert!(ignored.contains("MD033"));
    assert!(ignored.contains("MD041"));
}

#[test]
fn test_per_file_ignores_rule_name_normalization() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-ignores]
"README.md" = ["md033", "MD013", "Md041"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // All rule names should be normalized to uppercase
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
    assert_eq!(ignored.len(), 3);
    assert!(ignored.contains("MD033"));
    assert!(ignored.contains("MD013"));
    assert!(ignored.contains("MD041"));
}

#[test]
fn test_per_file_ignores_invalid_glob_pattern() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-ignores]
"[invalid" = ["MD033"]
"valid/*.md" = ["MD013"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Invalid pattern should be skipped, valid pattern should work
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("valid/test.md"));
    assert!(ignored.contains("MD013"));

    // Invalid pattern should not cause issues
    let ignored2 = config.get_ignored_rules_for_file(&PathBuf::from("[invalid"));
    assert!(ignored2.is_empty());
}

#[test]
fn test_per_file_ignores_empty_section() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
disable = ["MD001"]

[per-file-ignores]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Empty per-file-ignores should work fine
    assert_eq!(config.per_file_ignores.len(), 0);
    let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
    assert!(ignored.is_empty());
}

#[test]
fn test_per_file_ignores_with_underscores_in_pyproject() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
[tool.rumdl.per_file_ignores]
"README.md" = ["MD033"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Should support both per-file-ignores and per_file_ignores
    assert_eq!(config.per_file_ignores.len(), 1);
    assert_eq!(
        config.per_file_ignores.get("README.md"),
        Some(&vec!["MD033".to_string()])
    );
}

#[test]
fn test_per_file_ignores_absolute_path_matching() {
    // Regression test for issue #208: per-file-ignores should work with absolute paths
    // This is critical for GitHub Actions which uses absolute paths like $GITHUB_WORKSPACE
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // Create a subdirectory and file to match against
    let github_dir = temp_dir.path().join(".github");
    fs::create_dir_all(&github_dir).unwrap();
    let test_file = github_dir.join("pull_request_template.md");
    fs::write(&test_file, "Test content").unwrap();

    let config_content = r#"
[per-file-ignores]
".github/pull_request_template.md" = ["MD041"]
"docs/**/*.md" = ["MD013"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Test with absolute path (like GitHub Actions would use)
    let absolute_path = test_file.canonicalize().unwrap();
    let ignored = config.get_ignored_rules_for_file(&absolute_path);
    assert!(
        ignored.contains("MD041"),
        "Should match absolute path {absolute_path:?} against relative pattern"
    );
    assert_eq!(ignored.len(), 1);

    // Also verify relative path still works
    let relative_path = PathBuf::from(".github/pull_request_template.md");
    let ignored = config.get_ignored_rules_for_file(&relative_path);
    assert!(ignored.contains("MD041"), "Should match relative path");
}

// ==========================================
// Per-File-Flavor Tests
// ==========================================

#[test]
fn test_per_file_flavor_config_parsing() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-flavor]
"docs/**/*.md" = "mkdocs"
"**/*.mdx" = "mdx"
"**/*.qmd" = "quarto"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Verify per-file-flavor was loaded
    assert_eq!(config.per_file_flavor.len(), 3);
    assert_eq!(
        config.per_file_flavor.get("docs/**/*.md"),
        Some(&MarkdownFlavor::MkDocs)
    );
    assert_eq!(config.per_file_flavor.get("**/*.mdx"), Some(&MarkdownFlavor::MDX));
    assert_eq!(config.per_file_flavor.get("**/*.qmd"), Some(&MarkdownFlavor::Quarto));
}

#[test]
fn test_per_file_flavor_glob_matching() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-flavor]
"docs/**/*.md" = "mkdocs"
"**/*.mdx" = "mdx"
"components/**/*.md" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Test mkdocs flavor for docs directory
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/api/overview.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Test mdx flavor for .mdx extension
    let flavor = config.get_flavor_for_file(&PathBuf::from("src/components/Button.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    // Test mdx flavor for components directory
    let flavor = config.get_flavor_for_file(&PathBuf::from("components/Button/README.md"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    // Test non-matching path falls back to standard
    let flavor = config.get_flavor_for_file(&PathBuf::from("README.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_pyproject_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
[tool.rumdl.per-file-flavor]
"docs/**/*.md" = "mkdocs"
"**/*.mdx" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Verify per-file-flavor was loaded from pyproject.toml
    assert_eq!(config.per_file_flavor.len(), 2);
    assert_eq!(
        config.per_file_flavor.get("docs/**/*.md"),
        Some(&MarkdownFlavor::MkDocs)
    );
    assert_eq!(config.per_file_flavor.get("**/*.mdx"), Some(&MarkdownFlavor::MDX));
}

#[test]
fn test_per_file_flavor_first_match_wins() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Order matters - first match wins (IndexMap preserves order)
    let config_content = r#"
[per-file-flavor]
"docs/internal/**/*.md" = "quarto"
"docs/**/*.md" = "mkdocs"
"**/*.md" = "standard"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // More specific pattern should match first
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/internal/secret.md"));
    assert_eq!(flavor, MarkdownFlavor::Quarto);

    // Less specific pattern for other docs
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/public/readme.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Fallback to least specific pattern
    let flavor = config.get_flavor_for_file(&PathBuf::from("other/file.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_overrides_global_flavor() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
flavor = "mkdocs"

[per-file-flavor]
"**/*.mdx" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Per-file-flavor should override global flavor
    let flavor = config.get_flavor_for_file(&PathBuf::from("components/Button.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    // Non-matching files should use global flavor
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/readme.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);
}

#[test]
fn test_per_file_flavor_empty_map() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
disable = ["MD001"]

[per-file-flavor]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Empty per-file-flavor should fall back to auto-detection
    let flavor = config.get_flavor_for_file(&PathBuf::from("README.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);

    // MDX files should auto-detect
    let flavor = config.get_flavor_for_file(&PathBuf::from("test.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MDX);
}

#[test]
fn test_per_file_flavor_with_underscores() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
[tool.rumdl.per_file_flavor]
"docs/**/*.md" = "mkdocs"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Should support both per-file-flavor and per_file_flavor
    assert_eq!(config.per_file_flavor.len(), 1);
    assert_eq!(
        config.per_file_flavor.get("docs/**/*.md"),
        Some(&MarkdownFlavor::MkDocs)
    );
}

#[test]
fn test_per_file_flavor_absolute_path_matching() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");

    // Create a subdirectory and file to match against
    let docs_dir = temp_dir.path().join("docs");
    fs::create_dir_all(&docs_dir).unwrap();
    let test_file = docs_dir.join("guide.md");
    fs::write(&test_file, "Test content").unwrap();

    let config_content = r#"
[per-file-flavor]
"docs/**/*.md" = "mkdocs"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Test with absolute path
    let absolute_path = test_file.canonicalize().unwrap();
    let flavor = config.get_flavor_for_file(&absolute_path);
    assert_eq!(
        flavor,
        MarkdownFlavor::MkDocs,
        "Should match absolute path {absolute_path:?} against relative pattern"
    );

    // Also verify relative path still works
    let relative_path = PathBuf::from("docs/guide.md");
    let flavor = config.get_flavor_for_file(&relative_path);
    assert_eq!(flavor, MarkdownFlavor::MkDocs, "Should match relative path");
}

#[test]
fn test_per_file_flavor_all_flavors() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-flavor]
"standard/**/*.md" = "standard"
"mkdocs/**/*.md" = "mkdocs"
"mdx/**/*.md" = "mdx"
"quarto/**/*.md" = "quarto"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // All four flavors should be loadable
    assert_eq!(config.per_file_flavor.len(), 4);
    assert_eq!(
        config.per_file_flavor.get("standard/**/*.md"),
        Some(&MarkdownFlavor::Standard)
    );
    assert_eq!(
        config.per_file_flavor.get("mkdocs/**/*.md"),
        Some(&MarkdownFlavor::MkDocs)
    );
    assert_eq!(config.per_file_flavor.get("mdx/**/*.md"), Some(&MarkdownFlavor::MDX));
    assert_eq!(
        config.per_file_flavor.get("quarto/**/*.md"),
        Some(&MarkdownFlavor::Quarto)
    );
}

#[test]
fn test_per_file_flavor_invalid_glob_pattern() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Include an invalid glob pattern with unclosed bracket
    let config_content = r#"
[per-file-flavor]
"[invalid" = "mkdocs"
"valid/**/*.md" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Invalid pattern should be skipped, valid pattern should still work
    let flavor = config.get_flavor_for_file(&PathBuf::from("valid/test.md"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    // Non-matching should fall back to Standard
    let flavor = config.get_flavor_for_file(&PathBuf::from("other/test.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_paths_with_spaces() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-flavor]
"my docs/**/*.md" = "mkdocs"
"src/**/*.md" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Paths with spaces should match
    let flavor = config.get_flavor_for_file(&PathBuf::from("my docs/guide.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Regular path
    let flavor = config.get_flavor_for_file(&PathBuf::from("src/README.md"));
    assert_eq!(flavor, MarkdownFlavor::MDX);
}

#[test]
fn test_per_file_flavor_deeply_nested_paths() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[per-file-flavor]
"a/b/c/d/e/**/*.md" = "quarto"
"a/b/**/*.md" = "mkdocs"
"**/*.md" = "standard"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // 5-level deep path should match most specific pattern first
    let flavor = config.get_flavor_for_file(&PathBuf::from("a/b/c/d/e/f/deep.md"));
    assert_eq!(flavor, MarkdownFlavor::Quarto);

    // 3-level deep path
    let flavor = config.get_flavor_for_file(&PathBuf::from("a/b/c/test.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Root level
    let flavor = config.get_flavor_for_file(&PathBuf::from("root.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_complex_overlapping_patterns() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Complex pattern order testing - tests that IndexMap preserves TOML order
    let config_content = r#"
[per-file-flavor]
"docs/api/*.md" = "mkdocs"
"docs/**/*.mdx" = "mdx"
"docs/**/*.md" = "quarto"
"**/*.md" = "standard"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // docs/api/*.md should match first
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/api/reference.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // docs/api/nested/file.md should NOT match docs/api/*.md (no **), but match docs/**/*.md
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/api/nested/file.md"));
    assert_eq!(flavor, MarkdownFlavor::Quarto);

    // .mdx in docs should match docs/**/*.mdx
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/components/Button.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    // .md outside docs should match **/*.md
    let flavor = config.get_flavor_for_file(&PathBuf::from("src/README.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_extension_detection_interaction() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test that per-file-flavor pattern can override extension-based auto-detection
    let config_content = r#"
[per-file-flavor]
"legacy/**/*.mdx" = "standard"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // .mdx file in legacy dir should use pattern override (standard), not auto-detect (mdx)
    let flavor = config.get_flavor_for_file(&PathBuf::from("legacy/old.mdx"));
    assert_eq!(flavor, MarkdownFlavor::Standard);

    // .mdx file elsewhere should auto-detect as MDX
    let flavor = config.get_flavor_for_file(&PathBuf::from("src/component.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MDX);
}

#[test]
fn test_per_file_flavor_standard_alias_none() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test that "none" works as alias for "standard"
    let config_content = r#"
[per-file-flavor]
"plain/**/*.md" = "none"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // "none" should resolve to Standard
    let flavor = config.get_flavor_for_file(&PathBuf::from("plain/test.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_brace_expansion() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test brace expansion in glob patterns
    let config_content = r#"
[per-file-flavor]
"docs/**/*.{md,mdx}" = "mkdocs"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Should match .md files
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/guide.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Should match .mdx files
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/component.mdx"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);
}

#[test]
fn test_per_file_flavor_single_star_vs_double_star() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test difference between * (single level) and ** (recursive)
    let config_content = r#"
[per-file-flavor]
"docs/*.md" = "mkdocs"
"src/**/*.md" = "mdx"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Single * matches only direct children
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/README.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Single * does NOT match nested files
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/api/index.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard); // fallback

    // Double ** matches recursively
    let flavor = config.get_flavor_for_file(&PathBuf::from("src/components/Button.md"));
    assert_eq!(flavor, MarkdownFlavor::MDX);

    let flavor = config.get_flavor_for_file(&PathBuf::from("src/README.md"));
    assert_eq!(flavor, MarkdownFlavor::MDX);
}

#[test]
fn test_per_file_flavor_question_mark_wildcard() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test ? wildcard (matches single character)
    let config_content = r#"
[per-file-flavor]
"docs/v?.md" = "mkdocs"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // ? matches single character
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/v1.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/v2.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // ? does NOT match multiple characters
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/v10.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);

    // ? does NOT match zero characters
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/v.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

#[test]
fn test_per_file_flavor_character_class() {
    use std::path::PathBuf;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    // Test character class [abc]
    let config_content = r#"
[per-file-flavor]
"docs/[abc].md" = "mkdocs"
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Should match a, b, or c
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/a.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/b.md"));
    assert_eq!(flavor, MarkdownFlavor::MkDocs);

    // Should NOT match d
    let flavor = config.get_flavor_for_file(&PathBuf::from("docs/d.md"));
    assert_eq!(flavor, MarkdownFlavor::Standard);
}

// ==========================================
// Path normalization robustness tests
// (regression: per-file-flavor / per-file-ignores must work even when
// `project_root` was not discovered, as long as the file lives under CWD.
// This mirrors how rumdl is invoked from CI runners, language servers,
// and editors that pass absolute paths through the API.)
// ==========================================

/// Create an absolute file path inside the given temp dir by creating
/// the parent directories and an empty file at `rel`, then canonicalizing.
fn make_file(temp: &tempfile::TempDir, rel: &str) -> std::path::PathBuf {
    let abs = temp.path().join(rel);
    fs::create_dir_all(abs.parent().unwrap()).unwrap();
    fs::write(&abs, "").unwrap();
    abs.canonicalize().unwrap()
}

#[test]
fn test_normalize_match_path_uses_project_root() {
    // Happy path: project_root is set, file is under it. Result is the
    // path relative to project_root, regardless of where cwd points.
    let temp = tempdir().unwrap();
    let cwd = tempdir().unwrap(); // unrelated cwd
    let file = make_file(&temp, "docs/guide.md");
    let root = temp.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, Some(&root), Some(cwd.path()));
    assert_eq!(result.as_ref(), std::path::Path::new("docs/guide.md"));
}

#[test]
fn test_normalize_match_path_falls_back_to_cwd_when_project_root_none() {
    // The actual fix: when project_root is None but the file is under cwd,
    // the result must be the path relative to cwd.
    let temp = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");
    let cwd = temp.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, None, Some(&cwd));
    assert_eq!(result.as_ref(), std::path::Path::new("docs/guide.md"));
}

#[test]
fn test_normalize_match_path_falls_back_to_cwd_when_project_root_unrelated() {
    // When project_root is set but the file lives outside it (e.g. when the
    // user invokes rumdl on a file outside the configured project), fall back
    // to cwd-relative matching rather than blindly using the raw absolute path.
    let temp = tempdir().unwrap();
    let elsewhere = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");
    let cwd = temp.path().canonicalize().unwrap();
    let unrelated_root = elsewhere.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, Some(&unrelated_root), Some(&cwd));
    assert_eq!(result.as_ref(), std::path::Path::new("docs/guide.md"));
}

#[test]
fn test_normalize_match_path_relative_path_passthrough() {
    // A relative path needs no normalization regardless of project_root or cwd.
    let temp = tempdir().unwrap();
    let result = super::types::normalize_match_path(
        std::path::Path::new("docs/guide.md"),
        Some(temp.path()),
        Some(temp.path()),
    );
    assert_eq!(result.as_ref(), std::path::Path::new("docs/guide.md"));
}

#[test]
fn test_normalize_match_path_nonexistent_file_passthrough() {
    // Editor/LSP buffers may reference a path that does not exist on disk yet,
    // so canonicalize() will fail. Such relative paths must still be matchable.
    let result = super::types::normalize_match_path(std::path::Path::new("docs/draft.md"), None, None);
    assert_eq!(result.as_ref(), std::path::Path::new("docs/draft.md"));
}

#[test]
fn test_normalize_match_path_outside_cwd_returns_raw_path() {
    // Path is absolute and lives nowhere we can map to relative form.
    // Returning the raw path is the safe fallback — a relative glob pattern
    // simply won't match it, which is the desired behavior.
    let outside = tempdir().unwrap();
    let cwd = tempdir().unwrap();
    let file = make_file(&outside, "docs/elsewhere.md");
    let cwd_path = cwd.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, None, Some(&cwd_path));
    assert_eq!(result.as_ref(), file.as_path());
}

#[test]
fn test_normalize_match_path_silent_fallback_when_project_root_and_cwd_both_unrelated() {
    // Comprehensive silent-fallback case: file lives outside BOTH project_root
    // and cwd. The function must return the raw absolute path so the
    // downstream glob simply doesn't match — never panic, never short-circuit
    // to a wrong relative form.
    let project = tempdir().unwrap();
    let working = tempdir().unwrap();
    let elsewhere = tempdir().unwrap();
    let file = make_file(&elsewhere, "docs/orphan.md");
    let project_root = project.path().canonicalize().unwrap();
    let cwd = working.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, Some(&project_root), Some(&cwd));
    assert_eq!(
        result.as_ref(),
        file.as_path(),
        "silent fallback must return the raw absolute path verbatim",
    );
}

#[test]
fn test_per_file_flavor_matches_absolute_path_with_project_root_only_no_cwd() {
    // End-to-end: the public API must wire normalize_match_path correctly so
    // that an absolute path under project_root resolves to the override flavor.
    let temp = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");

    let mut per_file_flavor = indexmap::IndexMap::new();
    per_file_flavor.insert("docs/**/*.md".to_string(), MarkdownFlavor::MkDocs);
    let config = Config {
        per_file_flavor,
        project_root: Some(temp.path().canonicalize().unwrap()),
        ..Default::default()
    };

    let flavor = config.get_flavor_for_file(&file);
    assert_eq!(flavor, MarkdownFlavor::MkDocs);
}

#[test]
#[serial_test::serial]
fn test_per_file_flavor_matches_absolute_path_with_cwd_fallback() {
    // End-to-end: when project_root is None, an absolute path under cwd must
    // resolve via the cwd fallback path. This is the scenario from #591.
    // Mutates global cwd, so #[serial_test::serial] guards parallel races.
    let temp = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");
    let cwd = temp.path().canonicalize().unwrap();

    let mut per_file_flavor = indexmap::IndexMap::new();
    per_file_flavor.insert("docs/**/*.md".to_string(), MarkdownFlavor::MkDocs);
    let config = Config {
        per_file_flavor,
        project_root: None,
        ..Default::default()
    };

    let prev_cwd = std::env::current_dir().unwrap();
    std::env::set_current_dir(&cwd).unwrap();
    let result = std::panic::catch_unwind(|| config.get_flavor_for_file(&file));
    std::env::set_current_dir(&prev_cwd).unwrap();
    let flavor = result.unwrap();

    assert_eq!(flavor, MarkdownFlavor::MkDocs);
}

#[test]
#[serial_test::serial]
fn test_per_file_ignores_matches_absolute_path_with_cwd_fallback() {
    // Sibling end-to-end test for the per-file-ignores path, which uses the
    // same normalize_match_path helper. An absolute file path under cwd must
    // resolve the rule list correctly when project_root is None.
    use std::collections::HashMap;

    let temp = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");
    let cwd = temp.path().canonicalize().unwrap();

    let mut per_file_ignores = HashMap::new();
    per_file_ignores.insert("docs/**/*.md".to_string(), vec!["MD013".to_string()]);
    let config = Config {
        per_file_ignores,
        project_root: None,
        ..Default::default()
    };

    let prev_cwd = std::env::current_dir().unwrap();
    std::env::set_current_dir(&cwd).unwrap();
    let result = std::panic::catch_unwind(|| config.get_ignored_rules_for_file(&file));
    std::env::set_current_dir(&prev_cwd).unwrap();
    let ignored = result.unwrap();

    assert!(
        ignored.contains("MD013"),
        "MD013 should be ignored for docs/guide.md via cwd fallback. Got: {ignored:?}",
    );
}

#[test]
fn test_normalize_match_path_globset_round_trip() {
    // The full pipeline (normalize → globset match) must produce a relative
    // path that a forward-slash glob can match. On Windows this additionally
    // exercises UNC-prefix stripping (canonicalize() returns `\\?\C:\...`)
    // and backslash → forward-slash normalization in globset; on Unix the
    // canonical path is already free of UNC and uses forward slashes.
    let temp = tempdir().unwrap();
    let file = make_file(&temp, "docs/guide.md");
    let root = temp.path().canonicalize().unwrap();

    let result = super::types::normalize_match_path(&file, Some(&root), None);
    assert!(result.is_relative(), "expected relative path, got {result:?}");

    let glob = globset::GlobBuilder::new("docs/**/*.md")
        .literal_separator(true)
        .build()
        .unwrap()
        .compile_matcher();
    assert!(
        glob.is_match(result.as_ref()),
        "globset must match {result:?} against `docs/**/*.md`",
    );
}

#[test]
fn test_canonical_project_root_cache_returns_stable_reference() {
    // The cache contract is: subsequent calls return a borrow of the same
    // stored `PathBuf`, not a freshly canonicalized one. We verify this
    // structurally by comparing pointers — deterministic, no timing.
    let temp = tempdir().unwrap();
    let config = Config {
        project_root: Some(temp.path().to_path_buf()),
        ..Config::default()
    };

    let first: *const std::path::Path = config.canonical_project_root().expect("project_root canonicalizes");
    let second: *const std::path::Path = config.canonical_project_root().expect("cache hit");

    assert!(
        std::ptr::eq(first, second),
        "cached lookup must return a borrow of the stored PathBuf, not a fresh canonicalization",
    );
}

#[test]
fn test_first_call_warn_else_debug_returns_warn_then_debug() {
    use std::sync::OnceLock;

    let latch: OnceLock<()> = OnceLock::new();

    assert_eq!(
        super::types::first_call_warn_else_debug(&latch),
        log::Level::Warn,
        "first call must surface at warn level",
    );
    assert_eq!(
        super::types::first_call_warn_else_debug(&latch),
        log::Level::Debug,
        "second call must downgrade to debug",
    );
    assert_eq!(
        super::types::first_call_warn_else_debug(&latch),
        log::Level::Debug,
        "subsequent calls remain at debug",
    );
}

#[test]
fn test_format_silent_fallback_message_renders_paths_with_display_formatting() {
    // Paths must appear via Display (not Debug) so the diagnostic doesn't
    // contain stray quote characters that came from Debug's PathBuf impl.
    use std::path::PathBuf;

    let file = PathBuf::from("/elsewhere/notes/draft.md");
    let root = PathBuf::from("/projects/myrepo");
    let cwd = PathBuf::from("/tmp/build");

    let msg = super::types::format_silent_fallback_message(&file, Some(&root), Some(&cwd));

    assert_eq!(
        msg,
        "Per-file glob patterns will not match /elsewhere/notes/draft.md: \
         file is outside project_root (/projects/myrepo) and cwd (/tmp/build)",
        "exact message format is part of the diagnostic contract; got: {msg}",
    );
    assert!(
        !msg.contains('"'),
        "Display formatting must not emit Debug-style quotes; got: {msg}",
    );
}

#[test]
fn test_format_silent_fallback_message_renders_unset_root_and_cwd_explicitly() {
    // When project_root and/or cwd are unavailable the diagnostic must
    // surface that explicitly as "(unset)" rather than leaking Rust's
    // `None` Debug representation.
    use std::path::PathBuf;

    let file = PathBuf::from("/anywhere/file.md");
    let msg = super::types::format_silent_fallback_message(&file, None, None);

    assert_eq!(
        msg,
        "Per-file glob patterns will not match /anywhere/file.md: \
         file is outside project_root (<unset>) and cwd (<unset>)",
    );
    assert!(
        !msg.contains("None"),
        "must not surface Rust's Debug `None`; got: {msg}"
    );
}

#[test]
fn test_format_silent_fallback_message_renders_partial_unset() {
    // Mixed Some/None must render each independently — the placeholder
    // should appear only where it's actually unset.
    use std::path::PathBuf;

    let file = PathBuf::from("/file.md");
    let root = PathBuf::from("/projects/repo");

    let only_root = super::types::format_silent_fallback_message(&file, Some(&root), None);
    assert!(only_root.contains("project_root (/projects/repo)"), "got: {only_root}");
    assert!(only_root.contains("cwd (<unset>)"), "got: {only_root}");

    let only_cwd = super::types::format_silent_fallback_message(&file, None, Some(&root));
    assert!(only_cwd.contains("project_root (<unset>)"), "got: {only_cwd}");
    assert!(only_cwd.contains("cwd (/projects/repo)"), "got: {only_cwd}");
}

#[test]
fn test_first_call_warn_else_debug_independent_latches() {
    // Each latch tracks its own first-call state. A fresh latch must not
    // be influenced by a different latch having already been set.
    use std::sync::OnceLock;

    let latch_a: OnceLock<()> = OnceLock::new();
    let latch_b: OnceLock<()> = OnceLock::new();

    assert_eq!(super::types::first_call_warn_else_debug(&latch_a), log::Level::Warn);
    assert_eq!(super::types::first_call_warn_else_debug(&latch_a), log::Level::Debug);

    assert_eq!(
        super::types::first_call_warn_else_debug(&latch_b),
        log::Level::Warn,
        "latch_b is independent of latch_a",
    );
}

#[test]
fn test_canonical_project_root_cache_shared_across_clones() {
    // `Config: Clone` and the cache is wrapped in `Arc<OnceLock<_>>` so a
    // value computed by any clone is observable to all. Verify that:
    // a clone created BEFORE the cache is populated still sees the cached
    // value once the original populates it.
    let temp = tempdir().unwrap();
    let root = temp.path().to_path_buf();

    let original = Config {
        project_root: Some(root.clone()),
        ..Config::default()
    };
    let clone_before_init = original.clone();

    // Populate via the original.
    let canonical = original
        .canonical_project_root()
        .expect("project_root canonicalizes")
        .to_path_buf();

    // The pre-init clone must observe the same cached value without
    // re-canonicalizing, because both share the same `Arc<OnceLock<_>>`.
    let observed = clone_before_init
        .canonical_project_root()
        .expect("clone observes cached value");
    assert_eq!(observed, canonical.as_path());
}

#[test]
fn test_generate_json_schema() {
    use schemars::schema_for;
    use std::env;

    let schema = schema_for!(Config);
    let schema_json = serde_json::to_string_pretty(&schema).expect("Failed to serialize schema");

    // Write schema to file if RUMDL_UPDATE_SCHEMA env var is set
    if env::var("RUMDL_UPDATE_SCHEMA").is_ok() {
        let schema_path = env::current_dir().unwrap().join("rumdl.schema.json");
        fs::write(&schema_path, &schema_json).expect("Failed to write schema file");
        println!("Schema written to: {}", schema_path.display());
    }

    // Basic validation that schema was generated
    assert!(schema_json.contains("\"title\": \"Config\""));
    assert!(schema_json.contains("\"global\""));
    assert!(schema_json.contains("\"per-file-ignores\""));
}

#[test]
fn test_markdown_flavor_schema_matches_fromstr() {
    // Extract enum values from the actual generated schema
    // This ensures the test stays in sync with the schema automatically
    use schemars::schema_for;

    let schema = schema_for!(MarkdownFlavor);
    let schema_json = serde_json::to_value(&schema).expect("Failed to serialize schema");

    // Extract enum values from schema
    let enum_values = schema_json
        .get("enum")
        .expect("Schema should have 'enum' field")
        .as_array()
        .expect("enum should be an array");

    assert!(!enum_values.is_empty(), "Schema enum should not be empty");

    // Verify all schema enum values are parseable by FromStr
    for value in enum_values {
        let str_value = value.as_str().expect("enum value should be a string");
        let result = str_value.parse::<MarkdownFlavor>();
        assert!(
            result.is_ok(),
            "Schema value '{str_value}' should be parseable by FromStr but got: {:?}",
            result.err()
        );
    }

    // Also verify the aliases in FromStr that aren't in schema (empty string, none)
    for alias in ["", "none"] {
        let result = alias.parse::<MarkdownFlavor>();
        assert!(result.is_ok(), "FromStr alias '{alias}' should be parseable");
    }
}

#[test]
fn test_project_config_is_standalone() {
    // Ruff model: Project config is standalone, user config is NOT merged
    // This ensures reproducibility across machines and CI/local consistency
    let temp_dir = tempdir().unwrap();

    // Create a fake user config directory
    // Note: user_configuration_path_impl adds /rumdl to the config dir
    let user_config_dir = temp_dir.path().join("user_config");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    let user_config_path = rumdl_config_dir.join("rumdl.toml");

    // User config disables MD013 and MD041
    let user_config_content = r#"
[global]
disable = ["MD013", "MD041"]
line-length = 100
"#;
    fs::write(&user_config_path, user_config_content).unwrap();

    // Create a project config that enables MD001
    let project_config_path = temp_dir.path().join("project").join("pyproject.toml");
    fs::create_dir_all(project_config_path.parent().unwrap()).unwrap();
    let project_config_content = r#"
[tool.rumdl]
enable = ["MD001"]
"#;
    fs::write(&project_config_path, project_config_content).unwrap();

    // Load config with explicit project path, passing user_config_dir
    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(project_config_path.to_str().unwrap()),
        None,
        false,
        Some(&user_config_dir),
        None,
    )
    .unwrap();

    let config: Config = sourced.into_validated_unchecked().into();

    // User config settings should NOT be present (Ruff model: project is standalone)
    assert!(
        !config.global.disable.contains(&"MD013".to_string()),
        "User config should NOT be merged with project config"
    );
    assert!(
        !config.global.disable.contains(&"MD041".to_string()),
        "User config should NOT be merged with project config"
    );

    // Project config settings should be applied
    assert!(
        config.global.enable.contains(&"MD001".to_string()),
        "Project config enabled rules should be applied"
    );
}

#[serial_test::serial]
#[test]
fn test_user_config_as_fallback_when_no_project_config() {
    // Ruff model: User config is used as fallback when no project config exists
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // Create a fake user config directory
    let user_config_dir = temp_dir.path().join("user_config");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    let user_config_path = rumdl_config_dir.join("rumdl.toml");

    // User config with specific settings
    let user_config_content = r#"
[global]
disable = ["MD013", "MD041"]
line-length = 88
"#;
    fs::write(&user_config_path, user_config_content).unwrap();

    // Create a project directory WITHOUT any config
    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();

    // Change to project directory
    env::set_current_dir(&project_dir).unwrap();

    // Load config - should use user config as fallback
    let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None).unwrap();

    let config: Config = sourced.into_validated_unchecked().into();

    // User config should be loaded as fallback
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "User config should be loaded as fallback when no project config"
    );
    assert!(
        config.global.disable.contains(&"MD041".to_string()),
        "User config should be loaded as fallback when no project config"
    );
    assert_eq!(
        config.global.line_length.get(),
        88,
        "User config line-length should be loaded as fallback"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_user_config_fallback_supports_extends() {
    // User fallback config should support extends chains
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // Create a fake user config directory
    let user_config_dir = temp_dir.path().join("user_config");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();

    // Base config in user config directory
    let base_config_path = rumdl_config_dir.join("base.toml");
    fs::write(
        &base_config_path,
        r#"
[global]
disable = ["MD013"]
line-length = 92
"#,
    )
    .unwrap();

    // User fallback config extends base config
    let user_config_path = rumdl_config_dir.join("rumdl.toml");
    fs::write(
        &user_config_path,
        r#"extends = "base.toml"

[global]
extend-disable = ["MD033"]
"#,
    )
    .unwrap();

    // Create a project directory WITHOUT any config
    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();

    // Change to project directory
    env::set_current_dir(&project_dir).unwrap();

    // Load config - should use user config as fallback and resolve extends
    let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Inherited from base config
    assert!(config.global.disable.contains(&"MD013".to_string()));
    assert_eq!(config.global.line_length.get(), 92);
    // Added by child fallback config
    assert!(config.global.extend_disable.contains(&"MD033".to_string()));

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_home_dotfile_used_when_no_xdg_or_project_config() {
    // ~/.rumdl.toml is honored as a final fallback when neither a project config
    // nor a platform user-config file exists.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // Fake $HOME containing only a dotfile rumdl config
    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(
        fake_home.join(".rumdl.toml"),
        r#"
[global]
disable = ["MD041"]
line-length = 77
"#,
    )
    .unwrap();

    // Empty XDG config dir: present but contains no rumdl files
    let user_config_dir = temp_dir.path().join("user_config_empty");
    fs::create_dir_all(user_config_dir.join("rumdl")).unwrap();

    // Project dir without any config
    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        config.global.disable.contains(&"MD041".to_string()),
        "~/.rumdl.toml should be loaded as fallback when no project or XDG config exists"
    );
    assert_eq!(
        config.global.line_length.get(),
        77,
        "line-length from ~/.rumdl.toml should apply"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_home_rumdl_toml_used_when_no_dotfile_present() {
    // ~/rumdl.toml (no leading dot) is also honored, after ~/.rumdl.toml.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(fake_home.join("rumdl.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();

    let user_config_dir = temp_dir.path().join("user_config_empty");
    fs::create_dir_all(user_config_dir.join("rumdl")).unwrap();

    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "~/rumdl.toml should be loaded when ~/.rumdl.toml is absent"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_xdg_config_wins_over_home_dotfile() {
    // When both XDG (~/.config/rumdl/...) and ~/.rumdl.toml exist, XDG wins.
    // This preserves backwards-compatible behavior for users who already configured
    // the platform user-config directory.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // XDG config: disables MD013
    let user_config_dir = temp_dir.path().join("user_config");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    fs::write(rumdl_config_dir.join("rumdl.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();

    // Home dotfile: would disable MD041 if used
    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(fake_home.join(".rumdl.toml"), "[global]\ndisable = [\"MD041\"]\n").unwrap();

    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "XDG config should take precedence over ~/.rumdl.toml"
    );
    assert!(
        !config.global.disable.contains(&"MD041".to_string()),
        "Home dotfile should be ignored when XDG config exists"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_project_config_wins_over_home_dotfile() {
    // Project config is standalone -- a home dotfile must not bleed in.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(
        fake_home.join(".rumdl.toml"),
        "[global]\ndisable = [\"MD041\"]\nline-length = 77\n",
    )
    .unwrap();

    // Empty XDG dir
    let user_config_dir = temp_dir.path().join("user_config_empty");
    fs::create_dir_all(user_config_dir.join("rumdl")).unwrap();

    // Project with its own config
    let project_dir = temp_dir.path().join("project_with_config");
    fs::create_dir_all(&project_dir).unwrap();
    fs::write(
        project_dir.join(".rumdl.toml"),
        "[global]\nenable = [\"MD001\"]\nline-length = 120\n",
    )
    .unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        config.global.enable.contains(&"MD001".to_string()),
        "Project config should be loaded"
    );
    assert!(
        !config.global.disable.contains(&"MD041".to_string()),
        "Home dotfile must NOT bleed into project (project is standalone)"
    );
    assert_eq!(
        config.global.line_length.get(),
        120,
        "Project line-length wins, not home dotfile's"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_home_dotfile_supports_extends() {
    // ~/.rumdl.toml must support `extends` chains -- a relative `extends` resolves
    // against the dotfile's parent directory ($HOME), and the inherited config is
    // merged with UserConfig precedence just like the XDG path.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // Fake $HOME with a base config and a child that extends it
    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(
        fake_home.join("base.toml"),
        r#"
[global]
disable = ["MD013"]
line-length = 92
"#,
    )
    .unwrap();
    fs::write(
        fake_home.join(".rumdl.toml"),
        r#"extends = "base.toml"

[global]
extend-disable = ["MD033"]
"#,
    )
    .unwrap();

    let user_config_dir = temp_dir.path().join("user_config_empty");
    fs::create_dir_all(user_config_dir.join("rumdl")).unwrap();

    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Inherited from base.toml via extends
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "extends from ~/.rumdl.toml should pull base.toml's disable list"
    );
    assert_eq!(
        config.global.line_length.get(),
        92,
        "extends from ~/.rumdl.toml should pull base.toml's line-length"
    );
    // Added by the home dotfile itself
    assert!(
        config.global.extend_disable.contains(&"MD033".to_string()),
        "child fragment in ~/.rumdl.toml should still apply on top of extends"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[serial_test::serial]
#[test]
fn test_home_dotfile_picked_up_over_rumdl_toml() {
    // ~/.rumdl.toml takes precedence over ~/rumdl.toml when both exist.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    let fake_home = temp_dir.path().join("home");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(fake_home.join(".rumdl.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();
    fs::write(fake_home.join("rumdl.toml"), "[global]\ndisable = [\"MD041\"]\n").unwrap();

    let user_config_dir = temp_dir.path().join("user_config_empty");
    fs::create_dir_all(user_config_dir.join("rumdl")).unwrap();

    let project_dir = temp_dir.path().join("project_no_config");
    fs::create_dir_all(&project_dir).unwrap();
    env::set_current_dir(&project_dir).unwrap();

    let sourced =
        SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), Some(&fake_home)).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        ".rumdl.toml (dotfile) should win over rumdl.toml in $HOME"
    );
    assert!(
        !config.global.disable.contains(&"MD041".to_string()),
        "rumdl.toml in $HOME should be ignored when .rumdl.toml is present"
    );

    env::set_current_dir(original_dir).unwrap();
}

#[test]
fn test_typestate_validate_method() {
    use tempfile::tempdir;

    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let config_path = temp_dir.path().join("test.toml");

    // Create config with an unknown rule option to trigger a validation warning
    let config_content = r#"
[global]
enable = ["MD001"]

[MD013]
line_length = 80
unknown_option = true
"#;
    std::fs::write(&config_path, config_content).expect("Failed to write config");

    // Load config - this returns SourcedConfig<ConfigLoaded>
    let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
        .expect("Should load config");

    // Create a rule registry for validation
    let default_config = Config::default();
    let all_rules = crate::rules::all_rules(&default_config);
    let registry = RuleRegistry::from_rules(&all_rules);

    // Validate - this transitions to SourcedConfig<ConfigValidated>
    let validated = loaded.validate(&registry).expect("Should validate config");

    // Check that validation warnings were captured for the unknown option
    // Note: The validation checks rule options against the rule's schema
    let has_unknown_option_warning = validated
        .validation_warnings
        .iter()
        .any(|w| w.message.contains("unknown_option") || w.message.contains("Unknown option"));

    // Print warnings for debugging if assertion fails
    if !has_unknown_option_warning {
        for w in &validated.validation_warnings {
            eprintln!("Warning: {}", w.message);
        }
    }
    assert!(
        has_unknown_option_warning,
        "Should have warning for unknown option. Got {} warnings: {:?}",
        validated.validation_warnings.len(),
        validated
            .validation_warnings
            .iter()
            .map(|w| &w.message)
            .collect::<Vec<_>>()
    );

    // Now we can convert to Config (this would be a compile error with ConfigLoaded)
    let config: Config = validated.into();

    // Verify the config values are correct
    assert!(config.global.enable.contains(&"MD001".to_string()));
}

#[test]
fn test_typestate_validate_into_convenience_method() {
    use tempfile::tempdir;

    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let config_path = temp_dir.path().join("test.toml");

    let config_content = r#"
[global]
enable = ["MD022"]

[MD022]
lines_above = 2
"#;
    std::fs::write(&config_path, config_content).expect("Failed to write config");

    let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
        .expect("Should load config");

    let default_config = Config::default();
    let all_rules = crate::rules::all_rules(&default_config);
    let registry = RuleRegistry::from_rules(&all_rules);

    // Use the convenience method that validates and converts in one step
    let (config, warnings) = loaded.validate_into(&registry).expect("Should validate and convert");

    // Should have no warnings for valid config
    assert!(warnings.is_empty(), "Should have no warnings for valid config");

    // Config should be usable
    assert!(config.global.enable.contains(&"MD022".to_string()));
}

#[test]
fn test_resolve_rule_name_canonical() {
    // Canonical IDs should resolve to themselves
    assert_eq!(resolve_rule_name("MD001"), "MD001");
    assert_eq!(resolve_rule_name("MD013"), "MD013");
    assert_eq!(resolve_rule_name("MD069"), "MD069");
}

#[test]
fn test_resolve_rule_name_aliases() {
    // Aliases should resolve to canonical IDs
    assert_eq!(resolve_rule_name("heading-increment"), "MD001");
    assert_eq!(resolve_rule_name("line-length"), "MD013");
    assert_eq!(resolve_rule_name("no-bare-urls"), "MD034");
    assert_eq!(resolve_rule_name("ul-style"), "MD004");
}

#[test]
fn test_resolve_rule_name_case_insensitive() {
    // Case should not matter
    assert_eq!(resolve_rule_name("HEADING-INCREMENT"), "MD001");
    assert_eq!(resolve_rule_name("Heading-Increment"), "MD001");
    assert_eq!(resolve_rule_name("md001"), "MD001");
    assert_eq!(resolve_rule_name("MD001"), "MD001");
}

#[test]
fn test_resolve_rule_name_underscore_to_hyphen() {
    // Underscores should be converted to hyphens
    assert_eq!(resolve_rule_name("heading_increment"), "MD001");
    assert_eq!(resolve_rule_name("line_length"), "MD013");
    assert_eq!(resolve_rule_name("no_bare_urls"), "MD034");
}

#[test]
fn test_resolve_rule_name_unknown() {
    // Unknown names should fall back to normalization
    assert_eq!(resolve_rule_name("custom-rule"), "custom-rule");
    assert_eq!(resolve_rule_name("CUSTOM_RULE"), "custom-rule");
    assert_eq!(resolve_rule_name("md999"), "MD999"); // Looks like an MD rule
}

#[test]
fn test_resolve_rule_names_basic() {
    let result = resolve_rule_names("MD001,line-length,heading-increment");
    assert!(result.contains("MD001"));
    assert!(result.contains("MD013")); // line-length
    // Note: heading-increment also resolves to MD001, so set should contain MD001 and MD013
    assert_eq!(result.len(), 2);
}

#[test]
fn test_resolve_rule_names_with_whitespace() {
    let result = resolve_rule_names("  MD001 , line-length , MD034  ");
    assert!(result.contains("MD001"));
    assert!(result.contains("MD013"));
    assert!(result.contains("MD034"));
    assert_eq!(result.len(), 3);
}

#[test]
fn test_resolve_rule_names_empty_entries() {
    let result = resolve_rule_names("MD001,,MD013,");
    assert!(result.contains("MD001"));
    assert!(result.contains("MD013"));
    assert_eq!(result.len(), 2);
}

#[test]
fn test_resolve_rule_names_empty_string() {
    let result = resolve_rule_names("");
    assert!(result.is_empty());
}

#[test]
fn test_resolve_rule_names_mixed() {
    // Mix of canonical IDs, aliases, and unknown
    let result = resolve_rule_names("MD001,line-length,custom-rule");
    assert!(result.contains("MD001"));
    assert!(result.contains("MD013"));
    assert!(result.contains("custom-rule"));
    assert_eq!(result.len(), 3);
}

// =========================================================================
// Unit tests for is_valid_rule_name() and validate_cli_rule_names()
// =========================================================================

#[test]
fn test_is_valid_rule_name_canonical() {
    // Valid canonical rule IDs
    assert!(is_valid_rule_name("MD001"));
    assert!(is_valid_rule_name("MD013"));
    assert!(is_valid_rule_name("MD041"));
    assert!(is_valid_rule_name("MD069"));

    // Case insensitive
    assert!(is_valid_rule_name("md001"));
    assert!(is_valid_rule_name("Md001"));
    assert!(is_valid_rule_name("mD001"));
}

#[test]
fn test_is_valid_rule_name_aliases() {
    // Valid aliases
    assert!(is_valid_rule_name("line-length"));
    assert!(is_valid_rule_name("heading-increment"));
    assert!(is_valid_rule_name("no-bare-urls"));
    assert!(is_valid_rule_name("ul-style"));

    // Case insensitive
    assert!(is_valid_rule_name("LINE-LENGTH"));
    assert!(is_valid_rule_name("Line-Length"));

    // Underscore variant
    assert!(is_valid_rule_name("line_length"));
    assert!(is_valid_rule_name("ul_style"));
}

#[test]
fn test_is_valid_rule_name_special_all() {
    assert!(is_valid_rule_name("all"));
    assert!(is_valid_rule_name("ALL"));
    assert!(is_valid_rule_name("All"));
    assert!(is_valid_rule_name("aLl"));
}

#[test]
fn test_is_valid_rule_name_invalid() {
    // Non-existent rules
    assert!(!is_valid_rule_name("MD000"));
    assert!(!is_valid_rule_name("MD002")); // gap in numbering
    assert!(!is_valid_rule_name("MD006")); // gap in numbering
    assert!(!is_valid_rule_name("MD999"));
    assert!(!is_valid_rule_name("MD100"));

    // Invalid formats
    assert!(!is_valid_rule_name(""));
    assert!(!is_valid_rule_name("INVALID"));
    assert!(!is_valid_rule_name("not-a-rule"));
    assert!(!is_valid_rule_name("random-text"));
    assert!(!is_valid_rule_name("abc"));

    // Edge cases
    assert!(!is_valid_rule_name("MD"));
    assert!(!is_valid_rule_name("MD1"));
    assert!(!is_valid_rule_name("MD12"));
}

#[test]
fn test_validate_cli_rule_names_valid() {
    // All valid - should return no warnings
    let warnings = validate_cli_rule_names(
        Some("MD001,MD013"),
        Some("line-length"),
        Some("heading-increment"),
        Some("all"),
        None,
        None,
    );
    assert!(warnings.is_empty(), "Expected no warnings for valid rules");
}

#[test]
fn test_validate_cli_rule_names_invalid() {
    // Invalid rule in --enable
    let warnings = validate_cli_rule_names(Some("abc"), None, None, None, None, None);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("Unknown rule in --enable: abc"));

    // Invalid rule in --disable
    let warnings = validate_cli_rule_names(None, Some("xyz"), None, None, None, None);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("Unknown rule in --disable: xyz"));

    // Invalid rule in --extend-enable
    let warnings = validate_cli_rule_names(None, None, Some("nonexistent"), None, None, None);
    assert_eq!(warnings.len(), 1);
    assert!(
        warnings[0]
            .message
            .contains("Unknown rule in --extend-enable: nonexistent")
    );

    // Invalid rule in --extend-disable
    let warnings = validate_cli_rule_names(None, None, None, Some("fake-rule"), None, None);
    assert_eq!(warnings.len(), 1);
    assert!(
        warnings[0]
            .message
            .contains("Unknown rule in --extend-disable: fake-rule")
    );

    // Invalid rule in --fixable
    let warnings = validate_cli_rule_names(None, None, None, None, Some("not-a-rule"), None);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("Unknown rule in --fixable: not-a-rule"));

    // Invalid rule in --unfixable
    let warnings = validate_cli_rule_names(None, None, None, None, None, Some("bogus"));
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("Unknown rule in --unfixable: bogus"));
}

#[test]
fn test_validate_cli_rule_names_mixed() {
    // Mix of valid and invalid
    let warnings = validate_cli_rule_names(Some("MD001,abc,MD003"), None, None, None, None, None);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("abc"));
}

#[test]
fn test_validate_cli_rule_names_suggestions() {
    // Typo should suggest correction
    let warnings = validate_cli_rule_names(Some("line-lenght"), None, None, None, None, None);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message.contains("did you mean"));
    assert!(warnings[0].message.contains("line-length"));
}

#[test]
fn test_validate_cli_rule_names_none() {
    // All None - should return no warnings
    let warnings = validate_cli_rule_names(None, None, None, None, None, None);
    assert!(warnings.is_empty());
}

#[test]
fn test_validate_cli_rule_names_empty_string() {
    // Empty strings should produce no warnings
    let warnings = validate_cli_rule_names(Some(""), Some(""), Some(""), Some(""), Some(""), Some(""));
    assert!(warnings.is_empty());
}

#[test]
fn test_validate_cli_rule_names_whitespace() {
    // Whitespace handling
    let warnings = validate_cli_rule_names(Some("  MD001  ,  MD013  "), None, None, None, None, None);
    assert!(warnings.is_empty(), "Whitespace should be trimmed");
}

#[test]
fn test_validate_cli_rule_names_fixable_valid() {
    // Valid fixable and unfixable rules
    let warnings = validate_cli_rule_names(None, None, None, None, Some("MD001,MD013"), Some("MD040"));
    assert!(
        warnings.is_empty(),
        "Expected no warnings for valid fixable/unfixable rules"
    );
}

#[test]
fn test_all_implemented_rules_have_aliases() {
    // This test ensures we don't forget to add aliases when adding new rules.
    // If this test fails, add the missing rule to RULE_ALIAS_MAP in config.rs
    // with both the canonical entry (e.g., "MD071" => "MD071") and an alias
    // (e.g., "BLANK-LINE-AFTER-FRONTMATTER" => "MD071").

    // Get all implemented rules from the rules module
    let config = crate::config::Config::default();
    let all_rules = crate::rules::all_rules(&config);

    let mut missing_rules = Vec::new();
    for rule in &all_rules {
        let rule_name = rule.name();
        // Check if the canonical entry exists in RULE_ALIAS_MAP
        if resolve_rule_name_alias(rule_name).is_none() {
            missing_rules.push(rule_name.to_string());
        }
    }

    assert!(
        missing_rules.is_empty(),
        "The following rules are missing from RULE_ALIAS_MAP: {:?}\n\
             Add entries like:\n\
             - Canonical: \"{}\" => \"{}\"\n\
             - Alias: \"RULE-NAME-HERE\" => \"{}\"",
        missing_rules,
        missing_rules.first().unwrap_or(&"MDxxx".to_string()),
        missing_rules.first().unwrap_or(&"MDxxx".to_string()),
        missing_rules.first().unwrap_or(&"MDxxx".to_string()),
    );
}

// ==================== to_relative_display_path Tests ====================

#[test]
fn test_relative_path_in_cwd() {
    // Create a temp file in the current directory
    let cwd = std::env::current_dir().unwrap();
    let test_path = cwd.join("test_file.md");
    fs::write(&test_path, "test").unwrap();

    let result = super::to_relative_display_path(test_path.to_str().unwrap());

    // Should be relative (just the filename)
    assert_eq!(result, "test_file.md");

    // Cleanup
    fs::remove_file(&test_path).unwrap();
}

#[test]
fn test_relative_path_in_subdirectory() {
    // Create a temp file in a subdirectory
    let cwd = std::env::current_dir().unwrap();
    let subdir = cwd.join("test_subdir_for_relative_path");
    fs::create_dir_all(&subdir).unwrap();
    let test_path = subdir.join("test_file.md");
    fs::write(&test_path, "test").unwrap();

    let result = super::to_relative_display_path(test_path.to_str().unwrap());

    // Should be relative path with subdirectory
    assert_eq!(result, "test_subdir_for_relative_path/test_file.md");

    // Cleanup
    fs::remove_file(&test_path).unwrap();
    fs::remove_dir(&subdir).unwrap();
}

#[test]
fn test_relative_path_outside_cwd_returns_original() {
    // Use a path that's definitely outside CWD (root level)
    let outside_path = "/tmp/definitely_not_in_cwd_test.md";

    let result = super::to_relative_display_path(outside_path);

    // Can't make relative to CWD, should return original
    // (unless CWD happens to be /tmp, which is unlikely in tests)
    let cwd = std::env::current_dir().unwrap();
    if !cwd.starts_with("/tmp") {
        assert_eq!(result, outside_path);
    }
}

#[test]
fn test_relative_path_already_relative() {
    // Already relative path that doesn't exist
    let relative_path = "some/relative/path.md";

    let result = super::to_relative_display_path(relative_path);

    // Should return original since it can't be canonicalized
    assert_eq!(result, relative_path);
}

#[test]
fn test_relative_path_with_dot_components() {
    // Path with . and .. components
    let cwd = std::env::current_dir().unwrap();
    let test_path = cwd.join("test_dot_component.md");
    fs::write(&test_path, "test").unwrap();

    // Create path with redundant ./
    let dotted_path = cwd.join(".").join("test_dot_component.md");
    let result = super::to_relative_display_path(dotted_path.to_str().unwrap());

    // Should resolve to clean relative path
    assert_eq!(result, "test_dot_component.md");

    // Cleanup
    fs::remove_file(&test_path).unwrap();
}

#[test]
fn test_relative_path_empty_string() {
    let result = super::to_relative_display_path("");

    // Empty string should return empty string
    assert_eq!(result, "");
}

// ───── `enable = []` semantics ─────

#[test]
fn test_empty_enable_list_is_explicit_rumdl_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
enable = []
disable = ["MD013"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();

    // enable = [] should be treated as explicitly set (not Default)
    assert_ne!(
        sourced.global.enable.source,
        ConfigSource::Default,
        "Empty enable = [] should change source from Default (it was explicitly set)"
    );

    let config: Config = sourced.into_validated_unchecked().into();

    // enable should be empty and explicit → disables all rules
    assert!(config.global.enable.is_empty());
    assert!(config.global.enable_is_explicit);

    // disable should still be parsed
    assert_eq!(config.global.disable, vec!["MD013".to_string()]);
}

#[test]
fn test_empty_enable_list_is_explicit_pyproject() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
enable = []
disable = ["MD033"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();

    // enable = [] should be treated as explicitly set
    assert_ne!(
        sourced.global.enable.source,
        ConfigSource::Default,
        "Empty enable = [] in pyproject.toml should change source from Default"
    );
}

#[test]
fn test_enable_all_keyword_rumdl_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
enable = ["ALL"]
disable = ["MD013"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // enable should contain "ALL"
    assert!(config.global.enable.iter().any(|s| s.eq_ignore_ascii_case("all")));
    // disable should still be parsed
    assert_eq!(config.global.disable, vec!["MD013".to_string()]);
}

#[test]
fn test_enable_all_keyword_pyproject() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
enable = ["ALL"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(config.global.enable.iter().any(|s| s.eq_ignore_ascii_case("all")));
}

#[test]
fn test_nonempty_enable_list_still_works_rumdl_toml() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join(".rumdl.toml");
    let config_content = r#"
[global]
enable = ["MD001", "MD003"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();

    // Non-empty enable list should change source from Default
    assert_ne!(
        sourced.global.enable.source,
        ConfigSource::Default,
        "Non-empty enable list should override Default source"
    );

    let config: Config = sourced.into_validated_unchecked().into();
    assert_eq!(config.global.enable.len(), 2);
    assert!(config.global.enable.contains(&"MD001".to_string()));
    assert!(config.global.enable.contains(&"MD003".to_string()));
}

#[test]
fn test_nonempty_enable_list_still_works_pyproject() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("pyproject.toml");
    let config_content = r#"
[tool.rumdl]
enable = ["MD001", "MD003"]
"#;
    fs::write(&config_path, config_content).unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();

    assert_ne!(
        sourced.global.enable.source,
        ConfigSource::Default,
        "Non-empty enable list in pyproject.toml should override Default source"
    );

    let config: Config = sourced.into_validated_unchecked().into();
    assert_eq!(config.global.enable.len(), 2);
}

// ==================== extends tests ====================

#[test]
fn test_extends_basic_inheritance() {
    // Parent config disables MD013, child extends it without overriding disable
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013"]
line-length = 120
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
extend-disable = ["MD036"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Parent's disable should be inherited
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "Parent's disable should be inherited"
    );
    // Child's extend-disable should be present
    assert!(
        config.global.extend_disable.contains(&"MD036".to_string()),
        "Child's extend-disable should be present"
    );
    // Parent's line-length should be inherited
    assert_eq!(config.global.line_length.get(), 120);
}

#[test]
fn test_extends_child_overrides_parent() {
    // Child explicitly sets disable, which replaces parent's disable
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013", "MD033"]
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
disable = ["MD041"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Child's disable replaces parent's
    assert_eq!(config.global.disable, vec!["MD041".to_string()]);
}

#[test]
fn test_extends_additive_extend_enable() {
    // Both parent and child have extend-enable — values should accumulate
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
extend-enable = ["MD060"]
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
extend-enable = ["MD063"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Both extend-enable values should be present (union semantics)
    assert!(
        config.global.extend_enable.contains(&"MD060".to_string()),
        "Parent's extend-enable should be preserved"
    );
    assert!(
        config.global.extend_enable.contains(&"MD063".to_string()),
        "Child's extend-enable should be added"
    );
}

#[test]
fn test_extends_chain_three_levels() {
    // A extends B extends C — all three contribute settings
    let temp_dir = tempdir().unwrap();

    let grandparent_path = temp_dir.path().join("grandparent.toml");
    fs::write(
        &grandparent_path,
        r#"
[global]
line-length = 80
extend-enable = ["MD060"]
"#,
    )
    .unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        format!(
            r#"extends = "{}"

[global]
extend-enable = ["MD063"]
"#,
            grandparent_path.display()
        ),
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
extend-disable = ["MD013"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Grandparent's line-length should be inherited through chain
    assert_eq!(config.global.line_length.get(), 80);
    // Both grandparent and parent's extend-enable should accumulate
    assert!(config.global.extend_enable.contains(&"MD060".to_string()));
    assert!(config.global.extend_enable.contains(&"MD063".to_string()));
    // Child's extend-disable
    assert!(config.global.extend_disable.contains(&"MD013".to_string()));
}

#[test]
fn test_extends_circular_detection() {
    // A extends B, B extends A → should error
    let temp_dir = tempdir().unwrap();

    let a_path = temp_dir.path().join("a.toml");
    let b_path = temp_dir.path().join("b.toml");

    fs::write(
        &a_path,
        format!(
            r#"extends = "{}"

[global]
disable = ["MD013"]
"#,
            b_path.display()
        ),
    )
    .unwrap();

    fs::write(
        &b_path,
        format!(
            r#"extends = "{}"

[global]
disable = ["MD033"]
"#,
            a_path.display()
        ),
    )
    .unwrap();

    let result = SourcedConfig::load_with_discovery(Some(a_path.to_str().unwrap()), None, true);
    assert!(result.is_err(), "Circular extends should produce an error");
    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Circular extends") || err_msg.contains("circular"),
        "Error should mention circular: {err_msg}"
    );
}

#[test]
fn test_extends_self_reference() {
    // A extends A → circular error
    let temp_dir = tempdir().unwrap();

    let a_path = temp_dir.path().join("a.toml");
    fs::write(
        &a_path,
        format!(
            r#"extends = "{}"

[global]
disable = ["MD013"]
"#,
            a_path.display()
        ),
    )
    .unwrap();

    let result = SourcedConfig::load_with_discovery(Some(a_path.to_str().unwrap()), None, true);
    assert!(result.is_err(), "Self-referencing extends should produce an error");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("Circular extends") || err_msg.contains("circular"),
        "Error should mention circular: {err_msg}"
    );
}

#[test]
fn test_extends_depth_limit() {
    // Create a chain of 12 configs (exceeds limit of 10)
    let temp_dir = tempdir().unwrap();

    let mut paths = Vec::new();
    for i in 0..12 {
        paths.push(temp_dir.path().join(format!("config_{i}.toml")));
    }

    // Write the leaf config (no extends)
    fs::write(
        &paths[11],
        r#"
[global]
disable = ["MD013"]
"#,
    )
    .unwrap();

    // Write configs 1-10, each extending the next
    for i in (0..11).rev() {
        fs::write(
            &paths[i],
            format!(
                r#"extends = "{}"

[global]
extend-disable = ["MD{:03}"]
"#,
                paths[i + 1].display(),
                i + 1
            ),
        )
        .unwrap();
    }

    let result = SourcedConfig::load_with_discovery(Some(paths[0].to_str().unwrap()), None, true);
    assert!(result.is_err(), "Deep extends chain should produce an error");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("maximum depth") || err_msg.contains("depth"),
        "Error should mention depth: {err_msg}"
    );
}

#[test]
fn test_extends_relative_path() {
    // Child in subdirectory extends parent using relative path
    let temp_dir = tempdir().unwrap();
    let sub_dir = temp_dir.path().join("subdir");
    fs::create_dir(&sub_dir).unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013"]
"#,
    )
    .unwrap();

    let child_path = sub_dir.join(".rumdl.toml");
    fs::write(
        &child_path,
        r#"extends = "../parent.toml"

[global]
extend-disable = ["MD033"]
"#,
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Parent's disable inherited via relative path
    assert!(config.global.disable.contains(&"MD013".to_string()));
    // Child's extend-disable
    assert!(config.global.extend_disable.contains(&"MD033".to_string()));
}

#[test]
fn test_extends_missing_file() {
    let temp_dir = tempdir().unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        r#"extends = "nonexistent.toml"

[global]
disable = ["MD013"]
"#,
    )
    .unwrap();

    let result = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true);
    assert!(result.is_err(), "Missing extends target should produce an error");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("not found") || err_msg.contains("nonexistent"),
        "Error should mention file not found: {err_msg}"
    );
}

#[test]
fn test_extends_pyproject_toml() {
    // pyproject.toml with extends at [tool.rumdl] level
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013"]
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join("pyproject.toml");
    fs::write(
        &child_path,
        format!(
            r#"
[tool.rumdl]
extends = "{}"
extend-disable = ["MD033"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Parent's disable inherited
    assert!(config.global.disable.contains(&"MD013".to_string()));
    // Child's extend-disable
    assert!(config.global.extend_disable.contains(&"MD033".to_string()));
}

#[test]
fn test_extends_pyproject_child_overrides_rumdl_parent() {
    // pyproject child should override parent replace-fields from extended rumdl config
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013", "MD033"]
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join("pyproject.toml");
    fs::write(
        &child_path,
        format!(
            r#"
[tool.rumdl]
extends = "{}"
disable = ["MD041"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Child's disable should replace parent's disable
    assert_eq!(config.global.disable, vec!["MD041".to_string()]);
}

#[test]
fn test_extends_rule_specific_override() {
    // Parent sets MD007 indent to 4, child overrides to 2
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[MD007]
indent = 4
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[MD007]
indent = 2
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Child's rule config should override parent's
    let indent_val = get_rule_config_value::<i64>(&config, "MD007", "indent");
    assert_eq!(indent_val, Some(2), "Child should override parent's MD007 indent");
}

#[test]
fn test_extends_rule_inherited_when_not_overridden() {
    // Parent sets MD007 indent to 4, child does not set MD007 at all
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[MD007]
indent = 4
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
disable = ["MD013"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    // Parent's rule config should be inherited
    let indent_val = get_rule_config_value::<i64>(&config, "MD007", "indent");
    assert_eq!(indent_val, Some(4), "Parent's MD007 indent should be inherited");
}

#[test]
fn test_extends_loaded_files_tracking() {
    // Verify that both parent and child appear in loaded_files
    let temp_dir = tempdir().unwrap();

    let parent_path = temp_dir.path().join("parent.toml");
    fs::write(
        &parent_path,
        r#"
[global]
disable = ["MD013"]
"#,
    )
    .unwrap();

    let child_path = temp_dir.path().join(".rumdl.toml");
    fs::write(
        &child_path,
        format!(
            r#"extends = "{}"

[global]
extend-disable = ["MD033"]
"#,
            parent_path.display()
        ),
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery(Some(child_path.to_str().unwrap()), None, true).unwrap();

    // Both files should appear in loaded_files
    assert!(
        sourced.loaded_files.len() >= 2,
        "Both parent and child should be in loaded_files, got: {:?}",
        sourced.loaded_files
    );
    assert!(
        sourced.loaded_files.iter().any(|f| f.contains("parent.toml")),
        "parent.toml should be in loaded_files"
    );
    assert!(
        sourced.loaded_files.iter().any(|f| f.contains(".rumdl.toml")),
        ".rumdl.toml should be in loaded_files"
    );
}

#[test]
fn test_extends_base_values_propagate_when_child_silent() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("base.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();
    fs::write(dir.path().join(".rumdl.toml"), "extends = \"base.toml\"\n").unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.disable, vec!["MD013".to_string()]);
}

#[test]
fn test_extends_child_disable_replaces_base() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("base.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();
    fs::write(
        dir.path().join(".rumdl.toml"),
        "extends = \"base.toml\"\n[global]\ndisable = [\"MD001\"]\n",
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.disable, vec!["MD001".to_string()]);
}

#[test]
fn test_extends_three_level_chain_propagates_from_root() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("root.toml"), "[global]\ndisable = [\"MD013\"]\n").unwrap();
    fs::write(dir.path().join("middle.toml"), "extends = \"root.toml\"\n").unwrap();
    fs::write(dir.path().join(".rumdl.toml"), "extends = \"middle.toml\"\n").unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert_eq!(config.global.disable, vec!["MD013".to_string()]);
}

#[test]
fn test_extends_rule_config_inherits_from_base() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("base.toml"), "[MD013]\nline-length = 120\n").unwrap();
    fs::write(dir.path().join(".rumdl.toml"), "extends = \"base.toml\"\n").unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(line_length, Some(120));
}

#[test]
fn test_extends_child_rule_config_overrides_base() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("base.toml"), "[MD013]\nline-length = 100\n").unwrap();
    fs::write(
        dir.path().join(".rumdl.toml"),
        "extends = \"base.toml\"\n[MD013]\nline-length = 160\n",
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
    assert_eq!(line_length, Some(160));
}

#[test]
fn test_extends_enable_wins_over_inherited_disable() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("base.toml"),
        "[global]\ndisable = [\"MD013\", \"MD001\"]\n",
    )
    .unwrap();
    fs::write(
        dir.path().join(".rumdl.toml"),
        "extends = \"base.toml\"\n[global]\nenable = [\"MD001\"]\n",
    )
    .unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    )
    .unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    assert!(
        !config.global.disable.contains(&"MD001".to_string()),
        "MD001 should not be disabled when explicitly enabled"
    );
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "MD013 should still be disabled (only MD001 was re-enabled)"
    );
}

#[test]
fn test_extends_cycle_returns_error() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("a.toml"), "extends = \"b.toml\"\n").unwrap();
    fs::write(dir.path().join("b.toml"), "extends = \"a.toml\"\n").unwrap();

    let result = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join("a.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    );

    assert!(
        matches!(result, Err(ConfigError::CircularExtends { .. })),
        "Expected CircularExtends error, got: {result:?}"
    );
}

#[test]
fn test_extends_missing_file_returns_error() {
    let dir = tempdir().unwrap();
    fs::write(dir.path().join(".rumdl.toml"), "extends = \"nonexistent.toml\"\n").unwrap();

    let result = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(".rumdl.toml").to_str().unwrap()),
        None,
        true,
        None,
        None,
    );

    assert!(
        matches!(result, Err(ConfigError::ExtendsNotFound { .. })),
        "Expected ExtendsNotFound error, got: {result:?}"
    );
}

#[test]
fn test_extends_depth_limit_returns_error() {
    let dir = tempdir().unwrap();
    // Build MAX_EXTENDS_DEPTH + 1 levels so the loader hits the depth guard.
    // Mirrors MAX_EXTENDS_DEPTH = 10 from src/config/loading.rs.
    let max_depth: usize = 10;
    fs::write(dir.path().join("level_0.toml"), "[global]\n").unwrap();
    for i in 1..=max_depth {
        fs::write(
            dir.path().join(format!("level_{i}.toml")),
            format!("extends = \"level_{}.toml\"\n", i - 1),
        )
        .unwrap();
    }

    let result = SourcedConfig::load_with_discovery_impl(
        Some(dir.path().join(format!("level_{max_depth}.toml")).to_str().unwrap()),
        None,
        true,
        None,
        None,
    );

    assert!(
        matches!(result, Err(ConfigError::ExtendsDepthExceeded { .. })),
        "Expected ExtendsDepthExceeded error, got: {result:?}"
    );
}

#[serial_test::serial]
#[test]
fn test_user_config_loaded_alongside_markdownlint_config() {
    // When a markdownlint project config is discovered, the user config
    // must also be loaded as a base layer so rumdl-specific settings apply.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // User config sets a rumdl-specific setting (flavor) that markdownlint cannot express
    let user_config_dir = temp_dir.path().join("user_config");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    fs::write(rumdl_config_dir.join("rumdl.toml"), "[global]\nflavor = \"mkdocs\"\n").unwrap();

    // Project directory has a .markdownlint.yaml that disables MD013
    let project_dir = temp_dir.path().join("project");
    fs::create_dir_all(&project_dir).unwrap();
    fs::write(project_dir.join(".markdownlint.yaml"), "MD013: false\n").unwrap();

    env::set_current_dir(&project_dir).unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    env::set_current_dir(&original_dir).unwrap();

    // Markdownlint config setting must apply
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "Markdownlint config should disable MD013, got disable={:?}",
        config.global.disable
    );

    // User config setting must also apply (rumdl-specific, not expressible in markdownlint format)
    assert_eq!(
        config.global.flavor,
        MarkdownFlavor::MkDocs,
        "User config flavor should be loaded alongside markdownlint project config"
    );
}

#[serial_test::serial]
#[test]
fn test_user_config_settings_apply_when_markdownlint_present() {
    // User config settings that markdownlint does not override must still apply
    // after the fix (user config is loaded as a base layer).
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    // User config sets a non-default line-length
    let user_config_dir = temp_dir.path().join("user_config2");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    fs::write(rumdl_config_dir.join("rumdl.toml"), "[global]\nline-length = 200\n").unwrap();

    // Project directory has a .markdownlint.yaml that does NOT set line-length
    let project_dir = temp_dir.path().join("project2");
    fs::create_dir_all(&project_dir).unwrap();
    fs::write(project_dir.join(".markdownlint.yaml"), "default: true\n").unwrap();

    env::set_current_dir(&project_dir).unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    env::set_current_dir(&original_dir).unwrap();

    // Without the fix: user config never loaded → line-length stays at default (80)
    // With the fix: user config loaded → line-length = 200
    assert_eq!(
        config.global.line_length.get(),
        200,
        "User config line-length should apply when markdownlint project config is present"
    );
}

#[serial_test::serial]
#[test]
fn test_markdownlint_config_overrides_user_config_on_conflict() {
    // When user config and markdownlint project config set the same field,
    // the markdownlint config (ProjectConfig, precedence 3) must win over
    // user config (UserConfig, precedence 1) via merge_override.
    //
    // Scenario: user wants MD001 disabled; the project's markdownlint config
    // disables MD013 instead. The project's disable list replaces the user's.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    let user_config_dir = temp_dir.path().join("user_config3");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    fs::write(rumdl_config_dir.join("rumdl.toml"), "[global]\ndisable = [\"MD001\"]\n").unwrap();

    // Markdownlint config disables MD013, does not mention MD001
    let project_dir = temp_dir.path().join("project3");
    fs::create_dir_all(&project_dir).unwrap();
    fs::write(project_dir.join(".markdownlint.yaml"), "MD013: false\n").unwrap();

    env::set_current_dir(&project_dir).unwrap();

    let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None).unwrap();
    let config: Config = sourced.into_validated_unchecked().into();

    env::set_current_dir(&original_dir).unwrap();

    // Markdownlint disable list has higher precedence and replaces the user config's list
    assert!(
        config.global.disable.contains(&"MD013".to_string()),
        "Markdownlint config should disable MD013, got disable={:?}",
        config.global.disable
    );
    assert!(
        !config.global.disable.contains(&"MD001".to_string()),
        "Markdownlint config's disable list replaces user config's; MD001 should not be disabled, got disable={:?}",
        config.global.disable
    );
}

#[serial_test::serial]
#[test]
fn test_user_config_applies_when_markdownlint_config_is_malformed() {
    // When the discovered markdownlint config fails to parse, the user config
    // that was already loaded as a base layer must still apply.
    use std::env;

    let temp_dir = tempdir().unwrap();
    let original_dir = env::current_dir().unwrap();

    let user_config_dir = temp_dir.path().join("user_config_malformed");
    let rumdl_config_dir = user_config_dir.join("rumdl");
    fs::create_dir_all(&rumdl_config_dir).unwrap();
    fs::write(rumdl_config_dir.join("rumdl.toml"), "[global]\nflavor = \"obsidian\"\n").unwrap();

    let project_dir = temp_dir.path().join("project_malformed");
    fs::create_dir_all(&project_dir).unwrap();
    // Unclosed YAML mapping — guaranteed parse failure
    fs::write(project_dir.join(".markdownlint.yaml"), "{ not: [valid yaml\n").unwrap();

    env::set_current_dir(&project_dir).unwrap();

    let result = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir), None);

    env::set_current_dir(&original_dir).unwrap();

    // Load must succeed — a bad markdownlint file is not a fatal error
    let config: Config = result
        .expect("load_with_discovery_impl should succeed even with malformed markdownlint config")
        .into_validated_unchecked()
        .into();

    // User config flavor must still apply because it was loaded before the parse attempt
    assert_eq!(
        config.global.flavor,
        MarkdownFlavor::Obsidian,
        "User config flavor should apply when markdownlint config is malformed"
    );
}