rustdoc-markdown 0.91.0

A tool to convert Rust documentation to Markdown, for use with LLMs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::cognitive_complexity)] // Allow complex functions for now

//! `rustdoc-markdown` is a tool to convert Rust crate documentation into a
//! monolithic Markdown document, primarily designed for consumption by Large
//! Language Models (LLMs).
//!
//! It achieves this by:
//! 1. Fetching crate information from crates.io (if not using a local manifest).
//! 2. Downloading and unpacking the crate source.
//! 3. Running `rustdoc` to generate JSON output (`rustdoc_types::Crate`).
//! 4. Parsing the `Cargo.toml` of the crate.
//! 5. Optionally reading extra information like the crate's `README.md` and
//!    source code examples from the `examples/` directory.
//! 6. Processing the `rustdoc_types::Crate` and supplementary information.
//! 7. Rendering a structured Markdown document.
//!
//! ## Key Features
//!
//! - **LLM-Optimized Output**: The Markdown is structured for clarity and conciseness,
//!   aiming to provide effective context for LLMs. Header levels might exceed
//!   standard Markdown (h6) to maintain a consistent hierarchical structure.
//! - **Comprehensive Documentation**: Includes API documentation, README, and examples.
//! - **"Common Traits" Summarization**: To reduce output size, frequently implemented
//!   traits can be summarized at the crate and module levels. This can be disabled.
//! - **Path Filtering**: Allows generation of documentation for specific modules or items.
//! - **Template Mode**: Can output template markers instead of actual documentation,
//!   useful for identifying missing docstrings.
//!
//! ## Main Entry Points
//!
//! - [`Printer`]: The core struct responsible for orchestrating the documentation
//!   generation process. It uses a builder pattern for configuration.
//! - [`run_rustdoc`]: A utility function to execute `rustdoc` and parse its JSON output.
//! - [`CrateExtraReader`]: Reads supplementary information like READMEs and examples.
//!
//! ## Example Usage (Library)
//!
//! ```no_run
//! use anyhow::Result;
//! use cargo_manifest::Manifest;
//! use rustdoc_markdown::{Printer, CrateExtraReader, run_rustdoc, cratesio};
//! use std::path::Path;
//! use reqwest::Client; // Add this line
//!
//! async fn generate_docs_for_crate(
//!     crate_name: &str,
//!     version_req: &str,
//!     output_md_path: &Path,
//!     build_dir: &Path,
//! ) -> Result<()> {
//!     // 1. Setup client and directories
//!     let client = Client::new();
//!     std::fs::create_dir_all(build_dir)?;
//!
//!     // 2. Find the best version on crates.io
//!     let target_version = cratesio::find_best_version(
//!         &client,
//!         crate_name,
//!         version_req,
//!         false, // include_prerelease
//!     )
//!     .await?;
//!
//!     // 3. Download and unpack the crate
//!     let crate_dir = cratesio::download_and_unpack_crate(
//!         &client,
//!         &target_version,
//!         build_dir,
//!     )
//!     .await?;
//!
//!     // 4. Parse the crate's Cargo.toml
//!     let manifest_path = crate_dir.join("Cargo.toml");
//!     let manifest = Manifest::from_path(&manifest_path)?;
//!
//!     // 5. Run rustdoc to get rustdoc_types::Crate
//!     let krate_data = run_rustdoc(
//!         &crate_dir,
//!         &target_version.crate_name,
//!         None,    // features
//!         false,   // no_default_features
//!         None,    // target
//!         true,    // allow_rustup (ensure nightly is available)
//!     )?;
//!
//!     // 6. Read extra crate information (README, examples)
//!     let extra_reader = CrateExtraReader::new(); // Default: reads README and examples
//!     let crate_extra = extra_reader.read(&manifest, &crate_dir)?;
//!
//!     // 7. Configure and run the Printer
//!     let printer = Printer::new(&manifest, &krate_data)
//!         .crate_extra(crate_extra)
//!         // .paths(&["::my_module".to_string()]) // Optional: filter by path
//!         // .no_common_traits() // Optional: disable common traits summary
//!         ;
//!
//!     let markdown_content = printer.print()?;
//!
//!     // 8. Write to output file
//!     std::fs::write(output_md_path, markdown_content)?;
//!
//!     println!("Successfully generated Markdown for {} v{} at {}",
//!              crate_name, target_version.num, output_md_path.display());
//!
//!     Ok(())
//! }
//! ```

use anyhow::{Context, Result, bail}; // Add Context
use cargo_manifest::{FeatureSet, Manifest as CargoManifest, StringOrBool}; // Renamed Manifest to CargoManifest
use graph::{Edge, IdGraph, ResolvedModule};
use rustdoc_json::Builder;
use rustdoc_types::{
    Abi, Attribute, Constant, Crate, Discriminant, Enum, Function, GenericArg, GenericArgs,
    GenericBound, GenericParamDef, Generics, Id, Impl, Item, ItemEnum, ItemKind, Path, PolyTrait,
    Primitive, Struct, StructKind, Term, Trait, Type, Union, Variant, VariantKind, WherePredicate,
};
use std::collections::{HashMap, HashSet}; // Use HashMap instead of BTreeMap where needed
use std::fmt::Write as FmtWrite; // Use FmtWrite alias
use std::hash::{Hash, Hasher};
use std::path::Path as FilePath; // Corrected use statement
use tracing::{debug, info, trace, warn};
// Add fs import for CrateExtraReader
use std::fs;
use std::io::BufReader; // Added for reading JSON file

// Import pulldown-cmark related items
use pulldown_cmark::{Event, Parser as CmarkParser, Tag, TagEnd}; // Import Tag, TagEnd
use pulldown_cmark_to_cmark::cmark;

/// The specific nightly Rust toolchain version required by this crate.
pub const NIGHTLY_RUST_VERSION: &str = "nightly-2025-11-27";

pub mod cratesio;

#[doc(hidden)]
pub mod graph;

// --- CrateExtra Structures ---

/// Holds extra crate information like README and examples.
///
/// This data is read from the crate's source directory and can be
/// included in the generated Markdown documentation.
#[derive(Debug, Clone, Default)]
pub struct CrateExtra {
    /// The content of the crate's main `README.md` or `README` file.
    pub readme_content: Option<String>,
    /// The content of the `README.md` or `README` file within the `examples/` directory.
    pub examples_readme_content: Option<String>,
    /// A list of (filename, content) tuples for Rust files found in the `examples/` directory.
    pub examples: Vec<(String, String)>, // Vec of (filename, content)
}

/// Builder for reading [`CrateExtra`] data from a crate's source directory.
///
/// Allows selective reading of README files and examples.
#[derive(Debug, Default)]
pub struct CrateExtraReader {
    read_readme: bool,
    read_examples: bool,
}

impl CrateExtraReader {
    /// Creates a new `CrateExtraReader` with default settings, which will
    /// attempt to read the main README file and examples from the `examples/` directory.
    pub fn new() -> Self {
        Self {
            read_readme: true,
            read_examples: true,
        }
    }

    /// Disables reading of the crate's main README file (`README.md` or `README`).
    pub fn no_readme(mut self) -> Self {
        self.read_readme = false;
        self
    }

    /// Disables reading of example files from the `examples/` directory and its README.
    pub fn no_examples(mut self) -> Self {
        self.read_examples = false;
        self
    }

    /// Reads the extra crate information from the specified crate source directory.
    ///
    /// # Arguments
    ///
    /// * `manifest`: A reference to the parsed `Cargo.toml` of the package.
    /// * `package_dir`: The path to the root directory of the package.
    ///
    /// # Returns
    ///
    /// A `Result` containing the [`CrateExtra`] data, or an error if reading fails.
    pub fn read(&self, manifest: &CargoManifest, package_dir: &FilePath) -> Result<CrateExtra> {
        let mut extra = CrateExtra::default();

        if self.read_readme {
            let readme_path_from_manifest = manifest
                .package
                .as_ref()
                .and_then(|p| p.readme.as_ref())
                .and_then(|r| r.as_ref().as_local()); // Get local value of MaybeInherited

            let readme_file_to_read = match readme_path_from_manifest {
                Some(StringOrBool::String(readme_filename)) => {
                    Some(package_dir.join(readme_filename))
                }
                Some(StringOrBool::Bool(true)) | None => {
                    // Default to README.md if true or not specified
                    let default_readme_md = package_dir.join("README.md");
                    if default_readme_md.exists() {
                        Some(default_readme_md)
                    } else {
                        // Fallback to README if README.md doesn't exist
                        Some(package_dir.join("README"))
                    }
                }
                Some(StringOrBool::Bool(false)) => {
                    info!("README explicitly disabled in Cargo.toml.");
                    None
                }
            };

            if let Some(path) = readme_file_to_read {
                if path.exists() {
                    match fs::read_to_string(&path) {
                        Ok(content) => extra.readme_content = Some(content),
                        Err(_) => warn!("Failed to read README at {}", path.display()),
                    }
                } else {
                    info!(
                        "README file specified in Cargo.toml not found: {}",
                        path.display()
                    );
                }
            } else if readme_path_from_manifest.is_none() {
                // This case means readme was not specified, and default README.md/README were not found
                info!("No README specified in Cargo.toml and no default README found.");
            }
        }

        if self.read_examples {
            let examples_dir = package_dir.join("examples");
            if examples_dir.is_dir() {
                let ex_readme_md_path = examples_dir.join("README.md");
                let ex_readme_path = examples_dir.join("README");
                if let Some(path) = ex_readme_md_path
                    .exists()
                    .then_some(ex_readme_md_path)
                    .or_else(|| ex_readme_path.exists().then_some(ex_readme_path))
                    && let Ok(content) = fs::read_to_string(path)
                {
                    extra.examples_readme_content = Some(content);
                }

                if let Ok(entries) = fs::read_dir(&examples_dir) {
                    let mut found_examples = Vec::new();
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if path.is_file()
                            && path.extension().is_some_and(|ext| ext == "rs")
                            && let Some(filename_str) = path.file_name().and_then(|n| n.to_str())
                            && let Ok(content) = fs::read_to_string(&path)
                        {
                            found_examples.push((filename_str.to_string(), content));
                        }
                    }
                    if !found_examples.is_empty() {
                        found_examples.sort_by(|a, b| a.0.cmp(&b.0));
                        extra.examples = found_examples;
                    }
                }
            }
        }
        Ok(extra)
    }
}

// --- Manifest Data ---

#[derive(Debug, Clone, Default)]
struct CrateManifestData {
    description: Option<String>,
    homepage: Option<String>,
    repository: Option<String>,
    categories: Vec<String>,
    license: Option<String>,
    rust_version: Option<String>,
    edition: Option<String>,
    features: FeatureSet, // Using cargo-manifest's FeatureSet
}

impl CrateManifestData {
    fn from_cargo_manifest(manifest: &CargoManifest) -> Self {
        let package_data = manifest.package.as_ref();
        CrateManifestData {
            description: package_data
                .and_then(|p| p.description.as_ref())
                .and_then(|d| d.as_ref().as_local())
                .cloned(),
            homepage: package_data
                .and_then(|p| p.homepage.as_ref())
                .and_then(|h| h.as_ref().as_local())
                .cloned(),
            repository: package_data
                .and_then(|p| p.repository.as_ref())
                .and_then(|r| r.as_ref().as_local())
                .cloned(),
            categories: package_data
                .and_then(|p| p.categories.as_ref())
                .and_then(|c| c.as_ref().as_local())
                .cloned()
                .unwrap_or_default(),
            license: package_data
                .and_then(|p| p.license.as_ref())
                .and_then(|l| l.as_ref().as_local())
                .cloned(),
            rust_version: package_data
                .and_then(|p| p.rust_version.as_ref())
                .and_then(|rv| rv.as_ref().as_local())
                .cloned(),
            edition: package_data
                .and_then(|p| p.edition.as_ref())
                .and_then(|e| e.as_ref().as_local())
                .map(|e| e.as_str().to_string()),
            features: manifest.features.clone().unwrap_or_default(),
        }
    }
}

/// Runs `rustdoc` for a given crate and parses the resulting JSON output.
///
/// This function uses the `rustdoc-json` crate to invoke `rustdoc` with the
/// necessary flags to produce JSON output. It requires a specific nightly
/// Rust toolchain (see [`NIGHTLY_RUST_VERSION`]).
///
/// # Arguments
///
/// * `crate_dir`: Path to the root directory of the crate.
/// * `crate_name`: The name of the crate (as it appears in `Cargo.toml`).
/// * `features`: An optional space-separated string of features to enable.
/// * `no_default_features`: If `true`, the `default` feature will not be activated.
/// * `target`: An optional target triple to build documentation for.
/// * `allow_rustup`: If `true`, the function will attempt to install the required
///   nightly toolchain using `rustup`. If `false` and the toolchain is not
///   present, it may fail.
///
/// # Returns
///
/// A `Result` containing the parsed [`rustdoc_types::Crate`] data, or an error
/// if `rustdoc` execution or JSON parsing fails.
pub fn run_rustdoc(
    crate_dir: &FilePath,
    crate_name: &str,
    features: Option<&str>,
    no_default_features: bool,
    target: Option<&str>,
    allow_rustup: bool,
) -> Result<Crate> {
    let manifest_path = crate_dir.join("Cargo.toml");
    if !manifest_path.exists() {
        bail!(
            "Cargo.toml not found in unpacked crate at {}",
            manifest_path.display()
        );
    }

    if allow_rustup {
        // Install the required nightly toolchain
        rustup_toolchain::install(NIGHTLY_RUST_VERSION).unwrap();
    }

    info!("Generating rustdoc JSON using rustdoc-json crate...");

    let crate_name_underscore = crate_name.replace('-', "_");
    let json_output_path = crate_dir
        .join("target/doc")
        .join(format!("{}.json", crate_name_underscore));

    let mut builder = Builder::default()
        .manifest_path(manifest_path)
        .toolchain(NIGHTLY_RUST_VERSION) // Specify the nightly toolchain
        .target_dir(crate_dir.join("target")) // Set the output directory
        .package(crate_name); // Specify the package

    // Apply feature flags
    if let Some(features_str) = features {
        let feature_list: Vec<String> = features_str.split_whitespace().map(String::from).collect();
        if !feature_list.is_empty() {
            info!("Enabling features: {:?}", feature_list);
            builder = builder.features(feature_list);
        }
    }

    if no_default_features {
        info!("Disabling default features.");
        builder = builder.no_default_features(true);
    }

    // Apply target
    if let Some(target_str) = target {
        info!("Setting target: {}", target_str);
        builder = builder.target(target_str.to_string());
    }

    // Generate the JSON file
    match builder.build() {
        Ok(s) => {
            info!("Generated rustdoc JSON at: {}", s.display());
        }
        Err(e) => {
            // Attempt to read stderr if possible (rustdoc-json might not expose it easily)
            eprintln!("--- rustdoc-json build failed ---");
            eprintln!("{:?}", e); // Print the error itself

            // Try to read potential rustdoc output if the file exists but is invalid
            if json_output_path.exists()
                && let Ok(content) = std::fs::read_to_string(&json_output_path)
            {
                eprintln!(
                    "\n--- Potential content of {}: ---\n{}",
                    json_output_path.display(),
                    content
                );
            }

            bail!("rustdoc-json failed: {}", e);
        }
    }

    info!("Parsing rustdoc JSON: {}", json_output_path.display());
    let file = fs::File::open(&json_output_path)
        .with_context(|| format!("Failed to open JSON file: {}", json_output_path.display()))?;
    let reader = BufReader::new(file);
    let krate_data: Crate = serde_json::from_reader(reader)
        .with_context(|| format!("Failed to parse JSON file: {}", json_output_path.display()))?;
    info!(
        "Loaded rustdoc JSON for {} v{}",
        crate_name,
        krate_data.crate_version.as_deref().unwrap_or("?")
    );
    Ok(krate_data)
}

/// Gets the `Id` associated with a type, if it's a path-based type.
pub(crate) fn get_type_id(ty: &Type) -> Option<Id> {
    match ty {
        Type::ResolvedPath(p) => Some(p.id),
        Type::Generic(_) => None, // Generic types don't have a direct ID in this context
        Type::Primitive(_) => None,
        Type::FunctionPointer(_) => None, // Function pointers don't have an ID
        Type::Tuple(_) => None,
        Type::Slice(inner) => get_type_id(inner), // Look inside
        Type::Array { type_, .. } => get_type_id(type_), // Look inside
        Type::Pat { type_, .. } => get_type_id(type_), // Look inside
        Type::Infer => None,
        Type::RawPointer { type_, .. } => get_type_id(type_), // Look inside
        Type::BorrowedRef { type_, .. } => get_type_id(type_), // Look inside
        Type::QualifiedPath { self_type, .. } => get_type_id(self_type), // Focus on self_type for impl matching
        Type::ImplTrait(_) => None,
        Type::DynTrait(_) => None,
    }
}

// --- Formatting Helpers ---

/// Formats a list of attributes, filtering out derive attributes.
/// Each attribute is on a new line.
/// Returns a string like `#[attr1]\n#[attr2]\n` (with a trailing newline if not empty).
/// Convert an Attribute enum to a string representation
fn attribute_to_string(attr: &Attribute) -> String {
    match attr {
        Attribute::NonExhaustive => "#[non_exhaustive]".to_string(),
        Attribute::MustUse { reason } => {
            if let Some(r) = reason {
                format!("#[must_use = \"{}\"]", r)
            } else {
                "#[must_use]".to_string()
            }
        }
        Attribute::MacroExport => "#[macro_export]".to_string(),
        Attribute::ExportName(name) => format!("#[export_name = \"{}\"]", name),
        Attribute::LinkSection(section) => format!("#[link_section = \"{}\"]", section),
        Attribute::AutomaticallyDerived => "#[automatically_derived]".to_string(),
        Attribute::Repr(repr) => format!("#[repr({:?})]", repr),
        Attribute::NoMangle => "#[no_mangle]".to_string(),
        Attribute::TargetFeature { enable } => {
            format!("#[target_feature(enable = \"{}\")]", enable.join("\", \""))
        }
        Attribute::Other(s) => s.clone(),
    }
}

fn format_attributes(attrs: &[Attribute]) -> String {
    let filtered_attrs: Vec<String> = attrs
        .iter()
        .map(attribute_to_string)
        .filter(|attr| !attr.starts_with("#[derive("))
        .collect();

    if filtered_attrs.is_empty() {
        String::new()
    } else {
        filtered_attrs
            .iter()
            .map(|attr| format!("{}\n", attr))
            .collect::<String>()
    }
}

/// Formats a list of attributes, filtering out derive attributes, for inline display.
/// Returns a string like `#[attr1] #[attr2] ` (with a trailing space if not empty).
fn format_attributes_inline(attrs: &[Attribute]) -> String {
    let filtered_attrs: Vec<String> = attrs
        .iter()
        .map(attribute_to_string)
        .filter(|attr| !attr.starts_with("#[derive("))
        .collect();

    if filtered_attrs.is_empty() {
        String::new()
    } else {
        format!("{} ", filtered_attrs.join(" "))
    }
}

/// Helper to check if an item has non-empty documentation.
fn has_docs(item: &Item) -> bool {
    item.docs.as_ref().is_some_and(|d| !d.trim().is_empty())
}

/// Adjusts the markdown header levels in a string using pulldown-cmark.
/// Increases the level of each header (e.g., `#` -> `###`) based on the base level.
/// Caps the maximum level at 6 (`######`).
fn adjust_markdown_headers(markdown: &str, base_level: usize) -> String {
    let parser = CmarkParser::new(markdown);
    let transformed_events = parser.map(|event| match event {
        Event::Start(Tag::Heading {
            level,
            id,
            classes,
            attrs,
        }) => {
            // Explicitly match on HeadingLevel variants to get usize
            let old_level_usize = match level {
                pulldown_cmark::HeadingLevel::H1 => 1,
                pulldown_cmark::HeadingLevel::H2 => 2,
                pulldown_cmark::HeadingLevel::H3 => 3,
                pulldown_cmark::HeadingLevel::H4 => 4,
                pulldown_cmark::HeadingLevel::H5 => 5,
                pulldown_cmark::HeadingLevel::H6 => 6,
            };
            let new_level_usize = std::cmp::min(old_level_usize + base_level, 6);
            let new_level = pulldown_cmark::HeadingLevel::try_from(new_level_usize)
                .unwrap_or(pulldown_cmark::HeadingLevel::H6);
            Event::Start(pulldown_cmark::Tag::Heading {
                level: new_level,
                id,
                classes,
                attrs,
            })
        }
        Event::End(TagEnd::Heading(level)) => {
            // Explicitly match on HeadingLevel variants to get usize
            let old_level_usize = match level {
                pulldown_cmark::HeadingLevel::H1 => 1,
                pulldown_cmark::HeadingLevel::H2 => 2,
                pulldown_cmark::HeadingLevel::H3 => 3,
                pulldown_cmark::HeadingLevel::H4 => 4,
                pulldown_cmark::HeadingLevel::H5 => 5,
                pulldown_cmark::HeadingLevel::H6 => 6,
            };
            let new_level_usize = std::cmp::min(old_level_usize + base_level, 6);
            let new_level = pulldown_cmark::HeadingLevel::try_from(new_level_usize)
                .unwrap_or(pulldown_cmark::HeadingLevel::H6);
            Event::End(pulldown_cmark::TagEnd::Heading(new_level))
        }
        _ => event,
    });

    let mut out_buf = String::with_capacity(markdown.len() + 128); // Pre-allocate slightly
    cmark(transformed_events, &mut out_buf).expect("Markdown formatting failed");
    out_buf
}

