rumdl 0.1.78

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
use rumdl_lib::lint_context::LintContext;
use rumdl_lib::rule::Rule;
use rumdl_lib::rules::MD057ExistingRelativeLinks;
use std::fs::File;
use std::io::Write;
use tempfile::tempdir;

#[test]
fn test_missing_links() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create an existing file
    let exists_path = base_path.join("exists.md");
    File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();

    // Create test content with both existing and missing links
    let content = r#"
# Test Document

[Valid Link](exists.md)
[Invalid Link](missing.md)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have one warning for the missing link
    assert_eq!(result.len(), 1, "Expected 1 warning, got {}", result.len());
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md, got: {}",
        result[0].message
    );
}

#[test]
fn test_external_links() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create test content with external links
    let content = r#"
# Test Document with External Links

[Google](https://www.google.com)
[Example](http://example.com)
[Email](mailto:test@example.com)
[Domain](example.com)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have no warnings for external links
    assert_eq!(result.len(), 0, "Expected 0 warnings, got {}", result.len());
}

#[test]
fn test_special_uri_schemes() {
    // Issue #192: Special URI schemes should not be flagged as broken relative links
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Test Document with Special URI Schemes

[Local file](file:///path/to/file)
[Network share](smb://example.com/path/to/share)
[Mac App Store](macappstores://apps.apple.com/)
[Phone](tel:+1234567890)
[Data URI](data:text/plain;base64,SGVsbG8=)
[SSH](ssh://git@github.com/repo)
[Git](git://github.com/repo.git)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Expected no warnings for special URI schemes, got: {result:?}"
    );
}

#[test]
fn test_code_blocks() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create test content with links in code blocks
    let content = r#"
# Test Document

[Invalid Link](missing.md)

```markdown
[Another Invalid Link](also-missing.md)
```
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only have one warning for the link outside the code block
    assert_eq!(result.len(), 1, "Expected 1 warning, got {}", result.len());
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md, got: {}",
        result[0].message
    );

    // Make sure the link in the code block is not flagged
    for warning in &result {
        assert!(
            !warning.message.contains("also-missing.md"),
            "Found unexpected warning for link in code block: {}",
            warning.message
        );
    }
}

#[test]
fn test_disabled_rule() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create test content with disabled rule
    let content = r#"
# Test Document

<!-- markdownlint-disable MD057 -->
[Invalid Link](missing.md)
<!-- markdownlint-enable MD057 -->

[Another Invalid Link](also-missing.md)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule - note: this tests the single-file check() method
    // which doesn't have access to inline config filtering (that happens
    // in lint_and_index()). The cross-file check in run_cross_file_checks()
    // now respects inline config stored in FileIndex.
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // The check() method returns all warnings; filtering happens later
    // when running through lint_and_index() or run_cross_file_checks()
    assert_eq!(
        result.len(),
        2,
        "Expected 2 warnings from check(), got {}",
        result.len()
    );

    // Check that both links are flagged
    let has_missing = result.iter().any(|w| w.message.contains("missing.md"));
    let has_also_missing = result.iter().any(|w| w.message.contains("also-missing.md"));

    assert!(has_missing, "Missing warning for 'missing.md'");
    assert!(has_also_missing, "Missing warning for 'also-missing.md'");
}

#[test]
fn test_complex_paths() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create a nested directory structure
    let nested_dir = base_path.join("docs");
    std::fs::create_dir(&nested_dir).unwrap();

    // Create some existing files
    let exists_path = nested_dir.join("exists.md");
    File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();

    // Create test content with various path formats
    let content = r#"
# Test Document with Complex Paths

[Valid Nested Link](docs/exists.md)
[Missing Nested Link](docs/missing.md)
[Missing Directory](missing-dir/file.md)
[Parent Directory Link](../file.md)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have warnings for missing links but not for valid links
    assert_eq!(result.len(), 3, "Expected 3 warnings, got {}", result.len());

    // Check for specific warnings
    let has_missing_nested = result.iter().any(|w| w.message.contains("docs/missing.md"));
    let has_missing_dir = result.iter().any(|w| w.message.contains("missing-dir/file.md"));
    let has_parent_dir = result.iter().any(|w| w.message.contains("../file.md"));

    assert!(has_missing_nested, "Missing warning for 'docs/missing.md'");
    assert!(has_missing_dir, "Missing warning for 'missing-dir/file.md'");
    assert!(has_parent_dir, "Missing warning for '../file.md'");

    // Check that the valid link is not flagged
    for warning in &result {
        assert!(
            !warning.message.contains("docs/exists.md"),
            "Found unexpected warning for valid link: {}",
            warning.message
        );
    }
}

#[test]
fn test_no_base_path() {
    // Create test content with links
    let content = r#"
# Test Document

[Link](missing.md)
"#;

    // Initialize rule without setting a base path
    let rule = MD057ExistingRelativeLinks::new();

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have no warnings when no base path is set
    assert_eq!(
        result.len(),
        0,
        "Expected 0 warnings when no base path is set, got {}",
        result.len()
    );
}

#[test]
fn test_fragment_links() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create a file with headings to link to
    let test_file_path = base_path.join("test_file.md");
    let test_content = r#"
# Main Heading

## Sub Heading One

Some content here.

## Sub Heading Two

More content.
"#;
    File::create(&test_file_path)
        .unwrap()
        .write_all(test_content.as_bytes())
        .unwrap();

    // Create content with internal fragment links to the same document
    let content = r#"
# Test Document

- [Link to Heading](#main-heading)
- [Link to Sub Heading](#sub-heading-one)
- [Link to External File](other_file.md#some-heading)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have one warning for external file link only (fragment-only links are skipped)
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for external file link, got {}",
        result.len()
    );

    // Check that the external link is flagged
    let has_other_file = result.iter().any(|w| w.message.contains("other_file.md"));
    assert!(has_other_file, "Missing warning for 'other_file.md'");
}

#[test]
fn test_combined_links() {
    // Create a temporary directory for test files
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create an existing file and a missing file with fragments
    let exists_path = base_path.join("exists.md");
    File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();

    // Create content with combined file and fragment links
    let content = r#"
# Test Document

- [Link to existing file with fragment](exists.md#section)
- [Link to missing file with fragment](missing.md#section)
- [Link to fragment only](#local-section)
"#;

    // Initialize rule with the base path
    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

    // Test the rule
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only have one warning for the missing file link with fragment
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for missing file with fragment, got {}",
        result.len()
    );
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md, got: {}",
        result[0].message
    );

    // Make sure the existing file with fragment and fragment-only links are not flagged
    for warning in &result {
        assert!(
            !warning.message.contains("exists.md#section"),
            "Found unexpected warning for existing file with fragment: {}",
            warning.message
        );
        assert!(
            !warning.message.contains("#local-section"),
            "Found unexpected warning for fragment-only link: {}",
            warning.message
        );
    }
}

/// Test that each file resolves links relative to its own directory.
/// This is a regression test for issue #190 where the base_path was being
/// cached in the rule instance and incorrectly reused across files.
#[test]
fn test_multi_file_base_path_isolation() {
    // Create a temporary directory structure:
    // temp/
    //   dir1/
    //     index.md  -> [link](sub/file.md)
    //     sub/
    //       file.md  <- EXISTS
    //   dir2/
    //     index.md  -> [link](sub/file.md)
    //     (sub/ does NOT exist)
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create dir1 structure with existing file
    let dir1 = base_path.join("dir1");
    let dir1_sub = dir1.join("sub");
    std::fs::create_dir_all(&dir1_sub).unwrap();
    File::create(dir1_sub.join("file.md"))
        .unwrap()
        .write_all(b"# File in dir1/sub")
        .unwrap();

    // Create dir2 structure WITHOUT the sub/file.md
    let dir2 = base_path.join("dir2");
    std::fs::create_dir_all(&dir2).unwrap();

    // Both files have the same relative link
    let content = "[Link](sub/file.md)\n";

    // Create a single rule instance (simulating how rules are reused across files)
    let rule = MD057ExistingRelativeLinks::new();

    // Test dir1/index.md - should have NO warnings (file exists)
    let dir1_file = dir1.join("index.md");
    let ctx1 = LintContext::new(
        content,
        rumdl_lib::config::MarkdownFlavor::Standard,
        Some(dir1_file.clone()),
    );
    let result1 = rule.check(&ctx1).unwrap();
    assert_eq!(
        result1.len(),
        0,
        "dir1/index.md should have no warnings because dir1/sub/file.md exists, got: {:?}",
        result1.iter().map(|w| &w.message).collect::<Vec<_>>()
    );

    // Test dir2/index.md - should have ONE warning (file does not exist)
    let dir2_file = dir2.join("index.md");
    let ctx2 = LintContext::new(
        content,
        rumdl_lib::config::MarkdownFlavor::Standard,
        Some(dir2_file.clone()),
    );
    let result2 = rule.check(&ctx2).unwrap();
    assert_eq!(
        result2.len(),
        1,
        "dir2/index.md should have 1 warning because dir2/sub/file.md does NOT exist, got: {:?}",
        result2.iter().map(|w| &w.message).collect::<Vec<_>>()
    );

    // Now test in reverse order to ensure no caching issues either way
    let rule2 = MD057ExistingRelativeLinks::new();

    // Test dir2 first this time
    let ctx2_again = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, Some(dir2_file));
    let result2_again = rule2.check(&ctx2_again).unwrap();
    assert_eq!(
        result2_again.len(),
        1,
        "dir2 should still have 1 warning when processed first"
    );

    // Then test dir1
    let ctx1_again = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, Some(dir1_file));
    let result1_again = rule2.check(&ctx1_again).unwrap();
    assert_eq!(
        result1_again.len(),
        0,
        "dir1 should still have 0 warnings when processed second (regression test for issue #190)"
    );
}

#[test]
fn test_query_parameters_stripped() {
    // Issue #198: URLs with query parameters like ?raw=true should be handled correctly
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create an existing image file
    let image_path = base_path.join("image.png");
    File::create(&image_path)
        .unwrap()
        .write_all(b"fake image data")
        .unwrap();

    // Test content with query parameters
    let content = r#"
# Test Document

![Embed link to raw image](image.png?raw=true)
![Another image](path/to/image.jpg?raw=true&version=1)
[Link with query](document.md?raw=true)
[Link with fragment](document.md#section)
[Link with both](document.md?raw=true#section)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only warn about missing files, not about image.png?raw=true (file exists)
    // Should warn about path/to/image.jpg?raw=true (file doesn't exist)
    // Should warn about document.md (file doesn't exist)
    let messages: Vec<_> = result.iter().map(|w| w.message.as_str()).collect();

    // image.png exists, so no warning for that
    assert!(
        !messages.iter().any(|m| m.contains("image.png?raw=true")),
        "Should not warn about existing file with query parameter"
    );

    // path/to/image.jpg doesn't exist
    assert!(
        messages.iter().any(|m| m.contains("path/to/image.jpg?raw=true")),
        "Should warn about missing file with query parameter"
    );

    // document.md doesn't exist (should warn regardless of query/fragment)
    assert!(
        messages.iter().any(|m| m.contains("document.md")),
        "Should warn about missing document.md"
    );
}

// =============================================================================
// Extension-less links with fragments tests
// =============================================================================

/// Test that extension-less links with fragments resolve correctly when .md file exists
#[test]
fn test_extensionless_link_with_fragment_to_existing_md_file() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create docs/guide.md
    let docs_dir = base_path.join("docs");
    std::fs::create_dir_all(&docs_dir).unwrap();
    File::create(docs_dir.join("guide.md"))
        .unwrap()
        .write_all(b"# Guide\n\n## Installation\n")
        .unwrap();

    let content = r#"
# Test

[Link to guide](docs/guide#installation)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Should not warn about extension-less link when .md file exists: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test multiple extension-less link patterns
#[test]
fn test_extensionless_link_patterns() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create various files
    File::create(base_path.join("readme.md"))
        .unwrap()
        .write_all(b"# Readme")
        .unwrap();
    File::create(base_path.join("CONTRIBUTING.md"))
        .unwrap()
        .write_all(b"# Contributing")
        .unwrap();

    let docs_dir = base_path.join("docs");
    std::fs::create_dir_all(&docs_dir).unwrap();
    File::create(docs_dir.join("api.md"))
        .unwrap()
        .write_all(b"# API")
        .unwrap();

    let content = r#"
# Test Extension-less Links

[Readme](readme#section)
[Contributing](CONTRIBUTING#how-to)
[API Docs](docs/api#methods)
[Missing](missing#section)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only warn about the missing file
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for missing file, got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        result[0].message.contains("missing"),
        "Expected warning about 'missing', got: {}",
        result[0].message
    );
}

/// Test extension-less links without fragments (should still work)
#[test]
fn test_extensionless_link_without_fragment() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    File::create(base_path.join("guide.md"))
        .unwrap()
        .write_all(b"# Guide")
        .unwrap();

    // Note: Extension-less links without fragments may or may not resolve
    // depending on the file system and context. This test documents current behavior.
    let content = "[Link](guide)\n";

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // With extension-less resolution, guide -> guide.md should work
    assert!(
        result.is_empty(),
        "Extension-less link to existing .md file should resolve: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

// =============================================================================
// Rustdoc backtick-wrapped URL tests
// =============================================================================

/// Test that rustdoc intra-doc links are not flagged
#[test]
fn test_rustdoc_backtick_links_not_flagged() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Rust Documentation

See [`f32::is_subnormal`] for details on subnormal floats.

Check [`Vec::push`] for adding elements.

The [`Result::unwrap`] method panics on error.

[`f32::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_subnormal
[`Vec::push`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push
[`Result::unwrap`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Rustdoc backtick links should not be flagged: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test various rustdoc link patterns
#[test]
fn test_rustdoc_link_patterns() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Rustdoc Link Patterns

- [`panic!`] - macro
- [`Option`] - type
- [`std::fmt`] - module
- [`Iterator::next`] - trait method
- [`String::new`] - associated function
- [`Error`] - trait
- [`Err`] - enum variant
- [`Formatter`] - struct
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Rustdoc backtick reference links should not be flagged: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that regular broken links are still flagged alongside rustdoc links
#[test]
fn test_rustdoc_links_mixed_with_regular_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    File::create(base_path.join("existing.md"))
        .unwrap()
        .write_all(b"# Existing")
        .unwrap();

    let content = r#"
# Mixed Links

See [`Vec::push`] for details.

[Valid link](existing.md)
[Broken link](missing.md)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only warn about missing.md, not rustdoc links or existing.md
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning, got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md"
    );
}

/// Test inline rustdoc links (not reference style)
#[test]
fn test_rustdoc_inline_backtick_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Inline Rustdoc Links

Check [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html) for details.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Inline rustdoc links with external URLs should not be flagged: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

// =============================================================================
// Duplicate warning prevention tests
// =============================================================================

/// Test that malformed links don't produce duplicate warnings
#[test]
fn test_no_duplicate_warnings_for_malformed_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Content with malformed link that could potentially match multiple patterns
    let content = r#"
# Test

[Broken link](missing.md)
[Another broken](also-missing.md)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Count warnings per line
    let mut line_counts = std::collections::HashMap::new();
    for warning in &result {
        *line_counts.entry(warning.line).or_insert(0) += 1;
    }

    // Each line should have at most one warning
    for (line, count) in &line_counts {
        assert_eq!(*count, 1, "Line {line} has {count} warnings, expected at most 1");
    }
}

/// Test that reference-style links don't produce duplicate warnings
#[test]
fn test_no_duplicate_warnings_for_reference_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Test

[Link text][ref]
[Another][ref]

[ref]: missing.md
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should not have duplicate warnings for the same reference definition
    let messages: Vec<_> = result.iter().map(|w| &w.message).collect();

    // Allow multiple warnings if they're on different lines, but not duplicates
    assert!(
        result.len() <= 3,
        "Too many warnings, possible duplicates: {messages:?}"
    );
}

/// Test complex document with multiple link types doesn't produce duplicates
#[test]
fn test_complex_document_no_duplicates() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    File::create(base_path.join("exists.md"))
        .unwrap()
        .write_all(b"# Exists")
        .unwrap();

    let content = r#"
# Complex Document

[Valid](exists.md)
[Missing](missing.md)
[Fragment only](#section)
[External](https://example.com)
[Missing with fragment](missing.md#section)

## References

[ref1]: missing.md
[ref2]: exists.md
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Count warnings per file reference
    let mut file_warnings: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for warning in &result {
        // Extract the file path from the warning message
        if warning.message.contains("missing.md") {
            *file_warnings.entry("missing.md".to_string()).or_insert(0) += 1;
        }
    }

    // missing.md appears multiple times in content but shouldn't produce excessive warnings
    let missing_count = file_warnings.get("missing.md").unwrap_or(&0);
    assert!(
        *missing_count <= 3,
        "Too many warnings for missing.md ({missing_count}), possible duplicates"
    );
}

// =============================================================================
// LaTeX math span tests (Issue #289)
// =============================================================================

/// Test that link-like patterns inside single-line display math are not flagged
/// Issue #289: MD057 incorrectly triggers on LaTeX math formulas like $[x](\zeta)$
#[test]
fn test_latex_single_line_display_math_not_flagged() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Z-transform formula that looks like a markdown link
    let content = r#"
# Z-Transform

$$X(\zeta) = \mathcal Z [x](\zeta) = \sum_k x(k) \zeta^{-k}$$
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "LaTeX display math should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that link-like patterns inside inline math are not flagged
#[test]
fn test_latex_inline_math_not_flagged() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Inline Math

The function $[x](\zeta)$ represents the evaluation.

Also check $f[n](x)$ and $g[k](t)$ for more examples.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "LaTeX inline math should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that link-like patterns inside multi-line math blocks are not flagged
#[test]
fn test_latex_multiline_math_block_not_flagged() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Multi-line Math

$$
X(\zeta) = \mathcal Z [x](\zeta) = \sum_k x(k) \zeta^{-k}
$$

And another:

$$
[f](x) = \int_0^1 f(t) dt
$$
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "LaTeX multi-line math blocks should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that real broken links outside math are still flagged
#[test]
fn test_latex_math_mixed_with_real_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create an existing file
    File::create(base_path.join("exists.md"))
        .unwrap()
        .write_all(b"# Test")
        .unwrap();

    let content = r#"
# Mixed Content

The formula $$[x](\zeta)$$ is LaTeX math.

[Valid link](exists.md)
[Broken link](missing.md)

Inline math $[f](x)$ in text.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only flag the real broken link
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for missing.md, got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md"
    );
}

/// Test various LaTeX patterns that look like markdown links
#[test]
fn test_latex_link_like_patterns() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# LaTeX Patterns

- Evaluation: $[f](x)$
- Z-transform: $$\mathcal{Z}[x](z)$$
- Laplace: $\mathcal{L}[f](s)$
- Fourier: $$\mathcal{F}[g](\omega)$$
- Interval notation: $[a, b](c)$
- Set notation: $$[0, 1](x)$$
- Bracket function: $[n](k)$
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Various LaTeX patterns should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that adjacent math and real links are handled correctly
#[test]
fn test_latex_adjacent_to_real_links() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    File::create(base_path.join("doc.md"))
        .unwrap()
        .write_all(b"# Doc")
        .unwrap();

    let content = r#"
# Adjacent Content

See $[f](x)$ and [doc](doc.md) for details.

The formula $$[g](y)$$ appears before [missing](missing.md).
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should only flag the real broken link, not math
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for missing.md, got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        result[0].message.contains("missing.md"),
        "Expected warning about missing.md"
    );
}

/// Test math in code blocks is handled correctly (double protection)
#[test]
fn test_latex_math_in_code_block() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Code Example

```latex
$$[x](\zeta) = \sum_k x(k)$$
```

Regular text here.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Math in code blocks should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test complex document from issue #289
#[test]
fn test_issue_289_exact_example() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Exact content from issue #289
    let content = r#"$$X(\zeta) = \mathcal Z [x](\zeta) = \sum_k x(k) \zeta^{-k}$$"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Issue #289 example should not trigger MD057. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test that currency patterns are not treated as math (pulldown-cmark behavior)
#[test]
fn test_latex_currency_not_confused_with_math() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Currency patterns - pulldown-cmark requires balanced $ for math
    // $100 alone is not math, but $100$ would be
    let content = r#"
# Prices

The item costs $100 and [link](missing.md) is broken.

A range of $50-$100 is typical.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // The broken link should still be flagged (currency $ doesn't hide it)
    assert_eq!(
        result.len(),
        1,
        "Currency patterns shouldn't affect link detection. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

/// Test escaped dollar signs
#[test]
fn test_latex_escaped_dollar_signs() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Escaped Dollars

Use \$100 for escaped currency and [link](missing.md) is broken.

Real math: $[f](x)$ should be skipped.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Only the broken link should be flagged
    assert_eq!(
        result.len(),
        1,
        "Only missing.md should be flagged. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

/// Test math inside HTML comments (should be ignored - HTML comment takes precedence)
#[test]
fn test_latex_math_in_html_comment() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# HTML Comment

<!-- This has math $[x](y)$ and link [z](missing.md) inside comment -->

Real broken [link](missing.md) here.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Only the link outside the comment should be flagged
    assert_eq!(
        result.len(),
        1,
        "Only link outside HTML comment should be flagged. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test unbalanced/malformed math delimiters
#[test]
fn test_latex_unbalanced_delimiters() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Unbalanced $ should not be treated as math
    let content = r#"
# Unbalanced

Text with single $ sign and [link](missing.md) broken.

Also $$unclosed and [another](also-missing.md) broken.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Both broken links should be flagged since math is unbalanced
    assert_eq!(
        result.len(),
        2,
        "Unbalanced math shouldn't hide broken links. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

/// Test environment variable patterns ($PATH, $HOME)
#[test]
fn test_latex_env_var_patterns() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Environment Variables

Set $PATH and $HOME correctly. See [link](missing.md).

Real math $[f](x)$ is different.
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Only the broken link should be flagged
    assert_eq!(
        result.len(),
        1,
        "Env vars shouldn't affect link detection. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

/// Test math spans at document boundaries
#[test]
fn test_latex_math_at_boundaries() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Math at very start and end of document
    let content = r#"$[start](x)$ middle [link](missing.md) end $[end](y)$"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Only the broken link in the middle should be flagged
    assert_eq!(
        result.len(),
        1,
        "Math at boundaries should work correctly. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

/// Test nested-looking math patterns
#[test]
fn test_latex_nested_brackets() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"
# Nested Brackets in Math

Matrix: $$[[a](b)](c)$$

Function composition: $[f \circ g](x)$

Real broken: [link](missing.md)
"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Nested brackets in math should be handled. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

/// Test consecutive math spans
#[test]
fn test_latex_consecutive_math_spans() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = r#"$[a](x)$$[b](y)$$[c](z)$ and [broken](missing.md)"#;

    let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Consecutive math spans should all be detected. Got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(result[0].message.contains("missing.md"));
}

// --- Tests for AbsoluteLinksOption::RelativeToDocs ---

use rumdl_lib::rules::{AbsoluteLinksOption, MD057Config};
use std::fs;

/// Helper to create a MkDocs project structure with mkdocs.yml and docs_dir.
/// Returns the path to the docs directory.
fn setup_mkdocs_project(temp_dir: &std::path::Path, docs_dir_name: &str) -> std::path::PathBuf {
    let mkdocs_content = if docs_dir_name != "docs" {
        format!("site_name: test\ndocs_dir: {docs_dir_name}\n")
    } else {
        "site_name: test\n".to_string()
    };
    fs::write(temp_dir.join("mkdocs.yml"), mkdocs_content).unwrap();

    let docs_dir = temp_dir.join(docs_dir_name);
    fs::create_dir_all(&docs_dir).unwrap();
    docs_dir
}

#[test]
fn test_relative_to_docs_resolves_valid_link() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Create the target file
    fs::write(docs_dir.join("getting-started.md"), "# Getting Started").unwrap();

    let content = "[Guide](/getting-started.md)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Expected no warnings for valid absolute link, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_flags_missing_link() {
    let temp_dir = tempdir().unwrap();
    let _docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let content = "[Missing](/nonexistent.md)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config)
        .with_path(temp_dir.path().join("docs"));
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(result.len(), 1, "Expected 1 warning, got: {result:?}");
    assert!(
        result[0].message.contains("does not exist"),
        "Expected 'does not exist' in message, got: {}",
        result[0].message
    );
    assert!(
        result[0].message.contains("/nonexistent.md"),
        "Expected '/nonexistent.md' in message, got: {}",
        result[0].message
    );
}

#[test]
fn test_relative_to_docs_extensionless_link() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Create the target file with .md extension
    fs::write(docs_dir.join("guide.md"), "# Guide").unwrap();

    let content = "[Guide](/guide)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Extensionless link should resolve to guide.md, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_fallback_without_mkdocs_yml() {
    // Create a temp dir without mkdocs.yml
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = "[Link](/some-page)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning (fallback to warn), got: {result:?}"
    );
    assert!(
        result[0].message.contains("no mkdocs.yml found"),
        "Expected fallback message, got: {}",
        result[0].message
    );
}

#[test]
fn test_relative_to_docs_custom_docs_dir() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "documentation");

    // Create the target file
    fs::write(docs_dir.join("index.md"), "# Home").unwrap();

    let content = "[Home](/index.md)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Custom docs_dir should be respected, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_with_fragment() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Create the target file
    fs::write(docs_dir.join("guide.md"), "# Guide\n## Section").unwrap();

    let content = "[Guide Section](/guide.md#section)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Fragment should be stripped before file check, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_image() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Create an image file
    let img_dir = docs_dir.join("assets");
    fs::create_dir_all(&img_dir).unwrap();
    fs::write(img_dir.join("logo.png"), "PNG").unwrap();

    let content = "![Logo](/assets/logo.png)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Image absolute link should resolve via docs_dir, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_image_missing() {
    let temp_dir = tempdir().unwrap();
    let _docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let content = "![Missing](/assets/missing.png)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config)
        .with_path(temp_dir.path().join("docs"));
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(result.len(), 1, "Expected 1 warning for missing image, got: {result:?}");
    assert!(result[0].message.contains("does not exist"));
}

#[test]
fn test_relative_to_docs_reference_definition() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    fs::write(docs_dir.join("api.md"), "# API").unwrap();

    let content = "[api]: /api.md\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Reference definition with valid absolute link should pass, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_directory_index() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Create a directory with index.md
    let sub_dir = docs_dir.join("getting-started");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("index.md"), "# Getting Started").unwrap();

    let content = "[Getting Started](/getting-started/)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Directory link with index.md should pass, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_directory_without_index() {
    // Directory exists but has no index.md — should warn
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let sub_dir = docs_dir.join("empty-section");
    fs::create_dir_all(&sub_dir).unwrap();
    // No index.md inside

    let content = "[Empty](/empty-section/)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Directory without index.md should warn, got: {result:?}"
    );
    assert!(
        result[0].message.contains("no index.md"),
        "Message should mention missing index.md, got: {}",
        result[0].message
    );
}

#[test]
fn test_relative_to_docs_directory_without_trailing_slash() {
    // Link to directory path without trailing slash — directory has index.md
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let sub_dir = docs_dir.join("guide");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("index.md"), "# Guide").unwrap();

    let content = "[Guide](/guide)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Directory link without trailing slash should resolve via index.md, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_nested_subdirectory() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let nested = docs_dir.join("api").join("v2");
    fs::create_dir_all(&nested).unwrap();
    fs::write(nested.join("reference.md"), "# API v2 Reference").unwrap();

    let content = "[API Ref](/api/v2/reference.md)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Nested subdirectory link should resolve, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_url_encoded_path() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    fs::write(docs_dir.join("my guide.md"), "# My Guide").unwrap();

    let content = "[Guide](/my%20guide.md)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "URL-encoded absolute link should resolve, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_root_link() {
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    // Root link "/" should check for docs/index.md
    fs::write(docs_dir.join("index.md"), "# Home").unwrap();

    let content = "[Home](/)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Root link '/' should resolve to docs/index.md, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_root_link_missing_index() {
    let temp_dir = tempdir().unwrap();
    let _docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");
    // No index.md in docs/

    let content = "[Home](/)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config)
        .with_path(temp_dir.path().join("docs"));
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Root link without index.md should warn, got: {result:?}"
    );
}

#[test]
fn test_existing_ignore_and_warn_unchanged() {
    // Regression test: existing ignore/warn behavior unchanged
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = "[Link](/absolute-path)\n";

    // Test ignore (default)
    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::Ignore,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();
    assert!(result.is_empty(), "Ignore should produce no warnings, got: {result:?}");

    // Test warn
    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::Warn,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();
    assert_eq!(result.len(), 1, "Warn should produce 1 warning, got: {result:?}");
    assert!(
        result[0].message.contains("cannot be validated locally"),
        "Warn message should say 'cannot be validated locally', got: {}",
        result[0].message
    );
}

#[test]
fn test_absolute_links_config_deserialization() {
    // Verify all AbsoluteLinksOption variants deserialize correctly from TOML
    let toml_ignore: MD057Config = toml::from_str(r#"absolute-links = "ignore""#).unwrap();
    assert_eq!(toml_ignore.absolute_links, AbsoluteLinksOption::Ignore);

    let toml_warn: MD057Config = toml::from_str(r#"absolute-links = "warn""#).unwrap();
    assert_eq!(toml_warn.absolute_links, AbsoluteLinksOption::Warn);

    let toml_rtd: MD057Config = toml::from_str(r#"absolute-links = "relative_to_docs""#).unwrap();
    assert_eq!(toml_rtd.absolute_links, AbsoluteLinksOption::RelativeToDocs);

    // Also verify the snake_case alias works
    let toml_alias: MD057Config = toml::from_str(r#"absolute_links = "relative_to_docs""#).unwrap();
    assert_eq!(toml_alias.absolute_links, AbsoluteLinksOption::RelativeToDocs);

    // Default should be Ignore
    let toml_default: MD057Config = toml::from_str("").unwrap();
    assert_eq!(toml_default.absolute_links, AbsoluteLinksOption::Ignore);
}

#[test]
fn test_relative_to_docs_html_fallback() {
    // /page.html should resolve when page.md exists (HTML-to-markdown source fallback)
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    fs::write(docs_dir.join("about.md"), "# About").unwrap();

    let content = "[About](/about.html)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "HTML link should resolve via markdown source fallback, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_html_fallback_missing() {
    // /page.html should warn when neither page.html nor page.md exists
    let temp_dir = tempdir().unwrap();
    let _docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let content = "[Missing](/nonexistent.html)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config)
        .with_path(temp_dir.path().join("docs"));
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(result.len(), 1, "Missing HTML link should warn, got: {result:?}");
    assert!(result[0].message.contains("does not exist"));
}

#[test]
fn test_relative_to_docs_query_parameter() {
    // Query parameters should be stripped before checking file existence
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    fs::write(docs_dir.join("page.md"), "# Page").unwrap();

    let content = "[Page](/page.md?v=2&ref=nav)\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Query parameters should be stripped, got: {result:?}"
    );
}

#[test]
fn test_relative_to_docs_mixed_links() {
    // Multiple absolute links: some valid, some broken
    let temp_dir = tempdir().unwrap();
    let docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    fs::write(docs_dir.join("exists.md"), "# Exists").unwrap();

    let content = "\
[Valid](/exists.md)
[Missing1](/does-not-exist.md)
[Missing2](/also-missing)
";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        2,
        "Expected 2 warnings for broken links, valid link should pass, got: {result:?}"
    );
    assert!(result.iter().any(|w| w.message.contains("does-not-exist")));
    assert!(result.iter().any(|w| w.message.contains("also-missing")));
}

#[test]
fn test_relative_to_docs_reference_definition_missing() {
    // Reference definition with broken absolute link
    let temp_dir = tempdir().unwrap();
    let _docs_dir = setup_mkdocs_project(temp_dir.path(), "docs");

    let content = "[missing-ref]: /nonexistent-page.md\n";

    let config = MD057Config {
        absolute_links: AbsoluteLinksOption::RelativeToDocs,
        ..Default::default()
    };
    let rule = rumdl_lib::rules::MD057ExistingRelativeLinks::from_config_struct(config)
        .with_path(temp_dir.path().join("docs"));
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::MkDocs, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        1,
        "Missing ref def absolute link should warn, got: {result:?}"
    );
    assert!(result[0].message.contains("does not exist"));
}

// =============================================================================
// compact-paths tests (Issue #391)
// =============================================================================

fn make_compact_paths_config() -> MD057Config {
    MD057Config {
        compact_paths: true,
        ..Default::default()
    }
}

#[test]
fn test_compact_paths_disabled_by_default() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create sub_dir/file.md
    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    // From sub_dir/, ../sub_dir/file.md is unnecessarily long
    let content = "[link](../sub_dir/file.md)\n";

    // Default config — compact_paths is false
    let rule = MD057ExistingRelativeLinks::new().with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    // Should have no compact-paths warnings (feature disabled)
    assert!(
        result.iter().all(|w| !w.message.contains("simplified")),
        "Default config should not produce compact-paths warnings, got: {result:?}"
    );
}

#[test]
fn test_compact_paths_same_directory() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create sub_dir/file.md
    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    // From sub_dir/, link goes up then back into sub_dir
    let content = "[link](../sub_dir/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_dot_prefix() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("file.md"), "# File").unwrap();

    // ./file.md can be simplified to file.md
    let content = "[link](./file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning for ./file.md, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_deep_traversal() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create a/sub/file.md
    let deep_dir = base_path.join("a").join("sub");
    fs::create_dir_all(&deep_dir).unwrap();
    fs::write(deep_dir.join("file.md"), "# File").unwrap();

    // From a/sub/, ../../a/sub/file.md → file.md
    let content = "[link](../../a/sub/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&deep_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning for deep traversal, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_already_optimal() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create sibling/file.md
    let sub_dir = base_path.join("sub_dir");
    let sibling_dir = base_path.join("sibling");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::create_dir_all(&sibling_dir).unwrap();
    fs::write(sibling_dir.join("file.md"), "# File").unwrap();

    // From sub_dir/, ../sibling/file.md is already optimal
    let content = "[link](../sibling/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert!(
        compact_warnings.is_empty(),
        "Already optimal path should produce no compact-paths warnings, got: {compact_warnings:?}"
    );
}

#[test]
fn test_compact_paths_with_fragment() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File\n## Section").unwrap();

    // Fragment should be preserved in suggestion
    let content = "[link](../sub_dir/file.md#section)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md#section'"),
        "Should preserve fragment in suggestion, got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_with_query() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    // Query parameter should be preserved in suggestion
    let content = "[link](../sub_dir/file.md?v=1)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md?v=1'"),
        "Should preserve query in suggestion, got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_with_query_and_fragment() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File\n## Section").unwrap();

    // Both query and fragment should be preserved
    let content = "[link](../sub_dir/file.md?v=1#section)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md?v=1#section'"),
        "Should preserve both query and fragment in suggestion, got: {}",
        compact_warnings[0].message
    );

    // Verify fix also preserves both
    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(
        fixed, "[link](file.md?v=1#section)\n",
        "Fix should preserve query and fragment"
    );
}

#[test]
fn test_compact_paths_images() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("image.png"), "PNG data").unwrap();

    let content = "![img](../sub_dir/image.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning for image, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'image.png'"),
        "Should suggest 'image.png', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_reference_defs() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    let content = "[ref]: ../sub_dir/file.md\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Expected 1 compact-paths warning for ref def, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_nonexistent_file() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    // Do NOT create file.md — it doesn't exist

    // Should still warn about unnecessary traversal even if target is missing
    let content = "[link](../sub_dir/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    let broken_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("does not exist")).collect();

    assert_eq!(
        compact_warnings.len(),
        1,
        "Should still warn about path traversal, got: {compact_warnings:?}"
    );
    assert_eq!(
        broken_warnings.len(),
        1,
        "Should also warn about broken link, got: {broken_warnings:?}"
    );
}

#[test]
fn test_compact_paths_external_urls_skipped() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = "[link](https://example.com/../path)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "External URLs should not be checked for compact-paths, got: {result:?}"
    );
}

#[test]
fn test_compact_paths_fragment_only_skipped() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let content = "[link](#section)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Fragment-only links should not be checked, got: {result:?}"
    );
}

#[test]
fn test_compact_paths_plain_relative_no_warning() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("file.md"), "# File").unwrap();

    // file.md has no traversal — should not warn
    let content = "[link](file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert!(
        result.is_empty(),
        "Plain relative paths should not produce compact-paths warnings, got: {result:?}"
    );
}

#[test]
fn test_compact_paths_necessary_parent_traversal() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // Create structure: sub/child/ and file.md at root
    let sub_child = base_path.join("sub").join("child");
    fs::create_dir_all(&sub_child).unwrap();
    fs::write(base_path.join("file.md"), "# File").unwrap();

    // From sub/child/, ../../file.md is already the shortest path to root/file.md
    let content = "[link](../../file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_child);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert!(
        compact_warnings.is_empty(),
        "Necessary parent traversal should not produce compact-paths warnings, got: {compact_warnings:?}"
    );
}

#[test]
fn test_compact_paths_mixed_traversal() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    // ./sub/../file.md normalizes to file.md
    fs::write(base_path.join("file.md"), "# File").unwrap();
    fs::create_dir_all(base_path.join("sub")).unwrap();

    let content = "[link](./sub/../file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Mixed traversal should produce compact-paths warning, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_fix_produces_correct_output() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    let content = "[link](../sub_dir/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(fixed, "[link](file.md)\n", "Fix should replace path with compact form");
}

#[test]
fn test_compact_paths_fix_preserves_fragment() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File\n## Section").unwrap();

    let content = "[link](../sub_dir/file.md#section)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(fixed, "[link](file.md#section)\n", "Fix should preserve fragment");
}

#[test]
fn test_compact_paths_config_deserialization() {
    // Default: compact-paths should be false
    let config: MD057Config = toml::from_str("").unwrap();
    assert!(!config.compact_paths, "compact_paths should default to false");

    // Kebab-case
    let config: MD057Config = toml::from_str("compact-paths = true").unwrap();
    assert!(config.compact_paths, "kebab-case should work");

    // Snake_case alias
    let config: MD057Config = toml::from_str("compact_paths = true").unwrap();
    assert!(config.compact_paths, "snake_case alias should work");
}

#[test]
fn test_compact_paths_warning_positions() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    // "Some text [link](../sub_dir/file.md) more" — URL starts at column 18
    let content = "Some text [link](../sub_dir/file.md) more\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(compact_warnings.len(), 1);
    assert_eq!(compact_warnings[0].line, 1, "Should be on line 1");
    // URL "../sub_dir/file.md" starts at byte 17 (0-indexed), column 18 (1-indexed)
    assert!(
        compact_warnings[0].column > 1,
        "Column should reflect URL position, not start of line, got: {}",
        compact_warnings[0].column
    );
}

#[test]
fn test_compact_paths_multiple_links_fix() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("a.md"), "# A").unwrap();
    fs::write(sub_dir.join("b.md"), "# B").unwrap();
    fs::write(sub_dir.join("c.md"), "# C").unwrap();

    let content = "\
[first](../sub_dir/a.md)
[second](../sub_dir/b.md)
[third](../sub_dir/c.md)
";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);

    let result = rule.check(&ctx).unwrap();
    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        3,
        "All three links should have compact-paths warnings"
    );

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(
        fixed, "[first](a.md)\n[second](b.md)\n[third](c.md)\n",
        "All three links should be compacted without corruption"
    );
}

#[test]
fn test_compact_paths_unicode_before_link() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.md"), "# File").unwrap();

    // Multi-byte characters before the link test byte-offset calculation
    let content = "日本語テキスト [link](../sub_dir/file.md)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);

    let result = rule.check(&ctx).unwrap();
    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(compact_warnings.len(), 1);

    // Fix should work correctly despite multi-byte characters preceding the link
    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(
        fixed, "日本語テキスト [link](file.md)\n",
        "Fix should handle multi-byte characters correctly"
    );
}

#[test]
fn test_compact_paths_dot_prefix_image() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("img.png"), "PNG").unwrap();

    let content = "![alt](./img.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Image with ./ prefix should warn, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'img.png'"),
        "Should suggest 'img.png', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_dot_prefix_reference_def() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("file.md"), "# File").unwrap();

    let content = "[ref]: ./file.md\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(
        compact_warnings.len(),
        1,
        "Reference def with ./ prefix should warn, got: {compact_warnings:?}"
    );
    assert!(
        compact_warnings[0].message.contains("'file.md'"),
        "Should suggest 'file.md', got: {}",
        compact_warnings[0].message
    );
}

#[test]
fn test_compact_paths_image_fix_produces_correct_output() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub_dir");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("image.png"), "PNG data").unwrap();

    let content = "![my image](../sub_dir/image.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(
        fixed, "![my image](image.png)\n",
        "Image fix should only replace the URL, not corrupt the markdown syntax"
    );
}

#[test]
fn test_compact_paths_image_fix_dot_prefix() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("img.png"), "PNG").unwrap();

    let content = "![alt](./img.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(
        fixed, "![alt](img.png)\n",
        "Image fix with ./ prefix should only replace the URL portion"
    );
}

#[test]
fn test_compact_paths_image_fix_with_text_before() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    let sub_dir = base_path.join("sub");
    fs::create_dir_all(&sub_dir).unwrap();
    fs::write(sub_dir.join("photo.jpg"), "JPEG data").unwrap();

    let content = "Some text before ![photo](../sub/photo.jpg) and after\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&sub_dir);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(
        fixed, "Some text before ![photo](photo.jpg) and after\n",
        "Image fix should preserve surrounding text"
    );
}

#[test]
fn test_compact_paths_image_fix_unicode_before() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("img.png"), "PNG").unwrap();

    let content = "日本語 ![画像](./img.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    assert_eq!(
        fixed, "日本語 ![画像](img.png)\n",
        "Image fix should handle multi-byte characters correctly"
    );
}

#[test]
fn test_compact_paths_image_fix_byte_range_targets_url_only() {
    let temp_dir = tempdir().unwrap();
    let base_path = temp_dir.path();

    fs::write(base_path.join("img.png"), "PNG").unwrap();

    let content = "![alt](./img.png)\n";

    let config = make_compact_paths_config();
    let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    let compact_warnings: Vec<_> = result.iter().filter(|w| w.message.contains("simplified")).collect();
    assert_eq!(compact_warnings.len(), 1);

    let fix = compact_warnings[0].fix.as_ref().expect("Should have a fix");
    let replaced_text = &content[fix.range.clone()];
    assert_eq!(
        replaced_text, "./img.png",
        "Fix range should cover the URL './img.png', not '{replaced_text}'"
    );
}

/// Regression test for rumdl-vscode#109: MD057 must receive source_file
/// via the lint() API to resolve relative links correctly.
///
/// When source_file is None (as it was before the fix), MD057 silently
/// returns no warnings because it can't determine the base directory.
/// When source_file is provided, MD057 resolves links relative to the
/// file's parent directory.
#[test]
fn test_lint_api_passes_source_file_to_md057() {
    let temp_dir = tempdir().unwrap();
    let base = temp_dir.path();

    // Create directory structure:
    //   base/docs/guide.md  (the file being linted)
    //   base/docs/intro.md  (exists - valid link target)
    //   (base/docs/missing.md does NOT exist)
    let docs_dir = base.join("docs");
    std::fs::create_dir_all(&docs_dir).unwrap();

    let guide_path = docs_dir.join("guide.md");
    let content = "# Guide\n\n[Intro](intro.md)\n[Missing](missing.md)\n";
    std::fs::write(&guide_path, content).unwrap();

    let intro_path = docs_dir.join("intro.md");
    std::fs::write(&intro_path, "# Intro\n").unwrap();

    // Configure only MD057
    let mut config = rumdl_lib::config::Config::default();
    config.global.enable = vec!["MD057".to_string()];

    let rules = rumdl_lib::rules::all_rules(&config);
    let filtered = rumdl_lib::rules::filter_rules(&rules, &config.global);

    // With source_file=None, MD057 cannot resolve relative links and returns nothing
    let warnings_without_path = rumdl_lib::lint(
        content,
        &filtered,
        false,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
        Some(&config),
    )
    .unwrap();

    let md057_without: Vec<_> = warnings_without_path
        .iter()
        .filter(|w| w.rule_name.as_deref() == Some("MD057"))
        .collect();
    assert!(
        md057_without.is_empty(),
        "MD057 should produce no warnings when source_file is None (cannot resolve paths), \
         but got {}: {:?}",
        md057_without.len(),
        md057_without.iter().map(|w| &w.message).collect::<Vec<_>>()
    );

    // With source_file=Some(path), MD057 resolves links relative to the file's directory
    let warnings_with_path = rumdl_lib::lint(
        content,
        &filtered,
        false,
        rumdl_lib::config::MarkdownFlavor::Standard,
        Some(guide_path.clone()),
        Some(&config),
    )
    .unwrap();

    let md057_with: Vec<_> = warnings_with_path
        .iter()
        .filter(|w| w.rule_name.as_deref() == Some("MD057"))
        .collect();
    assert_eq!(
        md057_with.len(),
        1,
        "MD057 should report 1 warning for missing.md when source_file is provided, got {}: {:?}",
        md057_with.len(),
        md057_with.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        md057_with[0].message.contains("missing.md"),
        "Warning should mention 'missing.md', got: {}",
        md057_with[0].message
    );
}

/// Regression test for rumdl-vscode#109: compact-paths detection requires source_file.
///
/// The original bug: CLI reported "link can be simplified" but VS Code extension
/// reported "link does not exist" because it wasn't passing the file path.
#[test]
fn test_lint_api_compact_paths_with_source_file() {
    let temp_dir = tempdir().unwrap();
    let base = temp_dir.path();

    // Create directory structure:
    //   base/docs/guide.md       (the file being linted)
    //   base/docs/reference.md   (exists)
    let docs_dir = base.join("docs");
    std::fs::create_dir_all(&docs_dir).unwrap();

    let guide_path = docs_dir.join("guide.md");
    // Link "../docs/reference.md" from within docs/ is redundant - can be simplified to "reference.md"
    let content = "# Guide\n\n[Reference](../docs/reference.md)\n";
    std::fs::write(&guide_path, content).unwrap();

    let reference_path = docs_dir.join("reference.md");
    std::fs::write(&reference_path, "# Reference\n").unwrap();

    // Configure MD057 with compact-paths enabled
    let mut config = rumdl_lib::config::Config::default();
    config.global.enable = vec!["MD057".to_string()];
    let json = serde_json::json!({ "compact-paths": true });
    if let Some(rule_config) = rumdl_lib::rule_config_serde::json_to_rule_config(&json) {
        config.rules.insert("MD057".to_string(), rule_config);
    }

    let rules = rumdl_lib::rules::all_rules(&config);
    let filtered = rumdl_lib::rules::filter_rules(&rules, &config.global);

    // Without source_file: no warnings (MD057 can't resolve)
    let warnings_without = rumdl_lib::lint(
        content,
        &filtered,
        false,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
        Some(&config),
    )
    .unwrap();
    let md057_without: Vec<_> = warnings_without
        .iter()
        .filter(|w| w.rule_name.as_deref() == Some("MD057"))
        .collect();
    assert!(
        md057_without.is_empty(),
        "MD057 should produce no warnings without source_file"
    );

    // With source_file: should detect the compact-paths opportunity
    let warnings_with = rumdl_lib::lint(
        content,
        &filtered,
        false,
        rumdl_lib::config::MarkdownFlavor::Standard,
        Some(guide_path.clone()),
        Some(&config),
    )
    .unwrap();
    let md057_with: Vec<_> = warnings_with
        .iter()
        .filter(|w| w.rule_name.as_deref() == Some("MD057"))
        .collect();
    assert_eq!(
        md057_with.len(),
        1,
        "MD057 should report 1 compact-paths warning, got {}: {:?}",
        md057_with.len(),
        md057_with.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
    assert!(
        md057_with[0].message.contains("simplified"),
        "Warning should mention simplification, got: {}",
        md057_with[0].message
    );
    assert!(
        md057_with[0].message.contains("reference.md"),
        "Warning should mention the simplified path, got: {}",
        md057_with[0].message
    );
}