rumdl 0.1.88

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

#[test]
fn test_valid_link_fragment() {
    // Test internal link (fragment only) - should validate against current document
    let ctx = LintContext::new(
        "# Test Heading\n\nThis is a [link](#test-heading) to the heading.",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert!(result.is_empty());
}

#[test]
fn test_invalid_link_fragment() {
    // Test internal link with wrong fragment - should flag as invalid
    let ctx = LintContext::new(
        "# Test Heading\n\nThis is a [link](#wrong-heading) to the heading.",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert_eq!(result.len(), 1);
}

#[test]
fn test_multiple_headings() {
    // Test internal links to multiple headings
    let ctx = LintContext::new(
        "# First Heading\n\n## Second Heading\n\n[Link 1](#first-heading)\n[Link 2](#second-heading)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert!(result.is_empty());
}

#[test]
fn test_special_characters() {
    // Test internal link with special characters in heading
    let ctx = LintContext::new(
        "# Test & Heading!\n\nThis is a [link](#test--heading) to the heading.",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    // "Test & Heading!" should become "test--heading" (& becomes -- per GitHub spec, ! removed)
    // So the link to #test--heading should be VALID and no warnings should be generated
    assert_eq!(result.len(), 0);
}

#[test]
fn test_no_fragments() {
    let ctx = LintContext::new(
        "# Test Heading\n\nThis is a [link](https://example.com) without fragment.",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert!(result.is_empty());
}

#[test]
fn test_empty_content() {
    let ctx = LintContext::new("", rumdl_lib::config::MarkdownFlavor::Standard, None);
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert!(result.is_empty());
}

#[test]
fn test_multiple_invalid_fragments() {
    // Test multiple internal links with invalid fragments
    let ctx = LintContext::new(
        "# Test Heading\n\n[Link 1](#wrong1)\n[Link 2](#wrong2)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx).unwrap();
    assert_eq!(result.len(), 2);
}

#[test]
fn test_case_sensitivity() {
    let ctx = LintContext::new(
        r#"
# My Heading

[Valid Link](#my-heading)
[Valid Link Different Case](#MY-HEADING)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // Our implementation performs case-insensitive matching for fragments
    assert_eq!(0, warnings.len());

    // Note: this behavior is consistent with most Markdown parsers including
    // GitHub and CommonMark, which treat fragments as case-insensitive
}

#[test]
fn test_complex_heading_structures() {
    // Test internal links with various heading styles (ATX and Setext)
    let ctx = LintContext::new(
        "# Heading 1\n\nSome text\n\nHeading 2\n-------\n\n### Heading 3\n\n[Link to 1](#heading-1)\n[Link to 2](#heading-2)\n[Link to 3](#heading-3)\n[Link to missing](#heading-4)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();

    let result = rule.check(&ctx).unwrap();

    // Only the missing heading should be flagged
    assert_eq!(result.len(), 1);

    // Test with special characters in headings/links
    let ctx = LintContext::new(
        "# Heading & Special! Characters\n\n[Link](#heading--special-characters)\n[Bad Link](#heading-special-characters-bad)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let result = rule.check(&ctx).unwrap();

    // Only the invalid fragment should fail
    assert_eq!(result.len(), 1);
}

#[test]
fn test_heading_id_generation() {
    let ctx = LintContext::new(
        r#"
# Heading 1

[Link with space](#heading-1)
[Link with underscore](#heading-1)
[Link with multiple hyphens](#heading-1)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // All links are valid with our improved heading ID generation,
    // which now follows GitHub's algorithm more closely
    assert_eq!(0, warnings.len());
}

#[test]
fn test_heading_to_fragment_edge_cases() {
    let ctx = LintContext::new(
        "# Heading\n\n# Heading\n\n[Link 1](somepath#heading)\n[Link 2](somepath#heading-1)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();

    let result = rule.check(&ctx).unwrap();
    // Cross-file links should be ignored, so no warnings expected
    assert_eq!(result.len(), 0);

    // Test headings with only special characters
    let ctx = LintContext::new(
        "# @#$%^\n\n[Link](somepath#)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let result = rule.check(&ctx).unwrap();
    assert_eq!(result.len(), 0);

    // Test mixed internal/external links
    let ctx = LintContext::new(
        "# Heading\n\n[Internal](somepath#heading)\n[External](https://example.com#heading)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let result = rule.check(&ctx).unwrap();
    assert_eq!(result.len(), 0);
}

#[test]
fn test_fragment_in_code_blocks() {
    let ctx = LintContext::new(
        "# Real Heading\n\n```markdown\n# Fake Heading\n[Link](somepath#fake-heading)\n```\n\n[Link](somepath#real-heading)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();

    let result = rule.check(&ctx).unwrap();
    println!("Result has {} warnings", result.len());
    for (i, warning) in result.iter().enumerate() {
        println!("Warning {}: line {}, message: {}", i, warning.line, warning.message);
    }

    // With our improved implementation, code blocks are ignored
    assert_eq!(result.len(), 0);

    // Test headings in code blocks (should be ignored)
    let ctx = LintContext::new(
        "```markdown\n# Code Heading\n```\n\n[Link](#code-heading)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let result = rule.check(&ctx).unwrap();
    println!("Second test has {} warnings", result.len());
    for (i, warning) in result.iter().enumerate() {
        println!("Warning {}: line {}, message: {}", i, warning.line, warning.message);
    }

    // Headings in code blocks should be ignored and the link should fail
    assert_eq!(result.len(), 1);
}

#[test]
fn test_fragment_with_complex_content() {
    let ctx = LintContext::new(
        r#"
# Heading with **bold** and *italic*

[Link to heading](#heading-with-bold-and-italic)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // The implementation correctly handles formatting in headings
    // by stripping it when generating fragments, so the link should match
    assert_eq!(
        0,
        warnings.len(),
        "Link should correctly match the heading with stripped formatting"
    );
}

#[test]
fn test_nested_formatting_in_fragments() {
    let ctx = LintContext::new(
        r#"
# Heading with **bold *italic* text**

[Link to heading](#heading-with-bold-italic-text)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // Test that nested formatting is correctly handled
    assert_eq!(
        0,
        warnings.len(),
        "Link should match heading with nested bold and italic formatting"
    );
}

#[test]
fn test_multiple_formatting_styles() {
    let ctx = LintContext::new(
        r#"
# Heading with _underscores_ and **asterisks** mixed

[Link to heading](#heading-with-underscores-and-asterisks-mixed)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // Test that different styles of formatting are handled correctly
    assert_eq!(
        0,
        warnings.len(),
        "Link should match heading with mixed formatting styles"
    );
}

#[test]
fn test_complex_nested_formatting() {
    let ctx = LintContext::new(
        r#"
# **Bold** with *italic* and `code` and [link](https://example.com)

[Link to heading](#bold-with-italic-and-code-and-link)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::with_anchor_style(AnchorStyle::KramdownGfm);
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // Test that complex mixed formatting is handled correctly
    assert_eq!(0, warnings.len(), "Link should match heading with complex formatting");
}

#[test]
fn test_formatting_edge_cases() {
    let ctx = LintContext::new(
        r#"
# Heading with a**partial**bold and *italic with **nested** formatting*

[Link to partial bold](#heading-with-apartialbold-and-italic-with-nested-formatting)
[Link to nested formatting](#heading-with-apartialbold-and-italic-with-nested-formatting)
"#,
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    let rule = MD051LinkFragments::new();
    let result = rule.check(&ctx);
    assert!(result.is_ok());
    let warnings = result.unwrap();

    // This test may require adjustments based on expected behavior
    // The implementation should consistently generate the same fragment ID
    // Note: first link should be correct when partial bold is properly stripped
    assert!(
        warnings.len() <= 1,
        "At least one link should match the heading with partial formatting"
    );
}

#[test]
fn test_performance_md051() {
    let mut content = String::with_capacity(50_000);

    // Add 50 headings
    for i in 0..50 {
        content.push_str(&format!("# Heading {i}\n\n"));
        content.push_str("Some content paragraph with details about this section.\n\n");

        // Add some subheadings
        if i % 3 == 0 {
            content.push_str(&format!("## Subheading {i}.1\n\n"));
            content.push_str("Subheading content with more details.\n\n");
            content.push_str(&format!("## Subheading {i}.2\n\n"));
            content.push_str("More subheading content here.\n\n");
        }
    }

    // Add links section
    content.push_str("# Links Section\n\n");

    // Add 100 links, some valid, some invalid. MD051 only validates fragment-only
    // links (those starting with `#`); links with a path component are treated as
    // external and skipped, so the test URLs must omit the path.
    for i in 0..100 {
        if i % 3 == 0 {
            content.push_str(&format!("[Link to invalid heading](#heading-{})\n", i + 100));
        } else {
            content.push_str(&format!("[Link to heading {}](#heading-{})\n", i % 50, i % 50));
        }
    }

    // Measure performance
    let start = std::time::Instant::now();
    let rule = MD051LinkFragments::new();
    let ctx = LintContext::new(&content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();
    let duration = start.elapsed();

    println!(
        "MD051 check duration: {:?} for content length {}",
        duration,
        content.len()
    );
    println!("Found {} invalid fragments", result.len());

    // We expect about 1/3 of the 100 links to be invalid (those where i % 3 == 0)
    assert!(result.len() >= 30);
    assert!(result.len() <= 40);
}

#[test]
fn test_inline_code_spans() {
    let ctx = LintContext::new(
        "# Real Heading\n\nThis is a real link: [Link](somepath#real-heading)\n\nThis is a code example: `[Example](#missing-section)`",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let rule = MD051LinkFragments::new();

    let result = rule.check(&ctx).unwrap();

    // We should only have 0 warnings - the link in inline code should be ignored
    assert_eq!(result.len(), 0, "Link in inline code span should be ignored");

    // Test with multiple code spans and mix of valid and invalid links
    let ctx = LintContext::new(
        "# Heading One\n\n`[Invalid](#missing)` and [Valid](#heading-one) and `[Another Invalid](#nowhere)`",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );
    let result = rule.check(&ctx).unwrap();

    // Only the valid link should be checked, the ones in code spans should be ignored
    assert_eq!(result.len(), 0, "Only links outside code spans should be checked");

    // Test with a fragment link in inline code followed by a real invalid link
    let ctx = LintContext::new(
        "# Heading One\n\n`[Example](#missing-section)` and [Invalid Link](#section-two)",
        rumdl_lib::config::MarkdownFlavor::Standard,
        None,
    );

    // Debug: Let's check what the LintContext contains
    println!("=== Test 3 Debug ===");
    println!("Content: {:?}", ctx.content);
    println!("Line count: {}", ctx.lines.len());
    for (i, line_info) in ctx.lines.iter().enumerate() {
        println!(
            "Line {}: content='{}', in_code_block={}, byte_offset={}",
            i,
            line_info.content(ctx.content),
            line_info.in_code_block,
            line_info.byte_offset
        );
        if let Some(heading) = &line_info.heading {
            println!("  Has heading: level={}, text='{}'", heading.level, heading.text);
        }
    }

    let result = rule.check(&ctx).unwrap();

    // Debug output
    println!("Test 3 - Result count: {}", result.len());
    for (i, warning) in result.iter().enumerate() {
        println!(
            "Warning {}: line {}, col {}, message: {}",
            i, warning.line, warning.column, warning.message
        );
    }

    // Only the real invalid link should be caught
    assert_eq!(result.len(), 1, "Only real invalid links should be caught");
    assert_eq!(result[0].line, 3, "Warning should be on line 3");
    assert!(
        result[0].message.contains("section-two"),
        "Warning should be about 'section-two'"
    );
}

#[test]
fn test_readme_fragments() {
    let content = r#"# rumdl - A high-performance Markdown linter, written in Rust

## Table of Contents

- [rumdl - A high-performance Markdown linter, written in Rust](#rumdl---a-high-performance-markdown-linter-written-in-rust)
  - [Table of Contents](#table-of-contents)
"#;

    let rule = MD051LinkFragments::new();
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);

    let result = rule.check(&ctx).unwrap();
    assert!(
        result.is_empty(),
        "README-like fragments should match their headings; got warnings: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_md051_fragment_generation_regression() {
    // Regression test for the MD051 fragment generation bug
    // This test ensures that the GitHub-compatible fragment generation algorithm works correctly

    let rule = MD051LinkFragments::new();

    // Test cases that were previously failing - now tested through actual rule behavior
    let test_cases = vec![
        // Basic cases that should work
        ("Simple Heading", "simple-heading"),
        ("1. Numbered Heading", "1-numbered-heading"),
        ("Heading with Spaces", "heading-with-spaces"),
        // Ampersand cases (& becomes -- per GitHub spec)
        ("Test & Example", "test--example"),
        ("A&B", "ab"), // Fixed: & without spaces is removed
        ("A & B", "a--b"),
        ("Multiple & Ampersands & Here", "multiple--ampersands--here"),
        // Special characters
        ("Test. Period", "test-period"),
        ("Test: Colon", "test-colon"),
        ("Test! Exclamation", "test-exclamation"),
        ("Test? Question", "test-question"),
        ("Test (Parentheses)", "test-parentheses"),
        ("Test [Brackets]", "test-brackets"),
        // Complex cases
        ("1. Heading with Numbers & Symbols!", "1-heading-with-numbers--symbols"),
        (
            "Multiple!!! Exclamations & Symbols???",
            "multiple-exclamations--symbols",
        ),
        (
            "Heading with (Parentheses) & [Brackets]",
            "heading-with-parentheses--brackets",
        ),
        ("Special Characters: @#$%^&*()", "special-characters-"),
        // Edge cases
        ("Only!!! Symbols!!!", "only-symbols"),
        ("   Spaces   ", "spaces"), // Leading/trailing spaces
        ("Already-hyphenated", "already-hyphenated"),
        ("Multiple---hyphens", "multiple---hyphens"), // GitHub preserves consecutive hyphens
    ];

    for (heading, expected_fragment) in test_cases {
        // Create a test document with the heading and a link to it
        let content = format!("# {heading}\n\n[Link](#{expected_fragment})");
        let ctx = LintContext::new(&content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // If the fragment generation is correct, there should be no warnings
        assert_eq!(
            result.len(),
            0,
            "Fragment generation failed for heading '{}': expected fragment '{}' should be found, but got {} warnings: {:?}",
            heading,
            expected_fragment,
            result.len(),
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }
}

#[test]
fn test_md051_real_world_scenarios() {
    // Test real-world scenarios that should work with the fixed algorithm

    let content = r#"
# Main Title

## 1. Getting Started & Setup
[Link to setup](#1-getting-started--setup)

## 2. Configuration & Options
[Link to config](#2-configuration--options)

## 3. Advanced Usage (Examples)
[Link to advanced](#3-advanced-usage-examples)

## 4. FAQ & Troubleshooting
[Link to FAQ](#4-faq--troubleshooting)

## 5. API Reference: Methods & Properties
[Link to API](#5-api-reference-methods--properties)
"#;

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

    // All links should be valid with the fixed algorithm
    assert_eq!(
        result.len(),
        0,
        "Expected no warnings, but got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_md051_ampersand_variations() {
    // Specific test for ampersand handling variations

    let content = r#"
# Test & Example
[Link 1](#test--example)

# A&B
[Link 2](#ab)

# Multiple & Symbols & Here
[Link 3](#multiple--symbols--here)

# Test&End
[Link 4](#testend)

# &Start
[Link 5](#start)
"#;

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

    // All ampersand cases should be handled correctly
    assert_eq!(
        result.len(),
        0,
        "Expected no warnings for ampersand cases, but got: {:?}",
        result.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

// All MD051 tests are now complete and use integration testing approach
// rather than relying on debug methods that expose internal implementation

#[test]
fn test_cross_file_fragment_links() {
    // Test that cross-file fragment links are not validated by MD051
    // This addresses the bug where [bug](ISSUE_POLICY.md#bug-reports) was incorrectly flagged

    let content = r#"
# Main Heading

## Internal Section

This document has some internal links:
- [Valid internal link](#main-heading)
- [Another valid internal link](#internal-section)
- [Invalid internal link](#missing-section)

And some cross-file links that should be ignored by MD051:
- [Link to other file](README.md#installation)
- [Bug reports](ISSUE_POLICY.md#bug-reports)
- [Triage process](ISSUE_TRIAGE.rst#triage-section)
- [External file fragment](../docs/config.md#settings)
- [YAML config](config.yml#database)
- [JSON settings](app.json#server-config)
"#;

    let rule = MD051LinkFragments::new();
    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 internal fragment
    assert_eq!(
        result.len(),
        1,
        "Expected exactly 1 warning for missing internal fragment"
    );

    // Verify it's the correct warning
    assert!(
        result[0].message.contains("missing-section"),
        "Warning should be about the missing internal section, got: {}",
        result[0].message
    );

    // Verify that cross-file links are not flagged
    for warning in &result {
        assert!(
            !warning.message.contains("installation")
                && !warning.message.contains("bug-reports")
                && !warning.message.contains("triage-section")
                && !warning.message.contains("settings"),
            "Cross-file fragment should not be flagged: {}",
            warning.message
        );
    }
}

#[test]
fn test_fragment_only_vs_cross_file_links() {
    // Test to distinguish between fragment-only links (#section) and cross-file links (file.md#section)

    let content = r#"
# Existing Heading

## Another Section

Test various link types:
- [Fragment only - valid](#existing-heading)
- [Fragment only - invalid](#nonexistent-heading)
- [Cross-file with fragment](other.md#some-section)
- [Cross-file no fragment](other.md)
- [Fragment only - valid 2](#another-section)
"#;

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

    // Should only flag the invalid fragment-only link
    assert_eq!(
        result.len(),
        1,
        "Expected exactly 1 warning for invalid fragment-only link"
    );

    assert!(
        result[0].message.contains("nonexistent-heading"),
        "Warning should be about the nonexistent heading, got: {}",
        result[0].message
    );
}

#[test]
fn test_file_extension_edge_cases() {
    // Test various file extension cases that should be treated as cross-file links
    let content = r#"
# Main Heading

## Test Section

Cross-file links with various extensions (should be ignored by MD051):
- [Case insensitive](README.MD#section)
- [Upper case extension](file.HTML#heading)
- [Mixed case](doc.Rst#title)
- [Markdown variants](guide.markdown#intro)
- [Markdown short](notes.mkdn#summary)
- [Markdown extended](README.mdx#component)
- [Text file](data.txt#line)
- [XML file](config.xml#database)
- [YAML file](settings.yaml#server)
- [YAML short](app.yml#config)
- [JSON file](package.json#scripts)
- [PDF document](manual.pdf#chapter)
- [Word document](report.docx#results)
- [HTML page](index.htm#navbar)
- [Programming file](script.py#function)
- [Config file](settings.toml#section)
- [Generic extension](file.abc#section)

Fragment-only links (should be validated):
- [Valid fragment](#main-heading)
- [Another valid](#test-section)
- [Invalid fragment](#missing-section)
"#;

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

    // Should only flag the invalid fragment-only link
    assert_eq!(
        result.len(),
        1,
        "Expected exactly 1 warning for invalid fragment-only link"
    );
    assert!(
        result[0].message.contains("missing-section"),
        "Warning should be about missing-section, got: {}",
        result[0].message
    );
}

#[test]
fn test_complex_url_patterns() {
    // Test complex URL patterns that might confuse the parser
    let content = r#"
# Main Heading

## Documentation

Cross-file links (should be ignored):
- [Query params](file.md?version=1.0#section)
- [Relative path](../docs/readme.md#installation)
- [Deep relative](../../other/file.md#content)
- [Current dir](./local.md#section)
- [Encoded spaces](file%20name.md#section)
- [Complex path](path/to/deep/file.md#heading)
- [Windows style](folder\file.md#section)
- [Double hash](file.md#section#subsection)
- [Empty fragment](file.md#)
- [Archive file](data.tar.gz#section)
- [Backup file](config.ini.backup#settings)
- [No extension with dot](.gitignore#rules)
- [Hidden no extension](.hidden#section)
- [No extension](somefile#section)

Fragment-only tests:
- [Valid](#main-heading)
- [Invalid](#nonexistent)
"#;

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

    // Should flag only the invalid fragment-only link:
    // - `#nonexistent` - invalid fragment-only link
    // NOT flagged (all treated as cross-file links):
    // - `somefile#section` - GitHub-style extension-less cross-file link
    // - `.gitignore#rules` - hidden dotfile with extension
    // - `.hidden#section` - hidden file reference
    assert_eq!(result.len(), 1, "Expected 1 warning for invalid fragment-only link");

    // Check that we get warning for the invalid fragment
    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_nonexistent = warning_messages.iter().any(|msg| msg.contains("nonexistent"));

    assert!(contains_nonexistent, "Should warn about #nonexistent fragment");
}

#[test]
fn test_edge_case_file_extensions() {
    // Test edge cases with file extensions
    let content = r#"
# Valid Heading

Cross-file links (should be ignored):
- [Multiple dots](file.name.ext#section)
- [Just extension](.md#section)
- [URL with port](http://example.com:8080/file.md#section)
- [Network path](//server/file.md#section)
- [Absolute path](/absolute/file.md#section)
- [No extension](somefile#section)
- [Hidden file](.hidden#section)

Ambiguous paths (dot but empty extension, fragment validated):
- [Dot but no extension](file.#section)
- [Trailing dot](file.#section)

Fragment-only (should be validated):
- [Valid fragment](#valid-heading)
- [Invalid fragment](#invalid-heading)
"#;

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

    // Should flag:
    // - `file.#section` x2 - has dot but empty extension (ambiguous, validates fragment)
    // - `#invalid-heading` - invalid fragment-only
    // NOT flagged (all treated as cross-file links):
    // - `somefile#section` - GitHub-style extension-less
    // - `.hidden#section` - hidden file reference
    assert_eq!(
        result.len(),
        3,
        "Expected 3 warnings: 2 trailing dot + 1 invalid fragment"
    );

    // Verify we get warnings for the expected fragments
    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_section = warning_messages.iter().filter(|msg| msg.contains("section")).count();
    let contains_invalid = warning_messages.iter().any(|msg| msg.contains("invalid-heading"));

    assert_eq!(
        contains_section, 2,
        "Should have 2 warnings about #section from trailing dot paths"
    );
    assert!(contains_invalid, "Should warn about #invalid-heading fragment");
}

#[test]
fn test_malformed_and_boundary_cases() {
    // Test malformed links and boundary cases
    let content = r#"
# Test Heading

Boundary cases:
- [Empty URL]()
- [Just hash](#)
- [Hash no content](file.md#)
- [Multiple hashes](file.md##double)
- [Fragment with symbols](file.md#section-with-symbols!)
- [Very long filename](very-long-filename-that-exceeds-normal-length.md#section)

Reference links:
[ref1]: other.md#section
[ref2]: #test-heading
[ref3]: missing.md#section

- [Reference to cross-file][ref1]
- [Reference to valid fragment][ref2]
- [Reference to another cross-file][ref3]

Fragment validation:
- [Valid](#test-heading)
- [Invalid](#missing)
"#;

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

    // Should only flag the invalid fragment-only link
    assert_eq!(result.len(), 1, "Expected 1 warning for invalid fragment");
    assert!(
        result[0].message.contains("missing"),
        "Warning should be about missing fragment, got: {}",
        result[0].message
    );
}

#[test]
fn test_performance_stress_case() {
    // Test performance with many links
    let mut content = String::from("# Main\n\n## Section\n\n");

    // Add many cross-file links (should be ignored)
    for i in 0..100 {
        content.push_str(&format!("- [Link {i}](file{i}.md#section)\n"));
    }

    // Add some fragment-only links
    content.push_str("- [Valid](#main)\n");
    content.push_str("- [Valid 2](#section)\n");
    content.push_str("- [Invalid](#missing)\n");

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

    // Should only flag the one invalid fragment
    assert_eq!(result.len(), 1, "Expected 1 warning even with many cross-file links");
    assert!(
        result[0].message.contains("missing"),
        "Warning should be about missing fragment, got: {}",
        result[0].message
    );
}

#[test]
fn test_unicode_and_special_characters() {
    // Test Unicode characters in filenames and fragments
    let content = r#"
# Test Heading

## Café & Restaurant

Cross-file links with Unicode/special chars (should be ignored):
- [Unicode filename](文档.md#section)
- [Spaces in filename](my file.md#section)
- [Numbers in extension](file.md2#section)
- [Mixed case extension](FILE.Md#section)
- [Unicode no extension](文档#section)

Paths with special chars (not extension-less, fragment validated):
- [Special chars no extension](file@name#section)

Fragment tests:
- [Valid unicode](#café--restaurant)
- [Valid heading](#test-heading)
- [Invalid](#missing-heading)
"#;

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

    // Should flag:
    // - `file@name#section` → @ is not valid in extension-less paths, so validates fragment
    // - `#missing-heading` → invalid fragment
    // NOT flagged:
    // - `文档#section` → Unicode chars are alphanumeric, treated as extension-less cross-file link
    // - `#café--restaurant` → matches "Café & Restaurant" heading
    // Note: [Spaces no extension](my file#section) is NOT detected because pulldown-cmark
    // correctly rejects URLs with unencoded spaces per CommonMark spec
    assert_eq!(
        result.len(),
        2,
        "Expected 2 warnings: 1 path with special char + 1 invalid fragment"
    );

    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_section = warning_messages.iter().any(|msg| msg.contains("section"));
    let contains_missing = warning_messages.iter().any(|msg| msg.contains("missing-heading"));
    let contains_cafe = warning_messages.iter().any(|msg| msg.contains("café-restaurant"));

    assert!(
        contains_section,
        "Should warn about #section fragment from file@name#section"
    );
    assert!(contains_missing, "Should warn about #missing-heading fragment");
    assert!(
        !contains_cafe,
        "Should NOT warn about #café-restaurant fragment (matches heading per GitHub spec)"
    );
}

#[test]
fn test_edge_case_regressions() {
    // Test specific edge cases that could cause regressions
    let content = r#"
# Documentation

## Setup Guide

Links without fragments (should be ignored):
- [No extension no hash](filename)
- [Extension no hash](file.md)

Cross-file links (should be ignored):
- [Extension and hash](file.md#section)
- [Multiple dots in name](config.local.json#settings)
- [Extension in path](path/file.ext/sub.md#section)
- [Query with fragment](file.md?v=1#section)
- [Anchor with query](file.md#section?param=value)
- [Multiple extensions](archive.tar.gz#section)
- [Case sensitive](FILE.MD#section)
- [Generic extension](data.abc#section)

Paths with potential extensions (treated as cross-file links):
- [Dot in middle](my.file#section)
- [Custom extension](data.custom#section)

Fragment-only validation tests:
- [Hash only](#setup-guide)
- [Valid](#documentation)
- [Valid 2](#setup-guide)
- [Invalid](#nonexistent)
"#;

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

    // Should flag only 1 invalid fragment - ambiguous paths are now treated as cross-file links
    // because they have valid-looking extensions ("file" and "custom")
    assert_eq!(result.len(), 1, "Expected 1 warning: 1 invalid fragment");

    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_nonexistent = warning_messages.iter().any(|msg| msg.contains("nonexistent"));

    assert!(contains_nonexistent, "Should warn about #nonexistent fragment");
}

#[test]
fn test_url_protocol_edge_cases() {
    // Test URLs with protocols that should be treated as cross-file links
    let content = r#"
# Main Heading

## Setup

Protocol-based URLs (should be ignored as external links):
- [HTTP URL](http://example.com/page.html#section)
- [HTTPS URL](https://example.com/docs.md#heading)
- [FTP URL](ftp://server.com/file.txt#anchor)
- [File protocol](file:///path/to/doc.md#section)
- [Mailto with fragment](mailto:user@example.com#subject)

Fragment-only tests:
- [Valid](#main-heading)
- [Invalid](#missing)
"#;

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

    // Should only flag the invalid fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for invalid fragment");
    assert!(
        result[0].message.contains("missing"),
        "Warning should be about missing fragment, got: {}",
        result[0].message
    );
}

#[test]
fn test_fragment_normalization_edge_cases() {
    // Test various fragment formats and their normalization
    let content = r#"
# Test Heading

## Special Characters & Symbols

## Code `inline` Example

## Multiple   Spaces

Fragment tests with normalization:
- [Valid basic](#test-heading)
- [Valid special](#special-characters--symbols)
- [Valid code](#code-inline-example)
- [Valid spaces](#multiple---spaces)
- [Valid case insensitive](#Test-Heading)
- [Invalid symbols](#special-characters-&-symbols)
- [Invalid spacing](#multiple   spaces)
"#;

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

    // Should flag only the invalid symbol fragment
    // Note: [Invalid spacing](#multiple   spaces) is NOT detected because pulldown-cmark
    // correctly rejects URLs with unencoded spaces per CommonMark spec
    assert_eq!(
        result.len(),
        1,
        "Expected 1 warning for invalid fragment with unencoded &"
    );

    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_symbols = warning_messages
        .iter()
        .any(|msg| msg.contains("special-characters-&-symbols"));

    assert!(
        contains_symbols,
        "Should warn about & symbol in fragment (should be --)"
    );
}

#[test]
fn test_edge_case_file_paths() {
    // Test edge cases in file path detection
    let content = r#"
# Main Heading

Cross-file links with tricky paths (should be ignored):
- [Relative current](./README.md#section)
- [Relative parent](../docs/guide.md#intro)
- [Deep relative](../../other/project/file.md#content)
- [Absolute path](/usr/local/docs/manual.md#chapter)
- [Windows path](C:\Users\docs\readme.md#section)
- [Network path](\\server\share\file.md#section)
- [URL with port](http://localhost:8080/docs.md#api)

Fragment-only (should be validated):
- [Valid](#main-heading)
- [Invalid](#nonexistent)
"#;

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

    // Should only flag the invalid fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for invalid fragment");
    assert!(
        result[0].message.contains("nonexistent"),
        "Warning should be about nonexistent fragment, got: {}",
        result[0].message
    );
}

#[test]
fn test_malformed_link_edge_cases() {
    // Test malformed links and edge cases in link parsing
    let content = r#"
# Valid Heading

## Test Section

Malformed and edge case links:
- [Empty fragment](file.md#)
- [Just hash](#)
- [Multiple hashes](file.md#section#subsection)
- [Hash in middle](file.md#section?param=value)
- [No closing bracket](file.md#section
- [Valid file](document.pdf#page)
- [Valid fragment](#valid-heading)
- [Invalid fragment](#missing-heading)
"#;

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

    // Should flag the invalid fragment and potentially malformed links
    // (depends on how the parser handles malformed syntax)
    assert!(!result.is_empty(), "Expected at least 1 warning for invalid fragment");

    let warning_messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
    let contains_missing = warning_messages.iter().any(|msg| msg.contains("missing-heading"));

    assert!(contains_missing, "Should warn about missing-heading fragment");
}

#[test]
fn test_performance_with_many_links() {
    // Test performance with a large number of links
    let mut content = String::from("# Main Heading\n\n## Section One\n\n");

    // Add many cross-file links (should be ignored)
    for i in 0..100 {
        content.push_str(&format!("- [Link {i}](file{i}.md#section)\n"));
    }

    // Add some fragment-only links
    content.push_str("- [Valid](#main-heading)\n");
    content.push_str("- [Valid 2](#section-one)\n");
    content.push_str("- [Invalid](#nonexistent)\n");

    let rule = MD051LinkFragments::new();
    let ctx = LintContext::new(&content, rumdl_lib::config::MarkdownFlavor::Standard, None);

    let start = std::time::Instant::now();
    let result = rule.check(&ctx).unwrap();
    let duration = start.elapsed();

    // Should only flag the invalid fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for invalid fragment");
    assert!(
        result[0].message.contains("nonexistent"),
        "Warning should be about nonexistent fragment"
    );

    // Performance should be reasonable (less than 100ms for 100+ links)
    assert!(
        duration.as_millis() < 100,
        "Performance test failed: took {}ms",
        duration.as_millis()
    );

    println!(
        "MD051 performance test: {}ms for {} links",
        duration.as_millis(),
        ctx.links.len()
    );
}

#[test]
fn test_custom_header_id_formats() {
    // Test all supported custom header ID formats
    let content = r#"# Kramdown Style {#kramdown-id}

Some content here.

## Python-markdown with spaces { #spaced-id }

More content.

### Python-markdown with colon {:#colon-id}

Even more content.

#### Python-markdown full format {: #full-format }

Final content.

Links to test all formats:
- [Link to kramdown](#kramdown-id)
- [Link to spaced](#spaced-id)
- [Link to colon](#colon-id)
- [Link to full format](#full-format)

Links that should fail:
- [Link to nonexistent](#nonexistent-id)
"#;

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

    // Should only flag the nonexistent fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for nonexistent fragment");
    assert!(
        result[0].message.contains("nonexistent-id"),
        "Warning should be about nonexistent fragment, got: {}",
        result[0].message
    );

    // All valid custom ID formats should be recognized
    for warning in &result {
        assert!(
            !warning.message.contains("kramdown-id")
                && !warning.message.contains("spaced-id")
                && !warning.message.contains("colon-id")
                && !warning.message.contains("full-format"),
            "Valid custom ID format should not be flagged as missing: {}",
            warning.message
        );
    }
}

#[test]
fn test_extended_attr_list_support() {
    // Test attr-list with classes and other attributes alongside IDs
    let content = r#"# Simple ID { #simple-id }

## ID with single class {: #with-class .highlight }

### ID with multiple classes {: #multi-class .class1 .class2 }

#### ID with key-value attributes {: #with-attrs data-test="value" style="color: red" }

##### Complex combination {: #complex .highlight .important data-role="button" title="Test" }

###### Edge case with quotes {: #quotes title="Has \"nested\" quotes" }

Links to test extended attr-list support:
- [Simple ID](#simple-id)
- [With class](#with-class)
- [Multiple classes](#multi-class)
- [With attributes](#with-attrs)
- [Complex](#complex)
- [Quotes](#quotes)

Links that should fail:
- [Nonexistent](#nonexistent)
"#;

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

    // Should only flag the nonexistent fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for nonexistent fragment");
    assert!(
        result[0].message.contains("nonexistent"),
        "Warning should be about nonexistent fragment, got: {}",
        result[0].message
    );

    // All valid attr-list IDs should be recognized
    for warning in &result {
        assert!(
            !warning.message.contains("simple-id")
                && !warning.message.contains("with-class")
                && !warning.message.contains("multi-class")
                && !warning.message.contains("with-attrs")
                && !warning.message.contains("complex")
                && !warning.message.contains("quotes"),
            "Valid attr-list ID should not be flagged as missing: {}",
            warning.message
        );
    }
}

#[test]
fn test_jekyll_kramdown_next_line_attr_list() {
    // Test Jekyll/kramdown style attr-list on the line following the header
    let content = r#"# Main Title

## ATX Header
{#atx-next-line}

### Another ATX
{ #atx-spaced }

#### ATX with Class
{: #atx-with-class .highlight}

##### ATX Complex
{: #atx-complex .class1 .class2 data-test="value"}

Links to test next-line attr-list:
- [ATX Next Line](#atx-next-line)
- [ATX Spaced](#atx-spaced)
- [ATX with Class](#atx-with-class)
- [ATX Complex](#atx-complex)

Links that should fail:
- [Nonexistent](#nonexistent-next-line)
"#;

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

    // Should only flag the nonexistent fragment
    assert_eq!(result.len(), 1, "Expected 1 warning for nonexistent fragment");
    assert!(
        result[0].message.contains("nonexistent-next-line"),
        "Warning should be about nonexistent fragment, got: {}",
        result[0].message
    );

    // All valid next-line attr-list IDs should be recognized
    for warning in &result {
        assert!(
            !warning.message.contains("atx-next-line")
                && !warning.message.contains("atx-spaced")
                && !warning.message.contains("atx-with-class")
                && !warning.message.contains("atx-complex"),
            "Valid next-line attr-list ID should not be flagged as missing: {}",
            warning.message
        );
    }
}

#[test]
fn test_mixed_inline_and_next_line_attr_list() {
    // Test mixing inline and next-line attr-list in the same document
    let content = r#"# Mixed Styles

## Inline Style {#inline-id}

### Next Line Style
{#next-line-id}

#### Inline with Class {: #inline-class .highlight }

##### Next Line with Class
{: #next-line-class .important }

Links:
- [Inline](#inline-id)
- [Next Line](#next-line-id)
- [Inline Class](#inline-class)
- [Next Line Class](#next-line-class)
"#;

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

    // Should have no warnings - all IDs should be found
    assert_eq!(result.len(), 0, "Expected no warnings, got: {result:?}");
}

#[test]
fn debug_issue_39_fragment_generation() {
    // Debug test to see what fragments are actually generated
    let content = r#"
# Testing & Coverage

## cbrown --> sbrown: --unsafe-paths

## cbrown -> sbrown

## The End - yay

## API Reference: Methods & Properties

Links for testing:
- [Testing coverage](#testing--coverage)
- [Complex path](#cbrown----sbrown---unsafe-paths)
- [Simple arrow](#cbrown---sbrown)
- [API ref](#api-reference-methods--properties)
"#;

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

    println!("Number of errors: {}", result.len());
    for warning in &result {
        println!("Warning: {}", warning.message);
    }

    // If we fixed it correctly, we should have 0 errors
    if result.is_empty() {
        println!("SUCCESS: All fragments now match!");
    } else {
        println!("STILL BROKEN: Fragment generation needs more work");
    }
}

/// Regression tests for Issue #39: Two bugs in Links [MD051]
/// These tests ensure that the complex punctuation handling bugs are fixed and won't regress

#[test]
fn test_issue_39_duplicate_headings() {
    // Test case from issue 39: links to the second of repeated headers
    let content = r#"
# Title

## Section

This is a [reference](#section-1) to the second section.

## Section

There will be another section.
"#;

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

    // Should have no errors - link to second section should work
    assert_eq!(result.len(), 0, "Link to duplicate heading should work");
}

#[test]
fn test_issue_39_complex_punctuation_arrows() {
    // Test case from issue 39: complex arrow punctuation patterns
    let content = r#"
## cbrown --> sbrown: --unsafe-paths

## cbrown -> sbrown

## Arrow Test <-> bidirectional

## Double Arrow ==> Test

Links to test:
- [Complex unsafe](#cbrown----sbrown---unsafe-paths)
- [Simple arrow](#cbrown---sbrown)
- [Bidirectional](#arrow-test---bidirectional)
- [Double arrow](#double-arrow--test)
"#;

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

    // Should have no errors - all complex punctuation should be handled correctly
    assert_eq!(
        result.len(),
        0,
        "Complex arrow patterns should work: {:?}",
        result.iter().map(|r| &r.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_issue_39_ampersand_and_colons() {
    // Test case from issue 39: headers with ampersands and colons
    let content = r#"
# Testing & Coverage

## API Reference: Methods & Properties

## Config: Database & Cache Settings

Links to test:
- [Testing coverage](#testing--coverage)
- [API reference](#api-reference-methods--properties)
- [Config settings](#config-database--cache-settings)
"#;

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

    // Should have no errors - ampersands and colons should be handled correctly
    assert_eq!(
        result.len(),
        0,
        "Ampersand and colon patterns should work: {:?}",
        result.iter().map(|r| &r.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_issue_39_mixed_punctuation_clusters() {
    // Test edge cases with multiple types of punctuation in clusters
    let content = r#"
## Step 1: Setup (Prerequisites)

## Error #404 - Not Found!

## FAQ: What's Next?

## Version 2.0.1 - Release Notes

Links to test:
- [Setup guide](#step-1-setup-prerequisites)
- [Error page](#error-404---not-found)
- [FAQ section](#faq-whats-next)
- [Release notes](#version-201---release-notes)
"#;

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

    // Should have no errors - mixed punctuation should be handled correctly
    assert_eq!(
        result.len(),
        0,
        "Mixed punctuation clusters should work: {:?}",
        result.iter().map(|r| &r.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_issue_39_consecutive_hyphens_and_spaces() {
    // Test that consecutive hyphens are collapsed properly
    let content = r#"
## Test --- Multiple Hyphens

## Test  --  Spaced Hyphens

## Test - Single - Hyphen

Links to test:
- [Multiple](#test-----multiple-hyphens)
- [Spaced](#test------spaced-hyphens)
- [Single](#test---single---hyphen)
"#;

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

    // Should have no errors - consecutive hyphens should be collapsed
    assert_eq!(
        result.len(),
        0,
        "Consecutive hyphens should be collapsed: {:?}",
        result.iter().map(|r| &r.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_issue_39_edge_cases_from_comments() {
    // Test specific patterns mentioned in issue 39 comments
    let content = r#"
### PHP $_REQUEST

### sched_debug

#### Add ldap_monitor to delegator$

### cbrown --> sbrown: --unsafe-paths

Links to test:
- [PHP request](#php-_request)
- [Sched debug](#sched_debug)
- [LDAP monitor](#add-ldap_monitor-to-delegator)
- [Complex path](#cbrown----sbrown---unsafe-paths)
"#;

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

    // Should have no errors - all edge cases should work
    assert_eq!(
        result.len(),
        0,
        "Edge cases from issue comments should work: {:?}",
        result.iter().map(|r| &r.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_html_anchor_tags() {
    // Test HTML anchor tags with id attribute
    let content = r#"# Regular Heading

## Heading with anchor<a id="custom-id"></a>

## Another heading<a name="old-style"></a>

Links to test:
- [Regular heading](#regular-heading) - should work
- [Custom ID](#custom-id) - should work
- [Old style name](#old-style) - should work
- [Missing anchor](#missing) - should fail
"#;

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

    // Should only have 1 error for #missing
    assert_eq!(result.len(), 1, "Should only flag missing anchor");
    assert!(result[0].message.contains("#missing"));
}

#[test]
fn test_html_span_div_anchors() {
    // Test various HTML elements with id attributes
    let content = r#"# Document Title

## Section with span <span id="span-anchor">text</span>

<div id="div-anchor">
Some content in a div
</div>

<section id="section-anchor">
A section element
</section>

<h3 id="h3-anchor">HTML heading</h3>

Links to test:
- [Span anchor](#span-anchor) - should work
- [Div anchor](#div-anchor) - should work
- [Section anchor](#section-anchor) - should work
- [H3 anchor](#h3-anchor) - should work
- [Non-existent](#does-not-exist) - should fail
"#;

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

    // Should only have 1 error for #does-not-exist
    assert_eq!(result.len(), 1, "Should only flag non-existent anchor");
    assert!(result[0].message.contains("#does-not-exist"));
}

#[test]
fn test_html_anchors_in_code_blocks() {
    // HTML anchors in code blocks should be ignored
    let content = r#"# Test Document

```html
<a id="code-anchor">This is in a code block</a>
```

Links to test:
- [Code anchor](#code-anchor) - should fail (anchor is in code block)
"#;

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

    // Should have 1 error - anchors in code blocks don't count
    assert_eq!(result.len(), 1, "Anchors in code blocks should be ignored");
}

#[test]
fn test_multiple_ids_on_same_element() {
    // Test edge case: multiple id attributes (only first should be used per HTML spec)
    let content = r#"# Test Document

<div id="first-id" id="second-id">Content</div>

Links to test:
- [First ID](#first-id) - should work
- [Second ID](#second-id) - should fail (HTML only uses first id)
"#;

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

    // Should have 1 error for second-id
    assert_eq!(result.len(), 1, "Only first id attribute should be recognized");
    assert!(result[0].message.contains("#second-id"));
}

#[test]
fn test_mixed_markdown_and_html_anchors() {
    // Test document with both Markdown headings and HTML anchors
    let content = r#"# Main Title

## Regular Markdown Heading

## Heading with custom ID {#custom-markdown-id}

## Heading with HTML anchor<a id="html-anchor"></a>

<div id="standalone-div">Content</div>

Links to test:
- [Main title](#main-title) - Markdown auto-generated
- [Regular heading](#regular-markdown-heading) - Markdown auto-generated
- [Custom Markdown ID](#custom-markdown-id) - Markdown custom ID
- [HTML anchor](#html-anchor) - HTML anchor on heading
- [Div anchor](#standalone-div) - Standalone HTML element
- [Wrong link](#wrong) - Should fail
"#;

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

    // Should only have 1 error for #wrong
    assert_eq!(result.len(), 1, "Should support both Markdown and HTML anchors");
    assert!(result[0].message.contains("#wrong"));
}

#[test]
fn test_case_sensitivity_html_anchors() {
    // Under `ignore_case = false` (markdownlint strict parity), HTML id
    // attributes are matched case-sensitively, so wrong-case links are flagged.
    let content = r#"# Test Document

<div id="CamelCase">Content</div>
<span id="lowercase">Content</span>

Links to test:
- [Exact match CamelCase](#CamelCase) - should work
- [Wrong case camelcase](#camelcase) - should fail
- [Exact match lowercase](#lowercase) - should work
- [Wrong case LOWERCASE](#LOWERCASE) - should fail
"#;

    let rule = MD051LinkFragments::from_config_struct(rumdl_lib::rules::md051_link_fragments::MD051Config {
        ignore_case: false,
        ..rumdl_lib::rules::md051_link_fragments::MD051Config::default()
    });
    let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
    let result = rule.check(&ctx).unwrap();

    assert_eq!(
        result.len(),
        2,
        "HTML anchors should be case-sensitive when ignore_case=false"
    );
}

#[test]
fn test_case_insensitivity_html_anchors_default_ignore_case() {
    // Under the default `ignore_case = true`, HTML anchors match
    // case-insensitively, consistent with cross-file lookups and markdownlint's
    // `ignoreCase = true` mode.
    let content = r#"# Test Document

<div id="CamelCase">Content</div>
<span id="lowercase">Content</span>

Links to test:
- [Exact match CamelCase](#CamelCase) - should work
- [Different case camelcase](#camelcase) - should also work
- [Exact match lowercase](#lowercase) - should work
- [Different case LOWERCASE](#LOWERCASE) - should also work
"#;

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

    assert!(
        result.is_empty(),
        "All HTML anchor links must resolve under ignore_case=true, got {result:?}"
    );
}

#[test]
fn test_html_anchors_parity_with_markdownlint() {
    // This test ensures parity with markdownlint-cli behavior
    // Based on actual test case from ruff repository
    let content = r#"# Getting Started<a id="getting-started"></a>

## Configuration<a id="configuration"></a>

## Rules<a id="rules"></a>

## Contributing<a id="contributing"></a>

## Support<a id="support"></a>

## Acknowledgements<a id="acknowledgements"></a>

## Who's Using Ruff?<a id="whose-using-ruff"></a>

## License<a id="license"></a>

Table of contents:
1. [Getting Started](#getting-started)
1. [Configuration](#configuration)
1. [Rules](#rules)
1. [Contributing](#contributing)
1. [Support](#support)
1. [Acknowledgements](#acknowledgements)
1. [Who's Using Ruff?](#whose-using-ruff)
1. [License](#license)
"#;

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

    // All links should be valid - no errors
    assert_eq!(result.len(), 0, "All HTML anchor links should be valid");
}

#[test]
fn test_issue_82_arrow_patterns() {
    // Test for issue #82 - headers with arrows should generate correct anchors
    let content = r#"# Document

## Table of Contents
- [WAL->L0 Compaction](#wal-l0-compaction)
- [foo->bar->baz](#foo-bar-baz)
- [Header->with->Arrows](#header-with-arrows)

## WAL->L0 Compaction

Content about WAL to L0 compaction.

## foo->bar->baz

Content about foo bar baz.

## Header->with->Arrows

Content with arrows.
"#;

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

    // All links should be valid with the fixed arrow pattern handling
    assert_eq!(
        result.len(),
        0,
        "Arrow patterns in headers should generate correct anchors (issue #82)"
    );
}

// Extension-less cross-file link tests
// These tests verify that MD051 correctly recognizes and validates
// extension-less markdown links like `[link](page#section)` that resolve to `page.md#section`.
// Note: Due to file size, comprehensive edge case tests are in separate modules below.
mod extensionless_links {
    use rumdl_lib::config::{Config, MarkdownFlavor};
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::workspace_index::WorkspaceIndex;
    use std::fs;
    use tempfile::tempdir;

    /// Test the exact scenario from REMAINING-ISSUES.md
    ///
    /// Pattern: `[b#header1](b#header1)` where `b.md` exists
    /// Expected: Should recognize as cross-file link and validate fragment exists in b.md
    #[test]
    fn test_extensionless_link_exact_reproduction() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create target file with heading
        let target_file = base_path.join("b.md");
        fs::write(&target_file, "# header1\n\nContent here.\n").unwrap();

        // Create source file with extension-less link
        let source_file = base_path.join("a.md");
        let source_content = r#"# Source Document

This links to [header1 in b](b#header1).
"#;
        fs::write(&source_file, source_content).unwrap();

        // Get all rules
        let rules = rumdl_lib::rules::all_rules(&Config::default());

        // Lint and index both files
        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let target_content_str = fs::read_to_string(&target_file).unwrap();

        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );
        let (_, target_index) = rumdl_lib::lint_and_index(
            &target_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );

        // Build workspace index
        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target_file.clone(), target_index.clone());

        // Verify target file has the heading indexed
        let target_file_index = workspace_index.get_file(&target_file).unwrap();
        assert!(
            target_file_index.has_anchor("header1"),
            "Target file should have 'header1' anchor indexed"
        );

        // Verify extension-less link is recognized as cross-file
        let has_cross_file_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "b" && link.fragment == "header1");

        assert!(
            has_cross_file_link,
            "Extension-less link 'b#header1' should be recognized as cross-file link.\n\
             Cross-file links found: {:?}",
            source_index.cross_file_links
        );

        // Run cross-file validation
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        // Should have NO warnings because the fragment exists
        assert_eq!(
            warnings.len(),
            0,
            "Extension-less link to existing fragment should have no warnings.\n\
             Current warnings: {warnings:?}",
        );
    }

    /// Test extension-less link to non-existent fragment
    #[test]
    fn test_extensionless_link_missing_fragment() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create target file WITHOUT the heading
        let target_file = base_path.join("page.md");
        fs::write(&target_file, "# Other Heading\n\nContent.\n").unwrap();

        // Create source file with extension-less link to missing fragment
        let source_file = base_path.join("index.md");
        let source_content = r#"# Index

Link to [missing section](page#missing-section).
"#;
        fs::write(&source_file, source_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());

        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let target_content_str = fs::read_to_string(&target_file).unwrap();

        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );
        let (_, target_index) = rumdl_lib::lint_and_index(
            &target_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target_file.clone(), target_index.clone());

        // Verify link is recognized as cross-file
        let has_cross_file_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "page" && link.fragment == "missing-section");

        assert!(
            has_cross_file_link,
            "Extension-less link 'page#missing-section' should be recognized as cross-file"
        );

        // Run validation - should warn about missing fragment
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert_eq!(
            warnings.len(),
            1,
            "Should warn about missing fragment in extension-less link"
        );
        assert!(
            warnings[0].message.contains("missing-section"),
            "Warning should mention the missing fragment"
        );
        assert!(
            warnings[0].message.contains("page"),
            "Warning should mention the target file"
        );
    }

    /// Test extension-less links in subdirectories
    #[test]
    fn test_extensionless_link_subdirectory() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create subdirectory structure
        let docs_dir = base_path.join("docs");
        fs::create_dir_all(&docs_dir).unwrap();

        let target_file = docs_dir.join("guide.md");
        fs::write(&target_file, "# Getting Started\n\n## Installation\n\n## Usage\n").unwrap();

        let source_file = base_path.join("README.md");
        let source_content = r#"# Main README

See the [installation guide](docs/guide#installation).
"#;
        fs::write(&source_file, source_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());

        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let target_content_str = fs::read_to_string(&target_file).unwrap();

        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );
        let (_, target_index) = rumdl_lib::lint_and_index(
            &target_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target_file.clone(), target_index.clone());

        // Verify link is recognized
        let has_cross_file_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "docs/guide" && link.fragment == "installation");

        assert!(
            has_cross_file_link,
            "Extension-less link in subdirectory should be recognized"
        );

        // Should validate successfully
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert_eq!(
            warnings.len(),
            0,
            "Extension-less link to existing fragment in subdirectory should be valid"
        );
    }

    /// Test that extension-less links are distinguished from fragment-only links
    #[test]
    fn test_extensionless_vs_fragment_only() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("other.md");
        fs::write(&target_file, "# Target Heading\n").unwrap();

        let source_file = base_path.join("main.md");
        let source_content = r#"# Main Document

## Local Section

- [Fragment only](#local-section) - should validate against THIS file
- [Extension-less cross-file](other#target-heading) - should validate against other.md
- [Extension-less missing](other#missing) - should warn about missing fragment
"#;
        fs::write(&source_file, source_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());

        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let target_content_str = fs::read_to_string(&target_file).unwrap();

        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );
        let (_, target_index) = rumdl_lib::lint_and_index(
            &target_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target_file.clone(), target_index.clone());

        // Fragment-only link should NOT be in cross_file_links
        let has_fragment_only = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path.is_empty() || link.target_path == "#");

        assert!(
            !has_fragment_only,
            "Fragment-only link should NOT be in cross_file_links"
        );

        // Extension-less link SHOULD be in cross_file_links
        let has_extensionless = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "other");

        assert!(
            has_extensionless,
            "Extension-less link 'other#target-heading' should be in cross_file_links"
        );

        // Run validation
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        // Should only warn about the missing fragment in other.md
        assert_eq!(
            warnings.len(),
            1,
            "Should only warn about missing fragment in extension-less link"
        );
        assert!(
            warnings[0].message.contains("missing"),
            "Warning should be about missing fragment"
        );
    }

    /// Test edge case: extension-less link where file doesn't exist
    #[test]
    fn test_extensionless_link_file_not_exists() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Don't create the target file - it doesn't exist
        let source_file = base_path.join("index.md");
        let source_content = r#"# Index

Link to [non-existent](nonexistent#section).
"#;
        fs::write(&source_file, source_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());

        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        // Link should still be recognized as cross-file (even if file doesn't exist)
        let has_cross_file_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "nonexistent");

        assert!(
            has_cross_file_link,
            "Extension-less link should be recognized even if file doesn't exist yet"
        );

        // Validation should skip (file not in workspace index)
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        // No warnings because file isn't in workspace index
        assert_eq!(
            warnings.len(),
            0,
            "No warnings for files not in workspace (expected behavior)"
        );
    }

    /// Test that extension-less links work with various markdown extensions
    #[test]
    fn test_extensionless_link_markdown_variants() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Test .markdown extension
        let target1 = base_path.join("page.markdown");
        fs::write(&target1, "# Page Markdown\n").unwrap();

        // Test .md extension
        let target2 = base_path.join("doc.md");
        fs::write(&target2, "# Doc MD\n").unwrap();

        let source_file = base_path.join("index.md");
        let source_content = r#"# Index

- [Page](page#page-markdown)
- [Doc](doc#doc-md)
"#;
        fs::write(&source_file, source_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());

        let source_content_str = fs::read_to_string(&source_file).unwrap();
        let target1_content = fs::read_to_string(&target1).unwrap();
        let target2_content = fs::read_to_string(&target2).unwrap();

        let (_, source_index) = rumdl_lib::lint_and_index(
            &source_content_str,
            &rules,
            false,
            MarkdownFlavor::default(),
            None,
            None,
        );
        let (_, target1_index) =
            rumdl_lib::lint_and_index(&target1_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, target2_index) =
            rumdl_lib::lint_and_index(&target2_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target1.clone(), target1_index.clone());
        workspace_index.insert_file(target2.clone(), target2_index.clone());

        // Both links should be recognized
        let has_page_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "page");
        let has_doc_link = source_index
            .cross_file_links
            .iter()
            .any(|link| link.target_path == "doc");

        assert!(
            has_page_link && has_doc_link,
            "Both extension-less links should be recognized"
        );

        // Both should validate successfully
        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert_eq!(
            warnings.len(),
            0,
            "Extension-less links to .md and .markdown files should both work"
        );
    }
}

// =============================================================================
// URL-Encoded CJK Fragment Tests
// =============================================================================
// When documentation tools, browsers, or CI/CD systems generate markdown links
// with CJK fragments, they often URL-encode non-ASCII characters. Both forms
// should work: raw CJK (#インストール) and URL-encoded (#%E3%82%A4...).

mod url_encoded_cjk_tests {
    use super::*;
    use rumdl_lib::config::{Config, MarkdownFlavor};
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::workspace_index::WorkspaceIndex;
    use std::fs;
    use tempfile::tempdir;

    /// Test: Raw CJK fragment should work (baseline)
    #[test]
    fn test_raw_cjk_fragment_works() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Target file with Japanese heading
        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## インストール\n\nContent here.\n").unwrap();

        // Source file with raw CJK link
        let source_file = base_path.join("source.md");
        fs::write(&source_file, "# Source\n\n[Install](target.md#インストール)\n").unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(warnings.is_empty(), "Raw CJK fragment should work: {warnings:?}");
    }

    /// Test: URL-encoded Japanese fragment should work
    /// "インストール" URL-encoded = "%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB"
    #[test]
    fn test_url_encoded_japanese_fragment() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## インストール\n\nContent here.\n").unwrap();

        // Source file with URL-encoded CJK link
        let source_file = base_path.join("source.md");
        fs::write(
            &source_file,
            "# Source\n\n[Install](target.md#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB)\n",
        )
        .unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(
            warnings.is_empty(),
            "URL-encoded Japanese fragment should match raw anchor: {warnings:?}"
        );
    }

    /// Test: URL-encoded Korean fragment should work
    /// "한국어" URL-encoded = "%ED%95%9C%EA%B5%AD%EC%96%B4"
    #[test]
    fn test_url_encoded_korean_fragment() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## 한국어\n\nKorean content.\n").unwrap();

        let source_file = base_path.join("source.md");
        fs::write(
            &source_file,
            "# Source\n\n[Korean](target.md#%ED%95%9C%EA%B5%AD%EC%96%B4)\n",
        )
        .unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(
            warnings.is_empty(),
            "URL-encoded Korean fragment should match raw anchor: {warnings:?}"
        );
    }

    /// Test: URL-encoded Chinese fragment should work
    /// "中文" URL-encoded = "%E4%B8%AD%E6%96%87"
    #[test]
    fn test_url_encoded_chinese_fragment() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## 中文\n\nChinese content.\n").unwrap();

        let source_file = base_path.join("source.md");
        fs::write(&source_file, "# Source\n\n[Chinese](target.md#%E4%B8%AD%E6%96%87)\n").unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(
            warnings.is_empty(),
            "URL-encoded Chinese fragment should match raw anchor: {warnings:?}"
        );
    }

    /// Test: Mixed encoding (ASCII + URL-encoded CJK)
    /// "mixed-テスト" with テスト URL-encoded = "mixed-%E3%83%86%E3%82%B9%E3%83%88"
    #[test]
    fn test_mixed_encoding_fragment() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## Mixed テスト\n\nMixed content.\n").unwrap();

        let source_file = base_path.join("source.md");
        // GitHub generates: #mixed-テスト, URL-encoded: #mixed-%E3%83%86%E3%82%B9%E3%83%88
        fs::write(
            &source_file,
            "# Source\n\n[Mixed](target.md#mixed-%E3%83%86%E3%82%B9%E3%83%88)\n",
        )
        .unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(
            warnings.is_empty(),
            "Mixed ASCII + URL-encoded CJK should work: {warnings:?}"
        );
    }

    /// Test: Invalid URL encoding falls back gracefully
    #[test]
    fn test_invalid_url_encoding_fallback() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## Valid Heading\n\nContent.\n").unwrap();

        // Invalid URL encoding: %ZZ is not valid
        let source_file = base_path.join("source.md");
        fs::write(&source_file, "# Source\n\n[Bad](target.md#%ZZ%invalid)\n").unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        // Should still warn (invalid encoding doesn't match any anchor)
        assert_eq!(warnings.len(), 1, "Invalid URL encoding should warn");
    }

    /// Test: Case-insensitive URL encoding (%E3 vs %e3)
    #[test]
    fn test_url_encoding_case_insensitive() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## テスト\n\nContent.\n").unwrap();

        // Use lowercase hex: %e3%83%86%e3%82%b9%e3%83%88 instead of %E3%83%86%E3%82%B9%E3%83%88
        let source_file = base_path.join("source.md");
        fs::write(
            &source_file,
            "# Source\n\n[Test](target.md#%e3%83%86%e3%82%b9%e3%83%88)\n",
        )
        .unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(warnings.is_empty(), "Lowercase URL encoding should work: {warnings:?}");
    }

    /// Test: CJK heading with spaces becomes hyphenated anchor
    /// "한국어 테스트" -> "#한국어-테스트" URL-encoded = "#%ED%95%9C%EA%B5%AD%EC%96%B4-%ED%85%8C%EC%8A%A4%ED%8A%B8"
    #[test]
    fn test_url_encoded_cjk_with_spaces() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let target_file = base_path.join("target.md");
        fs::write(&target_file, "# Target\n\n## 한국어 테스트\n\nContent.\n").unwrap();

        // GitHub converts spaces to hyphens: 한국어-테스트
        let source_file = base_path.join("source.md");
        fs::write(
            &source_file,
            "# Source\n\n[Test](target.md#%ED%95%9C%EA%B5%AD%EC%96%B4-%ED%85%8C%EC%8A%A4%ED%8A%B8)\n",
        )
        .unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let target_content = fs::read_to_string(&target_file).unwrap();
        let source_content = fs::read_to_string(&source_file).unwrap();

        let (_, target_index) =
            rumdl_lib::lint_and_index(&target_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, source_index) =
            rumdl_lib::lint_and_index(&source_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(target_file.clone(), target_index);
        workspace_index.insert_file(source_file.clone(), source_index.clone());

        let md051 = MD051LinkFragments::default();
        let warnings = md051
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();

        assert!(
            warnings.is_empty(),
            "URL-encoded CJK with spaces->hyphens should work: {warnings:?}"
        );
    }
}

mod code_span_slug_tests {
    use rumdl_lib::config::MarkdownFlavor;
    use rumdl_lib::lint_context::LintContext;
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;

    #[test]
    fn test_code_span_preserves_underscores_in_slug() {
        // Heading with code span: underscores are literal, not emphasis
        // GitHub generates anchor "__hello__" (preserving underscores)
        let content = "## Introduction\n\n### `__hello__`\n\nThe `__hello__` module\n\n## Summary\n\n- This should match: [`__hello__`](#__hello__)\n- This should NOT match: [`hello`](#hello)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        // #__hello__ should match the heading, #hello should NOT match
        assert_eq!(
            result.len(),
            1,
            "Should have exactly 1 warning for #hello, got: {result:?}"
        );
        assert!(
            result[0].message.contains("#hello"),
            "Should flag #hello as non-existent, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_bare_emphasis_underscores_stripped() {
        // Heading without code span: underscores are emphasis, should be stripped
        // GitHub generates anchor "hello" (stripping emphasis underscores)
        let content =
            "### __hello__\n\n- This should match: [hello](#hello)\n- This should NOT match: [__hello__](#__hello__)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        // #hello should match the heading, #__hello__ should NOT match
        assert_eq!(
            result.len(),
            1,
            "Should have exactly 1 warning for #__hello__, got: {result:?}"
        );
        assert!(
            result[0].message.contains("#__hello__"),
            "Should flag #__hello__ as non-existent, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_mixed_code_and_emphasis() {
        // Mixed: code span preserves underscores, emphasis strips them
        let content = "### `__init__` method for __MyClass__\n\n- [correct](#__init__-method-for-myclass)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #__init__-method-for-myclass should match, got: {result:?}"
        );
    }

    #[test]
    fn test_multiple_code_spans_in_heading() {
        // Two code spans in one heading: each preserves its underscore content
        let content = "## `__a__` and `__b__`\n\n- [link](#__a__-and-__b__)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #__a__-and-__b__ should match heading with two code spans, got: {result:?}"
        );
    }

    #[test]
    fn test_multiple_code_spans_wrong_slug() {
        // Wrong slug that strips underscores should NOT match
        let content = "## `__a__` and `__b__`\n\n- [link](#a-and-b)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "Link #a-and-b should NOT match heading with code spans, got: {result:?}"
        );
    }

    #[test]
    fn test_code_span_with_parentheses() {
        // Parentheses are stripped by the character filter, spaces become hyphens
        let content = "## `__init__(self, name)`\n\n- [link](#__init__self-name)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #__init__self-name should match heading with parens in code span, got: {result:?}"
        );
    }

    #[test]
    fn test_digit_starting_custom_id_on_non_heading() {
        // Custom anchor IDs starting with a digit on non-heading lines
        let content = "Third-Party Library { #3rd-party }\n\n:   Some definition.\n\n[link](#3rd-party)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #3rd-party should match non-heading anchor {{ #3rd-party }}, got: {result:?}"
        );
    }

    #[test]
    fn test_digit_starting_custom_id_on_heading() {
        // Custom anchor IDs starting with a digit on headings (regression test)
        let content = "# Third-Party Library { #3rd-party }\n\n[link](#3rd-party)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #3rd-party should match heading anchor {{ #3rd-party }}, got: {result:?}"
        );
    }

    #[test]
    fn test_various_digit_starting_ids() {
        // Multiple digit-starting IDs with different formats
        let content = "\
Section One { #1 }\n\
\n\
Section Two { #123-foo }\n\
\n\
Section Three { #1st-section }\n\
\n\
Section Four { #2nd_item }\n\
\n\
[one](#1)\n\
[two](#123-foo)\n\
[three](#1st-section)\n\
[four](#2nd_item)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "All digit-starting anchor links should resolve, got: {result:?}"
        );
    }

    #[test]
    fn test_digit_starting_id_with_class() {
        // Digit-starting ID combined with a class in attr_list syntax
        let content = "Term { #3rd-party .glossary }\n\n[link](#3rd-party)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Link #3rd-party should match anchor with class, got: {result:?}"
        );
    }

    #[test]
    fn test_digit_starting_id_invalid_link_still_warns() {
        // A digit-starting anchor exists but the link points elsewhere
        let content = "Term { #3rd-party }\n\n[link](#nonexistent)\n";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::new();
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "Link #nonexistent should still be flagged even with digit-starting anchors present, got: {result:?}"
        );
    }
}

/// Regression tests for rvben/rumdl-vscode#113: HTML comments in headings were
/// being baked into the anchor (e.g. `hello----world---`) instead of being
/// stripped, so links that match the actually-rendered anchor (`hello-` on
/// GitHub, `title` on MkDocs) were flagged as missing.
mod html_comment_in_heading_regression {
    use super::*;

    #[test]
    fn github_style_accepts_post_comment_trailing_hyphen() {
        // Verified against GitHub.com: `# Hello <!-- world -->` renders with
        // anchor `hello-` (the trailing space before the comment becomes a
        // single hyphen; the comment itself contributes nothing).
        let content = "# Hello <!-- world -->\n\n[link](#hello-)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::with_anchor_style(AnchorStyle::GitHub);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "#hello- must match GitHub-rendered anchor, got: {result:?}"
        );
    }

    #[test]
    fn github_style_rejects_pre_fix_leaky_anchor() {
        // Before the fix, rumdl generated `hello----world---` for the same
        // heading. Any link that previously validated against that leaky
        // anchor must now be flagged.
        let content = "# Hello <!-- world -->\n\n[link](#hello----world---)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::with_anchor_style(AnchorStyle::GitHub);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "leaky anchor containing comment text must be flagged, got: {result:?}"
        );
    }

    #[test]
    fn kramdown_gfm_style_accepts_leading_comment_hyphen() {
        // Verified against kramdown 2.5.1 with GFM input: the space between a
        // stripped leading comment and the heading text becomes a leading hyphen.
        let content = "# <!-- hidden --> Title\n\n[link](#-title)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::with_anchor_style(AnchorStyle::KramdownGfm);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "#-title must match kramdown-GFM anchor for leading comment, got: {result:?}"
        );
    }

    #[test]
    fn python_markdown_style_accepts_collapsed_anchor() {
        // Verified against Python-Markdown 3.x TOC extension: comments never
        // enter the anchor, surrounding whitespace collapses via `[-\s]+`.
        let content = "# Hello <!-- world -->\n\n[link](#hello)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let rule = MD051LinkFragments::with_anchor_style(AnchorStyle::PythonMarkdown);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "#hello must match Python-Markdown TOC anchor, got: {result:?}"
        );
    }
}

mod ignored_pattern_tests {
    use rumdl_lib::lint_context::LintContext;
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::rules::md051_link_fragments::MD051Config;

    #[test]
    fn test_ignored_pattern_skips_matching_fragment() {
        // ignored_pattern matches on the fragment text (without the leading #).
        // A fragment that matches the pattern should never produce a warning,
        // even when the heading does not exist.
        let config = MD051Config {
            ignored_pattern: Some("^section-".to_string()),
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# Real heading\n\n[link](#section-missing)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "fragment matching ignored_pattern must be skipped, got {result:?}"
        );
    }

    #[test]
    fn test_ignored_pattern_does_not_skip_non_matching_fragment() {
        let config = MD051Config {
            ignored_pattern: Some("^section-".to_string()),
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# Real heading\n\n[link](#other-missing)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "non-matching fragment must still warn, got {result:?}");
    }

    #[test]
    fn test_ignored_pattern_default_unset_skips_nothing() {
        let rule = MD051LinkFragments::from_config_struct(MD051Config::default());
        let content = "# Real heading\n\n[link](#anything-missing)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "default empty pattern must not skip anything, got {result:?}"
        );
    }

    #[test]
    fn test_ignored_pattern_invalid_regex_is_treated_as_no_filter() {
        // Defensive: an invalid regex should not crash; treat as if unset.
        let config = MD051Config {
            ignored_pattern: Some("[unterminated".to_string()),
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# Real heading\n\n[link](#missing)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "invalid regex must not silently swallow violations, got {result:?}"
        );
    }

    #[test]
    fn test_ignored_pattern_kebab_case_parses() {
        let toml_str = "ignored-pattern = \"^x-\"\n";
        let config: MD051Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.ignored_pattern.as_deref(), Some("^x-"));
    }

    #[test]
    fn test_ignored_pattern_snake_case_alias_parses() {
        let toml_str = "ignored_pattern = \"^x-\"\n";
        let config: MD051Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.ignored_pattern.as_deref(), Some("^x-"));
    }
}

mod ignore_case_tests {
    use rumdl_lib::lint_context::LintContext;
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::rules::md051_link_fragments::MD051Config;

    #[test]
    fn test_ignore_case_default_true_accepts_case_mismatch() {
        // rumdl's default differs from markdownlint: ignore_case defaults to true,
        // so case-mismatched fragments are accepted. This preserves the long-standing
        // rumdl behavior; users seeking strict markdownlint parity must opt in
        // with ignore_case = false.
        let rule = MD051LinkFragments::from_config_struct(MD051Config::default());
        let content = "# My Heading\n\n[link](#MY-HEADING)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "default ignore_case=true must accept case-only mismatches, got {result:?}"
        );
    }

    #[test]
    fn test_ignore_case_false_warns_on_case_mismatch() {
        // Opt-in markdownlint-strict mode: case-only mismatches are reported.
        let config = MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# My Heading\n\n[link](#MY-HEADING)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "ignore_case=false must flag case-only mismatch, got {result:?}"
        );
    }

    #[test]
    fn test_ignore_case_false_accepts_exact_match() {
        let config = MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# My Heading\n\n[link](#my-heading)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "ignore_case=false must accept exact-case match, got {result:?}"
        );
    }

    #[test]
    fn test_ignore_case_false_warns_on_unknown_fragment() {
        let config = MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        };
        let rule = MD051LinkFragments::from_config_struct(config);
        let content = "# My Heading\n\n[link](#totally-different)\n";
        let ctx = LintContext::new(content, rumdl_lib::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "unknown fragment must always warn, got {result:?}");
    }

    #[test]
    fn test_ignore_case_kebab_case_parses() {
        let toml_str = "ignore-case = false\n";
        let config: MD051Config = toml::from_str(toml_str).unwrap();
        assert!(!config.ignore_case);
    }

    #[test]
    fn test_ignore_case_snake_case_alias_parses() {
        let toml_str = "ignore_case = false\n";
        let config: MD051Config = toml::from_str(toml_str).unwrap();
        assert!(!config.ignore_case);
    }

    #[test]
    fn test_ignore_case_default_is_true() {
        let config = MD051Config::default();
        assert!(
            config.ignore_case,
            "rumdl default ignore_case is true to preserve permissive behavior"
        );
    }
}

mod cross_file_options_tests {
    use rumdl_lib::config::{Config, MarkdownFlavor};
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::rules::md051_link_fragments::MD051Config;
    use rumdl_lib::workspace_index::WorkspaceIndex;
    use std::fs;
    use tempfile::tempdir;

    /// Helper: index two files (`source.md` linking to `target.md`) into a workspace.
    fn build_two_file_workspace(
        source_content: &str,
        target_content: &str,
    ) -> (
        std::path::PathBuf,
        rumdl_lib::workspace_index::FileIndex,
        WorkspaceIndex,
        tempfile::TempDir,
    ) {
        let temp_dir = tempdir().unwrap();
        let base = temp_dir.path();
        let source_file = base.join("source.md");
        let target_file = base.join("target.md");
        fs::write(&source_file, source_content).unwrap();
        fs::write(&target_file, target_content).unwrap();

        let rules = rumdl_lib::rules::all_rules(&Config::default());
        let (_, source_index) =
            rumdl_lib::lint_and_index(source_content, &rules, false, MarkdownFlavor::default(), None, None);
        let (_, target_index) =
            rumdl_lib::lint_and_index(target_content, &rules, false, MarkdownFlavor::default(), None, None);

        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(source_file.clone(), source_index.clone());
        workspace_index.insert_file(target_file, target_index);

        (source_file, source_index, workspace_index, temp_dir)
    }

    #[test]
    fn test_cross_file_ignored_pattern_skips_matching_fragment() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[missing](target.md#fn:1)\n", "# Real heading\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignored_pattern: Some("^fn:".to_string()),
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "cross-file fragment matching ignored_pattern must be skipped, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignored_pattern_does_not_skip_non_matching_fragment() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[missing](target.md#other-missing)\n", "# Real heading\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignored_pattern: Some("^fn:".to_string()),
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "non-matching cross-file fragment must still warn, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_default_true_accepts_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#MY-HEADING)\n", "# My Heading\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config::default());
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "default ignore_case=true must accept cross-file case-only mismatches, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_warns_on_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#MY-HEADING)\n", "# My Heading\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "ignore_case=false must flag cross-file case-only mismatch, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_accepts_exact_match() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#my-heading)\n", "# My Heading\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "ignore_case=false must accept cross-file exact-case match, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_accepts_html_anchor_exact_case() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#MyAnchor)\n", "<a id=\"MyAnchor\">target</a>\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "ignore_case=false must accept cross-file HTML anchor with matching original case, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_warns_on_html_anchor_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#myanchor)\n", "<a id=\"MyAnchor\">target</a>\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "ignore_case=false must flag cross-file HTML anchor case mismatch, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_true_accepts_html_anchor_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#myanchor)\n", "<a id=\"MyAnchor\">target</a>\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config::default());
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "default ignore_case=true must accept cross-file HTML anchor case-only mismatches, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_accepts_attribute_anchor_exact_case() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#MyAttr)\n", "Some text { #MyAttr }\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "ignore_case=false must accept cross-file attribute anchor with matching original case, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_warns_on_attribute_anchor_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#myattr)\n", "Some text { #MyAttr }\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "ignore_case=false must flag cross-file attribute anchor case mismatch, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_accepts_custom_heading_id_exact_case() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#CustomID)\n", "## Heading {#CustomID}\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert!(
            warnings.is_empty(),
            "ignore_case=false must accept cross-file custom heading ID exact-case, got {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_ignore_case_false_warns_on_custom_heading_id_case_mismatch() {
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[link](target.md#customid)\n", "## Heading {#CustomID}\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case: false,
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "ignore_case=false must flag cross-file custom heading ID case mismatch, got {warnings:?}"
        );
    }

    #[test]
    fn test_invalid_ignored_pattern_falls_back_gracefully() {
        // An unterminated character class like "[unterminated" must not panic and
        // must not silently swallow violations — fragments are validated normally.
        let (source_file, source_index, workspace_index, _td) =
            build_two_file_workspace("[broken](target.md#missing)\n", "# Real\n");

        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignored_pattern: Some("[unterminated".to_string()),
            ..MD051Config::default()
        });
        let warnings = rule
            .cross_file_check(&source_file, &source_index, &workspace_index)
            .unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "invalid ignored_pattern must fall back to no filter and still warn on missing fragments, got {warnings:?}"
        );
    }
}

mod same_doc_html_anchor_consistency_tests {
    //! Same-document HTML anchor matching must honor `ignore_case` identically
    //! to cross-file lookups, so users get the same behavior whether linking
    //! within a file or across files.

    use rumdl_lib::config::MarkdownFlavor;
    use rumdl_lib::lint_context::LintContext;
    use rumdl_lib::rule::Rule;
    use rumdl_lib::rules::MD051LinkFragments;
    use rumdl_lib::rules::md051_link_fragments::MD051Config;

    fn check(content: &str, ignore_case: bool) -> Vec<rumdl_lib::rule::LintWarning> {
        let rule = MD051LinkFragments::from_config_struct(MD051Config {
            ignore_case,
            ..MD051Config::default()
        });
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        rule.check(&ctx).unwrap()
    }

    #[test]
    fn test_same_doc_ignore_case_true_accepts_html_anchor_case_mismatch() {
        let content = "<a id=\"MyAnchor\">target</a>\n\n[link](#myanchor)\n";
        let warnings = check(content, true);
        assert!(
            warnings.is_empty(),
            "ignore_case=true must accept same-doc HTML anchor case-only mismatches, got {warnings:?}"
        );
    }

    #[test]
    fn test_same_doc_ignore_case_false_warns_on_html_anchor_case_mismatch() {
        let content = "<a id=\"MyAnchor\">target</a>\n\n[link](#myanchor)\n";
        let warnings = check(content, false);
        assert_eq!(
            warnings.len(),
            1,
            "ignore_case=false must flag same-doc HTML anchor case mismatch, got {warnings:?}"
        );
    }

    #[test]
    fn test_same_doc_ignore_case_false_accepts_html_anchor_exact_match() {
        let content = "<a id=\"MyAnchor\">target</a>\n\n[link](#MyAnchor)\n";
        let warnings = check(content, false);
        assert!(
            warnings.is_empty(),
            "ignore_case=false must accept same-doc HTML anchor exact-case match, got {warnings:?}"
        );
    }

    #[test]
    fn test_same_doc_ignore_case_true_accepts_html_anchor_exact_match() {
        let content = "<a id=\"MyAnchor\">target</a>\n\n[link](#MyAnchor)\n";
        let warnings = check(content, true);
        assert!(
            warnings.is_empty(),
            "ignore_case=true must accept same-doc HTML anchor exact-case match, got {warnings:?}"
        );
    }
}