/// Indents each line of a string by the specified amount.
fn indent_string(s: &str, amount: usize) -> String {
    let prefix = " ".repeat(amount);
    s.lines()
        .map(|line| format!("{}{}", prefix, line))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Cleans common prefixes like `core::marker::`, `core::ops::`, `alloc::`, `std::` from a path string.
fn clean_trait_path(path_str: &str) -> String {
    path_str
        .replace("core::marker::", "")
        .replace("core::ops::", "") // Add common core paths
        .replace("core::fmt::", "")
        .replace("core::cmp::", "")
        .replace("core::clone::", "")
        .replace("core::hash::", "")
        .replace("core::panic::unwind_safe::", "") // For UnwindSafe/RefUnwindSafe
        // Keep core::option::Option ? Maybe not needed as often in where clauses.
        .replace("core::", "") // General core removal last
        .replace("alloc::string::", "") // Clean alloc paths too
        .replace("alloc::vec::", "")
        .replace("alloc::boxed::", "")
        .replace("alloc::borrow::", "") // For Borrow/BorrowMut/ToOwned
        .replace("alloc::", "") // General alloc removal
        .replace("std::", "") // Also clean std paths potentially used via prelude
}

/// Formats the canonical path to an item ID, using its path from krate.paths.
fn format_id_path_canonical(id: &Id, krate: &Crate) -> String {
    krate
        .paths
        .get(id)
        .map(|p| p.path.join("::"))
        .unwrap_or_else(|| {
            // Fallback if not in paths (e.g., some external or generated IDs)
            krate
                .index
                .get(id)
                .and_then(|item| item.name.as_deref())
                .map_or_else(|| format!("{{id:{}}}", id.0), |name| name.to_string())
        })
}

/// Formats a Path struct, trying to use the canonical path for the ID.
fn format_path(path: &Path, krate: &Crate) -> String {
    // Use the canonical path if available, otherwise use the path string in the struct
    let base_path = format_id_path_canonical(&path.id, krate);

    let cleaned_base_path = clean_trait_path(&base_path); // Clean the base path
    // Use as_ref() to get Option<&GenericArgs> from Option<Box<GenericArgs>>
    if let Some(args) = path.args.as_ref() {
        let args_str = format_generic_args(args, krate);
        if !args_str.is_empty() {
            format!("{}<{}>", cleaned_base_path, args_str) // Use cleaned path
        } else {
            cleaned_base_path // Use cleaned path
        }
    } else {
        cleaned_base_path // Use cleaned path
    }
}

fn format_poly_trait(poly_trait: &PolyTrait, krate: &Crate) -> String {
    let hrtb = if poly_trait.generic_params.is_empty() {
        "".to_string()
    } else {
        format!(
            "for<{}> ",
            poly_trait
                .generic_params
                .iter()
                .map(|p| format_generic_param_def(p, krate)) // Format full param def
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    format!("{}{}", hrtb, format_path(&poly_trait.trait_, krate)) // Use format_path for the Path struct
}

fn format_type(ty: &Type, krate: &Crate) -> String {
    match ty {
        Type::ResolvedPath(p) => format_path(p, krate),
        Type::DynTrait(dt) => {
            let lifetime_bound = dt
                .lifetime
                .as_ref()
                .map(|lt| format!(" + {}", lt)) // Add quote for lifetime
                .unwrap_or_default();
            format!(
                "dyn {}{}",
                dt.traits
                    .iter()
                    .map(|pt| format_poly_trait(pt, krate))
                    .collect::<Vec<_>>()
                    .join(" + "),
                lifetime_bound
            )
        }
        Type::Generic(name) => name.clone(),
        Type::Primitive(name) => name.clone(),
        Type::FunctionPointer(fp) => {
            let hrtb = if fp.generic_params.is_empty() {
                "".to_string()
            } else {
                format!(
                    "for<{}> ",
                    fp.generic_params
                        .iter()
                        .map(|p| format_generic_param_def(p, krate))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            let abi = if !matches!(fp.header.abi, Abi::Rust) {
                format!("extern \"{:?}\" ", fp.header.abi) // Use Debug for Abi for now
            } else {
                "".to_string()
            };
            let unsafe_kw = if fp.header.is_unsafe { "unsafe " } else { "" };
            format!(
                "{}{}{}fn({}){}",
                hrtb,
                unsafe_kw,
                abi,
                fp.sig
                    .inputs
                    .iter()
                    .map(|(_name, type_)| format_type(type_, krate)) // Ignore name pattern for now
                    .collect::<Vec<_>>()
                    .join(", "),
                fp.sig
                    .output
                    .as_ref()
                    .map(|t| format!(" -> {}", format_type(t, krate)))
                    .unwrap_or_default()
            )
        }
        Type::Tuple(types) => {
            // Special case for empty tuple
            if types.is_empty() {
                "()".to_string()
            } else {
                format!(
                    "({})",
                    types
                        .iter()
                        .map(|t| format_type(t, krate))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
        }
        Type::Slice(inner) => format!("[{}]", format_type(inner, krate)),
        Type::Array { type_, len } => format!("[{}; {}]", format_type(type_, krate), len),
        Type::Pat { type_, .. } => format!("pat {}", format_type(type_, krate)), // Placeholder
        Type::ImplTrait(bounds) => {
            format!(
                "impl {}",
                bounds
                    .iter()
                    .map(|b| format_generic_bound(b, krate))
                    .collect::<Vec<_>>()
                    .join(" + ")
            )
        }
        Type::Infer => "_".to_string(),
        Type::RawPointer { is_mutable, type_ } => {
            format!(
                "*{}{}",
                if *is_mutable { "mut " } else { "const " },
                format_type(type_, krate)
            )
        }
        Type::BorrowedRef {
            lifetime,
            is_mutable,
            type_,
        } => format!(
            "&{}{}{}",
            lifetime
                .as_ref()
                .map(|lt| format!("{} ", lt)) // Add quote
                .unwrap_or_default(),
            if *is_mutable { "mut " } else { "" },
            format_type(type_, krate)
        ),
        Type::QualifiedPath {
            name,
            args,
            self_type,
            trait_,
        } => {
            let self_type_str = format_type(self_type, krate);
            let trait_str = trait_
                .as_ref()
                .map(|t| format_path(t, krate)) // Use format_path
                .unwrap_or("_".to_string());
            // Args here are for the associated type, not the trait bound
            let args_str = args
                .as_ref()
                .map(|a| format_generic_args(a, krate))
                .unwrap_or_default();

            format!(
                "<{} as {}>::{}{}",
                self_type_str,
                trait_str,
                name,
                if args_str.is_empty() {
                    "".to_string()
                } else {
                    format!("<{}>", args_str)
                }
            )
        }
    }
}

fn format_generic_args(args: &GenericArgs, krate: &Crate) -> String {
    match args {
        GenericArgs::AngleBracketed {
            args, constraints, ..
        } => {
            let arg_strs: Vec<String> = args.iter().map(|a| format_generic_arg(a, krate)).collect();
            let constraint_strs: Vec<String> = constraints
                .iter()
                .map(|c| match c {
                    rustdoc_types::AssocItemConstraint {
                        name,
                        args: assoc_args,
                        binding: rustdoc_types::AssocItemConstraintKind::Equality(term),
                    } => {
                        let assoc_args_str = assoc_args
                            .as_ref()
                            .map(|a| format_generic_args(a, krate))
                            .unwrap_or_default();
                        format!(
                            "{}{}{}{} = {}",
                            name,
                            if assoc_args_str.is_empty() { "" } else { "<" },
                            assoc_args_str,
                            if assoc_args_str.is_empty() { "" } else { ">" },
                            format_term(term, krate)
                        )
                    }
                    rustdoc_types::AssocItemConstraint {
                        name,
                        args: assoc_args,
                        binding: rustdoc_types::AssocItemConstraintKind::Constraint(bounds),
                    } => {
                        let assoc_args_str = assoc_args
                            .as_ref()
                            .map(|a| format_generic_args(a, krate))
                            .unwrap_or_default();
                        format!(
                            "{}{}{}{}: {}",
                            name,
                            if assoc_args_str.is_empty() { "" } else { "<" },
                            assoc_args_str,
                            if assoc_args_str.is_empty() { "" } else { ">" },
                            bounds
                                .iter()
                                .map(|bnd| format_generic_bound(bnd, krate))
                                .collect::<Vec<_>>()
                                .join(" + ")
                        )
                    }
                })
                .collect();
            let mut all_strs = arg_strs;
            all_strs.extend(constraint_strs);
            all_strs.join(", ")
        }
        GenericArgs::Parenthesized { inputs, output, .. } => {
            format!(
                "({}) -> {}",
                inputs
                    .iter()
                    .map(|t| format_type(t, krate))
                    .collect::<Vec<_>>()
                    .join(", "),
                output
                    .as_ref()
                    .map_or("()".to_string(), |t| format_type(t, krate))
            )
        }
        GenericArgs::ReturnTypeNotation => String::new(),
    }
}

fn format_const_expr(constant: &Constant) -> String {
    // Prefer `value` if present and different, otherwise use `expr`
    if let Some(v) = &constant.value
        && v != &constant.expr
    {
        return format!("{} /* = {} */", constant.expr, v);
    }
    constant.expr.clone()
}

/// Formats a discriminant expression, potentially showing the value if different.
fn format_discriminant_expr(discr: &Discriminant) -> String {
    if discr.value != discr.expr {
        format!("{} /* = {} */", discr.expr, discr.value)
    } else {
        discr.expr.clone()
    }
}

fn format_generic_arg(arg: &GenericArg, krate: &Crate) -> String {
    match arg {
        GenericArg::Lifetime(lt) => lt.to_string(), // Add quote
        GenericArg::Type(ty) => format_type(ty, krate),
        GenericArg::Const(c) => format_const_expr(c),
        GenericArg::Infer => "_".to_string(),
    }
}

fn format_generic_bound(bound: &GenericBound, krate: &Crate) -> String {
    match bound {
        GenericBound::TraitBound {
            trait_,         // Path struct
            generic_params, // HRTBs
            modifier,
            ..
        } => {
            let hrtb = if generic_params.is_empty() {
                "".to_string()
            } else {
                format!(
                    "for<{}> ",
                    generic_params
                        .iter()
                        .map(|p| format_generic_param_def(p, krate)) // Format full param def
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            let mod_str = match modifier {
                rustdoc_types::TraitBoundModifier::None => "",
                rustdoc_types::TraitBoundModifier::Maybe => "?",
                rustdoc_types::TraitBoundModifier::MaybeConst => "?const ", // Note the space
            };
            format!("{}{}{}", hrtb, mod_str, format_path(trait_, krate)) // Use format_path
        }
        GenericBound::Outlives(lifetime) => lifetime.to_string(), // Add quote
        GenericBound::Use(args) => {
            // use<'a, T> syntax
            format!(
                "use<{}>",
                args.iter()
                    .map(|a| match a {
                        rustdoc_types::PreciseCapturingArg::Lifetime(lt) => format!("'{}", lt),
                        rustdoc_types::PreciseCapturingArg::Param(id_str) => id_str.clone(), // Use string name directly
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    }
}

fn format_term(term: &Term, krate: &Crate) -> String {
    match term {
        Term::Type(t) => format_type(t, krate),
        Term::Constant(c) => format_const_expr(c),
    }
}

fn format_generic_param_def(p: &GenericParamDef, krate: &Crate) -> String {
    match &p.kind {
        rustdoc_types::GenericParamDefKind::Lifetime { .. } => p.name.to_string(), // Add quote
        rustdoc_types::GenericParamDefKind::Type {
            bounds,
            default,
            is_synthetic,
            ..
        } => {
            format!(
                "{}{}{}{}",
                if *is_synthetic { "impl " } else { "" },
                p.name,
                if bounds.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        ": {}",
                        bounds
                            .iter()
                            .map(|b| format_generic_bound(b, krate))
                            .collect::<Vec<_>>()
                            .join(" + ")
                    )
                },
                default
                    .as_ref()
                    .map(|t| format!(" = {}", format_type(t, krate)))
                    .unwrap_or_default()
            )
        }
        rustdoc_types::GenericParamDefKind::Const { type_, default, .. } => {
            format!(
                "const {}: {}{}",
                p.name,
                format_type(type_, krate),
                default
                    .as_deref()
                    .map(|d| format!(" = {}", d))
                    .unwrap_or_default()
            )
        }
    }
}

// Formats generics like <T: Bound> where T: OtherBound
fn format_generics_full(generics: &Generics, krate: &Crate) -> String {
    if generics.params.is_empty() && generics.where_predicates.is_empty() {
        return String::new();
    }

    let mut s = String::new();
    let params_str = if !generics.params.is_empty() {
        format!(
            "<{}>",
            generics
                .params
                .iter()
                .map(|p| format_generic_param_def(p, krate))
                .collect::<Vec<_>>()
                .join(", ")
        )
    } else {
        String::new()
    };

    let where_clause = format_generics_where_only(&generics.where_predicates, krate);

    if !params_str.is_empty() {
        write!(s, "{}", params_str).unwrap();
    }
    if !where_clause.is_empty() {
        // Add newline and indent if params were also present and where clause is multiline
        if !params_str.is_empty() && where_clause.contains('\n') {
            write!(s, "\n  {}", where_clause).unwrap();
        } else {
            write!(s, " {}", where_clause).unwrap(); // Append single line where clause or first line of multiline
        }
    }

    s
}

// Formats generics like <T: Bound>
fn format_generics_params_only(params: &[GenericParamDef], krate: &Crate) -> String {
    if params.is_empty() {
        return String::new();
    }
    format!(
        "<{}>",
        params
            .iter()
            .map(|p| format_generic_param_def(p, krate))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

// Formats only the where clause: "where T: Bound" or multi-line
fn format_generics_where_only(predicates: &[WherePredicate], krate: &Crate) -> String {
    if predicates.is_empty() {
        return String::new();
    }
    let clauses: Vec<String> = predicates
        .iter()
        .map(|p| match p {
            WherePredicate::BoundPredicate {
                type_,
                bounds,
                generic_params,
                ..
            } => {
                let hrtb = if generic_params.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        "for<{}> ",
                        generic_params
                            .iter()
                            .map(|gp| format_generic_param_def(gp, krate))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                };
                format!(
                    "{}{}: {}",
                    hrtb,
                    format_type(type_, krate),
                    bounds
                        .iter()
                        .map(|b| format_generic_bound(b, krate))
                        .collect::<Vec<_>>()
                        .join(" + ")
                )
            }
            WherePredicate::LifetimePredicate {
                lifetime, outlives, ..
            } => {
                format!(
                    "{}: {}",
                    lifetime,
                    outlives
                        .iter()
                        .map(|lt| lt.to_string()) // Add quotes
                        .collect::<Vec<_>>()
                        .join(" + ")
                )
            }
            WherePredicate::EqPredicate { lhs, rhs, .. } => {
                format!("{} == {}", format_type(lhs, krate), format_term(rhs, krate))
            }
        })
        .collect();

    // Determine if multi-line formatting is needed
    let total_len = clauses.iter().map(|s| s.len()).sum::<usize>();
    let is_multiline = clauses.len() > 1 || total_len > 60; // Heuristic for multi-line

    if is_multiline {
        format!("where\n    {}", clauses.join(",\n    ")) // Indent contents
    } else {
        format!("where {}", clauses.join(", "))
    }
}

// --- Structured Printing Logic ---

/// Category of a trait implementation for display purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TraitImplCategory {
    /// Simple, non-generic, non-blanket, non-auto impls.
    Simple,
    /// Impls with generics, associated items, or other complexities.
    GenericOrComplex,
    /// Auto traits (e.g., Send, Sync).
    Auto,
    /// Blanket implementations.
    Blanket,
}

/// Represents a normalized trait implementation for comparison and storage.
///
/// Apart from the optional `impl_id`, this trait description is decoupled
/// from any specific implementation so it can be used to render common
/// traits for a crate or module. Unless changing the design, keep this
/// comment, otherwise someone will make the mistake of adding implementation
/// state to this struct.
#[derive(Debug, Clone)]
struct FormattedTraitImpl {
    trait_id: Id,
    /// Generics of the trait path itself (e.g., `<'a>` in `Trait<'a>`).
    /// This `Generics` is from `rustdoc_types` and its internal `CowStr` will have lifetime 'a.
    trait_generics: Generics,
    is_unsafe_impl: bool,
    is_negative: bool,
    /// The category this trait implementation falls into.
    category: TraitImplCategory,
    /// The pre-formatted Markdown list entry for this trait.
    formatted_markdown_list_entry: String,
    /// Optionally link back to the real Impl item in the krate index.
    /// This is useful when representing implementation details for a specific
    /// type, as opposed to common trait implementations for a crate / module.
    /// This link helps track what items have been printed so far.
    impl_id: Option<Id>,
}

impl PartialEq for FormattedTraitImpl {
    /// Compares two FormattedTraitImpl instances for equality.
    /// For common trait identification, `impl_id` and `formatted_markdown_list_entry` are ignored.
    fn eq(&self, other: &Self) -> bool {
        self.trait_id == other.trait_id
            && self.trait_generics == other.trait_generics // Compare trait generics structure
            && self.is_unsafe_impl == other.is_unsafe_impl
            && self.is_negative == other.is_negative
            && self.category == other.category // Compare category
    }
}
impl Eq for FormattedTraitImpl {}

impl Hash for FormattedTraitImpl {
    /// Hashes the FormattedTraitImpl instance.
    /// For common trait identification, `impl_id` and `formatted_markdown_list_entry` are ignored.
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.trait_id.hash(state);
        self.trait_generics.hash(state); // Hash trait generics structure
        self.is_unsafe_impl.hash(state);
        self.is_negative.hash(state);
        self.category.hash(state); // Hash category
    }
}

// Helper function to convert GenericArgs to Generics
// This function attempts to create a Generics struct from GenericArgs.
// It's a simplification, primarily for representing the generics *of a path* (like a trait path).
fn generic_args_to_generics(args_opt: Option<Box<GenericArgs>>, krate: &Crate) -> Generics {
    let mut params = Vec::new();
    let mut where_predicates = Vec::new(); // Not typically part of GenericArgs directly

    if let Some(args_box) = args_opt
        && let GenericArgs::AngleBracketed {
            args, constraints, ..
        } = *args_box
    {
        for arg in args {
            match arg {
                GenericArg::Type(t) => {
                    let name = match t {
                        Type::Generic(g_name) => g_name,
                        _ => format_type(&t, krate), // Fallback to formatted type if not simple generic.
                    };
                    params.push(GenericParamDef {
                        name,
                        kind: rustdoc_types::GenericParamDefKind::Type {
                            bounds: vec![], // Bounds are in `constraints` or `where_predicates`
                            default: None,
                            is_synthetic: false,
                        },
                    });
                }
                GenericArg::Lifetime(lt_name) => {
                    params.push(GenericParamDef {
                        name: lt_name,
                        kind: rustdoc_types::GenericParamDefKind::Lifetime { outlives: vec![] },
                    });
                }
                GenericArg::Const(c) => {
                    params.push(GenericParamDef {
                        name: c.expr,
                        kind: rustdoc_types::GenericParamDefKind::Const {
                            type_: Type::Infer, // Type info might be lost here or in `c.type_`
                            default: None,
                        },
                    });
                }
                GenericArg::Infer => {
                    params.push(GenericParamDef {
                        name: "_".to_string(),
                        kind: rustdoc_types::GenericParamDefKind::Type {
                            bounds: vec![],
                            default: None,
                            is_synthetic: true,
                        },
                    });
                }
            }
        }
        // Convert AssocItemConstraints to WherePredicates (simplified)
        for constraint in constraints {
            match constraint {
                rustdoc_types::AssocItemConstraint {
                    name: assoc_name,
                    args: assoc_args, // GenericArgs for the associated type itself
                    binding: rustdoc_types::AssocItemConstraintKind::Equality(term),
                } => {
                    // Construct a Type for the LHS: Self::AssocName<Args>
                    let lhs_type = Type::QualifiedPath {
                        name: assoc_name,
                        args: assoc_args.clone(),
                        self_type: Box::new(Type::Generic("Self".to_string())), // Placeholder "Self"
                        trait_: None, // Assuming it's an associated type on "Self"
                    };
                    where_predicates.push(WherePredicate::EqPredicate {
                        lhs: lhs_type,
                        rhs: term,
                    });
                }
                rustdoc_types::AssocItemConstraint {
                    name: assoc_name,
                    args: assoc_args,
                    binding: rustdoc_types::AssocItemConstraintKind::Constraint(bounds),
                } => {
                    let for_type = Type::QualifiedPath {
                        name: assoc_name,
                        args: assoc_args.clone(),
                        self_type: Box::new(Type::Generic("Self".to_string())),
                        trait_: None,
                    };
                    where_predicates.push(WherePredicate::BoundPredicate {
                        type_: for_type,
                        bounds,
                        generic_params: vec![], // HRTBs not directly in constraints
                    });
                }
            }
        }
    }

    Generics {
        params,
        where_predicates,
    }
}

fn get_trait_for_type_generics(item: &Item) -> Option<&Generics> {
    match item.inner {
        ItemEnum::Struct(ref s) => Some(&s.generics),
        ItemEnum::Enum(ref e) => Some(&e.generics),
        ItemEnum::Union(ref u) => Some(&u.generics),
        _ => None,
    }
}

fn trait_impl_has_associated_items(imp: &Impl, krate: &Crate) -> bool {
    imp.items.iter().any(|id| {
        if let Some(item) = krate.index.get(id) {
            matches!(
                item.inner,
                ItemEnum::AssocType { .. } | ItemEnum::AssocConst { .. }
            )
        } else {
            false
        }
    })
}

/// Checks if an `Impl` is a "passthrough generic" implementation.
/// This means the `impl` block's generics directly mirror the generics of the type it's for,
/// and the `impl` doesn't introduce its own `where` clauses or complex associated type bindings
/// on the trait path itself.
fn is_passthrough_generic_impl_check(imp: &Impl, trait_path: &Path, krate: &Crate) -> bool {
    // Trait path must have no args or empty angle bracketed args/constraints
    let trait_path_is_simple = trait_path.args.as_ref().is_none_or(|ga| {
        matches!(ga.as_ref(), GenericArgs::AngleBracketed { args, constraints } if args.is_empty() && constraints.is_empty())
    });
    if !trait_path_is_simple {
        return false;
    }

    // Impl must not have associated items (types/consts)
    if trait_impl_has_associated_items(imp, krate) {
        return false;
    }

    // The `for_` type must be a ResolvedPath
    let Type::ResolvedPath(for_path) = &imp.for_ else {
        return false;
    };

    // The `for_` type item must exist and have generics
    let Some(for_type_item) = krate.index.get(&for_path.id) else {
        return false;
    };
    let Some(for_generics) = get_trait_for_type_generics(for_type_item) else {
        return false;
    };

    // The `for_` path must have AngleBracketed args
    let Some(for_args_box) = &for_path.args else {
        // If for_path has no args, then impl must also have no params for passthrough
        return imp.generics.params.is_empty() && imp.generics.where_predicates.is_empty();
    };
    let GenericArgs::AngleBracketed { args: for_args, .. } = for_args_box.as_ref() else {
        return false;
    };

    // Length of generics params must match
    if for_generics.params.len() != for_args.len()
        || for_generics.params.len() != imp.generics.params.len()
    {
        return false;
    }

    // Impl's where predicates must match the for_type's where predicates
    if for_generics.where_predicates != imp.generics.where_predicates {
        return false;
    }

    // Each generic argument in `for_path` must correspond to a generic parameter
    // in `imp.generics` with matching kinds and bounds.
    let impl_params_map: HashMap<&String, &GenericParamDef> =
        imp.generics.params.iter().map(|p| (&p.name, p)).collect();

    for (for_arg, for_param_def) in for_args.iter().zip(for_generics.params.iter()) {
        let for_arg_name = match for_arg {
            GenericArg::Lifetime(name) => Some(name),
            GenericArg::Type(Type::Generic(param_name)) => Some(param_name),
            _ => return false, // For_arg is not a simple generic param
        };

        let Some(for_arg_name_str) = for_arg_name else {
            return false;
        };
        let Some(impl_param_def) = impl_params_map.get(for_arg_name_str) else {
            return false; // Impl does not have a corresponding generic param
        };

        // Compare kinds and bounds (simplified check)
        match (&impl_param_def.kind, &for_param_def.kind) {
            (
                rustdoc_types::GenericParamDefKind::Lifetime {
                    outlives: impl_outlives,
                },
                rustdoc_types::GenericParamDefKind::Lifetime {
                    outlives: for_outlives,
                },
            ) => {
                if impl_outlives != for_outlives {
                    return false;
                }
            }
            (
                rustdoc_types::GenericParamDefKind::Type {
                    bounds: impl_bounds,
                    ..
                },
                rustdoc_types::GenericParamDefKind::Type {
                    bounds: for_bounds, ..
                },
            ) => {
                if impl_bounds != for_bounds {
                    return false;
                }
            }
            (
                rustdoc_types::GenericParamDefKind::Const { .. },
                rustdoc_types::GenericParamDefKind::Const { .. },
            ) => {
                // Basic check, could compare types if necessary
            }
            _ => return false, // Mismatched kinds
        }
    }

    // If all checks pass, it's a passthrough generic impl
    true
}

impl FormattedTraitImpl {
    /// Creates a FormattedTraitImpl from a rustdoc_types::Impl and the krate context.
    fn from_impl(
        imp: &Impl,
        impl_id: Option<Id>,
        trait_path: &Path,
        krate: &Crate,
        printer: &Printer, // Pass printer for generate_impl_trait_block
    ) -> Self {
        let trait_path_str = format_id_path_canonical(&trait_path.id, krate);
        let cleaned_trait_path = clean_trait_path(&trait_path_str);

        let display_path_with_generics = format!(
            "{}{}{}",
            if imp.is_negative {
                "!"
            } else {
                Default::default()
            },
            cleaned_trait_path,
            if let Some(args) = &trait_path.args {
                let args_str = format_generic_args(args, krate);
                if !args_str.is_empty() {
                    format!("<{}>", args_str)
                } else {
                    String::new()
                }
            } else {
                String::new()
            }
        );

        let is_passthrough_generic_impl = is_passthrough_generic_impl_check(imp, trait_path, krate);

        let category = if imp.is_synthetic {
            TraitImplCategory::Auto
        } else if imp.blanket_impl.is_some() {
            TraitImplCategory::Blanket
        } else if is_passthrough_generic_impl && !trait_impl_has_associated_items(imp, krate) {
            TraitImplCategory::Simple
        } else {
            TraitImplCategory::GenericOrComplex
        };

        let mut list_entry = String::new();
        match category {
            TraitImplCategory::Simple | TraitImplCategory::Auto => {
                write!(list_entry, "- `{}`", display_path_with_generics).unwrap();
            }
            TraitImplCategory::GenericOrComplex => {
                if let Some(impl_block_str) = generate_impl_trait_block(imp, printer.krate) {
                    if !impl_block_str.trim_end_matches("{\n}").trim().is_empty() {
                        writeln!(list_entry, "- `{}`", display_path_with_generics).unwrap();
                        writeln!(list_entry).unwrap();
                        let full_code_block = format!("```rust\n{}\n```", impl_block_str);
                        let indented_block = indent_string(&full_code_block, 4);
                        writeln!(list_entry, "{}", indented_block).unwrap(); // Keep trailing newline from indent
                    } else {
                        write!(list_entry, "- `{}`", display_path_with_generics).unwrap();
                    }
                } else {
                    write!(list_entry, "- `{}`", display_path_with_generics).unwrap();
                }
            }
            TraitImplCategory::Blanket => {
                let where_clause =
                    format_generics_where_only(&imp.generics.where_predicates, krate);
                if !where_clause.is_empty() {
                    if where_clause.lines().count() == 1 {
                        write!(
                            list_entry,
                            "- `{}` (`{}`)",
                            display_path_with_generics, where_clause,
                        )
                        .unwrap();
                    } else {
                        writeln!(list_entry, "- `{}`", display_path_with_generics).unwrap();
                        let code_block = format!("```rust\n{}\n```", where_clause);
                        let indented_block = indent_string(&code_block, 4);
                        write!(list_entry, "\n{}\n", indented_block).unwrap(); // Keep trailing newline
                    }
                } else {
                    write!(list_entry, "- `{}`", display_path_with_generics).unwrap();
                }
            }
        }

        FormattedTraitImpl {
            trait_id: trait_path.id,
            trait_generics: generic_args_to_generics(trait_path.args.clone(), krate),
            is_unsafe_impl: imp.is_unsafe,
            is_negative: imp.is_negative,
            category,
            formatted_markdown_list_entry: list_entry.trim_end().to_string(), // Trim trailing newline for consistency
            impl_id,
        }
    }

    /// Retrieves the `Impl` struct from the crate index if `impl_id` is Some.
    fn get_impl_data<'krate_borrow>(
        &self,
        krate: &'krate_borrow Crate,
    ) -> Option<(&'krate_borrow Impl, Id)> {
        self.impl_id
            .and_then(|id| krate.index.get(&id))
            .and_then(|item| match &item.inner {
                ItemEnum::Impl(imp_data) => Some((imp_data, item.id)),
                _ => None,
            })
    }

    /// Checks if the trait (referenced by trait_id) has any associated types or consts.
    #[allow(dead_code)] // Potentially useful later
    fn has_associated_items(&self, krate: &Crate) -> bool {
        if let Some(trait_item) = krate.index.get(&self.trait_id)
            && let ItemEnum::Trait(trait_data) = &trait_item.inner
        {
            return trait_data.items.iter().any(|assoc_id| {
                if let Some(assoc_item_details) = krate.index.get(assoc_id) {
                    matches!(
                        assoc_item_details.inner,
                        ItemEnum::AssocType { .. } | ItemEnum::AssocConst { .. }
                    )
                } else {
                    false
                }
            });
        }
        false
    }
}

/// Generates the primary declaration string for an item (e.g., `struct Foo`, `fn bar()`).
/// For functions, this is deliberately simplified (no attrs, no where clause).
/// For traits, structs, and enums, prepends the current module path.
fn generate_item_declaration(item: &Item, krate: &Crate, current_module_path: &[String]) -> String {
    let name = item.name.as_deref().unwrap_or(match &item.inner {
        ItemEnum::StructField(_) => "{unnamed_field}", // Special case for unnamed fields
        _ => "{unnamed}",
    });
    match &item.inner {
        ItemEnum::Struct(s) => {
            let mut fq_path_parts = current_module_path.to_vec();
            if !name.is_empty() {
                fq_path_parts.push(name.to_string());
            }
            let fq_path = fq_path_parts.join("::");
            format!(
                "struct {}{}",
                fq_path,
                format_generics_params_only(&s.generics.params, krate)
            )
        }
        ItemEnum::Enum(e) => {
            let mut fq_path_parts = current_module_path.to_vec();
            if !name.is_empty() {
                fq_path_parts.push(name.to_string());
            }
            let fq_path = fq_path_parts.join("::");
            format!(
                "enum {}{}",
                fq_path,
                format_generics_params_only(&e.generics.params, krate)
            )
        }
        ItemEnum::Union(u) => {
            let mut fq_path_parts = current_module_path.to_vec();
            if !name.is_empty() {
                fq_path_parts.push(name.to_string());
            }
            let fq_path = fq_path_parts.join("::");
            format!(
                "union {}{}",
                fq_path,
                format_generics_params_only(&u.generics.params, krate)
            )
        }
        ItemEnum::Trait(t) => {
            let unsafe_kw = if t.is_unsafe { "unsafe " } else { "" };
            let auto = if t.is_auto { "auto " } else { "" };
            let mut fq_path_parts = current_module_path.to_vec();
            if !name.is_empty() {
                fq_path_parts.push(name.to_string());
            }
            let fq_path = fq_path_parts.join("::");

            format!(
                "{}{}{}{}{}",
                auto,
                unsafe_kw,
                "trait ",
                fq_path, // Use fully qualified path
                format_generics_params_only(&t.generics.params, krate)
            )
        }
        ItemEnum::Function(f) => {
            // Simplified version for the header: no where clause, but include attributes
            let mut code = String::new();
            write!(code, "{}", format_attributes_inline(&item.attrs)).unwrap(); // Add attributes
            write!(code, "fn {}", name).unwrap();
            // Include only param generics here
            write!(
                code,
                "{}",
                format_generics_params_only(&f.generics.params, krate)
            )
            .unwrap();
            write!(code, "(").unwrap();
            let args_str = f
                .sig
                .inputs
                .iter()
                .map(|(n, t)| format!("{}: {}", n, format_type(t, krate))) // Use arg name from tuple
                .collect::<Vec<_>>()
                .join(", ");
            write!(code, "{}", args_str).unwrap();
            if f.sig.is_c_variadic {
                write!(code, ", ...").unwrap();
            }
            write!(code, ")").unwrap();
            if let Some(output_type) = &f.sig.output {
                write!(code, " -> {}", format_type(output_type, krate)).unwrap();
            }
            code
        }
        ItemEnum::TypeAlias(ta) => format!(
            "type {}{}",
            name,
            format_generics_params_only(&ta.generics.params, krate)
        ),
        ItemEnum::TraitAlias(ta) => format!(
            "trait {}{}",
            name,
            format_generics_params_only(&ta.generics.params, krate)
        ),
        ItemEnum::Constant { .. } => format!("const {}", name), // Type/value in code block
        ItemEnum::Static(s) => format!("static {}{}", if s.is_mutable { "mut " } else { "" }, name),
        ItemEnum::Macro(_) => format!("macro {}!", name),
        ItemEnum::ProcMacro(pm) => {
            let kind_str = match pm.kind {
                rustdoc_types::MacroKind::Bang => "!",
                rustdoc_types::MacroKind::Attr => "#[]",
                rustdoc_types::MacroKind::Derive => "#[derive]",
            };
            format!("proc_macro {}{}", name, kind_str)
        }
        ItemEnum::Primitive(_) => format!("primitive {}", name),
        ItemEnum::Module(_) => format!("mod {}", name), // Use simple name for items within modules
        ItemEnum::ExternCrate {
            name: crate_name, ..
        } => format!("extern crate {}", crate_name),
        ItemEnum::Use(_) => format!("use {}", name), // Basic format for Use items
        ItemEnum::ExternType => format!("extern type {}", name),
        ItemEnum::Variant(v) => format_variant_signature(item, v, krate), // Use helper
        ItemEnum::StructField(_) => name.to_string(), // Field name only for header
        ItemEnum::AssocConst { .. } => format!("const {}", name),
        ItemEnum::AssocType { .. } => format!("type {}", name),
        ItemEnum::Impl(_) => "impl".to_string(), // Impls handled specially
    }
}

/// Generates the `struct { ... }` code block.
fn generate_struct_code_block(item: &Item, s: &Struct, krate: &Crate) -> String {
    let name = item
        .name
        .as_deref()
        .expect("Struct item should have a name");
    let mut code = String::new();
    write!(
        code,
        "{}pub struct {}",
        format_attributes(&item.attrs), // Use multi-line attributes
        name
    )
    .unwrap();
    // Use full generics here, including where clause
    let generics_str = format_generics_full(&s.generics, krate);
    let where_is_multiline = generics_str.contains("where\n");
    write!(code, "{}", generics_str).unwrap();

    match &s.kind {
        StructKind::Plain { fields, .. } => {
            // fields_stripped ignored
            if where_is_multiline {
                write!(code, " {{").unwrap(); // Open brace on same line as multiline where
            } else {
                write!(code, " {{").unwrap(); // Open brace on same line as generics or no generics
            }

            if !fields.is_empty() {
                writeln!(code).unwrap();
            }
            for field_id in fields {
                if let Some(field_item) = krate.index.get(field_id)
                    && let ItemEnum::StructField(field_type) = &field_item.inner
                {
                    let field_name = field_item.name.as_deref().unwrap_or("_");
                    writeln!(
                        code,
                        "    {}pub {}: {},",
                        format_attributes_inline(&field_item.attrs), // Use multi-line attributes
                        field_name,
                        format_type(field_type, krate)
                    )
                    .unwrap();
                }
            }
            if !fields.is_empty() && !code.ends_with('\n') {
                writeln!(code).unwrap();
            }
            write!(code, "}}").unwrap();
        }
        StructKind::Tuple(fields) => {
            // fields_stripped ignored
            write!(code, "(").unwrap();
            let field_types: Vec<String> = fields
                .iter()
                .filter_map(|opt_id| {
                    opt_id
                        .as_ref()
                        .and_then(|id| krate.index.get(id))
                        .and_then(|field_item| {
                            if let ItemEnum::StructField(field_type) = &field_item.inner {
                                Some(format!(
                                    "{}pub {}",
                                    format_attributes_inline(&field_item.attrs), // Use multi-line attributes
                                    format_type(field_type, krate)
                                ))
                            } else {
                                None
                            }
                        })
                })
                .collect();
            write!(code, "{}", field_types.join(", ")).unwrap();
            write!(code, ")").unwrap();
            // Add semicolon only if where clause didn't add one implicitly via multiline format
            if !where_is_multiline {
                write!(code, ";").unwrap();
            }
        }
        StructKind::Unit => {
            // Add semicolon only if where clause didn't add one implicitly
            if !where_is_multiline {
                write!(code, ";").unwrap();
            }
        }
    }
    code
}

/// Generates the `enum { ... }` code block.
fn generate_enum_code_block(item: &Item, e: &Enum, krate: &Crate) -> String {
    let name = item.name.as_deref().expect("Enum item should have a name");
    let mut code = String::new();
    write!(
        code,
        "{}pub enum {}",
        format_attributes(&item.attrs), // Use multi-line attributes
        name
    )
    .unwrap();
    let generics_str = format_generics_full(&e.generics, krate);
    write!(code, "{}", generics_str).unwrap();
    write!(code, " {{").unwrap();

    if !e.variants.is_empty() {
        writeln!(code).unwrap();
    }
    for variant_id in &e.variants {
        if let Some(variant_item) = krate.index.get(variant_id)
            && let ItemEnum::Variant(variant_data) = &variant_item.inner
        {
            write!(
                code,
                "    {}",
                format_variant_definition(variant_item, variant_data, krate) // Pass variant_item
            )
            .unwrap();
            // Add discriminant if present
            if let Some(discr) = &variant_data.discriminant {
                // Use format_discriminant_expr for discriminant
                write!(code, " = {}", format_discriminant_expr(discr)).unwrap();
            }
            writeln!(code, ",").unwrap();
        }
    }
    if !e.variants.is_empty() && !code.ends_with('\n') {
        writeln!(code).unwrap();
    }
    write!(code, "}}").unwrap();
    code
}

/// Generates the `union { ... }` code block.
fn generate_union_code_block(item: &Item, u: &Union, krate: &Crate) -> String {
    let name = item.name.as_deref().expect("Union item should have a name");
    let mut code = String::new();
    write!(
        code,
        "{}pub union {}",
        format_attributes(&item.attrs), // Use multi-line attributes
        name
    )
    .unwrap();
    let generics_str = format_generics_full(&u.generics, krate);
    write!(code, "{}", generics_str).unwrap();
    write!(code, " {{").unwrap();

    if !u.fields.is_empty() {
        writeln!(code).unwrap();
    }
    for field_id in &u.fields {
        if let Some(field_item) = krate.index.get(field_id)
            && let ItemEnum::StructField(field_type) = &field_item.inner
        {
            let field_name = field_item.name.as_deref().unwrap_or("_");
            writeln!(
                code,
                "    {}pub {}: {},",
                format_attributes_inline(&field_item.attrs), // Use multi-line attributes
                field_name,
                format_type(field_type, krate)
            )
            .unwrap();
        }
    }
    if !u.fields.is_empty() && !code.ends_with('\n') {
        writeln!(code).unwrap();
    }
    write!(code, "}}").unwrap();
    code
}

/// Generates the full trait declaration code block.
fn generate_trait_code_block(item: &Item, t: &Trait, krate: &Crate) -> String {
    let name = item.name.as_deref().expect("Trait item should have a name");
    let mut code = String::new();

    write!(code, "{}", format_attributes(&item.attrs)).unwrap(); // Use multi-line attributes

    if t.is_auto {
        write!(code, "pub auto ").unwrap();
    }
    if t.is_unsafe {
        write!(code, "pub unsafe ").unwrap();
    } else if !t.is_auto {
        // Add pub if not auto or unsafe (which imply pub sometimes)
        write!(code, "pub ").unwrap();
    }
    write!(code, "trait {}", name).unwrap();
    // Add generics params and supertraits (bounds)
    write!(
        code,
        "{}",
        format_generics_params_only(&t.generics.params, krate)
    )
    .unwrap();
    if !t.bounds.is_empty() {
        write!(
            code,
            ": {}",
            t.bounds
                .iter()
                .map(|b| format_generic_bound(b, krate))
                .collect::<Vec<_>>()
                .join(" + ")
        )
        .unwrap();
    }
    // Add where clause
    let where_clause = format_generics_where_only(&t.generics.where_predicates, krate);
    if !where_clause.is_empty() {
        if where_clause.contains('\n') {
            write!(code, "\n  {}", where_clause).unwrap(); // Multiline where
        } else {
            write!(code, " {}", where_clause).unwrap(); // Single line where
        }
    }

    // Body
    if t.items.is_empty() {
        write!(code, " {{}}").unwrap();
    } else {
        if where_clause.contains('\n') {
            write!(code, " {{").unwrap(); // Open brace on same line as multiline where
        } else {
            write!(code, " {{").unwrap(); // Open brace on same line as signature
        }
        writeln!(code).unwrap();

        // Print associated items (simple versions)
        for item_id in &t.items {
            if let Some(assoc_item) = krate.index.get(item_id) {
                match &assoc_item.inner {
                    ItemEnum::AssocConst { type_, value, .. } => {
                        write!(
                            code,
                            "    {}const {}: {}",
                            format_attributes_inline(&assoc_item.attrs), // Use multi-line attributes
                            assoc_item.name.as_deref().unwrap_or("_"),
                            format_type(type_, krate)
                        )
                        .unwrap();
                        if let Some(val) = value {
                            write!(code, " = {};", val).unwrap(); // Use raw default string
                        } else {
                            write!(code, ";").unwrap();
                        }
                        writeln!(code).unwrap();
                    }
                    ItemEnum::AssocType { bounds, type_, .. } => {
                        write!(
                            code,
                            "    {}type {}",
                            format_attributes_inline(&assoc_item.attrs), // Use multi-line attributes
                            assoc_item.name.as_deref().unwrap_or("_")
                        )
                        .unwrap();
                        if !bounds.is_empty() {
                            write!(
                                code,
                                ": {}",
                                bounds
                                    .iter()
                                    .map(|b| format_generic_bound(b, krate))
                                    .collect::<Vec<_>>()
                                    .join(" + ")
                            )
                            .unwrap();
                        }
                        if let Some(ty) = type_ {
                            write!(code, " = {};", format_type(ty, krate)).unwrap();
                        } else {
                            write!(code, ";").unwrap();
                        }
                        writeln!(code).unwrap();
                    }
                    ItemEnum::Function(f) => {
                        // Print simple function signature within trait def
                        writeln!(
                            code,
                            "    {};",
                            generate_function_code_block(assoc_item, f, krate)
                        )
                        .unwrap();
                    }
                    _ => {} // Ignore others
                }
            }
        }
        if !code.ends_with('\n') {
            writeln!(code).unwrap();
        }
        write!(code, "}}").unwrap();
    }
    code
}

/// Helper to format an impl block or trait impl declaration line.
fn format_impl_decl(imp: &Impl, krate: &Crate) -> String {
    let mut decl = String::new();
    if imp.is_unsafe {
        write!(decl, "unsafe ").unwrap();
    }
    write!(decl, "impl").unwrap();

    // Add generics params <...>
    let generics_params = format_generics_params_only(&imp.generics.params, krate);
    if !generics_params.is_empty() {
        write!(decl, "{}", generics_params).unwrap();
    }

    // Add Trait for Type
    if let Some(trait_path) = &imp.trait_ {
        write!(decl, " {} for", format_path(trait_path, krate)).unwrap();
    }
    write!(decl, " {}", format_type(&imp.for_, krate)).unwrap();

    // Add where clause
    let where_clause = format_generics_where_only(&imp.generics.where_predicates, krate);
    if !where_clause.is_empty() {
        if where_clause.contains('\n') {
            write!(decl, "\n  {}", where_clause).unwrap(); // Multiline where
        } else {
            write!(decl, " {}", where_clause).unwrap(); // Single line where
        }
    }
    decl
}

/// Helper to format only the header part of an impl declaration (e.g., `impl MyTrait for MyStruct<T>`)
fn format_impl_decl_header_only(imp: &Impl, krate: &Crate) -> String {
    let mut decl = String::new();
    if imp.is_unsafe {
        write!(decl, "unsafe ").unwrap();
    }
    write!(decl, "impl").unwrap();

    // Add generics params <...> to the impl block itself (not the trait part)
    let generics_params = format_generics_params_only(&imp.generics.params, krate);
    if !generics_params.is_empty() {
        write!(decl, "{}", generics_params).unwrap();
    }

    // Add Trait (if it's a trait impl)
    if let Some(trait_path) = &imp.trait_ {
        // For trait impl header, format trait_path with its own generics
        write!(decl, " {} for", format_path(trait_path, krate)).unwrap();
    }

    // Add Type it's for
    write!(decl, " {}", format_type(&imp.for_, krate)).unwrap();

    // DO NOT add where clause here
    decl
}

/// Generates the full code block string for a trait impl, including associated items.
/// Returns None if the impl block was already printed or is effectively empty.
/// Skips methods within the impl block.
fn generate_impl_trait_block(imp: &Impl, krate: &Crate) -> Option<String> {
    let mut code = String::new();
    let impl_header = format_impl_decl(imp, krate);
    writeln!(code, "{} {{", impl_header).unwrap();

    let mut assoc_items_content = String::new();
    let mut has_printable_assoc_items = false;

    // Note: we assume that the caller already checked that the given Impl is selected
    // for printing so we don't also check the individual items.
    for assoc_item_id in &imp.items {
        if let Some(assoc_item) = krate.index.get(assoc_item_id) {
            match &assoc_item.inner {
                ItemEnum::AssocConst { type_, value, .. } => {
                    has_printable_assoc_items = true;
                    write!(
                        assoc_items_content,
                        "    {}const {}: {}",
                        format_attributes_inline(&assoc_item.attrs), // Use multi-line attributes
                        assoc_item.name.as_deref().unwrap_or("_"),
                        format_type(type_, krate)
                    )
                    .unwrap();
                    if let Some(val) = value {
                        write!(assoc_items_content, " = {};", val).unwrap();
                    } else {
                        write!(assoc_items_content, ";").unwrap();
                    }
                    writeln!(assoc_items_content).unwrap();
                }
                ItemEnum::AssocType { bounds, type_, .. } => {
                    has_printable_assoc_items = true;
                    write!(
                        assoc_items_content,
                        "    {}type {}",
                        format_attributes_inline(&assoc_item.attrs), // Use multi-line attributes
                        assoc_item.name.as_deref().unwrap_or("_")
                    )
                    .unwrap();
                    if !bounds.is_empty() {
                        let bounds_str = bounds
                            .iter()
                            .map(|b| format_generic_bound(b, krate))
                            .collect::<Vec<_>>()
                            .join(" + ");
                        write!(assoc_items_content, ": {}", bounds_str).unwrap();
                    }
                    if let Some(ty) = type_ {
                        write!(assoc_items_content, " = {}", format_type(ty, krate)).unwrap();
                    }
                    write!(assoc_items_content, ";").unwrap();
                    writeln!(assoc_items_content).unwrap();
                }
                _ => {}
            }
        }
    }

    if has_printable_assoc_items {
        if impl_header.contains('\n') && !assoc_items_content.starts_with('\n') {
            writeln!(code).unwrap();
        }
        write!(code, "{}", assoc_items_content).unwrap();
        if !code.ends_with('\n') && !assoc_items_content.is_empty() {
            writeln!(code).unwrap();
        }
    } else if impl_header.contains('\n') {
        writeln!(code).unwrap();
    }

    write!(code, "}}").unwrap();
    if !has_printable_assoc_items {
        return None;
    }
    Some(code)
}

/// Generates the full function signature for a code block.
fn generate_function_code_block(item: &Item, f: &Function, krate: &Crate) -> String {
    let name = item.name.as_deref().expect("Function should have a name");
    let mut code = String::new();

    // Attributes/Keywords
    write!(code, "{}", format_attributes_inline(&item.attrs)).unwrap(); // Use inline attributes
    write!(code, "pub ").unwrap();
    if f.header.is_const {
        write!(code, "const ").unwrap();
    }
    if f.header.is_async {
        write!(code, "async ").unwrap();
    }
    if f.header.is_unsafe {
        write!(code, "unsafe ").unwrap();
    }
    if !matches!(f.header.abi, Abi::Rust) {
        write!(code, "extern \"{:?}\" ", f.header.abi).unwrap(); // Use Debug for Abi
    }

    // Core signature
    write!(code, "fn {}", name).unwrap();
    // Include full generics here, including where clause
    let generics_str = format_generics_full(&f.generics, krate);
    let where_is_multiline = generics_str.contains("where\n");
    write!(code, "{}", generics_str).unwrap();

    // Parameters
    write!(code, "(").unwrap();
    let args_str = f
        .sig
        .inputs
        .iter()
        .map(|(n, t)| format!("{}: {}", n, format_type(t, krate))) // Use name from tuple
        .collect::<Vec<_>>()
        .join(", ");
    write!(code, "{}", args_str).unwrap();
    if f.sig.is_c_variadic {
        // Correctly write to the 'code' buffer
        write!(code, ", ...").unwrap();
    }
    write!(code, ")").unwrap();

    // Return type
    if let Some(output_type) = &f.sig.output {
        write!(code, " -> {}", format_type(output_type, krate)).unwrap();
    }

    // Add semicolon or body indicator based on if it has implementation
    if f.has_body {
        if where_is_multiline {
            write!(code, " {{ ... }}").unwrap(); // Body on same line as multiline where
        } else {
            write!(code, " {{ ... }}").unwrap(); // Body on same line
        }
    } else if !where_is_multiline {
        // Add semicolon if it's just a declaration and doesn't already end with one (e.g., from multiline where clause)
        write!(code, ";").unwrap();
    }

    code
}

/// Formats a single enum variant's definition for the code block.
fn format_variant_definition(item: &Item, v: &Variant, krate: &Crate) -> String {
    let name = item.name.as_deref().unwrap_or("{Unnamed}");
    let attrs_str = format_attributes_inline(&item.attrs); // Use multi-line attributes
    match &v.kind {
        VariantKind::Plain => format!("{}{}", attrs_str, name),
        VariantKind::Tuple(fields) => {
            // fields_stripped ignored
            let types: Vec<String> = fields
                .iter()
                .filter_map(|opt_id| {
                    opt_id
                        .as_ref()
                        .and_then(|id| krate.index.get(id))
                        .and_then(|field_item| {
                            if let ItemEnum::StructField(ty) = &field_item.inner {
                                Some(format!(
                                    "{}{}",                                      // No pub for tuple variant fields
                                    format_attributes_inline(&field_item.attrs), // Use multi-line attributes
                                    format_type(ty, krate)
                                ))
                            } else {
                                None
                            }
                        })
                })
                .collect();
            format!("{}{}({})", attrs_str, name, types.join(", "))
        }
        VariantKind::Struct { fields, .. } => {
            // fields_stripped ignored
            let fields_str: Vec<String> = fields
                .iter()
                .filter_map(|id| {
                    krate.index.get(id).and_then(|field_item| {
                        if let ItemEnum::StructField(ty) = &field_item.inner {
                            let field_name = field_item.name.as_deref().unwrap_or("_");
                            Some(format!(
                                "{}{}: {}",                                  // No pub for struct variant fields
                                format_attributes_inline(&field_item.attrs), // Use multi-line attributes
                                field_name,
                                format_type(ty, krate)
                            ))
                        } else {
                            None
                        }
                    })
                })
                .collect();
            format!("{}{}{{ {} }}", attrs_str, name, fields_str.join(", "))
        }
    }
}

/// Formats an enum variant's signature for the `#####` header.
fn format_variant_signature(item: &Item, v: &Variant, krate: &Crate) -> String {
    // Similar to definition but potentially simpler, without pub, maybe add discriminant visually
    // Attributes are NOT included in the Hx header for variants.
    let name = item.name.as_deref().unwrap_or("{Unnamed}");
    let mut sig = match &v.kind {
        VariantKind::Plain => name.to_string(),
        VariantKind::Tuple(fields) => {
            let types: Vec<String> = fields
                .iter()
                .filter_map(|opt_id| {
                    opt_id
                        .as_ref()
                        .and_then(|id| krate.index.get(id))
                        .and_then(|field_item| {
                            if let ItemEnum::StructField(ty) = &field_item.inner {
                                Some(format_type(ty, krate)) // No attributes here
                            } else {
                                None
                            }
                        })
                })
                .collect();
            format!("{}({})", name, types.join(", "))
        }
        VariantKind::Struct { fields, .. } => {
            let fields_str: Vec<String> = fields
                .iter()
                .filter_map(|id| {
                    krate.index.get(id).and_then(|field_item| {
                        if let ItemEnum::StructField(ty) = &field_item.inner {
                            let field_name = field_item.name.as_deref().unwrap_or("_");
                            Some(format!("{}: {}", field_name, format_type(ty, krate)))
                        // No attributes here
                        } else {
                            None
                        }
                    })
                })
                .collect();
            format!("{} {{ {} }}", name, fields_str.join(", "))
        }
    };

    if let Some(discr) = &v.discriminant {
        // Use format_discriminant_expr
        write!(sig, " = {}", format_discriminant_expr(discr)).unwrap();
    }
    sig
}

/// Represents the module hierarchy.
#[derive(Debug, Default, Clone)] // Added Clone derive
struct ModuleTree {
    /// Maps a module ID to its direct submodule IDs.
    children: HashMap<Id, Vec<Id>>,
    /// Stores the IDs of all known modules.
    all_modules: HashSet<Id>,
    /// Stores the IDs of top-level modules (excluding crate root).
    top_level_modules: Vec<Id>,
}

/// `Printer` is responsible for generating Markdown documentation from a [`rustdoc_types::Crate`].
///
/// It uses a builder pattern for configuration. The typical workflow is:
///
/// 1. Create a `Printer` with `Printer::new(&manifest, &krate)`.
/// 2. Configure it using builder methods like [`paths()`](Printer::paths),
///    [`crate_extra()`](Printer::crate_extra), etc.
/// 3. Call [`print()`](Printer::print) to generate the Markdown string.
///
/// ## Features
///
/// - **Path Filtering**: Use [`paths()`](Printer::paths) to specify which items
///   (and their dependencies) should be included in the documentation.
/// - **README and Examples**: Include the crate's README and examples using
///   [`crate_extra()`](Printer::crate_extra) with data from [`CrateExtraReader`].
/// - **"Other" Items**: Control the inclusion of items not fitting standard categories
///   with [`include_other()`](Printer::include_other).
/// - **Template Mode**: Generate template markers instead of documentation content
///   using [`template_mode()`](Printer::template_mode), useful for identifying
///   missing documentation.
/// - **Common Traits Summarization**: By default, traits frequently implemented by types
///   are summarized. This can be disabled with [`no_common_traits()`](Printer::no_common_traits).
///
/// ## Example
///
/// For a complete example of using `Printer` along with other parts of this crate
/// to generate documentation, see the [crate-level documentation](crate).
pub struct Printer<'a> {
    krate: &'a Crate,
    manifest_data: CrateManifestData,
    // Builder options
    paths: Vec<String>,
    crate_extra: Option<CrateExtra>,
    include_other: bool,
    template_mode: bool,
    no_common_traits: bool,
    // Internal state
    selected_ids: HashSet<Id>,
    resolved_modules: HashMap<Id, ResolvedModule>,
    graph: IdGraph,
    printed_ids: HashMap<Id, String>, // Stores ID and the header prefix where it was first printed
    output: String,
    module_tree: ModuleTree,
    doc_path: Vec<usize>,
    current_module_path: Vec<String>,
    crate_common_traits: HashSet<FormattedTraitImpl>,
    all_type_ids_with_impls: HashSet<Id>,
    module_common_traits: HashMap<Id, HashSet<FormattedTraitImpl>>,
}

impl<'a> Printer<'a> {
    /// Creates a new `Printer` instance.
    ///
    /// # Arguments
    ///
    /// * `manifest`: The parsed `Cargo.toml` data for the crate, as a [`cargo_manifest::Manifest`].
    /// * `krate`: The [`rustdoc_types::Crate`] data produced by `rustdoc`.
    pub fn new(manifest: &'a CargoManifest, krate: &'a Crate) -> Self {
        Printer {
            krate,
            manifest_data: CrateManifestData::from_cargo_manifest(manifest),
            paths: Vec::new(),
            crate_extra: None,
            include_other: false,
            template_mode: false,
            no_common_traits: false,
            selected_ids: HashSet::new(), // Will be populated by print()
            resolved_modules: HashMap::new(), // Will be populated by print()
            graph: IdGraph::default(),    // Will be populated by print()
            printed_ids: HashMap::new(),  // Changed to HashMap
            output: String::new(),
            module_tree: Self::build_module_tree(krate), // Initial build based on krate
            doc_path: Vec::new(),
            current_module_path: vec![],
            crate_common_traits: HashSet::new(), // Will be populated by print()
            all_type_ids_with_impls: HashSet::new(), // Will be populated by print()
            module_common_traits: HashMap::new(), // Will be populated during printing
        }
    }

    /// Sets the item path filters for documentation generation.
    ///
    /// Items matching these paths (and their dependencies) will be included.
    ///
    /// ## Path Matching Rules:
    ///
    /// - Paths starting with `::` (e.g., `::my_module::MyStruct`) are treated as absolute
    ///   within the current crate.
    /// - Paths without `::` (e.g., `my_module::MyStruct` or `MyStruct`) are assumed to be
    ///   relative to the crate root and will be prefixed with the crate name (e.g.,
    ///   `crate_name::my_module::MyStruct`).
    /// - Matches are prefix-based. For example, `"::style"` will match `"::style::TextStyle"`
    ///   and `"::style::Color"`.
    ///
    /// If no paths are provided (the default), all items in the crate are considered
    /// for selection.
    pub fn paths(mut self, paths: &[String]) -> Self {
        self.paths = paths.to_vec();
        self
    }

    /// Adds [`CrateExtra`] data (README, examples) to be included in the documentation.
    ///
    /// Use [`CrateExtraReader`] to obtain the `CrateExtra` instance.
    pub fn crate_extra(mut self, extra: CrateExtra) -> Self {
        self.crate_extra = Some(extra);
        self
    }

    /// Includes items that don't fit standard categories in a final "Other" section.
    ///
    /// By default, such items (e.g., unprinted selected items that are not modules,
    /// impls, or struct fields) are logged as warnings and not included in the output.
    /// If this method is called, these items will appear at the end of the documentation,
    /// potentially with their source location and dependency graph context.
    pub fn include_other(mut self) -> Self {
        self.include_other = true;
        self
    }

    /// Enables template mode for documentation output.
    ///
    /// In template mode, instead of the actual documentation content for an item,
    /// Mustache-like markers (e.g., `{{MISSING_DOCS_1_2_1}}`) are inserted.
    /// This is useful for identifying where documentation is present or missing
    /// in the source crate when generating documentation for LLM training or analysis.
    ///
    /// The default is `false` (template mode disabled).
    pub fn template_mode(mut self) -> Self {
        self.template_mode = true;
        self
    }

    /// Disables the "Common Traits" summarization sections.
    ///
    /// By default, traits that are frequently implemented by types within the crate
    /// or specific modules are summarized in "Common Traits" sections at the crate
    /// and module levels. This helps to reduce redundancy in the documentation.
    ///
    /// If this method is called, these summary sections are omitted, and all
    /// implemented traits for each item will be listed directly with that item's
    /// documentation.
    pub fn no_common_traits(mut self) -> Self {
        self.no_common_traits = true;
        self
    }

    /// Generates the Markdown documentation based on the configured options.
    ///
    /// This method consumes the `Printer` and returns the generated Markdown as a `String`.
    /// It performs several steps:
    /// 1. Resolves module items (handling `use` statements).
    /// 2. Selects items based on path filters and builds a dependency graph.
    /// 3. Calculates common traits for the crate.
    /// 4. Prints the crate header, README (if any), and common traits.
    /// 5. Recursively prints modules and their contents.
    /// 6. Prints any remaining "other" items if configured.
    /// 7. Appends examples if configured.
    ///
    /// # Returns
    ///
    /// A `Result` containing the generated Markdown `String`, or an error if
    /// any step fails.
    pub fn print(mut self) -> Result<String> {
        self.resolved_modules = graph::build_resolved_module_index(self.krate);
        let (selected_ids, graph) =
            graph::select_items(self.krate, &self.paths, &self.resolved_modules)?;
        self.selected_ids = selected_ids;
        self.graph = graph;

        info!(
            "Generating documentation for {} selected items.",
            self.selected_ids.len()
        );
        if self.selected_ids.is_empty()
            && self
                .crate_extra
                .as_ref()
                .is_none_or(|ce| ce.examples.is_empty())
        {
            return Ok("No items selected for documentation and no examples found.".to_string());
        }

        let (crate_common_traits, all_type_ids_with_impls) = Self::calculate_crate_common_traits(
            self.krate,
            &self.selected_ids, // Pass reference directly
            self.no_common_traits,
            &self, // Pass self for FormattedTraitImpl::from_impl
        );
        self.crate_common_traits = crate_common_traits;
        self.all_type_ids_with_impls = all_type_ids_with_impls;

        // The finalize method consumes self and returns the String
        Ok(self.finalize())
    }

    /// Pre-calculates common traits for the entire crate.
    fn calculate_crate_common_traits(
        krate: &Crate,
        selected_ids: &HashSet<Id>,
        no_common_traits: bool,
        printer: &Printer,
    ) -> (HashSet<FormattedTraitImpl>, HashSet<Id>) {
        let mut all_type_ids_with_impls = HashSet::new();
        if no_common_traits {
            for item in krate.index.values() {
                if let ItemEnum::Impl(imp) = &item.inner
                    && let Some(for_type_id) = get_type_id(&imp.for_)
                    && selected_ids.contains(&for_type_id)
                {
                    all_type_ids_with_impls.insert(for_type_id);
                }
            }
            return (HashSet::new(), all_type_ids_with_impls);
        }

        // Trait Path ID -> (FormattedTraitImpl -> Count)
        let mut trait_format_counts: HashMap<Id, HashMap<FormattedTraitImpl, usize>> =
            HashMap::new();

        for item in krate.index.values() {
            if let ItemEnum::Impl(imp) = &item.inner
                && let Some(for_type_id) = get_type_id(&imp.for_)
                && selected_ids.contains(&for_type_id)
            {
                all_type_ids_with_impls.insert(for_type_id);
                if let Some(trait_path) = &imp.trait_ {
                    let norm_impl =
                        FormattedTraitImpl::from_impl(imp, None, trait_path, krate, printer);
                    *trait_format_counts
                        .entry(trait_path.id)
                        .or_default()
                        .entry(norm_impl)
                        .or_insert(0) += 1;
                }
            }
        }
        debug!(
            "Found {} types with trait implementations for crate-level common trait calculation.",
            all_type_ids_with_impls.len()
        );

        if all_type_ids_with_impls.len() < 2 {
            debug!("Too few trait implementations, skipping crate 'Common Traits'");
            return (HashSet::new(), all_type_ids_with_impls);
        }

        let mut common_traits_set = HashSet::new();
        if all_type_ids_with_impls.is_empty() {
            return (common_traits_set, all_type_ids_with_impls);
        }

        let type_count_threshold = (all_type_ids_with_impls.len() as f32 * 0.5).ceil() as usize;
        debug!(
            "Crate common trait threshold (types implementing): {} (out of {} types)",
            type_count_threshold,
            all_type_ids_with_impls.len()
        );

        for (trait_id, format_map) in trait_format_counts {
            let total_implementations_for_trait = format_map.values().sum::<usize>();

            if total_implementations_for_trait < type_count_threshold {
                trace!(
                    "Trait ID {:?} not common enough ({} implementations, need {})",
                    trait_id, total_implementations_for_trait, type_count_threshold
                );
                continue;
            }

            // Check for mixed positive/negative implementations
            let mut has_positive = false;
            let mut has_negative = false;
            for f_impl in format_map.keys() {
                if f_impl.is_negative {
                    has_negative = true;
                } else {
                    has_positive = true;
                }
            }
            if has_positive && has_negative {
                warn!(
                    "Trait ID {:?} has mixed positive and negative implementations, cannot be common.",
                    trait_id
                );
                continue;
            }

            if format_map.len() == 1 {
                // Only one format for this trait path
                if let Some(formatted_impl) = format_map.keys().next() {
                    common_traits_set.insert(formatted_impl.clone());
                    debug!(
                        "Identified crate-common trait (single format): {:?} for trait ID {:?}",
                        formatted_impl.formatted_markdown_list_entry, trait_id
                    );
                }
            } else {
                // Multiple formats, check if "Simple" is predominant
                let simple_format_count = format_map
                    .iter()
                    .find(|(f_impl, _)| f_impl.category == TraitImplCategory::Simple)
                    .map_or(0, |(_, count)| *count);

                if simple_format_count * 2 > total_implementations_for_trait {
                    // Simple format is implemented by >50% of *this trait's* implementors
                    if let Some(simple_impl) = format_map
                        .keys()
                        .find(|f_impl| f_impl.category == TraitImplCategory::Simple)
                    {
                        common_traits_set.insert(simple_impl.clone());
                        debug!(
                            "Identified crate-common trait (simple format predominant): {:?} for trait ID {:?}",
                            simple_impl.formatted_markdown_list_entry, trait_id
                        );
                    }
                } else {
                    trace!(
                        "Trait ID {:?} has multiple formats, but Simple is not predominant ({} of {}).",
                        trait_id, simple_format_count, total_implementations_for_trait
                    );
                }
            }
        }
        (common_traits_set, all_type_ids_with_impls)
    }

    /// Calculates common traits for a specific module.
    fn calculate_module_common_traits(&self, module_id: &Id) -> HashSet<FormattedTraitImpl> {
        if self.no_common_traits {
            return HashSet::new();
        }

        let mut module_common_traits = self.crate_common_traits.clone();
        let mut module_types_considered = HashSet::new();

        if let Some(resolved_mod) = self.resolved_modules.get(module_id) {
            for item_id_in_mod in &resolved_mod.items {
                if let Some(item) = self.krate.index.get(item_id_in_mod)
                    && matches!(
                        item.inner,
                        ItemEnum::Struct(_)
                            | ItemEnum::Enum(_)
                            | ItemEnum::Union(_)
                            | ItemEnum::Primitive(_)
                    )
                    && self.selected_ids.contains(item_id_in_mod)
                {
                    let has_impls = self.krate.index.values().any(|idx_item| {
                        if let ItemEnum::Impl(imp) = &idx_item.inner
                            && let Some(for_id) = get_type_id(&imp.for_)
                        {
                            return for_id == *item_id_in_mod;
                        }
                        false
                    });
                    if has_impls {
                        module_types_considered.insert(*item_id_in_mod);
                    }
                }
            }
        }

        let module_types_with_impls_count = module_types_considered.len();
        if module_types_with_impls_count <= 1 {
            return module_common_traits;
        }

        let mut trait_format_counts: HashMap<Id, HashMap<FormattedTraitImpl, usize>> =
            HashMap::new();

        for item_id_in_mod in &module_types_considered {
            for krate_item in self.krate.index.values() {
                if let ItemEnum::Impl(imp) = &krate_item.inner
                    && let Some(for_id) = get_type_id(&imp.for_)
                    && for_id == *item_id_in_mod
                    && let Some(trait_path) = &imp.trait_
                {
                    let norm_impl =
                        FormattedTraitImpl::from_impl(imp, None, trait_path, self.krate, self);
                    *trait_format_counts
                        .entry(trait_path.id)
                        .or_default()
                        .entry(norm_impl)
                        .or_insert(0) += 1;
                }
            }
        }

        let type_count_threshold = (module_types_with_impls_count as f32 * 0.5).ceil() as usize;
        debug!(
            "Module {:?} common trait threshold (types implementing): {} (out of {} types in module)",
            module_id, type_count_threshold, module_types_with_impls_count
        );

        for (trait_id, format_map) in trait_format_counts {
            let total_implementations_for_trait = format_map.values().sum::<usize>();

            if total_implementations_for_trait < type_count_threshold {
                trace!(
                    "Module {:?} trait ID {:?} not common enough ({} implementations, need {})",
                    module_id, trait_id, total_implementations_for_trait, type_count_threshold
                );
                continue;
            }

            let mut has_positive = false;
            let mut has_negative = false;
            for f_impl in format_map.keys() {
                if f_impl.is_negative {
                    has_negative = true;
                } else {
                    has_positive = true;
                }
            }
            if has_positive && has_negative {
                warn!(
                    "Module {:?} trait ID {:?} has mixed positive and negative implementations, cannot be common.",
                    module_id, trait_id
                );
                continue;
            }

            if format_map.len() == 1 {
                if let Some(formatted_impl) = format_map.keys().next()
                    && module_common_traits.insert(formatted_impl.clone())
                {
                    debug!(
                        "Identified module-specific common trait (single format) for {:?}: {:?} for trait ID {:?}",
                        self.krate
                            .paths
                            .get(module_id)
                            .map(|p| p.path.join("::"))
                            .unwrap_or_default(),
                        formatted_impl.formatted_markdown_list_entry,
                        trait_id
                    );
                }
            } else {
                let simple_format_count = format_map
                    .iter()
                    .find(|(f_impl, _)| f_impl.category == TraitImplCategory::Simple)
                    .map_or(0, |(_, count)| *count);

                if simple_format_count * 2 > total_implementations_for_trait {
                    if let Some(simple_impl) = format_map
                        .keys()
                        .find(|f_impl| f_impl.category == TraitImplCategory::Simple)
                        && module_common_traits.insert(simple_impl.clone())
                    {
                        debug!(
                            "Identified module-specific common trait (simple format predominant) for {:?}: {:?} for trait ID {:?}",
                            self.krate
                                .paths
                                .get(module_id)
                                .map(|p| p.path.join("::"))
                                .unwrap_or_default(),
                            simple_impl.formatted_markdown_list_entry,
                            trait_id
                        );
                    }
                } else {
                    trace!(
                        "Module {:?} trait ID {:?} has multiple formats, but Simple is not predominant ({} of {}).",
                        module_id, trait_id, simple_format_count, total_implementations_for_trait
                    );
                }
            }
        }
        module_common_traits
    }

    /// Builds the module hierarchy tree.
    fn build_module_tree(krate: &'a Crate) -> ModuleTree {
        let mut tree = ModuleTree::default();
        let mut parent_map: HashMap<Id, Id> = HashMap::new(); // Child -> Parent

        for (id, item) in &krate.index {
            if let ItemEnum::Module(module_data) = &item.inner {
                tree.all_modules.insert(*id);
                let mut children = Vec::new();
                for child_id in &module_data.items {
                    if let Some(child_item) = krate.index.get(child_id)
                        && let ItemEnum::Module(_) = child_item.inner
                    {
                        children.push(*child_id);
                        parent_map.insert(*child_id, *id);
                    }
                }
                if !children.is_empty() {
                    // Sort children alphabetically by name/path here for consistent ordering within a parent
                    children.sort_by_key(|child_id| {
                        krate
                            .paths
                            .get(child_id)
                            .map(|p| p.path.join("::"))
                            .unwrap_or_default()
                    });
                    tree.children.insert(*id, children);
                }
            }
        }

        // Identify top-level modules (excluding crate root)
        for module_id in &tree.all_modules {
            if *module_id != krate.root && !parent_map.contains_key(module_id) {
                tree.top_level_modules.push(*module_id);
            }
        }

        // Sort top-level modules alphabetically by path
        tree.top_level_modules.sort_by_key(|id| {
            krate
                .paths
                .get(id)
                .map(|p| p.path.join("::"))
                .unwrap_or_default()
        });

        tree
    }

    /// Gets the current markdown header level based on the doc_path length.
    fn get_current_header_level(&self) -> usize {
        self.doc_path.len() + 1 // H1 if path is empty, H2 if path has one element, etc.
    }

    /// Generates the header prefix string (e.g., "1.2.1:") based on the doc_path stack.
    /// H2 headers always get just "N:". H3+ get the full path "N.M.O:".
    fn get_header_prefix(&self) -> String {
        let level = self.get_current_header_level();
        if self.doc_path.is_empty() || level < 2 {
            return String::new(); // No prefix for H1 or if stack is empty
        }

        if level == 2 {
            // Module headers (H2) use only the last element (the H2 counter)
            format!("{}:", self.doc_path.last().unwrap_or(&0))
        } else {
            // H3+ headers use the full path stored in doc_path
            self.doc_path
                .iter()
                .map(|n| n.to_string())
                .collect::<Vec<_>>()
                .join(".")
                + ":"
        }
    }

    /// Generates the template marker string (e.g., "{{MISSING_DOCS_1_2_1}}")
    fn get_template_marker(&self) -> String {
        if self.doc_path.is_empty() {
            "{{MISSING_DOCS}}".to_string()
        } else {
            format!(
                "{{{{MISSING_DOCS_{}}}}}", // Double {{ for literal {
                self.doc_path
                    .iter()
                    .map(|n| n.to_string())
                    .collect::<Vec<_>>()
                    .join("_")
            )
        }
    }

    /// Increments the counter for the current document level.
    /// Note: we increment _after_ outputting something at a given level because
    /// we always initialize the level to 1 via `doc_path.push(1)`
    fn post_increment_current_level(&mut self) {
        if let Some(last) = self.doc_path.last_mut() {
            *last += 1;
        } else {
            warn!("Attempted to increment document path level when path was empty.");
        }
    }

    /// Pushes a new level (starting at 1) onto the document path.
    fn push_level(&mut self) {
        self.doc_path.push(1);
    }

    /// Pops the last level from the document path.
    fn pop_level(&mut self) {
        self.doc_path.pop();
    }

    fn get_item_kind(&self, id: &Id) -> Option<ItemKind> {
        // Prefer index over paths for kind, as paths might be missing for some items?
        self.krate
            .index
            .get(id)
            .map(Printer::infer_item_kind) // Use associated function syntax
            .or_else(|| self.krate.paths.get(id).map(|summary| summary.kind))
    }

    // Fallback for inferring ItemKind if not found in paths map (should be equivalent to index anyway)
    pub(crate) fn infer_item_kind(item: &Item) -> ItemKind {
        match item.inner {
            ItemEnum::Module(_) => ItemKind::Module,
            ItemEnum::ExternCrate { .. } => ItemKind::ExternCrate,
            ItemEnum::Use { .. } => ItemKind::Use, // Keep Use kind for completeness
            ItemEnum::Union(_) => ItemKind::Union,
            ItemEnum::Struct(_) => ItemKind::Struct,
            ItemEnum::StructField(_) => ItemKind::StructField,
            ItemEnum::Enum(_) => ItemKind::Enum,
            ItemEnum::Variant(_) => ItemKind::Variant,
            ItemEnum::Function(_) => ItemKind::Function,
            ItemEnum::Trait(_) => ItemKind::Trait,
            ItemEnum::TraitAlias(_) => ItemKind::TraitAlias,
            ItemEnum::Impl { .. } => ItemKind::Impl,
            ItemEnum::TypeAlias(_) => ItemKind::TypeAlias,
            ItemEnum::Constant { .. } => ItemKind::Constant, // Use struct pattern
            ItemEnum::Static(_) => ItemKind::Static,
            ItemEnum::ExternType => ItemKind::ExternType, // Renamed
            ItemEnum::Macro(_) => ItemKind::Macro,
            ItemEnum::ProcMacro(ref pm) => match pm.kind {
                rustdoc_types::MacroKind::Bang => ItemKind::Macro, // Treat bang proc macro as Macro kind
                rustdoc_types::MacroKind::Attr => ItemKind::ProcAttribute,
                rustdoc_types::MacroKind::Derive => ItemKind::ProcDerive,
            },
            ItemEnum::Primitive(_) => ItemKind::Primitive,
            ItemEnum::AssocConst { .. } => ItemKind::AssocConst,
            ItemEnum::AssocType { .. } => ItemKind::AssocType,
        }
    }

    /// Prints the documentation string for an item, applying template mode if active.
    /// Header level is determined internally by the doc_path.
    fn print_docs(&mut self, item: &Item) {
        let header_level = self.get_current_header_level(); // Level of the item owning the docs
        match (&item.docs, self.template_mode) {
            // Template mode and docs exist: Print mustache marker
            (Some(_), true) => {
                let marker = self.get_template_marker();
                writeln!(self.output, "{}\n", marker).unwrap();
            }
            // Not template mode or no docs: Print original docs if non-empty
            (Some(docs), false) => {
                if !docs.trim().is_empty() {
                    // Use the new adjust_markdown_headers function
                    let adjusted_docs = adjust_markdown_headers(docs.trim(), header_level);
                    writeln!(self.output, "{}\n", adjusted_docs).unwrap();
                }
                // If docs are Some but empty, print nothing (existing behavior)
            }
            // Docs are None: Print nothing
            (None, _) => {}
        }
    }

    /// Prints the details of a single selected item.
    /// Manages the doc_path stack for the item's header.
    /// Returns true if full details were printed, false if a cross-reference was printed or skipped.
    fn print_item_details(&mut self, id: &Id) -> bool {
        if !self.selected_ids.contains(id) {
            return false; // Skip unselected items
        }

        let Some(item) = self.krate.index.get(id) else {
            warn!("Item details for ID {id:?} not found in index");
            return false;
        };

        // Skip printing details for 'Use' items, they are handled by resolution
        // Also skip Modules here, they are handled by the main traversal in finalize
        if matches!(item.inner, ItemEnum::Use(_) | ItemEnum::Module(_)) {
            return false;
        }

        let item_header_level = self.get_current_header_level();
        let header_prefix = self.get_header_prefix();
        let declaration = generate_item_declaration(item, self.krate, &self.current_module_path);

        if let Some(existing_prefix) = self.printed_ids.get(id) {
            // Item already printed, print cross-reference instead of full details
            // This case is primarily for when print_item_details is called directly
            // (e.g., from print_items_of_kind) for an item that was already
            // printed via a different module path.
            writeln!(
                self.output,
                "\n{} {} `{}` (See section {} for details)\n",
                "#".repeat(item_header_level),
                header_prefix,
                declaration,
                existing_prefix
            )
            .unwrap();
            // Do not push/pop level or print further details for cross-referenced item
            return false; // Indicate that full details were not printed
        }

        // Store the prefix *before* printing details, as this is its first detailed print
        self.printed_ids.insert(*id, header_prefix.clone());

        // Print Header (e.g. `### 1.1.1: `declaration``)
        writeln!(
            self.output,
            "\n{} {} `{}`\n", // Add newline after header
            "#".repeat(item_header_level),
            header_prefix,
            declaration
        )
        .unwrap();

        self.push_level();

        // Print Code Block for Struct/Enum/Trait/Function (if needed)
        let code_block = match &item.inner {
            ItemEnum::Struct(s) => Some(generate_struct_code_block(item, s, self.krate)),
            ItemEnum::Enum(e) => Some(generate_enum_code_block(item, e, self.krate)),
            ItemEnum::Union(u) => Some(generate_union_code_block(item, u, self.krate)),
            ItemEnum::Trait(t) => Some(generate_trait_code_block(item, t, self.krate)),
            ItemEnum::Function(f) => {
                // Check if function has attrs or where clause
                let has_attrs = f.header.is_const
                    || f.header.is_async
                    || f.header.is_unsafe
                    || !matches!(f.header.abi, Abi::Rust)
                    || !item.attrs.is_empty(); // Check item.attrs for function attributes
                let has_where = !f.generics.where_predicates.is_empty();
                if has_attrs || has_where {
                    Some(generate_function_code_block(item, f, self.krate))
                } else {
                    None // No code block needed for simple function
                }
            }
            // TODO: Add code blocks for other types like TypeAlias, Constant if desired
            _ => None,
        };

        if let Some(code) = code_block {
            writeln!(self.output, "```rust\n{}\n```\n", code).unwrap();
        }

        let has_stripped = matches!(
            &item.inner,
            ItemEnum::Struct(Struct {
                kind: StructKind::Plain {
                    has_stripped_fields: true,
                    ..
                },
                ..
            })
        );

        if has_stripped {
            writeln!(self.output, "_[Private fields hidden]_\n").unwrap();
        }

        // Print Documentation (using the helper method)
        self.print_docs(item);

        match &item.inner {
            ItemEnum::Struct(s) => self.print_struct_fields(item, s),
            ItemEnum::Enum(e) => self.print_enum_variants(item, e),
            ItemEnum::Union(u) => self.print_union_fields(item, u),
            ItemEnum::Trait(t) => self.print_trait_associated_items(item, t),
            // Add other kinds requiring detailed sections if necessary
            _ => {}
        }

        // Print Implementations (common to Struct, Enum, Trait, Primitive, etc.)
        let impl_ids = match &item.inner {
            ItemEnum::Struct(s) => Some(&s.impls),
            ItemEnum::Enum(e) => Some(&e.impls),
            ItemEnum::Trait(t) => Some(&t.implementations), // Traits list implementors
            ItemEnum::Union(u) => Some(&u.impls),
            ItemEnum::Primitive(p) => Some(&p.impls),
            _ => None,
        };

        if let Some(ids) = impl_ids {
            match &item.inner {
                ItemEnum::Trait(_) => self.print_trait_implementors(ids, item),
                _ => self.print_item_implementations(ids, item),
            }
        }

        self.pop_level();

        true // Full details were printed
    }

    /// Checks if any selected field within a struct has documentation or if template mode is on.
    #[allow(unused)]
    fn has_documented_fields(&self, s: &Struct) -> bool {
        let field_ids = match &s.kind {
            StructKind::Plain { fields, .. } => fields.clone(),
            StructKind::Tuple(fields) => fields.iter().filter_map(|opt_id| *opt_id).collect(),
            StructKind::Unit => vec![],
        };
        field_ids.iter().any(|field_id| {
            self.selected_ids.contains(field_id)
                && self.krate.index.get(field_id).is_some_and(|item| {
                    // Consider it "documented" if template mode is on and docs are Some
                    (self.template_mode && item.docs.is_some()) || has_docs(item)
                })
        })
    }

    /// Prints the "Fields" section for a struct, only if needed.
    /// Also marks fields without documentation as printed.
    fn print_struct_fields(&mut self, _item: &Item, s: &Struct) {
        let all_field_ids: Vec<Id> = match &s.kind {
            StructKind::Plain { fields, .. } => fields.clone(),
            StructKind::Tuple(fields) => fields.iter().filter_map(|opt_id| *opt_id).collect(),
            StructKind::Unit => vec![],
        };

        let mut has_printable_field = false;

        // First pass: Mark unselected/undocumented/non-templated fields printed and check if any are printable.
        for field_id in &all_field_ids {
            if !self.selected_ids.contains(field_id) {
                continue; // Skip unselected fields
            }

            if let Some(item) = self.krate.index.get(field_id) {
                let field_has_printable_docs =
                    (self.template_mode && item.docs.is_some()) || has_docs(item);
                if field_has_printable_docs {
                    // Check if it's already printed to avoid double counting
                    if !self.printed_ids.contains_key(field_id) {
                        has_printable_field = true;
                    }
                } else {
                    // Mark non-printable field as printed immediately
                    self.printed_ids.insert(*field_id, self.get_header_prefix());
                }
            } else {
                // If item doesn't exist in index but ID was present, mark it printed to avoid issues
                self.printed_ids.insert(*field_id, self.get_header_prefix());
            }
        }

        // Only print the "Fields" section if there's a printable field
        if !has_printable_field {
            return;
        }

        let fields_header_level = self.get_current_header_level();
        let header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "{} {} Fields\n", // Add newline after header
            "#".repeat(fields_header_level),
            header_prefix
        )
        .unwrap();

        // Push a new level for the field items themselves
        self.push_level();
        for field_id in &all_field_ids {
            if self.print_field_details(field_id) {
                self.post_increment_current_level();
            }
        }
        self.pop_level(); // Pop the field item level

        self.post_increment_current_level();
    }

    /// Prints the "Fields" section for a union, only if needed.
    fn print_union_fields(&mut self, _item: &Item, u: &Union) {
        let all_field_ids: Vec<Id> = u.fields.clone();
        let mut has_printable_field = false;

        for field_id in &all_field_ids {
            if !self.selected_ids.contains(field_id) {
                continue;
            }
            if let Some(item) = self.krate.index.get(field_id) {
                let field_has_printable_docs =
                    (self.template_mode && item.docs.is_some()) || has_docs(item);
                if field_has_printable_docs {
                    if !self.printed_ids.contains_key(field_id) {
                        has_printable_field = true;
                    }
                } else {
                    self.printed_ids.insert(*field_id, self.get_header_prefix());
                }
            } else {
                self.printed_ids.insert(*field_id, self.get_header_prefix());
            }
        }

        if !has_printable_field && !u.has_stripped_fields {
            return;
        }

        let fields_header_level = self.get_current_header_level();
        let header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "{} {} Fields\n",
            "#".repeat(fields_header_level),
            header_prefix
        )
        .unwrap();

        self.push_level();
        for field_id in &all_field_ids {
            if self.print_field_details(field_id) {
                self.post_increment_current_level();
            }
        }
        if u.has_stripped_fields {
            writeln!(self.output, "_[Private fields hidden]_").unwrap();
        }
        self.pop_level();
        self.post_increment_current_level();
    }

    /// Prints the details for a single struct field, only if it has printable documentation.
    /// Returns true if the field was printed, false otherwise.
    fn print_field_details(&mut self, field_id: &Id) -> bool {
        if !self.selected_ids.contains(field_id) || self.printed_ids.contains_key(field_id) {
            return false; // Skip unselected or already printed
        }

        if let Some(item) = self.krate.index.get(field_id) {
            let field_has_printable_docs =
                (self.template_mode && item.docs.is_some()) || has_docs(item);

            // Only proceed if the field has printable documentation
            if !field_has_printable_docs {
                // Should already be marked printed in print_struct_fields
                return false;
            }

            let header_prefix = self.get_header_prefix();
            // Mark as printed *before* printing details
            self.printed_ids.insert(*field_id, header_prefix.clone());

            if let ItemEnum::StructField(_field_type) = &item.inner {
                let name = item.name.as_deref().unwrap_or("_");
                let field_header_level = self.get_current_header_level();

                // Header: e.g., ##### 1.1.1.1: `field_name`
                writeln!(
                    self.output,
                    "{} {} `{}`\n", // Add newline after header
                    "#".repeat(field_header_level),
                    header_prefix,
                    name
                )
                .unwrap();

                // Print docs (using helper, handles template mode)
                self.print_docs(item);

                // Type (optional, could add here if needed)
                // writeln!(self.output, "_Type: `{}`_\n", format_type(field_type, self.krate)).unwrap();
                return true; // Field was printed
            }
        }
        // Mark as printed even if item lookup failed (shouldn't happen ideally)
        self.printed_ids.insert(*field_id, self.get_header_prefix());
        false
    }

    /// Prints the details for a single enum variant field, only if it has printable documentation.
    /// Returns true if the field was printed, false otherwise.
    fn print_variant_field_details(&mut self, field_id: &Id) -> bool {
        if !self.selected_ids.contains(field_id) || self.printed_ids.contains_key(field_id) {
            return false; // Skip unselected or already printed
        }

        if let Some(item) = self.krate.index.get(field_id) {
            let field_has_printable_docs =
                (self.template_mode && item.docs.is_some()) || has_docs(item);

            // Only proceed if the field has printable documentation
            if !field_has_printable_docs {
                // If no docs, the ID should already be marked printed in print_variant_details
                return false;
            }
            let header_prefix = self.get_header_prefix();
            // Mark as printed *before* printing details
            self.printed_ids.insert(*field_id, header_prefix.clone());

            if let ItemEnum::StructField(_field_type) = &item.inner {
                let name = item.name.as_deref().unwrap_or("_"); // Might be _ for tuple fields
                let field_header_level = self.get_current_header_level();

                // Header: e.g., ###### 1.1.1.1.1: `field_name`
                // Use field index for tuple fields if name is "_" (name is often '0', '1' etc.)
                let header_name = if name == "_" || name.chars().all(|c| c.is_ascii_digit()) {
                    format!("Field {}", name)
                } else {
                    name.to_string()
                };
                writeln!(
                    self.output,
                    "{} {} `{}`\n", // Add newline after header
                    "#".repeat(field_header_level),
                    header_prefix,
                    header_name
                )
                .unwrap();

                // Print Docs (using helper, handles template mode)
                self.print_docs(item);

                // Increment level counter for this field item
                self.post_increment_current_level();

                // Type (optional)
                // writeln!(self.output, "_Type: `{}`_\n", format_type(field_type, self.krate)).unwrap();
                return true; // Field was printed
            }
        }
        // Mark as printed even if item lookup failed
        self.printed_ids.insert(*field_id, self.get_header_prefix());
        false
    }

    /// Checks if any selected variant or its fields have printable documentation.
    #[allow(unused)]
    fn has_printable_variants(&self, e: &Enum) -> bool {
        e.variants.iter().any(|variant_id| {
            if !self.selected_ids.contains(variant_id) {
                return false;
            }
            if let Some(item) = self.krate.index.get(variant_id) {
                // Check variant itself
                if (self.template_mode && item.docs.is_some()) || has_docs(item) {
                    return true;
                }
                // Check fields within the variant
                if let ItemEnum::Variant(v) = &item.inner {
                    let field_ids: Vec<Id> = match &v.kind {
                        VariantKind::Plain => vec![],
                        VariantKind::Tuple(fields) => {
                            fields.iter().filter_map(|opt_id| *opt_id).collect()
                        }
                        VariantKind::Struct { fields, .. } => fields.clone(),
                    };
                    for field_id in field_ids {
                        if self.selected_ids.contains(&field_id)
                            && let Some(f_item) = self.krate.index.get(&field_id)
                            && ((self.template_mode && f_item.docs.is_some()) || has_docs(f_item))
                        {
                            return true;
                        }
                    }
                }
            }
            false
        })
    }

    /// Prints the "Variants" section for an enum, only if needed.
    /// Also marks variants *and their fields* without printable documentation as printed.
    fn print_enum_variants(&mut self, _item: &Item, e: &Enum) {
        let mut has_printable_variant_or_field = false;
        let mut printed_any_variant = false;

        // First pass: Mark non-printable variants/fields printed and check if any are printable.
        for variant_id in &e.variants {
            if !self.selected_ids.contains(variant_id) {
                continue; // Skip unselected variants
            }

            if let Some(item) = self.krate.index.get(variant_id) {
                let variant_has_printable_docs =
                    (self.template_mode && item.docs.is_some()) || has_docs(item);
                let mut variant_has_printable_field = false;

                // Check fields within the variant
                if let ItemEnum::Variant(v) = &item.inner {
                    let field_ids: Vec<Id> = match &v.kind {
                        VariantKind::Plain => vec![],
                        VariantKind::Tuple(fields) => {
                            fields.iter().filter_map(|opt_id| *opt_id).collect()
                        }
                        VariantKind::Struct { fields, .. } => fields.clone(),
                    };

                    for field_id in field_ids {
                        if self.selected_ids.contains(&field_id) {
                            let field_has_printable_docs =
                                self.krate.index.get(&field_id).is_some_and(|f_item| {
                                    (self.template_mode && f_item.docs.is_some())
                                        || has_docs(f_item)
                                });
                            if field_has_printable_docs {
                                if !self.printed_ids.contains_key(&field_id) {
                                    variant_has_printable_field = true;
                                }
                            } else {
                                self.printed_ids.insert(field_id, self.get_header_prefix());
                                // Mark non-printable field printed
                            }
                        } else {
                            // Mark unselected field id printed if present
                            self.printed_ids.insert(field_id, self.get_header_prefix());
                        }
                    }
                }

                if variant_has_printable_docs || variant_has_printable_field {
                    // Check if the variant itself is already printed to avoid double counting
                    if !self.printed_ids.contains_key(variant_id) {
                        has_printable_variant_or_field = true;
                    }
                } else {
                    // Mark non-printable variant (with no printable fields) as printed immediately
                    self.printed_ids
                        .insert(*variant_id, self.get_header_prefix());
                }
            } else {
                // If item doesn't exist in index but ID was present, mark it printed
                self.printed_ids
                    .insert(*variant_id, self.get_header_prefix());
            }
        }

        // Only print the "Variants" section if there's a printable variant/field or stripped variants exist
        if !has_printable_variant_or_field && !e.has_stripped_variants {
            return;
        }

        let variants_header_level = self.get_current_header_level();
        let header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "{} {} Variants\n", // Add newline after header
            "#".repeat(variants_header_level),
            header_prefix
        )
        .unwrap();

        // Push a new level for the variant items themselves
        self.push_level();
        // Second pass: Print details for variants that have printable docs or contain printable fields
        for variant_id in &e.variants {
            if self.print_variant_details(variant_id) {
                printed_any_variant = true;
            }
        }

        if e.has_stripped_variants {
            // Add newline before stripped message only if variants were printed
            if printed_any_variant {
                writeln!(self.output).unwrap();
            }
            writeln!(self.output, "_[Private variants hidden]_").unwrap();
        }
        self.pop_level(); // Pop the variant item level
        self.post_increment_current_level();
    }

    /// Prints the details for a single enum variant. Includes variant docs and docs for its fields if present.
    /// Returns true if the variant was printed (because it or its fields had printable docs), false otherwise.
    fn print_variant_details(&mut self, variant_id: &Id) -> bool {
        if !self.selected_ids.contains(variant_id) {
            // If already printed, do not print full details again.
            // Cross-referencing for variants re-exported in other modules is not typical.
            // If a variant is listed in a module, it's usually because its enum is listed.
            if self.printed_ids.contains_key(variant_id) {
                return false;
            }
        } else if self.printed_ids.contains_key(variant_id) {
            // Already printed, skip
            return false;
        }

        if let Some(item) = self.krate.index.get(variant_id)
            && let ItemEnum::Variant(variant_data) = &item.inner
        {
            let variant_has_printable_docs =
                (self.template_mode && item.docs.is_some()) || has_docs(item);
            let mut printable_fields = Vec::new();
            let mut printed_any_field = false;

            // Determine fields and check their printable docs
            let (field_ids, stripped) = match &variant_data.kind {
                VariantKind::Plain => (vec![], false),
                VariantKind::Tuple(fields) => {
                    (fields.iter().filter_map(|opt_id| *opt_id).collect(), false)
                }
                VariantKind::Struct {
                    fields,
                    has_stripped_fields: s,
                } => (fields.clone(), *s),
            };

            for field_id in &field_ids {
                if self.selected_ids.contains(field_id) {
                    let field_has_printable_docs =
                        self.krate.index.get(field_id).is_some_and(|f_item| {
                            (self.template_mode && f_item.docs.is_some()) || has_docs(f_item)
                        });
                    if field_has_printable_docs && !self.printed_ids.contains_key(field_id) {
                        printable_fields.push(*field_id);
                    } else {
                        // Mark unselected or non-printable field printed
                        self.printed_ids.insert(*field_id, self.get_header_prefix());
                    }
                } else {
                    // Mark unselected field printed
                    self.printed_ids.insert(*field_id, self.get_header_prefix());
                }
            }

            // Only print the variant if it has printable docs OR it has printable fields to print
            if !variant_has_printable_docs && printable_fields.is_empty() {
                // Mark variant as printed if skipped
                self.printed_ids
                    .insert(*variant_id, self.get_header_prefix());
                return false;
            }

            let header_prefix = self.get_header_prefix();
            // Mark as printed *before* printing details
            self.printed_ids.insert(*variant_id, header_prefix.clone());

            let signature = format_variant_signature(item, variant_data, self.krate);
            let variant_header_level = self.get_current_header_level();

            // Header: e.g., ##### 1.1.1.1: `VariantSignature`
            writeln!(
                self.output,
                "{} {} `{}`\n", // Add newline after header
                "#".repeat(variant_header_level),
                header_prefix,
                signature
            )
            .unwrap();
            self.push_level();

            // Print Variant Docs (using helper)
            self.print_docs(item);

            // Print documented fields (if any)
            if !printable_fields.is_empty() || stripped {
                let field_section_level = self.get_current_header_level();
                let fields_header_prefix = self.get_header_prefix();
                writeln!(
                    self.output,
                    "{} {} Fields\n", // Add newline after header
                    "#".repeat(field_section_level),
                    fields_header_prefix
                )
                .unwrap();
                self.push_level();

                for field_id in printable_fields {
                    if self.print_variant_field_details(&field_id) {
                        printed_any_field = true;
                    }
                }

                if stripped {
                    if printed_any_field {
                        writeln!(self.output).unwrap(); // Add newline before stripped message
                    }
                    writeln!(self.output, "_[Private fields hidden]_").unwrap();
                }
                self.pop_level();
            }

            self.pop_level();
            self.post_increment_current_level();

            return true; // Variant (or its fields) was printed
        }
        // Mark as printed even if item lookup failed
        self.printed_ids
            .insert(*variant_id, self.get_header_prefix());
        false
    }

    /// Prints the "Associated Items" section for a trait, categorized.
    fn print_trait_associated_items(&mut self, _trait_item: &Item, t: &Trait) {
        let mut required_types = Vec::new();
        let mut required_methods = Vec::new();
        let mut provided_methods = Vec::new();
        let mut has_printable_assoc_item = false;

        // Filter and categorize selected associated items.
        for item_id in &t.items {
            if !self.selected_ids.contains(item_id) {
                continue;
            }
            // Mark the item as printed now, regardless of docs, to prevent it from going to "Other"
            // Only mark if not already printed elsewhere with a different prefix.
            // This is tricky because an assoc item's "primary" print location is under its trait.
            if !self.printed_ids.contains_key(item_id) {
                self.printed_ids.insert(*item_id, self.get_header_prefix());
            }

            if let Some(assoc_item) = self.krate.index.get(item_id) {
                let item_has_printable_docs =
                    (self.template_mode && assoc_item.docs.is_some()) || has_docs(assoc_item);
                if item_has_printable_docs {
                    has_printable_assoc_item = true;
                }

                match &assoc_item.inner {
                    ItemEnum::AssocType { .. } => {
                        required_types.push((*item_id, item_has_printable_docs));
                    }
                    ItemEnum::Function(f) => {
                        if !f.has_body {
                            required_methods.push((*item_id, item_has_printable_docs));
                        } else {
                            provided_methods.push((*item_id, item_has_printable_docs));
                        }
                    }
                    ItemEnum::AssocConst { .. } => {
                        // For now, treat associated consts similarly to required types or methods.
                        // Could be a separate category if needed.
                        // Let's put them with required types for now as they don't have 'body'.
                        required_types.push((*item_id, item_has_printable_docs));
                    }
                    _ => {} // Ignore others
                }
            }
        }

        // If no selected associated item has printable documentation, skip printing the entire section
        if !has_printable_assoc_item {
            return;
        }

        // Sort items within each category
        required_types.sort_by_key(|(id, _)| self.krate.index.get(id).and_then(|i| i.name.clone()));
        required_methods
            .sort_by_key(|(id, _)| self.krate.index.get(id).and_then(|i| i.name.clone()));
        provided_methods
            .sort_by_key(|(id, _)| self.krate.index.get(id).and_then(|i| i.name.clone()));

        if required_types.iter().any(|(_, has_docs)| *has_docs) {
            let sub_level = self.get_current_header_level();
            let sub_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "{} {} Required Associated Types\n",
                "#".repeat(sub_level),
                sub_prefix
            )
            .unwrap();
            self.push_level();
            for (id, has_docs) in required_types {
                if has_docs {
                    self.print_associated_item_summary(&id);
                }
            }
            self.pop_level();
            self.post_increment_current_level();
        }

        if required_methods.iter().any(|(_, has_docs)| *has_docs) {
            let sub_level = self.get_current_header_level();
            let sub_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "{} {} Required Methods\n",
                "#".repeat(sub_level),
                sub_prefix
            )
            .unwrap();
            self.push_level();
            for (id, has_docs) in required_methods {
                if has_docs {
                    self.print_associated_item_summary(&id);
                }
            }
            self.pop_level();
            self.post_increment_current_level();
        }

        if provided_methods.iter().any(|(_, has_docs)| *has_docs) {
            let sub_level = self.get_current_header_level();
            let sub_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "{} {} Provided Methods\n",
                "#".repeat(sub_level),
                sub_prefix
            )
            .unwrap();
            self.push_level();
            for (id, has_docs) in provided_methods {
                if has_docs {
                    self.print_associated_item_summary(&id);
                }
            }
            self.pop_level();
            self.post_increment_current_level();
        }
    }

    /// Generates the formatted summary string for an associated item (for use within impl blocks or trait defs).
    /// Does NOT include the markdown header. Includes docs with adjusted headers, respecting template mode.
    fn generate_associated_item_summary(&mut self, assoc_item_id: &Id) -> Option<String> {
        if !self.selected_ids.contains(assoc_item_id) {
            return None;
        }
        if let Some(item) = self.krate.index.get(assoc_item_id) {
            let mut summary = String::new();
            // Get level AFTER incrementing for the item header
            // let assoc_item_header_level = self.get_current_header_level(); // Level not needed here

            // Add code block for associated functions if they have attrs/where clauses
            if let ItemEnum::Function(f) = &item.inner {
                let has_attrs = f.header.is_const
                    || f.header.is_async
                    || f.header.is_unsafe
                    || !matches!(f.header.abi, Abi::Rust)
                    || !item.attrs.is_empty(); // Check item.attrs for function attributes
                let has_where = !f.generics.where_predicates.is_empty();
                if has_attrs || has_where {
                    let code = generate_function_code_block(item, f, self.krate);
                    writeln!(summary, "```rust\n{}\n```\n", code).unwrap();
                }
            }

            // Print Documentation (using helper)
            // Create a temporary DocPrinter to isolate output
            let mut temp_printer = self.clone_with_new_output();
            // Copy current doc path to temp printer for correct template marker generation
            temp_printer.doc_path = self.doc_path.clone();
            temp_printer.print_docs(item);
            write!(summary, "{}", temp_printer.output).unwrap();

            // Potentially add default values/bounds for assoc const/type here
            match &item.inner {
                // Use correct fields { type_, value }
                ItemEnum::AssocConst { type_, value } => {
                    writeln!(summary, "_Type: `{}`_", format_type(type_, self.krate)).unwrap();
                    if let Some(val) = value {
                        writeln!(summary, "_Default: `{}`_\n", val).unwrap(); // Add newline
                    }
                }
                ItemEnum::AssocType { bounds, type_, .. } => {
                    // Use renamed field type_
                    if !bounds.is_empty() {
                        let bounds_str = bounds
                            .iter()
                            .map(|b| format_generic_bound(b, self.krate))
                            .collect::<Vec<_>>()
                            .join(" + ");
                        writeln!(summary, "_Bounds: `{}`_", bounds_str).unwrap();
                    }
                    if let Some(ty) = type_ {
                        writeln!(summary, "_Default: `{}`_\n", format_type(ty, self.krate))
                            .unwrap(); // Add newline
                    }
                }
                _ => {}
            }
            Some(summary)
        } else {
            None
        }
    }

    /// Prints the header and summary for a single associated item (const, type, function).
    fn print_associated_item_summary(&mut self, assoc_item_id: &Id) {
        if let Some(item) = self.krate.index.get(assoc_item_id) {
            // Generate summary first (handles template mode internally)
            if let Some(summary) = self.generate_associated_item_summary(assoc_item_id) {
                let declaration =
                    generate_item_declaration(item, self.krate, &self.current_module_path);
                let assoc_item_header_level = self.get_current_header_level();
                let header_prefix = self.get_header_prefix();
                // Print Header (e.g. ##### 1.1.1.1: `declaration`)
                writeln!(
                    self.output,
                    "{} {} `{}`\n", // Add newline after header
                    "#".repeat(assoc_item_header_level),
                    header_prefix,
                    declaration
                )
                .unwrap();
                // Print the generated summary
                if !summary.trim().is_empty() {
                    writeln!(self.output, "{}", summary.trim()).unwrap();
                }
                writeln!(self.output).unwrap(); // Ensure a blank line afterwards

                self.post_increment_current_level();
            }
            // If generate_associated_item_summary returns None, the item wasn't selected,
            // so we don't print anything, and the level increment effectively skips it.
        }
    }

    /// Helper to categorize and format a list of FormattedTraitImpls for display.
    fn format_trait_list(&mut self, traits_to_format: &[FormattedTraitImpl]) -> String {
        if traits_to_format.is_empty() {
            return String::new();
        }

        let mut output = String::new();
        let mut simple_impls = Vec::new();
        let mut generic_or_complex_impls = Vec::new();
        let mut auto_traits = Vec::new();
        let mut blanket_impls = Vec::new();

        for norm_trait in traits_to_format {
            match norm_trait.category {
                TraitImplCategory::Simple => simple_impls.push(norm_trait),
                TraitImplCategory::GenericOrComplex => generic_or_complex_impls.push(norm_trait),
                TraitImplCategory::Auto => auto_traits.push(norm_trait),
                TraitImplCategory::Blanket => blanket_impls.push(norm_trait),
            }
        }

        // Sort each category by the pre-formatted list entry string
        simple_impls.sort_by_key(|t| &t.formatted_markdown_list_entry);
        generic_or_complex_impls.sort_by_key(|t| &t.formatted_markdown_list_entry);
        auto_traits.sort_by_key(|t| &t.formatted_markdown_list_entry);
        blanket_impls.sort_by_key(|t| &t.formatted_markdown_list_entry);

        self.push_level();
        let mut preceding_section = false;

        let mut print_section =
            |traits: &[&FormattedTraitImpl], current_output: &mut String, _section_name: &str| {
                if !traits.is_empty() {
                    if preceding_section {
                        writeln!(current_output).unwrap();
                    }
                    for norm_trait in traits {
                        writeln!(
                            current_output,
                            "{}",
                            norm_trait.formatted_markdown_list_entry
                        )
                        .unwrap();
                        if let Some((trait_impl, impl_id)) = norm_trait.get_impl_data(self.krate) {
                            self.printed_ids.insert(impl_id, self.get_header_prefix());
                            for assoc_item_id in &trait_impl.items {
                                if self.selected_ids.contains(assoc_item_id) {
                                    self.printed_ids
                                        .insert(*assoc_item_id, self.get_header_prefix());
                                }
                            }
                        }
                        self.post_increment_current_level();
                    }
                    preceding_section = true;
                }
            };

        print_section(&simple_impls, &mut output, "Simple");
        print_section(&generic_or_complex_impls, &mut output, "Generic or Complex");
        print_section(&auto_traits, &mut output, "Auto");
        print_section(&blanket_impls, &mut output, "Blanket");

        self.pop_level();
        output
    }

    /// Prints Inherent and Trait Implementations *for* an item (Struct, Enum, Union, Primitive).
    fn print_item_implementations(&mut self, impl_ids: &[Id], target_item: &Item) {
        let target_item_id = target_item.id;
        let target_name = target_item
            .name
            .as_deref()
            .unwrap_or(match &target_item.inner {
                ItemEnum::Primitive(Primitive { name, .. }) => name.as_str(),
                _ => "{unknown_item_type}",
            });

        let mut item_specific_impl_data = Vec::new();
        for impl_id in impl_ids {
            if let Some(impl_item) = self.krate.index.get(impl_id)
                && self.selected_ids.contains(&impl_item.id)
                && let ItemEnum::Impl(imp) = &impl_item.inner
            {
                // Critical: Only consider this impl if it's FOR the target_item_id
                if get_type_id(&imp.for_) == Some(target_item_id) {
                    item_specific_impl_data.push((impl_item, imp.clone()));
                }
            }
        }

        // --- Inherent Impls ---
        let inherent_impl_items: Vec<_> = item_specific_impl_data
            .iter()
            .filter(|(_, imp)| imp.trait_.is_none())
            .collect();

        if !inherent_impl_items.is_empty() {
            for (impl_item, imp) in inherent_impl_items {
                if self.printed_ids.contains_key(&impl_item.id) {
                    continue;
                }
                self.print_impl_block_details(impl_item, imp);
            }
        }

        // --- Trait Impls ---
        let trait_impl_data: Vec<FormattedTraitImpl> = item_specific_impl_data
            .iter()
            .filter_map(|(impl_item, imp)| {
                if self.printed_ids.contains_key(&impl_item.id) {
                    return None; // Skip already printed impls
                }
                imp.trait_.as_ref().map(|tp| {
                    FormattedTraitImpl::from_impl(imp, Some(impl_item.id), tp, self.krate, self)
                })
            })
            .collect();

        if trait_impl_data.is_empty() {
            return;
        }

        let current_module_id = self
            .current_module_path
            .last()
            .and_then(|mod_name| {
                self.resolved_modules
                    .values()
                    .find(|rm| {
                        self.krate
                            .paths
                            .get(&rm.id)
                            .is_some_and(|p| p.path.last() == Some(mod_name))
                    })
                    .map(|rm| rm.id)
            })
            .unwrap_or(self.krate.root);

        let module_common_traits = self
            .module_common_traits
            .get(&current_module_id)
            .cloned()
            .unwrap_or_default();

        let mut non_common_trait_impls = Vec::new();
        let mut missing_module_common_trait_paths = HashSet::new(); // Store trait_id of common traits

        for common_trait_format in &module_common_traits {
            missing_module_common_trait_paths.insert(common_trait_format.trait_id);
        }

        for norm_trait in &trait_impl_data {
            // Check if this trait's path (trait_id) is among the common trait paths
            if module_common_traits
                .iter()
                .any(|ct| ct.trait_id == norm_trait.trait_id)
            {
                // It implements a trait that *could* be common. Remove it from missing.
                missing_module_common_trait_paths.remove(&norm_trait.trait_id);

                // Now check if the *specific format* of this impl is common
                if !module_common_traits.contains(norm_trait) {
                    // The specific format is not common, so list it individually
                    non_common_trait_impls.push(norm_trait.clone());
                } else {
                    // The specific format *is* common, mark it printed
                    if let Some((trait_impl, impl_id)) = norm_trait.get_impl_data(self.krate) {
                        self.printed_ids.insert(impl_id, self.get_header_prefix());
                        for assoc_item_id in &trait_impl.items {
                            if self.selected_ids.contains(assoc_item_id) {
                                self.printed_ids
                                    .insert(*assoc_item_id, self.get_header_prefix());
                            }
                        }
                    }
                }
            } else {
                // This trait path was never common, so list this specific impl
                non_common_trait_impls.push(norm_trait.clone());
            }
        }

        if !non_common_trait_impls.is_empty() || !missing_module_common_trait_paths.is_empty() {
            let trait_impl_header_level = self.get_current_header_level();
            let header_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "{} {} Trait Implementations for `{}`\n",
                "#".repeat(trait_impl_header_level),
                header_prefix,
                target_name
            )
            .unwrap();

            if !missing_module_common_trait_paths.is_empty() {
                let mut sorted_missing_common_trait_names: Vec<String> =
                    missing_module_common_trait_paths
                        .iter()
                        .filter_map(|trait_id| {
                            // Find the corresponding FormattedTraitImpl from module_common_traits
                            // to get its display name (which should be the simple form)
                            module_common_traits
                                .iter()
                                .find(|ct| ct.trait_id == *trait_id)
                                .map(|ct| {
                                    ct.formatted_markdown_list_entry
                                        .split_once("`")
                                        .and_then(|(_, rest)| rest.split_once("`"))
                                        .map(|(path, _)| path.to_string())
                                        .unwrap_or_else(|| {
                                            format_id_path_canonical(trait_id, self.krate)
                                        }) // Fallback
                                })
                        })
                        .collect();
                sorted_missing_common_trait_names.sort_unstable();
                if !sorted_missing_common_trait_names.is_empty() {
                    writeln!(
                        self.output,
                        "**(Note: Does not implement common trait(s): `{}`)**\n",
                        sorted_missing_common_trait_names.join("`, `")
                    )
                    .unwrap();
                }
            }

            let formatted_list = self.format_trait_list(&non_common_trait_impls);
            if !formatted_list.is_empty() {
                write!(self.output, "{}", formatted_list).unwrap();
            }

            self.post_increment_current_level();
        }
    }

    /// Prints implementors *of* a trait. Handles template mode for the impl docs.
    fn print_trait_implementors(&mut self, impl_ids: &[Id], _trait_item: &Item) {
        let implementors: Vec<&Item> = impl_ids
            .iter()
            .filter_map(|id| self.krate.index.get(id))
            .filter(|item| {
                self.selected_ids.contains(&item.id) && matches!(item.inner, ItemEnum::Impl(_))
            })
            .collect();

        if !implementors.is_empty() {
            let implementors_section_level = self.get_current_header_level();
            let header_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "{} {} Implementors\n",
                "#".repeat(implementors_section_level),
                header_prefix
            )
            .unwrap();

            self.push_level();
            for impl_item in implementors {
                if let ItemEnum::Impl(imp) = &impl_item.inner {
                    let impl_header_only = format_impl_decl_header_only(imp, self.krate);
                    let impl_header_level = self.get_current_header_level();
                    let impl_prefix = self.get_header_prefix();

                    writeln!(
                        self.output,
                        "{} {} `{}`\n",
                        "#".repeat(impl_header_level),
                        impl_prefix,
                        impl_header_only.trim()
                    )
                    .unwrap();

                    // Print where clause if it exists
                    if !imp.generics.where_predicates.is_empty() {
                        let where_clause =
                            format_generics_where_only(&imp.generics.where_predicates, self.krate);
                        writeln!(self.output, "```rust\n{}\n```\n", where_clause).unwrap();
                    }

                    // Print docs for the impl block itself
                    let mut temp_printer = self.clone_with_new_output();
                    temp_printer.doc_path = self.doc_path.clone();
                    temp_printer.print_docs(impl_item);
                    write!(self.output, "{}", temp_printer.output).unwrap();

                    // Mark the impl_item ID and its associated items as printed
                    self.printed_ids
                        .insert(impl_item.id, self.get_header_prefix());
                    for assoc_item_id in &imp.items {
                        if self.selected_ids.contains(assoc_item_id) {
                            self.printed_ids
                                .insert(*assoc_item_id, self.get_header_prefix());
                        }
                    }

                    self.post_increment_current_level();
                }
            }
            self.pop_level();
            self.post_increment_current_level();
        }
    }

    /// Prints the details of a specific impl block (header, associated items).
    /// Handles template mode for the impl block's docs.
    fn print_impl_block_details(&mut self, impl_item: &Item, imp: &Impl) {
        let header_prefix = self.get_header_prefix();
        // Mark as printed *now* before printing details
        if self
            .printed_ids
            .insert(impl_item.id, header_prefix.clone())
            .is_some()
        {
            // Already printed with a (potentially different) prefix, skip full details.
            // This case should ideally be caught by the caller, but as a safeguard.
            return;
        }

        // Increment level counter for this impl block
        self.post_increment_current_level();
        let impl_header_level = self.get_current_header_level();
        let impl_header = format_impl_decl(imp, self.krate);

        // Print the impl block header (e.g. #### 1.1.1: `impl ...`)
        writeln!(
            self.output,
            "{} {} `{}`\n", // Add newline after header
            "#".repeat(impl_header_level),
            header_prefix,      // Use the stored/current prefix
            impl_header.trim()  // Trim potential trailing space if no where clause added
        )
        .unwrap();

        // Print impl block docs (using helper)
        // Create a temporary DocPrinter to isolate output
        let mut temp_printer = self.clone_with_new_output();
        // Copy current doc path to temp printer for correct template marker generation
        temp_printer.doc_path = self.doc_path.clone();
        temp_printer.print_docs(impl_item);
        write!(self.output, "{}", temp_printer.output).unwrap();

        // Print associated items within this impl block
        let mut assoc_consts = vec![];
        let mut assoc_types = vec![];
        let mut assoc_fns = vec![];
        for assoc_item_id in &imp.items {
            // Important: Only process associated items that are *selected*
            if !self.selected_ids.contains(assoc_item_id) {
                continue;
            }

            if let Some(assoc_item) = self.krate.index.get(assoc_item_id) {
                match &assoc_item.inner {
                    ItemEnum::AssocConst { .. } => assoc_consts.push(assoc_item_id),
                    ItemEnum::AssocType { .. } => assoc_types.push(assoc_item_id),
                    ItemEnum::Function(_) => assoc_fns.push(assoc_item_id),
                    _ => {} // Should not happen in impl block
                }
            }
        }

        // Push level for associated items within the impl block
        self.push_level();

        if !assoc_consts.is_empty() {
            for id in assoc_consts {
                self.print_associated_item_summary(id);
                if !self.printed_ids.contains_key(id) {
                    self.printed_ids.insert(*id, self.get_header_prefix());
                }
            }
        }
        if !assoc_types.is_empty() {
            for id in assoc_types {
                self.print_associated_item_summary(id);
                if !self.printed_ids.contains_key(id) {
                    self.printed_ids.insert(*id, self.get_header_prefix());
                }
            }
        }
        if !assoc_fns.is_empty() {
            for id in assoc_fns {
                self.print_associated_item_summary(id);
                if !self.printed_ids.contains_key(id) {
                    self.printed_ids.insert(*id, self.get_header_prefix());
                }
            }
        }

        self.pop_level(); // Pop associated item level
    }

    /// Prints items of a specific kind within a given list of IDs.
    fn print_items_of_kind(&mut self, item_ids: &[Id], kind: ItemKind, header_name: &str) -> bool {
        // Filter and sort items of the target kind
        let mut items_to_print: Vec<&Id> = item_ids
            .iter()
            .filter(|id| self.selected_ids.contains(id))
            .filter(|id| self.get_item_kind(id) == Some(kind))
            .collect();

        if items_to_print.is_empty() {
            return false; // Nothing to print for this kind
        }

        items_to_print
            .sort_by_key(|id| self.krate.index.get(id).and_then(|item| item.name.clone()));

        let section_header_level = self.get_current_header_level();
        let header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "\n{} {} {}",
            "#".repeat(section_header_level),
            header_prefix,
            header_name
        )
        .unwrap();

        self.push_level();
        // Print item details
        for id in items_to_print {
            // print_item_details now returns true if full details were printed
            if self.print_item_details(id) {
                self.post_increment_current_level();
            } else {
                // If it was a cross-reference or skipped, we still need to increment
                // the counter for the list item itself if we decide to print a list item.
                // For now, print_item_details handles the cross-ref header.
                // If we change print_module_contents to print list items for cross-refs,
                // then this post_increment might need adjustment.
                // For now, if print_item_details printed a cross-ref header,
                // it means an "item" was output, so we increment.
                self.post_increment_current_level();
            }
        }
        self.pop_level(); // Pop the item level for this section

        true
    }

    /// Prints the non-module contents of a specific module (identified by its ID).
    /// Uses the `resolved_modules` index to get the list of items.
    fn print_module_contents(&mut self, module_id: &Id) {
        if let Some(resolved_module) = self.resolved_modules.get(module_id) {
            let mut items_by_kind: HashMap<ItemKind, Vec<Id>> = HashMap::new();
            let mut cross_referenced_items: Vec<(Id, String, String)> = Vec::new(); // (Id, Declaration, Prefix)

            for id in &resolved_module.items {
                if !self.selected_ids.contains(id) {
                    continue;
                }

                if let Some(existing_prefix) = self.printed_ids.get(id) {
                    if let Some(item) = self.krate.index.get(id) {
                        // Only add to cross-reference list if it's a kind we'd normally list directly
                        if !matches!(
                            item.inner,
                            ItemEnum::Impl(_)
                                | ItemEnum::Use { .. }
                                | ItemEnum::StructField(_)
                                | ItemEnum::Variant(_) // Variants are part of enums
                                | ItemEnum::AssocConst { .. } // Assoc items are part of traits/impls
                                | ItemEnum::AssocType { .. }
                                | ItemEnum::Module(_)
                        ) {
                            let decl = generate_item_declaration(
                                item,
                                self.krate,
                                &self.current_module_path,
                            );
                            cross_referenced_items.push((*id, decl, existing_prefix.clone()));
                        }
                    }
                    continue; // Skip adding to items_by_kind if already printed
                }

                if let Some(kind) = self.get_item_kind(id) {
                    match kind {
                        ItemKind::Impl
                        | ItemKind::Variant // Handled by Enum
                        | ItemKind::StructField // Handled by Struct/Union/Variant
                        | ItemKind::AssocConst // Handled by Trait/Impl
                        | ItemKind::AssocType // Handled by Trait/Impl
                        | ItemKind::Use // Resolved, not printed directly
                        | ItemKind::Module => continue, // Handled by main loop
                        _ => {}
                    }
                    items_by_kind.entry(kind).or_default().push(*id);
                }
            }

            // Sort items by name within each kind
            for ids in items_by_kind.values_mut() {
                ids.sort_by_key(|id| self.krate.index.get(id).and_then(|item| item.name.clone()));
            }
            cross_referenced_items.sort_by_key(|(_, decl, _)| decl.clone());

            let print_order = [
                (ItemKind::Macro, "Macros"),
                (ItemKind::ProcAttribute, "Attribute Macros"),
                (ItemKind::ProcDerive, "Derive Macros"),
                (ItemKind::Struct, "Structs"),
                (ItemKind::Enum, "Enums"),
                (ItemKind::Union, "Unions"),
                (ItemKind::Trait, "Traits"),
                (ItemKind::Function, "Functions"),
                (ItemKind::TypeAlias, "Type Aliases"),
                (ItemKind::TraitAlias, "Trait Aliases"),
                (ItemKind::Static, "Statics"),
                (ItemKind::Constant, "Constants"),
                (ItemKind::ExternCrate, "External Crates"),
                (ItemKind::ExternType, "External Types"),
                (ItemKind::Primitive, "Primitives"),
            ];

            for (kind, header_name) in print_order {
                if let Some(ids) = items_by_kind.get(&kind) {
                    if ids.is_empty() {
                        continue;
                    }
                    if self.print_items_of_kind(ids, kind, header_name) {
                        self.post_increment_current_level();
                    }
                }
            }

            // Print cross-referenced items at the end of the module's direct items
            if !cross_referenced_items.is_empty() {
                let re_exports_header_level = self.get_current_header_level();
                let re_exports_prefix = self.get_header_prefix();
                writeln!(
                    self.output,
                    "\n{} {} Re-exports\n",
                    "#".repeat(re_exports_header_level),
                    re_exports_prefix
                )
                .unwrap();
                for (_id, declaration, original_prefix) in cross_referenced_items {
                    writeln!(
                        self.output,
                        "- `{}` (See section {} for details)",
                        declaration, original_prefix
                    )
                    .unwrap();
                }
                writeln!(self.output).unwrap(); // Add a blank line after the list
                self.post_increment_current_level();
            }
        } else {
            warn!(
                "Could not find resolved module data for ID: {:?}",
                module_id
            );
        }
    }

    /// Prints graph context for an unprinted item.
    fn print_graph_context(&mut self, id: &Id) {
        // Collect incoming edges first to release immutable borrow on self.graph
        let incoming_edges_data: Vec<Edge> = self
            .graph
            .find_incoming_edges(id)
            .into_iter()
            .cloned()
            .collect();

        if !incoming_edges_data.is_empty() {
            writeln!(self.output, "_Referenced by:_").unwrap();
            // Sort edges for consistent output
            let mut sorted_edges = incoming_edges_data;
            sorted_edges.sort_by_key(|edge| {
                (
                    format_id_path_canonical(&edge.source, self.krate),
                    format!("{:?}", edge.label),
                )
            });

            // Push level for this list (for template markers)
            self.push_level();
            for edge in sorted_edges {
                self.post_increment_current_level(); // Increment for this list item
                let source_path = format_id_path_canonical(&edge.source, self.krate);
                let template_marker = if self.template_mode
                    && self
                        .krate
                        .index
                        .get(&edge.source)
                        .is_some_and(|i| i.docs.is_some())
                {
                    format!("\n  {}", self.get_template_marker())
                } else {
                    "".to_string()
                };
                writeln!(
                    self.output,
                    "- `{}` ({}){}",
                    source_path,
                    edge.label, // Use Display impl for EdgeLabel
                    template_marker
                )
                .unwrap();
            }
            self.pop_level(); // Pop list level
            writeln!(self.output).unwrap(); // Add trailing newline
        } else {
            writeln!(
                self.output,
                "_Item has no known incoming references in the graph._\n"
            )
            .unwrap();
        }
    }

    /// Creates a clone of the printer with an empty output buffer.
    fn clone_with_new_output(&self) -> Self {
        Printer {
            krate: self.krate,
            manifest_data: self.manifest_data.clone(),
            paths: self.paths.clone(),
            crate_extra: self.crate_extra.clone(),
            include_other: self.include_other,
            template_mode: self.template_mode,
            no_common_traits: self.no_common_traits,
            selected_ids: self.selected_ids.clone(), // Clone relevant fields
            resolved_modules: self.resolved_modules.clone(),
            graph: self.graph.clone(),
            printed_ids: self.printed_ids.clone(),
            output: String::new(), // New output buffer
            module_tree: self.module_tree.clone(),
            doc_path: self.doc_path.clone(),
            current_module_path: self.current_module_path.clone(),
            crate_common_traits: self.crate_common_traits.clone(),
            all_type_ids_with_impls: self.all_type_ids_with_impls.clone(),
            module_common_traits: self.module_common_traits.clone(),
        }
    }

    /// Recursive function to print modules and their contents depth-first.
    fn print_module_recursive(&mut self, module_id: Id) {
        // Skip if not selected. If already printed, we still need to list its re-exports.
        if module_id != self.krate.root && !self.selected_ids.contains(&module_id) {
            return;
        }

        if let Some(item) = self.krate.index.get(&module_id) {
            // Update current_module_path
            let module_segment = item.name.as_deref().unwrap_or("").to_string();
            if module_id == self.krate.root {
                // For root module, use the crate name
                self.current_module_path = vec![
                    self.krate
                        .index
                        .get(&self.krate.root)
                        .unwrap()
                        .name
                        .as_ref()
                        .unwrap()
                        .replace('-', "_"),
                ];
            } else {
                self.current_module_path.push(module_segment);
            }

            let module_header_level = self.get_current_header_level(); // Should be 2
            let header_prefix = self.get_header_prefix();
            let module_path_str = self.current_module_path.join("::");
            let display_path = if module_path_str.is_empty() {
                item.name.as_deref().unwrap_or("::")
            } else {
                &module_path_str
            };

            // Print module header (always H2)
            writeln!(
                self.output,
                "\n{} {} Module: `{}`\n", // Module header uses level 2
                "#".repeat(module_header_level),
                header_prefix,
                display_path
            )
            .unwrap();

            // Mark module as printed only AFTER printing its header, if not already printed
            // This ensures the first time a module is encountered, its prefix is stored.
            self.printed_ids
                .entry(module_id)
                .or_insert_with(|| header_prefix.clone());

            self.push_level();

            // Print module docs (using helper)
            self.print_docs(item);

            // --- Module Common Traits ---
            if !self.no_common_traits {
                let mod_common = self.calculate_module_common_traits(&module_id);
                self.module_common_traits
                    .insert(module_id, mod_common.clone()); // Store for later use

                let displayable_module_common: Vec<FormattedTraitImpl> = mod_common
                    .iter()
                    .filter(|nt| !self.crate_common_traits.contains(nt)) // Only those not in crate common
                    .cloned()
                    .collect();

                if !displayable_module_common.is_empty() {
                    let common_traits_header_level = self.get_current_header_level(); // Should be H3
                    let common_traits_prefix = self.get_header_prefix();
                    writeln!(
                        self.output,
                        "{} {} Common Traits\n",
                        "#".repeat(common_traits_header_level),
                        common_traits_prefix
                    )
                    .unwrap();
                    writeln!(self.output, "In addition to the crate's 'Common Traits', the following traits are commonly implemented by types in this module. Unless otherwise noted, you can assume these traits are implemented:\n").unwrap();
                    let formatted_list = self.format_trait_list(&displayable_module_common);
                    if !formatted_list.is_empty() {
                        write!(self.output, "{}", formatted_list).unwrap();
                    }
                    self.post_increment_current_level(); // Increment for this section
                }
            }

            // Print module contents (non-module items only)
            self.print_module_contents(&module_id);

            self.pop_level();
            self.post_increment_current_level();

            // Recursively print child modules
            if let Some(children) = self.module_tree.children.get(&module_id).cloned() {
                for child_id in children {
                    self.print_module_recursive(child_id);
                }
            }

            // Restore current_module_path
            if module_id != self.krate.root {
                self.current_module_path.pop();
            }
        }
    }

    /// Finalizes the documentation string, printing the crate header and contents.
    fn finalize(mut self) -> String {
        let root_item = self.krate.index.get(&self.krate.root).unwrap(); // Assume root exists
        let crate_name = root_item.name.as_deref().unwrap_or("Unknown Crate");
        let crate_version = self.krate.crate_version.as_deref().unwrap_or("");
        let crate_header_level = 1; // Level 1 for crate header

        // Clear doc path before starting
        self.doc_path.clear();

        // Print Crate Header (# Crate Name (Version)) - No prefix
        writeln!(
            self.output,
            "{} {} API ({})\n", // Add newline after header
            "#".repeat(crate_header_level),
            crate_name,
            crate_version
        )
        .unwrap();
        // Push H2 level before starting sections/modules
        self.push_level();

        // Print Crate Description (if available) - NEW
        if let Some(desc) = &self.manifest_data.description {
            writeln!(self.output, "{}\n", desc).unwrap();
        }

        // Print Manifest Section (H2) - NEW
        let manifest_section_level = self.get_current_header_level(); // Should be 2
        let manifest_header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "{} {} Manifest\n",
            "#".repeat(manifest_section_level),
            manifest_header_prefix
        )
        .unwrap();

        // Use simple list format for manifest details
        if let Some(hp) = &self.manifest_data.homepage {
            writeln!(self.output, "- Homepage: <{}>", hp).unwrap();
        }
        if let Some(repo) = &self.manifest_data.repository {
            writeln!(self.output, "- Repository: <{}>", repo).unwrap();
        }
        if !self.manifest_data.categories.is_empty() {
            writeln!(
                self.output,
                "- Categories: {}",
                self.manifest_data.categories.join(", ")
            )
            .unwrap();
        }
        if let Some(lic) = &self.manifest_data.license {
            writeln!(self.output, "- License: {}", lic).unwrap();
        }
        if let Some(rv) = &self.manifest_data.rust_version {
            writeln!(self.output, "- rust-version: `{}`", rv).unwrap();
        }
        if let Some(ed) = &self.manifest_data.edition {
            writeln!(self.output, "- edition: `{}`", ed).unwrap();
        }
        writeln!(self.output).unwrap(); // Add a newline after the list

        // Print Features Sub-section (H3) - NEW
        let features_section_level = self.get_current_header_level() + 1; // H3
        self.push_level(); // Push for the H3 features section
        let features_header_prefix = self.get_header_prefix();
        writeln!(
            self.output,
            "{} {} Features\n",
            "#".repeat(features_section_level),
            features_header_prefix
        )
        .unwrap();

        // List features or state None
        if self.manifest_data.features.is_empty() {
            writeln!(self.output, "- None").unwrap();
        } else {
            // Sort features for consistent output
            let mut sorted_features: Vec<_> = self.manifest_data.features.keys().collect();
            sorted_features.sort_unstable();
            for feature_name in sorted_features {
                // TODO: Maybe show what features a feature enables? Requires more parsing.
                writeln!(self.output, "- `{}`", feature_name).unwrap();
            }
        }
        writeln!(self.output).unwrap(); // Add newline after features list
        self.pop_level(); // Pop H3 features level

        // Increment H2 counter for the next section (README or Common Traits)
        self.post_increment_current_level();

        // Print README content if available from CrateExtra
        if let Some(extra) = &self.crate_extra
            && let Some(readme) = &extra.readme_content
        {
            info!("Injecting README content.");
            let section_level = self.get_current_header_level(); // Should be 2
            let header_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "\n{} {} README\n",
                "#".repeat(section_level),
                header_prefix
            )
            .unwrap();
            let adjusted_readme = adjust_markdown_headers(readme, section_level);
            writeln!(self.output, "{}\n", adjusted_readme).unwrap();
            self.post_increment_current_level(); // Increment H2 counter
        }

        // Print Crate Common Traits Section (H2)
        if !self.no_common_traits && !self.crate_common_traits.is_empty() {
            let common_traits_level = self.get_current_header_level(); // Should be 2
            let common_traits_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "\n{} {} Common Traits\n",
                "#".repeat(common_traits_level),
                common_traits_prefix
            )
            .unwrap();
            writeln!(self.output, "The following traits are commonly implemented by types in this crate. Unless otherwise noted, you can assume these traits are implemented:\n").unwrap();

            let sorted_common_traits: Vec<FormattedTraitImpl> = {
                let mut traits: Vec<_> = self.crate_common_traits.iter().cloned().collect();
                traits.sort_by_key(|t| t.formatted_markdown_list_entry.clone());
                traits
            };

            let formatted_list = self.format_trait_list(&sorted_common_traits);
            if !formatted_list.is_empty() {
                write!(self.output, "{}", formatted_list).unwrap();
            }
            writeln!(self.output).unwrap();
            self.post_increment_current_level(); // Increment H2 counter
        }

        // --- Print Top-Level Sections (Macros first, then Modules) ---

        // --- Macros Section (Level 2) ---
        // Find macros directly under the resolved root module
        if let Some(resolved_root_module) = self.resolved_modules.get(&self.krate.root) {
            let macro_ids: Vec<Id> = resolved_root_module
                .items
                .iter()
                .filter(|id| self.selected_ids.contains(id))
                .filter(|id| {
                    matches!(
                        self.get_item_kind(id),
                        Some(ItemKind::Macro | ItemKind::ProcAttribute | ItemKind::ProcDerive)
                    )
                })
                .cloned() // Clone the IDs
                .collect();

            if !macro_ids.is_empty() {
                let section_level = self.get_current_header_level(); // Should be 2
                let header_prefix = self.get_header_prefix();
                writeln!(
                    self.output,
                    "\n{} {} Macros",
                    "#".repeat(section_level),
                    header_prefix
                )
                .unwrap();

                self.push_level(); // Push H3 level for macro items
                let mut sorted_macros = macro_ids;
                sorted_macros
                    .sort_by_key(|id| self.krate.index.get(id).and_then(|item| item.name.clone()));
                for id in sorted_macros {
                    self.print_item_details(&id); // Macro details at level 3
                }
                self.pop_level(); // Pop H3 level
                self.post_increment_current_level(); // Increment H2 counter
            }
        }

        // --- Modules (Depth-First Traversal) ---

        // 1. Print Crate Root Module explicitly (will increment H2 counter)
        self.print_module_recursive(self.krate.root);

        // 2. Iterate through sorted top-level modules and print recursively
        // Clone the list to avoid borrowing issues
        let top_level_ids = self.module_tree.top_level_modules.clone();
        for module_id in top_level_ids {
            self.print_module_recursive(module_id); // Will increment H2 counter
        }

        // --- Handle "Other" Items ---
        let mut unprinted_ids = Vec::new();
        for id in &self.selected_ids {
            if !self.printed_ids.contains_key(id) {
                // Skip impl items and use items as they are handled implicitly or ignored
                // Also skip struct fields as they are handled within their containers
                // Also skip Modules as they are handled explicitly above
                if let Some(item) = self.krate.index.get(id) {
                    if !matches!(
                        item.inner,
                        ItemEnum::Impl(_)
                            | ItemEnum::Use { .. }
                            | ItemEnum::StructField(_)
                            | ItemEnum::Module(_) // Modules explicitly skipped here
                    ) && item.name.is_some()
                    {
                        unprinted_ids.push(*id);
                    }
                    // If it doesn't have a name or is a StructField/Module but is selected & unprinted, mark it printed now to avoid the warning
                    else if item.name.is_none()
                        || matches!(item.inner, ItemEnum::StructField(_) | ItemEnum::Module(_))
                    {
                        self.printed_ids.insert(*id, "SKIPPED_OTHER".to_string());
                    }
                } else {
                    // ID selected but not in index - treat as unprinted for "Other"
                    unprinted_ids.push(*id);
                }
            }
        }

        if !unprinted_ids.is_empty() {
            if self.include_other {
                warn!(
                    "Found {} selected items that were not printed in the main structure. Including them in the 'Other' section.",
                    unprinted_ids.len()
                );
                let other_section_level = self.get_current_header_level(); // Should be 2
                let header_prefix = self.get_header_prefix();
                writeln!(
                    self.output,
                    "\n{} {} Other", // Use ## level for this section
                    "#".repeat(other_section_level),
                    header_prefix
                )
                .unwrap();

                // Push H3 level for items in Other
                self.push_level();
                // Sort unprinted items for consistent output
                unprinted_ids.sort_by_key(|id| {
                    (
                        self.krate.paths.get(id).map(|p| p.path.clone()),
                        self.krate.index.get(id).and_then(|i| i.name.clone()),
                    )
                });

                for id in &unprinted_ids {
                    let path_str = format_id_path_canonical(id, self.krate);
                    warn!("Including unprinted item in 'Other' section: {}", path_str);

                    // Fetch the item to print its header and span
                    if let Some(item) = self.krate.index.get(id) {
                        // Print details (handles level incrementing internally)
                        self.print_item_details(id);

                        // Get level AFTER printing details for graph context
                        // let item_level = self.get_current_header_level(); // Should be H3+1 = H4 // Level not needed here

                        // Print Source Location (if available) ONLY for "Other" items
                        if let Some(span) = &item.span {
                            writeln!(
                                self.output,
                                "_Source: `{}:{}:{}`_\n", // Italic, newline after
                                span.filename.display(),
                                span.begin.0 + 1, // Line numbers are 0-based
                                span.begin.1 + 1  // Column numbers are 0-based
                            )
                            .unwrap();
                        }
                        // Always print graph context afterwards for items in "Other"
                        self.print_graph_context(id);
                    } else {
                        // Handle case where ID is selected but not in index (rare)
                        self.post_increment_current_level(); // Increment level for this item
                        let other_item_level = self.get_current_header_level();
                        let item_prefix = self.get_header_prefix();
                        writeln!(
                            self.output,
                            "\n{} {} `{}`\n",
                            "#".repeat(other_item_level),
                            item_prefix,
                            path_str // Use path string as header
                        )
                        .unwrap();
                        writeln!(self.output, "_Error: Item details not found in index._\n")
                            .unwrap();
                        self.print_graph_context(id); // Still print graph context
                    }
                }
                self.pop_level(); // Pop H3 level for items
            } else {
                // Group by kind and log counts
                let mut counts_by_kind: HashMap<ItemKind, usize> = HashMap::new(); // Use HashMap
                for id in &unprinted_ids {
                    if let Some(kind) = self.get_item_kind(id) {
                        *counts_by_kind.entry(kind).or_insert(0) += 1;
                    } else {
                        // Count items where kind couldn't be determined (e.g., ID not in index)
                        *counts_by_kind.entry(ItemKind::StructField).or_insert(0) += 1;
                        // Use a placeholder kind like StructField
                    }
                }
                warn!(
                    "Skipped printing {} items not fitting into standard sections (use --include-other to see them):",
                    unprinted_ids.len()
                );
                // Convert HashMap to Vec for sorting before printing warnings
                let mut sorted_counts: Vec<_> = counts_by_kind.into_iter().collect();
                sorted_counts.sort_by_key(|(kind, _)| format!("{:?}", kind)); // Sort by debug representation for consistency

                for (kind, count) in sorted_counts {
                    warn!("  - {:?}: {}", kind, count);
                }
            }
        }

        // --- Examples Appendix ---
        // Clone the necessary data from self.crate_extra before the loop
        let examples_readme_content_clone = self
            .crate_extra
            .as_ref()
            .and_then(|extra| extra.examples_readme_content.clone());
        let examples_clone = self
            .crate_extra
            .as_ref()
            .map_or_else(Vec::new, |extra| extra.examples.clone());

        if !examples_clone.is_empty() || examples_readme_content_clone.is_some() {
            let examples_section_level = self.get_current_header_level(); // Should be 2
            let header_prefix = self.get_header_prefix();
            writeln!(
                self.output,
                "\n{} {} Examples Appendix\n",
                "#".repeat(examples_section_level),
                header_prefix
            )
            .unwrap();
            self.push_level(); // Push for H3 example headers

            if let Some(readme) = examples_readme_content_clone {
                let adjusted_readme = adjust_markdown_headers(&readme, examples_section_level);
                writeln!(self.output, "{}\n", adjusted_readme).unwrap();
            }

            for (filename, content) in &examples_clone {
                let example_header_level = self.get_current_header_level(); // Should be 3
                let example_prefix = self.get_header_prefix();
                writeln!(
                    self.output,
                    "{} {} `{}`\n",
                    "#".repeat(example_header_level),
                    example_prefix,
                    filename
                )
                .unwrap();
                writeln!(self.output, "```rust\n{}\n```\n", content).unwrap();
                self.post_increment_current_level(); // Increment H3 counter for next example
            }
            self.pop_level(); // Pop H3 example level
            self.post_increment_current_level(); // Increment H2 counter for next top-level section
        }
        self.output
    }
}