xberg 1.0.5

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 98 formats and 306 programming languages via tree-sitter code intelligence with async/sync APIs.
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
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
//! Main PDF-to-Markdown pipeline orchestrator (oxide backend).

use std::borrow::Cow;

use crate::pdf::bookmarks::PdfOutlineEntry;
use crate::pdf::error::Result;
use crate::pdf::hierarchy::{BoundingBox, SegmentData, TextBlock, assign_heading_levels_smart, cluster_font_sizes};
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use super::assembly::assemble_internal_document;
use super::classify::{
    classify_paragraphs, demote_heading_runs, demote_structure_annotation_headings, demote_unnumbered_subsections,
    mark_arxiv_noise, mark_cross_page_repeating_short_text, mark_cross_page_repeating_text, refine_heading_hierarchy,
};
use super::constants::{FULL_LINE_FRACTION, MIN_BLOCKS_FOR_FONT_HEADING, MIN_HEADING_FONT_GAP, MIN_HEADING_FONT_RATIO};
use super::lines::is_cjk_char;
use super::paragraphs::{merge_continuation_paragraphs, split_embedded_list_items};
use super::text_repair::{
    apply_to_all_segments, clean_duplicate_punctuation, collapse_spaced_hyphens,
    expand_ligatures_with_space_absorption, normalize_text_encoding, normalize_unicode_text,
    repair_contextual_ligatures, repair_ligature_spaces,
};
use super::types::{LayoutHint, PdfParagraph};

const SPARSE_REPEATED_TIER_MIN_PAGES: usize = 2;
const SPARSE_FONT_TIER_CLUSTER_COUNT: usize = 2;
const SPARSE_FONT_TIER_TOLERANCE: f32 = 0.5;
// A tier repeated at the top of multiple pages represents peer sections, not a
// unique document title; reserve H1 for a title and emit these sections as H2. ~keep
const SPARSE_REPEATED_TIER_HEADING_LEVEL: u8 = 2;

type HeadingMap = Vec<(f32, Option<u8>)>;

fn sparse_multi_page_heading_map(
    all_page_segments: &[Vec<SegmentData>],
    heuristic_pages: &[usize],
    all_blocks: &[TextBlock],
    has_struct_tree_blocks: bool,
) -> Result<Option<HeadingMap>> {
    if has_struct_tree_blocks || heuristic_pages.len() < SPARSE_REPEATED_TIER_MIN_PAGES {
        return Ok(None);
    }

    let clusters = cluster_font_sizes(all_blocks, SPARSE_FONT_TIER_CLUSTER_COUNT)?;
    if clusters.len() != SPARSE_FONT_TIER_CLUSTER_COUNT {
        return Ok(None);
    }

    let has_only_two_narrow_font_tiers = all_blocks.iter().all(|block| {
        block.font_size.is_finite()
            && clusters
                .iter()
                .any(|cluster| (block.font_size - cluster.centroid).abs() <= SPARSE_FONT_TIER_TOLERANCE)
    });
    if !has_only_two_narrow_font_tiers {
        return Ok(None);
    }

    let heading_font_size = clusters[0].centroid;
    let body_font_size = clusters[1].centroid;
    let has_distinct_body_tier = heading_font_size - body_font_size > SPARSE_FONT_TIER_TOLERANCE;
    let clears_font_gate = heading_font_size >= body_font_size * MIN_HEADING_FONT_RATIO
        && heading_font_size >= body_font_size + MIN_HEADING_FONT_GAP;
    if !has_distinct_body_tier || !clears_font_gate {
        return Ok(None);
    }

    let repeated_pages: ahash::AHashSet<usize> = heuristic_pages
        .iter()
        .copied()
        .filter(|&page_index| {
            all_page_segments[page_index]
                .iter()
                .find(|segment| !segment.text.trim().is_empty())
                .is_some_and(|segment| {
                    segment.font_size.is_finite()
                        && (segment.font_size - heading_font_size).abs() <= SPARSE_FONT_TIER_TOLERANCE
                })
        })
        .collect();
    if repeated_pages.len() < SPARSE_REPEATED_TIER_MIN_PAGES {
        return Ok(None);
    }

    Ok(Some(
        clusters
            .iter()
            .map(|cluster| {
                let level = ((cluster.centroid - heading_font_size).abs() <= SPARSE_FONT_TIER_TOLERANCE)
                    .then_some(SPARSE_REPEATED_TIER_HEADING_LEVEL);
                (cluster.centroid, level)
            })
            .collect(),
    ))
}

/// Stage 2: Cluster font sizes globally and assign heading levels.
///
/// Returns (heading_map, set of struct-tree page indices needing font-size classification).
#[allow(clippy::type_complexity)]
fn build_heading_map(
    all_page_segments: &[Vec<SegmentData>],
    struct_tree_results: &[Option<Vec<PdfParagraph>>],
    heuristic_pages: &[usize],
    k_clusters: usize,
) -> Result<(Vec<(f32, Option<u8>)>, ahash::AHashSet<usize>)> {
    let struct_tree_needs_classify: ahash::AHashSet<usize> = struct_tree_results
        .iter()
        .enumerate()
        .filter_map(|(i, result)| {
            result.as_ref().and_then(|paragraphs| {
                let has_headings = paragraphs.iter().any(|p| p.heading_level.is_some());
                if !has_headings && has_font_size_variation(paragraphs) {
                    Some(i)
                } else {
                    None
                }
            })
        })
        .collect();

    let mut all_blocks: Vec<TextBlock> = Vec::new();
    let empty_bbox = BoundingBox {
        left: 0.0,
        top: 0.0,
        right: 0.0,
        bottom: 0.0,
    };
    // The text is carried so `assign_heading_levels_smart` can pick the body
    // cluster by character mass (char-weighted body size). Leaving it empty makes
    // every cluster tie at length 0, so `max_by_key` falls back to the smallest
    // font as "body" and over-promotes every larger run to a heading. ~keep
    for &i in heuristic_pages {
        for seg in &all_page_segments[i] {
            if seg.text.trim().is_empty() {
                continue;
            }
            all_blocks.push(TextBlock {
                text: seg.text.clone(),
                bbox: empty_bbox,
                font_size: seg.font_size,
            });
        }
    }
    for &i in &struct_tree_needs_classify {
        if let Some(paragraphs) = &struct_tree_results[i] {
            for para in paragraphs {
                let text = if !para.text.is_empty() {
                    para.text.clone()
                } else {
                    para.lines
                        .iter()
                        .flat_map(|l| l.segments.iter())
                        .map(|s| s.text.as_str())
                        .collect::<Vec<_>>()
                        .join(" ")
                };
                all_blocks.push(TextBlock {
                    text,
                    bbox: empty_bbox,
                    font_size: para.dominant_font_size,
                });
            }
        }
    }

    let paragraph_count = all_blocks.len();
    let heading_map = if all_blocks.is_empty() {
        Vec::new()
    } else if paragraph_count < MIN_BLOCKS_FOR_FONT_HEADING {
        if let Some(map) = sparse_multi_page_heading_map(
            all_page_segments,
            heuristic_pages,
            &all_blocks,
            !struct_tree_needs_classify.is_empty(),
        )? {
            tracing::debug!(
                paragraph_count,
                "heading map: promoting a repeated sparse font tier across pages"
            );
            map
        } else {
            // Sparsity gate: too few text blocks to establish a reliable body-font
            // baseline. Return a body-only map (every cluster centroid mapped to
            // `None`) and skip both k-means heading promotion and the fallback
            // title promotion, so a lone larger line on a cover/title/one-line
            // document is not over-promoted to a heading. ~keep
            tracing::debug!(
                paragraph_count,
                min_blocks = MIN_BLOCKS_FOR_FONT_HEADING,
                "heading map: document too sparse for font-size heading inference; suppressing promotion"
            );
            let clusters = cluster_font_sizes(&all_blocks, 1)?;
            clusters.iter().map(|c| (c.centroid, None)).collect()
        }
    } else {
        let effective_k = if paragraph_count < 20 {
            k_clusters.min(2usize.max(paragraph_count / 4))
        } else {
            k_clusters
        };

        let clusters = cluster_font_sizes(&all_blocks, effective_k)?;
        let mut map = assign_heading_levels_smart(&clusters, MIN_HEADING_FONT_RATIO, MIN_HEADING_FONT_GAP);

        let has_any_heading = map.iter().any(|(_, level)| level.is_some());
        if !has_any_heading && !heuristic_pages.is_empty() {
            let first_page = heuristic_pages[0];
            let first_seg_font = all_page_segments[first_page]
                .iter()
                .find(|s| !s.text.trim().is_empty())
                .map(|s| s.font_size);

            if let Some(first_font) = first_seg_font {
                let mut sizes: Vec<f32> = all_blocks.iter().map(|b| b.font_size).collect();
                sizes.sort_by(|a, b| a.total_cmp(b));
                let median = if sizes.is_empty() { 0.0 } else { sizes[sizes.len() / 2] };

                if median > 0.0
                    && first_font >= median * 1.2
                    && let Some(entry) = map.iter_mut().find(|(fs, _)| (*fs - first_font).abs() < 0.5)
                {
                    entry.1 = Some(1);
                }
            }
        }

        map
    };

    Ok((heading_map, struct_tree_needs_classify))
}

/// Build a heading map from structure-tree-assigned roles on segments.
///
/// Instead of clustering font sizes heuristically, this examines the
/// `assigned_role` field on each segment (populated from the PDF structure tree).
/// Each unique font size is mapped to the heading level most commonly assigned
/// to segments at that size. Font sizes with no assigned role are treated as body text.
fn build_heading_map_from_assigned_roles(all_page_segments: &[Vec<SegmentData>]) -> Vec<(f32, Option<u8>)> {
    use std::collections::HashMap;

    let mut size_roles: HashMap<u32, Vec<Option<u8>>> = HashMap::new();
    for page_segs in all_page_segments {
        for seg in page_segs {
            if seg.text.trim().is_empty() {
                continue;
            }
            let key = (seg.font_size * 10.0).round() as u32;
            size_roles.entry(key).or_default().push(seg.assigned_role);
        }
    }

    let mut heading_map: Vec<(f32, Option<u8>)> = size_roles
        .into_iter()
        .map(|(quantized_size, roles)| {
            let font_size = quantized_size as f32 / 10.0;
            let total = roles.len();
            let mut level_counts: HashMap<u8, usize> = HashMap::new();
            let mut none_count = 0usize;
            for role in &roles {
                match role {
                    Some(level) => *level_counts.entry(*level).or_default() += 1,
                    None => none_count += 1,
                }
            }
            let dominant_level = level_counts
                .into_iter()
                .max_by_key(|(_, count)| *count)
                .and_then(|(level, count)| if count * 2 >= total { Some(level) } else { None });

            if none_count > total / 2 && dominant_level.is_none() {
                (font_size, None)
            } else {
                (font_size, dominant_level)
            }
        })
        .collect();

    heading_map.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));

    heading_map
}

/// Font-size tolerance (points) for merging consecutive raw segments into one
/// logical block in [`count_logical_blocks`]. Matches the font-change
/// threshold `blocks_to_paragraphs` uses to decide paragraph breaks, so a
/// single logical line that a font extractor split into several same-size
/// runs (ligature repair, kerning artifacts, mid-word splits) is not
/// double-counted as multiple blocks.
const LOGICAL_BLOCK_FONT_TOLERANCE: f32 = 1.5;

/// Count logical text blocks by merging consecutive same-role, same-size
/// segments, rather than counting raw segments.
///
/// Raw segment extraction can split one visual line into several runs (a
/// mid-word split from a font-encoding quirk, a bold/italic switch inside a
/// single sentence) that all carry the same `assigned_role`. Counting those
/// raw segments as separate "blocks" over-counts a document's real size and
/// can push a genuinely tiny document (see `hello_structure.pdf`,
/// `issue-987-test.pdf`) above the sparsity floor it should fall under.
/// Consecutive segments on the same page with the same `assigned_role` and a
/// font size within [`LOGICAL_BLOCK_FONT_TOLERANCE`] points collapse into a
/// single block, matching the granularity `total_paragraphs` eventually
/// reports after paragraph assembly.
fn count_logical_blocks(all_page_segments: &[Vec<SegmentData>]) -> usize {
    let mut total = 0usize;
    for page_segs in all_page_segments {
        let mut prev: Option<&SegmentData> = None;
        for seg in page_segs {
            if seg.text.trim().is_empty() {
                continue;
            }
            let continues_prev = prev.is_some_and(|p| {
                p.assigned_role == seg.assigned_role
                    && (p.font_size - seg.font_size).abs() <= LOGICAL_BLOCK_FONT_TOLERANCE
            });
            if !continues_prev {
                total += 1;
            }
            prev = Some(seg);
        }
    }
    total
}

/// Suppress structure-tree heading roles on documents too sparse to trust them.
///
/// A tagged PDF's structure tree is normally a reliable ground truth for
/// heading levels, but on a document with only a handful of text blocks (a
/// one-line note, a cover slide, a two-paragraph test fixture) the same
/// per-block noise that makes font-size clustering unreliable on small
/// samples (see [`MIN_BLOCKS_FOR_FONT_HEADING`] on the heuristic path) also
/// undermines the structure tree: a single mis-tagged or inconsistently
/// authored run is enough to make an entire tiny document look like it is
/// "mostly headings" even when nothing in it is a genuine section heading.
/// Below the same block floor, heading roles are suppressed regardless of
/// whether a body tier is present, matching the heuristic path's rule that
/// a reliable body-font baseline (or, here, a reliable heading/body
/// contrast) needs more than a couple of paragraphs to establish.
///
/// When the condition holds, every segment's `assigned_role` is cleared so
/// paragraph classification (which reads `assigned_role` directly,
/// bypassing the heading map) also treats the document as plain text, and
/// `heading_map` is rewritten to a single body-only entry.
///
/// Returns `true` when suppression fired.
fn suppress_all_heading_roles_when_sparse_and_untrusted(
    heading_map: &mut Vec<(f32, Option<u8>)>,
    all_page_segments: &mut [Vec<SegmentData>],
) -> bool {
    let total_blocks = count_logical_blocks(all_page_segments);
    let has_any_heading = heading_map.iter().any(|(_, level)| level.is_some());

    if total_blocks == 0 || total_blocks >= MIN_BLOCKS_FOR_FONT_HEADING || !has_any_heading {
        return false;
    }

    tracing::debug!(
        total_blocks,
        min_blocks = MIN_BLOCKS_FOR_FONT_HEADING,
        "structure tree: document too sparse to trust tagged heading roles; suppressing all heading roles"
    );

    for page_segs in all_page_segments.iter_mut() {
        for seg in page_segs.iter_mut() {
            seg.assigned_role = None;
        }
    }
    heading_map.clear();
    true
}

/// Promote an untagged document-title font tier above structure-tree headings.
///
/// Word processors tag the document title with a non-heading structure type
/// (e.g. LibreOffice's "Title" style resolves to a non-`H*` element), so
/// `build_heading_map_from_assigned_roles` classifies it as body text even
/// though it is visually the top-level heading. When such a tier exists —
/// strictly larger than every tagged heading font, bold, few segments, and
/// present on the first page — assign it level 1 and demote all tagged
/// heading levels by one (Title = h1, tagged H1 = h2, ...), matching the
/// pandoc/HTML convention that the document title outranks section headings.
///
/// Returns `true` when a title tier was promoted. The caller must then also
/// demote the per-segment `assigned_role` values (see
/// `demote_assigned_roles`), because paragraph classification honours
/// `assigned_role` directly, bypassing the heading map.
fn promote_untagged_document_title(
    heading_map: &mut [(f32, Option<u8>)],
    all_page_segments: &[Vec<SegmentData>],
) -> bool {
    /// A title is a handful of segments at most; more means a body/pull-quote tier.
    const MAX_TITLE_SEGMENTS: usize = 3;

    let Some(max_heading_font) = heading_map
        .iter()
        .filter(|(_, level)| level.is_some())
        .map(|(font, _)| *font)
        .fold(None, |acc: Option<f32>, f| Some(acc.map_or(f, |a| a.max(f))))
    else {
        return false;
    };

    let candidate = heading_map
        .iter()
        .position(|(font, level)| level.is_none() && *font > max_heading_font);
    let Some(candidate_idx) = candidate else {
        return false;
    };
    let candidate_font = heading_map[candidate_idx].0;

    let mut tier_segments = 0usize;
    let mut all_bold = true;
    let mut on_first_page = false;
    for (page_idx, page_segs) in all_page_segments.iter().enumerate() {
        for seg in page_segs {
            if seg.text.trim().is_empty() || (seg.font_size - candidate_font).abs() >= 0.05 {
                continue;
            }
            tier_segments += 1;
            all_bold &= seg.is_bold;
            on_first_page |= page_idx == 0;
        }
    }
    if tier_segments == 0 || tier_segments > MAX_TITLE_SEGMENTS || !all_bold || !on_first_page {
        return false;
    }

    tracing::debug!(
        title_font = candidate_font,
        max_heading_font,
        tier_segments,
        "structure tree: promoting untagged document-title tier to h1, demoting tagged levels"
    );
    for (font, level) in heading_map.iter_mut() {
        if let Some(l) = level {
            *level = Some((*l + 1).min(6));
        } else if (*font - candidate_font).abs() < 0.05 {
            *level = Some(1);
        }
    }
    true
}

/// Demote every structure-tree-assigned heading role by one level (capped at 6).
///
/// Companion to `promote_untagged_document_title`: paragraph classification
/// (`bridge.rs`) uses `assigned_role` directly as "the author's stated intent",
/// so the map-level demotion must be mirrored on the segments themselves.
fn demote_assigned_roles(all_page_segments: &mut [Vec<SegmentData>]) {
    for page_segs in all_page_segments.iter_mut() {
        for seg in page_segs.iter_mut() {
            if let Some(role) = seg.assigned_role {
                seg.assigned_role = Some((role + 1).min(6));
            }
        }
    }
}

/// Per-page input bundle for Stage 3 parallel processing.
///
/// Each page's data is pre-extracted before `into_par_iter` so all threads
/// receive owned, non-overlapping slices of the document's data.
struct PageInput {
    /// Index of this page in the document (0-based).
    page_index: usize,
    /// Paragraphs from the PDF structure tree, if extraction succeeded.
    struct_paragraphs: Option<Vec<PdfParagraph>>,
    /// Segments from heuristic extraction (non-empty only when `struct_paragraphs` is `None`).
    heuristic_segments: Vec<SegmentData>,
    /// Layout hints for this page, if layout detection was run.
    page_hints: Option<Vec<LayoutHint>>,
    /// Bounding boxes of tables that were successfully extracted for this page.
    table_bboxes: Vec<crate::types::BoundingBox>,
    /// Whether native semantic classification should be preserved while layout
    /// hints continue to control reading order and record region provenance.
    preserve_native_semantics: bool,
    /// Whether layout geometry should reorder native paragraphs on this page.
    /// Semantic refinement runs in native order before this spatial order is
    /// applied during final assembly.
    use_layout_reading_order: bool,
    /// Per-hint validation results from CC analysis (parallel to page_hints).
    /// Empty when layout-detection is not active.
    #[cfg(feature = "layout-detection")]
    hint_validations: Vec<super::regions::layout_validation::RegionValidation>,
    /// Actual PDF page width in points, used by layout reading-order refinement.
    #[cfg(feature = "layout-detection")]
    page_width_pts: Option<f32>,
    /// Whether this page's structure-tree paragraphs need font-size classification.
    needs_classify: bool,
    /// Y-coordinates of paragraph gaps detected from segment boundaries.
    paragraph_gap_ys: Vec<f32>,
    /// When true, paragraphs classified as `PageHeader` by the layout model are
    /// preserved rather than marked as furniture. Mirrors `ContentFilterConfig::include_headers`.
    include_headers: bool,
    /// When true, paragraphs classified as `PageFooter` by the layout model are
    /// preserved rather than marked as furniture. Mirrors `ContentFilterConfig::include_footers`.
    include_footers: bool,
}

/// Process a single page's data through Stage 3: classification, text repair,
/// layout overrides, dehyphenation, and list splitting.
///
/// This function is intentionally free of any shared mutable state so it can be
/// called from multiple threads via `rayon::par_iter`.
fn process_single_page(
    input: PageInput,
    heading_map: &[(f32, Option<u8>)],
    doc_body_font_size: Option<f32>,
) -> Vec<PdfParagraph> {
    let PageInput {
        page_index: i,
        struct_paragraphs,
        heuristic_segments,
        page_hints,
        table_bboxes,
        preserve_native_semantics,
        use_layout_reading_order,
        #[cfg(feature = "layout-detection")]
        hint_validations,
        #[cfg(feature = "layout-detection")]
        page_width_pts,
        needs_classify,
        paragraph_gap_ys,
        include_headers,
        include_footers,
    } = input;
    #[cfg(not(feature = "layout-detection"))]
    let _ = preserve_native_semantics;
    #[cfg(not(feature = "layout-detection"))]
    let _ = use_layout_reading_order;
    if let Some(mut paragraphs) = struct_paragraphs {
        apply_text_repair_to_structure_tree_paragraphs(&mut paragraphs, true);
        if needs_classify {
            tracing::debug!(
                page = i,
                "PDF structure pipeline: classifying struct tree page via font-size clustering"
            );
            classify_paragraphs(&mut paragraphs, heading_map);
        }
        merge_continuation_paragraphs(&mut paragraphs);
        synchronize_paragraph_text_metadata(&mut paragraphs);
        merge_spatial_footnote_markers(&mut paragraphs);
        if let Some(ref hints) = page_hints {
            let classification_hints = regular_layout_hints(hints);
            super::layout_classify::apply_layout_overrides(
                &mut paragraphs,
                &classification_hints,
                0.5,
                0.2,
                doc_body_font_size,
            );
            un_mark_layout_furniture_per_config(&mut paragraphs, include_headers, include_footers);
            tracing::debug!(
                page = i,
                headings = paragraphs.iter().filter(|p| p.heading_level.is_some()).count(),
                lists = paragraphs.iter().filter(|p| p.is_list_item).count(),
                furniture = paragraphs.iter().filter(|p| p.is_page_furniture).count(),
                "layout overrides applied"
            );
            retain_page_furniture_safely(&mut paragraphs);
        }
        demote_structure_annotation_headings(&mut paragraphs);
        paragraphs
    } else {
        let page_segments = heuristic_segments;
        tracing::debug!(
            page = i,
            segments = page_segments.len(),
            has_layout_hints = page_hints.is_some(),
            "process_single_page: heuristic path"
        );
        let page_segments = filter_segments_by_table_bboxes(page_segments, &table_bboxes);
        #[cfg(feature = "layout-detection")]
        let mut paragraphs = if let Some(ref hints) = page_hints {
            let wrapper_ownership = wrapper_ownership_by_hint(hints, &hint_validations);
            if use_layout_reading_order
                && crate::extractors::pdf::reading_order::has_eligible_layout_hints(hints, &wrapper_ownership)
            {
                process_layout_segment_groups(
                    page_segments,
                    hints,
                    &wrapper_ownership,
                    LayoutParagraphContext {
                        heading_map,
                        paragraph_gap_ys: &paragraph_gap_ys,
                        doc_body_font_size,
                        include_headers,
                        include_footers,
                        page_width_pts,
                        apply_layout_overrides: !preserve_native_semantics,
                    },
                )
            } else {
                let mut paragraphs = segments_to_paragraphs(page_segments, heading_map, &paragraph_gap_ys);
                let classification_hints = regular_layout_hints(hints);
                super::layout_classify::annotate_layout_classes(&mut paragraphs, &classification_hints, 0.5, 0.2);
                paragraphs
            }
        } else {
            segments_to_paragraphs(page_segments, heading_map, &paragraph_gap_ys)
        };
        #[cfg(not(feature = "layout-detection"))]
        let mut paragraphs = segments_to_paragraphs(page_segments, heading_map, &paragraph_gap_ys);
        tracing::debug!(
            page = i,
            paragraphs = paragraphs.len(),
            "heuristic paragraphs classified"
        );
        #[cfg(not(feature = "layout-detection"))]
        if let Some(ref hints) = page_hints {
            let classification_hints = regular_layout_hints(hints);
            super::layout_classify::apply_layout_overrides(
                &mut paragraphs,
                &classification_hints,
                0.5,
                0.2,
                doc_body_font_size,
            );
            un_mark_layout_furniture_per_config(&mut paragraphs, include_headers, include_footers);
        }
        if page_hints.is_some() {
            tracing::debug!(
                page = i,
                headings = paragraphs.iter().filter(|p| p.heading_level.is_some()).count(),
                lists = paragraphs.iter().filter(|p| p.is_list_item).count(),
                furniture = paragraphs.iter().filter(|p| p.is_page_furniture).count(),
                "layout overrides applied"
            );
        }
        demote_structure_annotation_headings(&mut paragraphs);
        merge_spatial_footnote_markers(&mut paragraphs);
        retain_page_furniture_safely(&mut paragraphs);
        paragraphs
    }
}

const TABLE_DOMINANT_MIN_BODY_ROWS: usize = 40;
const TABLE_DOMINANT_MIN_VISIBLE_CHAR_SHARE: f64 = 0.85;
const TABLE_SPILL_MIN_PARAGRAPH_OVERLAP: f64 = 0.2;

/// Remove non-semantic spill inside table regions on overwhelmingly tabular pages.
///
/// Layout table crops can leave out-of-bounds table continuations as ordinary
/// paragraphs. The page-level dominance guards are only activation gates: a
/// paragraph is removed only when enough of its own geometry overlaps an emitted
/// table rectangle and its content looks like a row continuation or marker,
/// preserving surrounding headings and short explanatory prose.
fn suppress_table_dominant_paragraph_spill(pages: &mut [Vec<PdfParagraph>], emitted_tables: &[crate::types::Table]) {
    for (page_index, paragraphs) in pages.iter_mut().enumerate() {
        let page_number = page_index.saturating_add(1) as u32;
        let page_tables = emitted_tables
            .iter()
            .filter(|table| table.page_number == page_number)
            .collect::<Vec<_>>();
        let body_rows = page_tables
            .iter()
            .map(|table| table.cells.len().saturating_sub(1))
            .sum::<usize>();
        if body_rows < TABLE_DOMINANT_MIN_BODY_ROWS {
            continue;
        }

        let table_chars = page_tables
            .iter()
            .flat_map(|table| table.cells.iter().flatten())
            .map(|cell| visible_char_count(cell))
            .sum::<usize>();
        let paragraph_chars = paragraphs
            .iter()
            .map(paragraph_text_raw)
            .map(|text| visible_char_count(&text))
            .sum::<usize>();
        let total_chars = table_chars.saturating_add(paragraph_chars);
        let table_share = if total_chars == 0 {
            0.0
        } else {
            table_chars as f64 / total_chars as f64
        };
        if table_share < TABLE_DOMINANT_MIN_VISIBLE_CHAR_SHARE {
            continue;
        }

        let table_bboxes = page_tables
            .iter()
            .filter_map(|table| table.bounding_box.as_ref())
            .collect::<Vec<_>>();
        if table_bboxes.is_empty() {
            continue;
        }
        let before = paragraphs.len();
        paragraphs.retain(|paragraph| !is_table_crop_spill(paragraph, &table_bboxes));
        tracing::debug!(
            page = page_number,
            body_rows,
            table_share,
            removed = before.saturating_sub(paragraphs.len()),
            "table-dominant paragraph spill cleanup"
        );
    }
}

fn visible_char_count(text: &str) -> usize {
    text.chars().filter(|character| !character.is_whitespace()).count()
}

fn is_table_crop_spill(paragraph: &PdfParagraph, table_bboxes: &[&crate::types::BoundingBox]) -> bool {
    if is_preserved_table_page_annotation(paragraph) {
        return false;
    }
    let Some(paragraph_bbox) = paragraph_geometry_bbox(paragraph) else {
        return false;
    };
    if !table_bboxes.iter().any(|table_bbox| {
        table_paragraph_overlap_fraction(paragraph_bbox, table_bbox) >= TABLE_SPILL_MIN_PARAGRAPH_OVERLAP
    }) {
        return false;
    }

    let text = paragraph_text_raw(paragraph);
    let alphabetic_chars = text.chars().filter(|character| character.is_alphabetic()).count();
    let numeric_chars = text.chars().filter(|character| character.is_numeric()).count();
    paragraph.word_count >= 13 || alphabetic_chars < 5 || numeric_chars >= alphabetic_chars
}

fn table_paragraph_overlap_fraction(
    paragraph_bbox: (f32, f32, f32, f32),
    table_bbox: &crate::types::BoundingBox,
) -> f64 {
    let (raw_left, raw_bottom, raw_right, raw_top) = paragraph_bbox;
    let paragraph_left = raw_left.min(raw_right) as f64;
    let paragraph_right = raw_left.max(raw_right) as f64;
    let paragraph_bottom = raw_bottom.min(raw_top) as f64;
    let paragraph_top = raw_bottom.max(raw_top) as f64;
    let paragraph_area = (paragraph_right - paragraph_left) * (paragraph_top - paragraph_bottom);
    if paragraph_area <= 0.0 {
        return 0.0;
    }

    let intersection_width = (paragraph_right.min(table_bbox.x0.max(table_bbox.x1))
        - paragraph_left.max(table_bbox.x0.min(table_bbox.x1)))
    .max(0.0);
    let intersection_height = (paragraph_top.min(table_bbox.y0.max(table_bbox.y1))
        - paragraph_bottom.max(table_bbox.y0.min(table_bbox.y1)))
    .max(0.0);
    intersection_width * intersection_height / paragraph_area
}

fn is_preserved_table_page_annotation(paragraph: &PdfParagraph) -> bool {
    if paragraph.heading_level.is_some()
        || paragraph.caption_for.is_some()
        || paragraph.is_list_item
        || paragraph.is_code_block
        || paragraph.is_formula
        || matches!(
            paragraph.layout_class,
            Some(
                super::types::LayoutHintClass::Title
                    | super::types::LayoutHintClass::SectionHeader
                    | super::types::LayoutHintClass::Caption
                    | super::types::LayoutHintClass::Footnote
                    | super::types::LayoutHintClass::PageHeader
                    | super::types::LayoutHintClass::PageFooter
                    | super::types::LayoutHintClass::ListItem
                    | super::types::LayoutHintClass::Code
                    | super::types::LayoutHintClass::Formula
                    | super::types::LayoutHintClass::DocumentIndex
                    | super::types::LayoutHintClass::Form
                    | super::types::LayoutHintClass::KeyValueRegion
            )
        )
    {
        return true;
    }

    let text = paragraph_text_raw(paragraph);
    let label = text
        .trim_start()
        .split_once(char::is_whitespace)
        .map_or(text.trim(), |(first, _)| first)
        .trim_end_matches([':', '.'])
        .to_ascii_lowercase();
    matches!(label.as_str(), "note" | "notes" | "source" | "sources" | "table")
}

fn is_wrapper_layout_hint(hint: &LayoutHint) -> bool {
    hint.class_name.is_wrapper()
}

fn regular_layout_hints(hints: &[LayoutHint]) -> Vec<LayoutHint> {
    hints
        .iter()
        .filter(|hint| !is_wrapper_layout_hint(hint))
        .cloned()
        .collect()
}

fn segments_to_paragraphs(
    segments: Vec<SegmentData>,
    heading_map: &[(f32, Option<u8>)],
    paragraph_gap_ys: &[f32],
) -> Vec<PdfParagraph> {
    let mut paragraphs = blocks_to_paragraphs(segments, heading_map, paragraph_gap_ys);
    apply_text_repair_to_structure_tree_paragraphs(&mut paragraphs, true);
    merge_continuation_paragraphs(&mut paragraphs);
    synchronize_paragraph_text_metadata(&mut paragraphs);
    paragraphs
}

#[cfg(feature = "layout-detection")]
fn wrapper_ownership_by_hint(
    hints: &[LayoutHint],
    validations: &[super::regions::layout_validation::RegionValidation],
) -> Vec<bool> {
    hints
        .iter()
        .enumerate()
        .map(|(index, hint)| {
            !is_wrapper_layout_hint(hint)
                || !matches!(
                    validations.get(index),
                    Some(super::regions::layout_validation::RegionValidation::Empty)
                )
        })
        .collect()
}

#[cfg(feature = "layout-detection")]
struct LayoutParagraphContext<'a> {
    heading_map: &'a [(f32, Option<u8>)],
    paragraph_gap_ys: &'a [f32],
    doc_body_font_size: Option<f32>,
    include_headers: bool,
    include_footers: bool,
    page_width_pts: Option<f32>,
    apply_layout_overrides: bool,
}

#[cfg(feature = "layout-detection")]
struct NativeLayoutProjection {
    groups: Vec<crate::extractors::pdf::reading_order::LayoutSegmentGroup>,
    group_bounds: Vec<Option<(f32, f32, f32, f32)>>,
    classification_hints: Vec<LayoutHint>,
}

#[cfg(feature = "layout-detection")]
fn process_layout_segment_groups(
    segments: Vec<SegmentData>,
    hints: &[LayoutHint],
    wrapper_ownership: &[bool],
    context: LayoutParagraphContext<'_>,
) -> Vec<PdfParagraph> {
    let no_reorder = super::layout_debug::layout_debug_flags().no_reorder;
    let groups = crate::extractors::pdf::reading_order::plan_segment_groups_by_layout(
        &segments,
        hints,
        wrapper_ownership,
        no_reorder,
        context.page_width_pts,
    );
    if matches!(groups.as_slice(), [group] if group.hint_indices.is_empty() && group.region_path.is_none()) {
        return segments_to_paragraphs(segments, context.heading_map, context.paragraph_gap_ys);
    }
    if !context.apply_layout_overrides {
        let group_bounds = layout_group_bounds(&groups, &segments);
        let mut paragraphs = segments_to_paragraphs(segments, context.heading_map, context.paragraph_gap_ys);
        assign_native_paragraph_layout(&mut paragraphs, &groups, &group_bounds);
        let classification_hints = regular_layout_hints(hints);
        super::layout_classify::annotate_layout_classes(&mut paragraphs, &classification_hints, 0.5, 0.2);
        return paragraphs;
    }
    let mut slots = segments.into_iter().map(Some).collect::<Vec<_>>();
    let mut paragraphs = Vec::new();

    for group in groups {
        let region_path = group.region_path;
        let group_segments = group
            .segment_indices
            .into_iter()
            .filter_map(|index| slots.get_mut(index).and_then(Option::take))
            .collect::<Vec<_>>();
        if group_segments.is_empty() {
            continue;
        }
        let gap_ys = compute_paragraph_gap_ys(&group_segments);
        let mut group_paragraphs = segments_to_paragraphs(group_segments, context.heading_map, &gap_ys);
        let group_hints = group
            .hint_indices
            .into_iter()
            .filter_map(|index| hints.get(index).cloned())
            .collect::<Vec<_>>();
        if context.apply_layout_overrides {
            super::layout_classify::apply_layout_overrides(
                &mut group_paragraphs,
                &group_hints,
                0.5,
                0.2,
                context.doc_body_font_size,
            );
            un_mark_layout_furniture_per_config(
                &mut group_paragraphs,
                context.include_headers,
                context.include_footers,
            );
        } else {
            super::layout_classify::annotate_layout_classes(&mut group_paragraphs, &group_hints, 0.5, 0.2);
        }
        for paragraph in &mut group_paragraphs {
            paragraph.layout_region_path = region_path;
        }
        paragraphs.extend(group_paragraphs);
    }

    let leftovers = slots.into_iter().flatten().collect::<Vec<_>>();
    if !leftovers.is_empty() {
        tracing::warn!(
            segments = leftovers.len(),
            "layout region plan omitted segments; appending an unsorted fallback group"
        );
        let gap_ys = compute_paragraph_gap_ys(&leftovers);
        paragraphs.extend(segments_to_paragraphs(leftovers, context.heading_map, &gap_ys));
    }
    paragraphs
}

#[cfg(feature = "layout-detection")]
fn assign_native_paragraph_layout(
    paragraphs: &mut Vec<PdfParagraph>,
    groups: &[crate::extractors::pdf::reading_order::LayoutSegmentGroup],
    group_bounds: &[Option<(f32, f32, f32, f32)>],
) {
    for paragraph in paragraphs {
        let group_rank = paragraph_geometry_bbox(paragraph).and_then(|paragraph_bbox| {
            groups
                .iter()
                .enumerate()
                .filter_map(|(group_index, _)| {
                    let overlap = group_bounds
                        .get(group_index)
                        .and_then(|bounds| *bounds)
                        .map_or(0.0, |bounds| rectangle_overlap_area(paragraph_bbox, bounds));
                    (overlap > 0.0).then_some((group_index, overlap))
                })
                .max_by(|left, right| left.1.total_cmp(&right.1).then_with(|| right.0.cmp(&left.0)))
                .map(|(group_index, _)| group_index)
        });
        let Some(group_index) = group_rank else {
            continue;
        };
        let Some(mut path) = groups[group_index].region_path else {
            continue;
        };
        let original_root_id = path.root.id;
        let root_order = groups
            .iter()
            .position(|group| {
                group
                    .region_path
                    .is_some_and(|candidate| candidate.root.id == original_root_id)
            })
            .unwrap_or(group_index);
        path.root.id = root_order;
        if let Some(child) = &mut path.child {
            child.id = group_index;
        }
        paragraph.layout_region_path = Some(path);
    }
}

fn reorder_pages_by_layout_region(pages: &mut [Vec<PdfParagraph>]) {
    for page in pages {
        page.sort_by_key(|paragraph| {
            paragraph
                .layout_region_path
                .map(|path| path.child.map_or(path.root.id, |child| child.id))
                .unwrap_or(usize::MAX)
        });
    }
}

fn paragraph_geometry_bbox(paragraph: &PdfParagraph) -> Option<(f32, f32, f32, f32)> {
    if let Some(block_bbox) = paragraph.block_bbox {
        return Some(block_bbox);
    }
    let mut segments = paragraph.lines.iter().flat_map(|line| line.segments.iter());
    let first = segments.next()?;
    let mut bounds = (
        first.x,
        first.y.min(first.baseline_y),
        first.x + first.width,
        (first.y + first.height).max(first.baseline_y + first.height),
    );
    for segment in segments {
        bounds.0 = bounds.0.min(segment.x);
        bounds.1 = bounds.1.min(segment.y.min(segment.baseline_y));
        bounds.2 = bounds.2.max(segment.x + segment.width);
        bounds.3 = bounds
            .3
            .max((segment.y + segment.height).max(segment.baseline_y + segment.height));
    }
    Some(bounds)
}

#[cfg(feature = "layout-detection")]
fn layout_group_bounds(
    groups: &[crate::extractors::pdf::reading_order::LayoutSegmentGroup],
    segments: &[SegmentData],
) -> Vec<Option<(f32, f32, f32, f32)>> {
    groups
        .iter()
        .map(|group| {
            let mut group_segments = group.segment_indices.iter().filter_map(|index| segments.get(*index));
            let first = group_segments.next()?;
            let mut bounds = (
                first.x,
                first.y.min(first.baseline_y),
                first.x + first.width,
                (first.y + first.height).max(first.baseline_y + first.height),
            );
            for segment in group_segments {
                bounds.0 = bounds.0.min(segment.x);
                bounds.1 = bounds.1.min(segment.y.min(segment.baseline_y));
                bounds.2 = bounds.2.max(segment.x + segment.width);
                bounds.3 = bounds
                    .3
                    .max((segment.y + segment.height).max(segment.baseline_y + segment.height));
            }
            Some(bounds)
        })
        .collect()
}

#[cfg(feature = "layout-detection")]
fn rectangle_overlap_area(left: (f32, f32, f32, f32), right: (f32, f32, f32, f32)) -> f32 {
    let width = left.2.min(right.2) - left.0.max(right.0);
    let height = left.3.min(right.3) - left.1.max(right.1);
    width.max(0.0) * height.max(0.0)
}

/// Multiple of the median line height a whitespace band must exceed to count
/// as a paragraph break. Normal line pitch leaves well under one line height of
/// whitespace; a blank line leaves more than one.
const PARAGRAPH_GAP_HEIGHT_FACTOR: f32 = 1.5;
const INLINE_STYLE_BASELINE_TOLERANCE: f32 = 0.5;
const INLINE_STYLE_MAX_FORWARD_GAP_FONT_FACTOR: f32 = 1.0;
const INLINE_STYLE_MAX_OVERLAP_FONT_FACTOR: f32 = 0.15;

/// Detect paragraph-break y-positions from horizontal whitespace bands.
///
/// Segments are clustered into visual lines after sorting by y — stream order
/// is not positional (multi-column PDFs interleave columns, which a pairwise
/// scan misreads as phantom gaps). A break is recorded only where the band
/// between two consecutive lines is taller than
/// [`PARAGRAPH_GAP_HEIGHT_FACTOR`] × the median line height: pure blank-line
/// spacing. Bands between two monospace lines are skipped, because code
/// listings legitimately contain blank lines inside one logical block.
///
/// Without this, the heuristic path only breaks paragraphs on font/bold/list
/// changes, fusing visually separated blocks (standalone headings, display
/// formulas) into surrounding prose.
fn compute_paragraph_gap_ys(segments: &[SegmentData]) -> Vec<f32> {
    if segments.len() < 2 {
        return Vec::new();
    }

    let mut order: Vec<usize> = (0..segments.len()).collect();
    order.sort_by(|&a, &b| {
        segments[b]
            .y
            .partial_cmp(&segments[a].y)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    struct LineBand {
        top: f32,
        bottom: f32,
        height: f32,
        monospace: bool,
        anchor_y: f32,
    }
    let mut lines: Vec<LineBand> = Vec::new();
    for &i in &order {
        let seg = &segments[i];
        let tolerance = (seg.height * 0.5).max(1.0);
        match lines.last_mut() {
            Some(line) if (seg.y - line.anchor_y).abs() <= tolerance => {
                line.top = line.top.max(seg.y + seg.height);
                line.bottom = line.bottom.min(seg.y);
                line.height = line.height.max(seg.height);
                line.monospace &= seg.is_monospace;
            }
            _ => lines.push(LineBand {
                top: seg.y + seg.height,
                bottom: seg.y,
                height: seg.height,
                monospace: seg.is_monospace,
                anchor_y: seg.y,
            }),
        }
    }
    if lines.len() < 2 {
        return Vec::new();
    }

    let mut heights: Vec<f32> = lines.iter().map(|l| l.height).collect();
    heights.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let gap_threshold = heights[heights.len() / 2] * PARAGRAPH_GAP_HEIGHT_FACTOR;

    let mut gap_ys = Vec::new();
    for pair in lines.windows(2) {
        let gap = pair[0].bottom - pair[1].top;
        if gap > gap_threshold && !(pair[0].monospace && pair[1].monospace) {
            gap_ys.push((pair[0].bottom + pair[1].top) / 2.0);
        }
    }
    gap_ys
}

/// Convert a flat list of text segments into grouped paragraphs.
///
/// Groups consecutive segments by font changes, bold changes, list markers, and
/// paragraph gap positions. Each group is then classified via `finalize_paragraph`.
fn blocks_to_paragraphs(
    lines: Vec<SegmentData>,
    heading_map: &[(f32, Option<u8>)],
    paragraph_gap_ys: &[f32],
) -> Vec<PdfParagraph> {
    if lines.is_empty() {
        return Vec::new();
    }

    let gap_info = super::classify::precompute_gap_info(heading_map);

    let mut paragraphs: Vec<PdfParagraph> = Vec::new();
    let mut current_lines: Vec<&SegmentData> = Vec::new();
    let mut current_is_single_visual_line = true;

    for (line_idx, line) in lines.iter().enumerate() {
        let should_break = if current_lines.is_empty() {
            false
        } else {
            let prev = current_lines.last().unwrap();
            let font_change = (line.font_size - prev.font_size).abs() > 1.5;
            let role_change = line.assigned_role != prev.assigned_role;
            let bold_change =
                line.is_bold != prev.is_bold && !is_inline_style_transition(current_is_single_visual_line, prev, line);
            let starts_new_line = (line.baseline_y - prev.baseline_y).abs() > INLINE_STYLE_BASELINE_TOLERANCE;
            let has_same_line_follower = lines
                .get(line_idx + 1)
                .is_some_and(|next| (next.baseline_y - line.baseline_y).abs() <= INLINE_STYLE_BASELINE_TOLERANCE);
            let is_list = starts_new_line
                && (looks_like_list_item(&line.text) || (has_same_line_follower && is_bare_list_marker(&line.text)));
            let crossed_gap = paragraph_gap_ys.iter().any(|&gap_y| {
                let (upper, lower) = if prev.baseline_y > line.baseline_y {
                    (prev.baseline_y, line.baseline_y)
                } else {
                    (line.baseline_y, prev.baseline_y)
                };
                gap_y < upper && gap_y > lower
            });
            font_change || role_change || bold_change || is_list || crossed_gap
        };

        if should_break && !current_lines.is_empty() {
            if let Some(para) = finalize_paragraph(&current_lines, heading_map, &gap_info) {
                paragraphs.push(para);
            }
            current_lines.clear();
            current_is_single_visual_line = true;
        }
        if let Some(first) = current_lines.first() {
            current_is_single_visual_line &=
                (line.baseline_y - first.baseline_y).abs() <= INLINE_STYLE_BASELINE_TOLERANCE;
        }
        current_lines.push(line);
    }

    if !current_lines.is_empty()
        && let Some(para) = finalize_paragraph(&current_lines, heading_map, &gap_info)
    {
        paragraphs.push(para);
    }

    tracing::debug!(
        input_lines = lines.len(),
        output_paragraphs = paragraphs.len(),
        headings = paragraphs.iter().filter(|p| p.heading_level.is_some()).count(),
        lists = paragraphs.iter().filter(|p| p.is_list_item).count(),
        "blocks_to_paragraphs complete"
    );

    paragraphs
}

/// Whether a style transition is an inline run on the same visual line.
///
/// PDF glyph runs can overlap slightly because of font metrics. Larger
/// overlaps, reverse ordering, and wide gaps remain structural boundaries.
fn is_inline_style_transition(current_is_single_visual_line: bool, previous: &SegmentData, next: &SegmentData) -> bool {
    if !current_is_single_visual_line
        || previous.is_monospace
        || next.is_monospace
        || previous.assigned_role != next.assigned_role
    {
        return false;
    }
    if !previous.font_size.is_finite()
        || !next.font_size.is_finite()
        || previous.font_size <= 0.0
        || next.font_size <= 0.0
        || !previous.baseline_y.is_finite()
        || !next.baseline_y.is_finite()
        || !previous.x.is_finite()
        || !next.x.is_finite()
        || !previous.width.is_finite()
        || !next.width.is_finite()
        || previous.width < 0.0
        || next.width < 0.0
        || next.x < previous.x
    {
        return false;
    }
    if (next.baseline_y - previous.baseline_y).abs() > INLINE_STYLE_BASELINE_TOLERANCE {
        return false;
    }

    let font_size = previous.font_size.max(next.font_size);
    let horizontal_gap = next.x - (previous.x + previous.width);
    horizontal_gap >= -(font_size * INLINE_STYLE_MAX_OVERLAP_FONT_FACTOR)
        && horizontal_gap <= font_size * INLINE_STYLE_MAX_FORWARD_GAP_FONT_FACTOR
}

/// Reconstruct PdfLine objects from a flat list of SegmentData, grouping by baseline_y.
///
/// This preserves inline formatting information (is_bold, is_italic, is_monospace)
/// at the segment level so that the assembly layer can emit properly annotated markdown
/// with bold/italic emphasis.
fn reconstruct_pdf_lines(segments: &[&SegmentData]) -> Vec<super::types::PdfLine> {
    if segments.is_empty() {
        return Vec::new();
    }

    let mut lines: Vec<super::types::PdfLine> = Vec::new();
    let mut current_baseline = segments[0].baseline_y;
    let mut current_segments: Vec<SegmentData> = Vec::new();

    for seg in segments {
        if (seg.baseline_y - current_baseline).abs() > 0.5 {
            if !current_segments.is_empty() {
                let dominant_font_size = current_segments.iter().map(|s| s.font_size).fold(0.0, |a, b| {
                    if a > 0.0 && b > a / 2.0 && b < a * 2.0 {
                        (a + b) / 2.0
                    } else {
                        a.max(b)
                    }
                });
                let is_bold = current_segments.iter().filter(|s| s.is_bold).count() > current_segments.len() / 2;
                let is_monospace = current_segments.iter().all(|s| s.is_monospace);
                lines.push(super::types::PdfLine {
                    segments: current_segments.clone(),
                    baseline_y: current_baseline,
                    dominant_font_size,
                    is_bold,
                    is_monospace,
                });
            }
            current_baseline = seg.baseline_y;
            current_segments.clear();
        }
        current_segments.push((*seg).clone());
    }

    if !current_segments.is_empty() {
        let dominant_font_size = current_segments.iter().map(|s| s.font_size).fold(0.0, |a, b| {
            if a > 0.0 && b > a / 2.0 && b < a * 2.0 {
                (a + b) / 2.0
            } else {
                a.max(b)
            }
        });
        let is_bold = current_segments.iter().filter(|s| s.is_bold).count() > current_segments.len() / 2;
        let is_monospace = current_segments.iter().all(|s| s.is_monospace);
        lines.push(super::types::PdfLine {
            segments: current_segments,
            baseline_y: current_baseline,
            dominant_font_size,
            is_bold,
            is_monospace,
        });
    }

    lines
}

/// Build a PdfParagraph from a group of consecutive lines with compatible font properties.
fn finalize_paragraph(
    lines: &[&SegmentData],
    heading_map: &[(f32, Option<u8>)],
    gap_info: &super::classify::GapInfo,
) -> Option<PdfParagraph> {
    if lines.is_empty() {
        return None;
    }

    let text: String = lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n");

    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }

    let first = lines[0];
    let word_count = trimmed.split_whitespace().count();
    let is_bold = lines.iter().filter(|l| l.is_bold).count() > lines.len() / 2;
    let has_mixed_inline_styles = lines
        .iter()
        .skip(1)
        .any(|line| line.is_bold != first.is_bold || line.is_italic != first.is_italic);

    let reconstructed_lines = reconstruct_pdf_lines(lines);
    let starts_with_split_list_marker = lines.get(1).is_some_and(|body| {
        is_bare_list_marker(&first.text)
            && (body.baseline_y - first.baseline_y).abs() <= INLINE_STYLE_BASELINE_TOLERANCE
            && !body.text.trim().is_empty()
    });
    let is_list_candidate = looks_like_list_item(trimmed) || starts_with_split_list_marker;

    let structure_tree_role = {
        let role_counts: std::collections::HashMap<u8, usize> =
            lines
                .iter()
                .filter_map(|l| l.assigned_role)
                .fold(std::collections::HashMap::new(), |mut acc, level| {
                    *acc.entry(level).or_default() += 1;
                    acc
                });
        role_counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(level, _)| level)
    };
    if let Some(level) = structure_tree_role {
        let para_text = trimmed.to_string();
        let word_count = PdfParagraph::compute_word_count(&para_text, &reconstructed_lines);
        return Some(PdfParagraph {
            text: if has_mixed_inline_styles {
                String::new()
            } else {
                para_text
            },
            lines: reconstructed_lines,
            dominant_font_size: first.font_size,
            heading_level: Some(level),
            is_bold,
            is_list_item: is_list_candidate,
            is_code_block: first.is_monospace && lines.len() > 1,
            is_formula: false,
            is_page_furniture: false,
            layout_class: None,
            layout_region_path: None,
            caption_for: None,
            block_bbox: None,
            word_count,
        });
    }

    let page_number_like = word_count <= 10 && is_page_number_pattern(trimmed);

    let mut heading_level = super::classify::find_heading_level(first.font_size, heading_map, gap_info);
    if heading_level.is_some()
        && (word_count > 20 || super::layout_classify::is_separator_text(trimmed) || page_number_like)
    {
        heading_level = None;
    }

    let body_font_size = heading_map
        .iter()
        .find(|(_, level)| level.is_none())
        .map(|(centroid, _)| *centroid)
        .unwrap_or(0.0);

    // A bold, short, single-line paragraph is only a heading candidate when
    // its font is also meaningfully larger than the document's body font
    // (the same ratio/gap the font-size clustering path already requires via
    // `assign_heading_levels_smart`). Without this check, any bold one-word
    // line — including body-sized emphasis, or a stray oversized glyph from
    // a font-metric artifact — gets promoted regardless of scale, which is
    // exactly the pattern that over-promoted "Big"/"Text" in a 3-paragraph
    // document with no real headings. ~keep
    let clears_bold_font_gate = body_font_size > 0.0
        && first.font_size >= body_font_size * super::constants::MIN_HEADING_FONT_RATIO
        && first.font_size >= body_font_size + super::constants::MIN_HEADING_FONT_GAP;

    if heading_level.is_none()
        && is_bold
        && clears_bold_font_gate
        && (1..=8).contains(&word_count)
        && lines.len() == 1
        && !trimmed.ends_with('.')
        && !trimmed.ends_with(':')
        && !trimmed.ends_with(',')
        && !trimmed.ends_with(';')
        && !trimmed.contains('@')
        && !trimmed.contains('(')
        && !trimmed.contains(',')
        && trimmed
            .chars()
            .next()
            .is_some_and(|c| c.is_uppercase() || c.is_ascii_digit())
        && !super::layout_classify::is_separator_text(trimmed)
        && !super::regions::looks_like_figure_label(trimmed)
    {
        heading_level = Some(2);
    }

    if heading_level.is_none() {
        let min_heading_threshold = body_font_size * super::constants::MIN_HEADING_FONT_RATIO;
        if body_font_size > 0.0
            && first.font_size >= min_heading_threshold
            && first.font_size > body_font_size + 0.5
            && word_count <= super::constants::MAX_BOLD_HEADING_WORD_COUNT
            && lines.len() <= 2
            && !trimmed.ends_with(':')
            && !trimmed.contains('@')
            && (super::classify::is_section_pattern(trimmed) || is_structural_heading_word(trimmed))
            && !super::layout_classify::is_separator_text(trimmed)
            && !super::regions::looks_like_figure_label(trimmed)
            && !is_list_candidate
            && !page_number_like
        {
            heading_level = Some(2);
        }
    }

    let is_list_item = heading_level.is_none() && is_list_candidate;
    let is_code_block =
        heading_level.is_none() && !is_list_item && lines.iter().all(|l| l.is_monospace) && lines.len() >= 2;

    let is_page_furniture = heading_level.is_none()
        && !is_list_item
        && !is_code_block
        && word_count <= 10
        && is_page_number_pattern(trimmed);

    tracing::debug!(
        font_size = first.font_size,
        is_bold,
        word_count,
        heading_level = ?heading_level,
        is_list_item,
        is_code_block,
        is_page_furniture,
        text_preview = %&trimmed.chars().take(60).collect::<String>(),
        "classified paragraph"
    );

    let para_text = trimmed.to_string();
    let word_count = PdfParagraph::compute_word_count(&para_text, &reconstructed_lines);

    Some(PdfParagraph {
        text: if has_mixed_inline_styles {
            String::new()
        } else {
            para_text
        },
        lines: reconstructed_lines,
        dominant_font_size: first.font_size,
        heading_level,
        is_bold,
        is_list_item,
        is_code_block,
        is_formula: false,
        is_page_furniture,
        layout_class: None,
        layout_region_path: None,
        caption_for: None,
        block_bbox: Some({
            let left = lines.iter().map(|l| l.x).fold(f32::MAX, f32::min);
            let bottom = lines.iter().map(|l| l.baseline_y).fold(f32::MAX, f32::min);
            let right = lines.iter().map(|l| l.x + l.width).fold(f32::MIN, f32::max);
            let top = lines.iter().map(|l| l.baseline_y + l.height).fold(f32::MIN, f32::max);
            (left, bottom, right, top)
        }),
        word_count,
    })
}

/// Check if text is ENTIRELY a list marker with no item text after it.
///
/// Word processors often emit list numbering as its own text run, so the
/// marker ("1.", "a)", "(2)", "•") and the item body arrive as separate
/// spans on the same line. `looks_like_list_item` rejects those markers
/// because it requires trailing text; this predicate accepts them.
fn is_bare_list_marker(text: &str) -> bool {
    let t = text.trim();
    if t.is_empty() || t.chars().count() > 5 {
        return false;
    }
    if matches!(t, "" | "·" | "" | "" | "" | "" | "-" | "*") {
        return true;
    }
    super::list_marker::parse_ordered_list_marker(t).is_some_and(|marker| !marker.has_content)
}

/// Check if text starts with a common list marker.
fn looks_like_list_item(text: &str) -> bool {
    let t = text.trim_start();

    if t.starts_with('') || t.starts_with('·') || t.starts_with('') || t.starts_with('') {
        return true;
    }

    if let Some(rest) = t.strip_prefix('').or_else(|| t.strip_prefix('')) {
        if !rest.starts_with(' ') && !rest.starts_with('\t') {
            return false;
        }
        let body = rest.trim_start_matches([' ', '\t']);
        return !body.is_empty() && !body.starts_with('\r') && !body.starts_with('\n');
    }

    if let Some(rest) = t.strip_prefix("- ") {
        return rest.chars().next().is_some_and(|c| c.is_alphabetic());
    }

    if super::classify::is_numbered_section_heading(t) {
        return false;
    }
    let Some(marker) = super::list_marker::parse_ordered_list_marker(t) else {
        return false;
    };
    marker.has_content
        && marker.has_separator
        && !is_probable_author_byline(t)
        && t.get(marker.content_start..)
            .and_then(|content| content.chars().next())
            .is_some_and(char::is_alphabetic)
}

/// Whether a single-capital marker is more likely the first author initial.
///
/// The comma plus a second compact initial or journal-style slash supplies
/// the contextual evidence; a standalone `A. First item` remains a list.
pub(super) fn is_probable_author_byline(text: &str) -> bool {
    let mut chars = text.chars();
    if !chars.next().is_some_and(|c| c.is_ascii_uppercase()) || chars.next() != Some('.') {
        return false;
    }
    let remainder = chars.as_str().trim_start();
    let Some((surname, remainder)) = remainder.split_once(char::is_whitespace) else {
        return false;
    };
    surname.ends_with(',') && starts_with_author_initial_or_slash(remainder.trim_start())
}

fn starts_with_author_initial_or_slash(text: &str) -> bool {
    if text.starts_with('/') {
        return true;
    }
    let mut chars = text.chars().peekable();
    let mut initials = 0;
    while chars.peek().is_some_and(|c| c.is_ascii_uppercase()) {
        chars.next();
        if chars.next() != Some('.') {
            return false;
        }
        initials += 1;
    }
    initials > 0 && chars.peek().is_some_and(|c| c.is_whitespace())
}

/// Check if text is a well-known structural heading word.
///
/// These single-word headings appear frequently in academic papers and reports
/// and are reliable heading indicators when combined with a larger-than-body font.
fn is_structural_heading_word(text: &str) -> bool {
    let t = text.trim();
    matches!(
        t,
        "Abstract"
            | "References"
            | "Appendix"
            | "Acknowledgments"
            | "Acknowledgements"
            | "Conclusion"
            | "Conclusions"
            | "Bibliography"
            | "Contents"
            | "Index"
            | "Glossary"
            | "Summary"
            | "Discussion"
            | "Methods"
            | "Results"
            | "Methodology"
    )
}

/// Check if text matches common page number patterns.
///
/// Detects standalone page numbers, "Page X", "Page X of Y", Roman numerals,
/// and similar patterns that appear as page furniture.
fn is_page_number_pattern(text: &str) -> bool {
    let t = text.trim();
    if t.is_empty() {
        return false;
    }
    if t.chars().all(|c| c.is_ascii_digit()) && t.len() <= 4 {
        return true;
    }
    let lower = t.to_lowercase();
    if lower.starts_with("page ") {
        return true;
    }
    if (t.starts_with("- ") || t.starts_with("")) && (t.ends_with(" -") || t.ends_with("")) {
        let inner = t
            .trim_start_matches("- ")
            .trim_start_matches("")
            .trim_end_matches(" -")
            .trim_end_matches("")
            .trim();
        if inner.chars().all(|c| c.is_ascii_digit()) && inner.len() <= 4 {
            return true;
        }
    }
    if t.len() <= 5 && t.chars().all(|c| matches!(c, 'i' | 'v' | 'x' | 'I' | 'V' | 'X')) {
        return true;
    }
    false
}

/// Build a structured `InternalDocument` from pre-extracted per-page segments.
///
/// This is the oxide-backend entry point. It accepts segments already extracted
/// via `oxide::hierarchy::extract_all_segments` and runs the same font-clustering,
/// heading-classification, paragraph-assembly, and post-processing stages without
/// requiring a PDF document.
///
/// Image positions can be supplied to insert image placeholders into the document.
/// Layout hints (from RT-DETR layout detection) are optional; when present they
/// drive furniture marking, heading overrides, and table region detection.
///
/// Returns the assembled `InternalDocument`.
pub(crate) struct SegmentStructureConfig<'a> {
    pub k_clusters: usize,
    pub tables: &'a [crate::types::Table],
    pub outline_entries: &'a [PdfOutlineEntry],
    pub strip_repeating_text: bool,
    pub include_headers: bool,
    pub include_footers: bool,
    pub used_structure_tree: bool,
    pub image_positions: &'a [(u32, u32)],
    pub images: Option<&'a [crate::types::ExtractedImage]>,
    pub inject_placeholders: bool,
    pub layout_hints: Option<&'a [Vec<LayoutHint>]>,
    pub allow_single_column: bool,
    pub cancel_token: Option<&'a crate::cancellation::CancellationToken>,
    #[cfg(feature = "layout-detection")]
    pub layout_images: Option<&'a [image::RgbImage]>,
    #[cfg(feature = "layout-detection")]
    pub layout_results: Option<&'a [super::types::PageLayoutResult]>,
    #[cfg(feature = "layout-detection")]
    pub table_model: crate::core::config::layout::TableModel,
    #[cfg(feature = "layout-detection")]
    pub table_overlap_preference: crate::core::config::layout::TableOverlapPreference,
    #[cfg(feature = "layout-detection")]
    pub acceleration: Option<&'a crate::core::config::acceleration::AccelerationConfig>,
    #[cfg(feature = "layout-detection")]
    pub session_thread_budget: usize,
}

#[cfg(feature = "layout-detection")]
fn slanet_variant_for_table_model(table_model: crate::core::config::layout::TableModel) -> Option<&'static str> {
    use crate::core::config::layout::TableModel;

    match table_model {
        TableModel::SlanetWired | TableModel::SlanetAuto => Some("slanet_wired"),
        TableModel::SlanetWireless => Some("slanet_wireless"),
        TableModel::SlanetPlus => Some("slanet_plus"),
        TableModel::Tatr | TableModel::Disabled => None,
    }
}

pub(crate) fn extract_document_structure_from_segments(
    mut all_page_segments: Vec<Vec<SegmentData>>,
    config: SegmentStructureConfig<'_>,
) -> Result<crate::types::internal::InternalDocument> {
    let SegmentStructureConfig {
        k_clusters,
        tables,
        outline_entries,
        strip_repeating_text,
        include_headers,
        include_footers,
        used_structure_tree,
        image_positions,
        images,
        inject_placeholders,
        layout_hints,
        allow_single_column,
        cancel_token,
        #[cfg(feature = "layout-detection")]
        layout_images,
        #[cfg(feature = "layout-detection")]
        layout_results,
        #[cfg(feature = "layout-detection")]
        table_model,
        #[cfg(feature = "layout-detection")]
        table_overlap_preference,
        #[cfg(feature = "layout-detection")]
        acceleration,
        #[cfg(feature = "layout-detection")]
        session_thread_budget,
    } = config;
    let page_count = all_page_segments.len();
    tracing::debug!(
        page_count,
        used_structure_tree,
        "oxide structure pipeline: starting from pre-extracted segments"
    );

    let struct_tree_results: Vec<Option<Vec<PdfParagraph>>> = vec![None; page_count];
    let heuristic_pages: Vec<usize> = (0..page_count).collect();

    let (heading_map, doc_body_font_size) = if used_structure_tree {
        let mut heading_map = build_heading_map_from_assigned_roles(&all_page_segments);
        if !suppress_all_heading_roles_when_sparse_and_untrusted(&mut heading_map, &mut all_page_segments)
            && promote_untagged_document_title(&mut heading_map, &all_page_segments)
        {
            demote_assigned_roles(&mut all_page_segments);
        }
        let doc_body_font_size: Option<f32> = heading_map
            .iter()
            .find(|(_, level)| level.is_none())
            .map(|(size, _)| *size);
        tracing::debug!(
            heading_map_len = heading_map.len(),
            "oxide structure pipeline: heading map from structure tree"
        );
        (heading_map, doc_body_font_size)
    } else {
        let (heading_map, _struct_tree_needs_classify) =
            build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, k_clusters)?;
        let doc_body_font_size: Option<f32> = heading_map
            .iter()
            .find(|(_, level)| level.is_none())
            .map(|(size, _)| *size);
        (heading_map, doc_body_font_size)
    };

    let page_heights: Vec<f32> = all_page_segments
        .iter()
        .map(|segs| segs.iter().map(|s| s.y + s.height).fold(0.0_f32, f32::max).max(792.0))
        .collect();

    let mut layout_tables: Vec<crate::types::Table> = Vec::new();
    if let Some(hints_pages) = layout_hints {
        struct TablePageData {
            page_idx: usize,
            words: Vec<crate::pdf::table_reconstruct::HocrWord>,
            page_height: f32,
        }
        let mut table_pages: Vec<TablePageData> = Vec::new();
        // Geometric fallback (#1316): pages the ML detector left without any
        // Table region, but whose text geometry forms a column-aligned grid.
        // Reconstructed through the same guarded path as ML hints, below.
        let mut geometric_table_pages: Vec<(
            usize,
            Vec<crate::pdf::table_reconstruct::HocrWord>,
            f32,
            Vec<LayoutHint>,
        )> = Vec::new();

        #[allow(clippy::needless_range_loop)]
        for page_idx in 0..page_count {
            if cancel_token.is_some_and(|t| t.is_cancelled()) {
                tracing::debug!(page_idx, "oxide structure pipeline: cancelled during table page prep");
                break;
            }
            let Some(hints) = hints_pages.get(page_idx) else {
                continue;
            };
            let ml_table_hints: Vec<&LayoutHint> = hints
                .iter()
                .filter(|h| h.class_name == super::types::LayoutHintClass::Table)
                .collect();
            let has_table_hint = !ml_table_hints.is_empty();
            #[cfg(feature = "layout-detection")]
            let page_height = layout_results
                .and_then(|results| results.get(page_idx))
                .map(|pr| pr.page_height_pts)
                .unwrap_or(page_heights[page_idx]);
            #[cfg(not(feature = "layout-detection"))]
            let page_height = page_heights[page_idx];
            let words = crate::pdf::table_reconstruct::segments_to_words(&all_page_segments[page_idx], page_height);
            if words.is_empty() {
                tracing::trace!(
                    page = page_idx,
                    "oxide layout table extraction: no words from segments, skipping"
                );
                continue;
            }
            // Run the geometric fallback per-region rather than per-page (#1321):
            // an ML `Table` hint elsewhere on the page must not suppress recovery
            // of a spatially separate borderless region, so both paths run
            // whenever a page has words, with the fallback excluding words
            // already claimed by an ML table hint.
            let synthetic = super::regions::detect_geometric_table_hints(&words, page_height, &ml_table_hints);
            if !synthetic.is_empty() {
                tracing::debug!(
                    page = page_idx,
                    regions = synthetic.len(),
                    has_table_hint,
                    "geometric table fallback: synthesized Table region(s) outside existing ML hints"
                );
                geometric_table_pages.push((page_idx, words.clone(), page_height, synthetic));
            }
            if has_table_hint {
                tracing::trace!(
                    page = page_idx,
                    word_count = words.len(),
                    page_height,
                    "oxide layout table extraction: page prepared"
                );
                table_pages.push(TablePageData {
                    page_idx,
                    words,
                    page_height,
                });
            }
        }

        #[cfg(feature = "layout-detection")]
        {
            use crate::core::config::layout::TableModel;

            let use_model_inference = table_model != TableModel::Disabled;

            let slanet_variant = slanet_variant_for_table_model(table_model);
            let is_auto = table_model == TableModel::SlanetAuto;

            let model_name = match table_model {
                TableModel::Tatr => "TATR",
                TableModel::SlanetWired | TableModel::SlanetWireless | TableModel::SlanetPlus => "SLANeXT",
                TableModel::SlanetAuto => "SLANeXT (auto)",
                TableModel::Disabled => "disabled",
            };

            let has_table_model = if use_model_inference {
                let available = match table_model {
                    TableModel::Tatr => crate::layout::is_tatr_available(acceleration, session_thread_budget),
                    TableModel::SlanetWired
                    | TableModel::SlanetWireless
                    | TableModel::SlanetPlus
                    | TableModel::SlanetAuto => slanet_variant.is_some_and(|variant| {
                        crate::layout::is_slanet_available(variant, acceleration, session_thread_budget)
                    }),
                    TableModel::Disabled => false,
                };

                if !available && !table_pages.is_empty() {
                    return Err(crate::pdf::error::PdfError::TextExtractionFailed(format!(
                        "Layout detection found table regions but {model_name} model is not available. \
                         Ensure the ONNX model is downloaded. Tables cannot be extracted without it."
                    )));
                }
                available
            } else {
                false
            };

            if has_table_model {
                if let (Some(images @ [_, ..]), Some(results @ [_, ..])) = (layout_images, layout_results) {
                    #[cfg(not(target_arch = "wasm32"))]
                    let recognized_tables: Vec<Vec<crate::types::Table>> = table_pages
                        .iter()
                        .map(|tp| {
                            if let Some(variant) = slanet_variant {
                                let Some(mut slanet) =
                                    crate::layout::take_or_create_slanet(variant, acceleration, session_thread_budget)
                                else {
                                    tracing::warn!("SLANeXT model unavailable in worker thread");
                                    return Vec::new();
                                };

                                if let (Some(page_image), Some(page_result)) =
                                    (images.get(tp.page_idx), results.get(tp.page_idx))
                                {
                                    let hints = &hints_pages[tp.page_idx];
                                    let mut classifier_pair = if is_auto {
                                        match (
                                            crate::layout::take_or_create_table_classifier(
                                                acceleration,
                                                session_thread_budget,
                                            ),
                                            crate::layout::take_or_create_slanet(
                                                "slanet_wireless",
                                                acceleration,
                                                session_thread_budget,
                                            ),
                                        ) {
                                            (Some(classifier), Some(alternate)) => Some((classifier, alternate)),
                                            _ => None,
                                        }
                                    } else {
                                        None
                                    };
                                    let classifier_arg = classifier_pair
                                        .as_mut()
                                        .map(|(classifier, alternate)| (&mut ***classifier, &mut ***alternate));
                                    let slanet_tables = super::regions::recognize_tables_slanet(
                                        page_image,
                                        hints,
                                        &tp.words,
                                        page_result,
                                        tp.page_height,
                                        tp.page_idx,
                                        &mut slanet,
                                        classifier_arg,
                                    );
                                    if !slanet_tables.is_empty() {
                                        return slanet_tables;
                                    }
                                }

                                let hints = &hints_pages[tp.page_idx];
                                super::regions::extract_tables_from_layout_hints(
                                    &tp.words,
                                    hints,
                                    tp.page_idx,
                                    tp.page_height,
                                    0.5,
                                    allow_single_column,
                                    false,
                                )
                            } else {
                                let Some(mut tatr) =
                                    crate::layout::take_or_create_tatr(acceleration, session_thread_budget)
                                else {
                                    tracing::warn!("TATR model unavailable in worker thread");
                                    return Vec::new();
                                };

                                if let (Some(page_image), Some(page_result)) =
                                    (images.get(tp.page_idx), results.get(tp.page_idx))
                                {
                                    let hints = &hints_pages[tp.page_idx];
                                    let tatr_tables = super::regions::recognize_tables_for_native_page(
                                        page_image,
                                        hints,
                                        &tp.words,
                                        page_result,
                                        tp.page_height,
                                        super::regions::NativeTatrRecognitionOptions {
                                            page_index: tp.page_idx,
                                            allow_single_column,
                                        },
                                        &mut tatr,
                                    );
                                    if !tatr_tables.is_empty() {
                                        return tatr_tables;
                                    }
                                }

                                let hints = &hints_pages[tp.page_idx];
                                super::regions::extract_tables_from_layout_hints(
                                    &tp.words,
                                    hints,
                                    tp.page_idx,
                                    tp.page_height,
                                    0.5,
                                    allow_single_column,
                                    false,
                                )
                            }
                        })
                        .collect();
                    #[cfg(target_arch = "wasm32")]
                    let recognized_tables: Vec<Vec<crate::types::Table>> = table_pages
                        .iter()
                        .map(|tp| {
                            if let (Some(page_image), Some(page_result)) =
                                (images.get(tp.page_idx), results.get(tp.page_idx))
                            {
                                let hints = &hints_pages[tp.page_idx];
                                let Some(mut tatr) =
                                    crate::layout::take_or_create_tatr(acceleration, session_thread_budget)
                                else {
                                    return Vec::new();
                                };
                                let tatr_tables = super::regions::recognize_tables_for_native_page(
                                    page_image,
                                    hints,
                                    &tp.words,
                                    page_result,
                                    tp.page_height,
                                    super::regions::NativeTatrRecognitionOptions {
                                        page_index: tp.page_idx,
                                        allow_single_column,
                                    },
                                    &mut tatr,
                                );
                                if !tatr_tables.is_empty() {
                                    return tatr_tables;
                                }
                                super::regions::extract_tables_from_layout_hints(
                                    &tp.words,
                                    hints,
                                    tp.page_idx,
                                    tp.page_height,
                                    0.5,
                                    allow_single_column,
                                    false,
                                )
                            } else {
                                Vec::new()
                            }
                        })
                        .collect();
                    layout_tables.extend(recognized_tables.into_iter().flatten());
                } else {
                    for tp in &table_pages {
                        if cancel_token.is_some_and(|t| t.is_cancelled()) {
                            tracing::debug!("oxide structure pipeline: cancelled during heuristic table extraction");
                            break;
                        }
                        let hints = &hints_pages[tp.page_idx];
                        layout_tables.extend(super::regions::extract_tables_from_layout_hints(
                            &tp.words,
                            hints,
                            tp.page_idx,
                            tp.page_height,
                            0.5,
                            allow_single_column,
                            false,
                        ));
                    }
                }
            } else {
                for tp in &table_pages {
                    if cancel_token.is_some_and(|t| t.is_cancelled()) {
                        tracing::debug!("oxide structure pipeline: cancelled during heuristic table extraction");
                        break;
                    }
                    let hints = &hints_pages[tp.page_idx];
                    layout_tables.extend(super::regions::extract_tables_from_layout_hints(
                        &tp.words,
                        hints,
                        tp.page_idx,
                        tp.page_height,
                        0.5,
                        allow_single_column,
                        false,
                    ));
                }
            }
        }

        #[cfg(not(feature = "layout-detection"))]
        for tp in &table_pages {
            if cancel_token.is_some_and(|t| t.is_cancelled()) {
                tracing::debug!("oxide structure pipeline: cancelled during heuristic table extraction");
                break;
            }
            let hints = &hints_pages[tp.page_idx];
            layout_tables.extend(super::regions::extract_tables_from_layout_hints(
                &tp.words,
                hints,
                tp.page_idx,
                tp.page_height,
                0.5,
                allow_single_column,
                false,
            ));
        }

        // Geometric table fallback (#1316): reconstruct the synthesized regions
        // through the SAME guarded path (post_process_table, is_well_formed_table,
        // numeric-exemption prose gate, code-listing/single-cell-row guards). This
        // never runs the ML table models — it only recovers tables the detector
        // missed on otherwise Table-region-free pages.
        for (page_idx, words, page_height, synthetic_hints) in &geometric_table_pages {
            if cancel_token.is_some_and(|t| t.is_cancelled()) {
                tracing::debug!("oxide structure pipeline: cancelled during geometric table fallback");
                break;
            }
            let before = layout_tables.len();
            layout_tables.extend(super::regions::extract_tables_from_layout_hints(
                words,
                synthetic_hints,
                *page_idx,
                *page_height,
                0.5,
                allow_single_column,
                // Geometrically pre-vetted (row/column/gutter guards): skip the
                // downstream columnar-prose heuristic that mistakes a regular
                // key-value grid for wrapped prose (#1319).
                true,
            ));
            let recovered = layout_tables.len() - before;
            if recovered > 0 {
                tracing::debug!(
                    page = page_idx,
                    recovered,
                    "geometric table fallback: recovered table(s) the ML detector missed"
                );
            }
        }
    }

    tracing::debug!(
        layout_tables_found = layout_tables.len(),
        "oxide layout table extraction complete"
    );

    #[cfg(feature = "layout-detection")]
    let overlap_preference = table_overlap_preference;
    #[cfg(not(feature = "layout-detection"))]
    let overlap_preference = crate::core::config::layout::TableOverlapPreference::Content;
    let stitched_native_tables = stitch_fragmented_tables(tables.to_vec(), &all_page_segments);
    let emitted_tables = prepare_emitted_tables(&stitched_native_tables, layout_tables, overlap_preference);

    let extracted_table_bboxes_by_page = table_bboxes_by_page(&emitted_tables);
    tracing::debug!(
        native_tables = tables.len(),
        emitted_tables = emitted_tables.len(),
        pages_with_bboxes = extracted_table_bboxes_by_page.len(),
        "oxide table bbox suppression map built"
    );

    #[cfg(feature = "layout-detection")]
    let validations_by_page: ahash::AHashMap<usize, Vec<super::regions::layout_validation::RegionValidation>> = {
        let mut map = ahash::AHashMap::new();
        if let (Some(images), Some(results), Some(hints_pages)) = (layout_images, layout_results, layout_hints) {
            for page_idx in 0..page_count {
                if let (Some(img), Some(res), Some(hints)) =
                    (images.get(page_idx), results.get(page_idx), hints_pages.get(page_idx))
                {
                    let validations = super::regions::layout_validation::validate_page_regions(img, hints, res);
                    if validations.contains(&super::regions::layout_validation::RegionValidation::Empty) {
                        tracing::debug!(
                            page = page_idx,
                            empty_count = validations
                                .iter()
                                .filter(|v| **v == super::regions::layout_validation::RegionValidation::Empty)
                                .count(),
                            "oxide layout validation: found empty regions"
                        );
                    }
                    map.insert(page_idx, validations);
                }
            }
        }
        map
    };
    #[cfg(feature = "layout-detection")]
    let effective_layout_hints = layout_hints;
    #[cfg(feature = "layout-detection")]
    let native_layout_projections: Vec<Option<NativeLayoutProjection>> = (0..page_count)
        .map(|page_index| {
            let hints = effective_layout_hints.and_then(|pages| pages.get(page_index))?;
            let validations = validations_by_page
                .get(&page_index)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let wrapper_ownership = wrapper_ownership_by_hint(hints, validations);
            if !crate::extractors::pdf::reading_order::has_eligible_layout_hints(hints, &wrapper_ownership) {
                return None;
            }

            let table_bboxes = extracted_table_bboxes_by_page
                .get(&page_index)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let projected_segments =
                filter_segments_by_table_bboxes(all_page_segments[page_index].clone(), table_bboxes);
            let no_reorder = super::layout_debug::layout_debug_flags().no_reorder;
            let page_width_pts = layout_results
                .and_then(|results| results.get(page_index))
                .map(|result| result.page_width_pts);
            let groups = crate::extractors::pdf::reading_order::plan_segment_groups_by_layout(
                &projected_segments,
                hints,
                &wrapper_ownership,
                no_reorder,
                page_width_pts,
            );
            let group_bounds = layout_group_bounds(&groups, &projected_segments);
            Some(NativeLayoutProjection {
                groups,
                group_bounds,
                classification_hints: regular_layout_hints(hints),
            })
        })
        .collect();
    let page_inputs: Vec<PageInput> = (0..page_count)
        .map(|i| {
            let heuristic_segments = std::mem::take(&mut all_page_segments[i]);
            let paragraph_gap_ys = compute_paragraph_gap_ys(&heuristic_segments);
            PageInput {
                page_index: i,
                struct_paragraphs: None,
                heuristic_segments,
                // Native paragraphs are fully refined without layout semantic
                // annotations. Geometry is projected after semantic refinement.
                page_hints: None,
                table_bboxes: extracted_table_bboxes_by_page.get(&i).cloned().unwrap_or_default(),
                preserve_native_semantics: true,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: validations_by_page.get(&i).cloned().unwrap_or_default(),
                #[cfg(feature = "layout-detection")]
                page_width_pts: layout_results
                    .and_then(|results| results.get(i))
                    .map(|result| result.page_width_pts),
                needs_classify: false,
                paragraph_gap_ys,
                include_headers,
                include_footers,
            }
        })
        .collect();

    if cancel_token.is_some_and(|t| t.is_cancelled()) {
        return Err(crate::pdf::error::PdfError::TextExtractionFailed(
            "extraction cancelled".to_string(),
        ));
    }

    #[cfg(not(target_arch = "wasm32"))]
    let mut all_page_paragraphs: Vec<Vec<PdfParagraph>> = page_inputs
        .into_par_iter()
        .map(|input| process_single_page(input, &heading_map, doc_body_font_size))
        .collect();
    #[cfg(target_arch = "wasm32")]
    let mut all_page_paragraphs: Vec<Vec<PdfParagraph>> = page_inputs
        .into_iter()
        .map(|input| process_single_page(input, &heading_map, doc_body_font_size))
        .collect();

    refine_heading_hierarchy(&mut all_page_paragraphs);
    demote_unnumbered_subsections(&mut all_page_paragraphs);
    demote_heading_runs(&mut all_page_paragraphs);
    split_colon_semicolon_run_in_lists(&mut all_page_paragraphs);

    if strip_repeating_text {
        mark_cross_page_repeating_text(&mut all_page_paragraphs, &page_heights);
        mark_cross_page_repeating_short_text(&mut all_page_paragraphs);
    }
    mark_arxiv_noise(&mut all_page_paragraphs);
    recover_headings_from_outline(&mut all_page_paragraphs, outline_entries);
    for page in &mut all_page_paragraphs {
        retain_page_furniture_safely(page);
    }
    if strip_repeating_text {
        deduplicate_paragraphs(&mut all_page_paragraphs);
    }
    compact_final_heading_hierarchy(&mut all_page_paragraphs);
    #[cfg(feature = "layout-detection")]
    for (page, projection) in all_page_paragraphs.iter_mut().zip(native_layout_projections) {
        let Some(projection) = projection else {
            continue;
        };
        assign_native_paragraph_layout(page, &projection.groups, &projection.group_bounds);
        super::layout_classify::annotate_layout_classes(page, &projection.classification_hints, 0.5, 0.2);
    }
    // Spill cleanup runs after deferred annotation so layout-only captions,
    // footnotes, and furniture retain their semantic provenance.
    suppress_table_dominant_paragraph_spill(&mut all_page_paragraphs, &emitted_tables);
    // Native semantic roles are finalized in source order before the
    // independent layout geometry projection controls final reading order.
    reorder_pages_by_layout_region(&mut all_page_paragraphs);

    let total_paragraphs: usize = all_page_paragraphs.iter().map(|p| p.len()).sum();
    tracing::debug!(
        total_paragraphs,
        heading_map_len = heading_map.len(),
        "oxide structure pipeline: paragraph extraction complete, assembling document"
    );

    let effective_image_positions = if inject_placeholders { image_positions } else { &[] };
    let mut doc = assemble_internal_document(all_page_paragraphs, &emitted_tables, images, effective_image_positions);

    for elem in &mut doc.elements {
        if elem.text.is_empty() {
            continue;
        }
        let t1 = repair_contextual_ligatures(&elem.text);
        let t2 = expand_ligatures_with_space_absorption(&t1);
        let t3 = normalize_unicode_text(&t2);
        if let Cow::Owned(normalized) = t3 {
            elem.text = normalized;
        } else if let Cow::Owned(normalized) = t2 {
            elem.text = normalized;
        } else if let Cow::Owned(normalized) = t1 {
            elem.text = normalized;
        }
    }

    tracing::debug!(
        elements = doc.elements.len(),
        "oxide structure pipeline: assembly complete"
    );

    Ok(doc)
}

/// Maximum vertical gap (PDF points) between one fragment's bottom edge and the
/// next fragment's top edge for the two to be considered the same physical
/// table split by `oxide::table`'s row-gap clustering.
const TABLE_STITCH_Y_GAP_TOLERANCE_PTS: f64 = 4.0;
/// Maximum difference in a chain's shared left/right edge for two fragments to
/// be considered the same table (rather than two unrelated tables that happen
/// to sit close together vertically).
const TABLE_STITCH_X_TOLERANCE_PTS: f64 = 6.0;
/// Bound on fragments merged into one stitched chain. Real continuation splits
/// rarely exceed a handful of fragments; this caps the (already page-scoped,
/// already `oxide::table::MAX_REGIONS_PER_PAGE`-bounded) chain walk.
const TABLE_STITCH_MAX_CHAIN_FRAGMENTS: usize = 12;
/// Bound on additional data rows the trailing-continuation recovery pass will
/// attempt to pull from raw page segments below a stitched chain's last known
/// fragment. Keeps the scan from reading arbitrarily far down the page.
const TABLE_STITCH_TRAILING_RECOVERY_MAX_ROWS: usize = 6;
/// Row-gap multiplier used to split recovered trailing words into per-entity
/// bands. Mirrors `oxide::table::cluster_words_into_vertical_regions`'s
/// `row_gap_split`; reimplemented here because that clustering helper is
/// private to the `oxide::table` module, which this pass cannot depend on.
const TABLE_STITCH_TRAILING_ROW_GAP_MULTIPLIER: f32 = 1.8;

/// Stitch table fragments that `oxide::table`'s row-gap region clustering split
/// out of one physical table back into a single table.
///
/// `oxide::table::cluster_words_into_vertical_regions` splits a page's words
/// into regions at any row-gap exceeding `median_height * 1.8`. A table whose
/// header wraps onto several lines, or whose rows are visually separated by
/// generous line spacing, can land in several such regions — each one then
/// independently goes through header/data-row post-processing, which corrupts
/// a real multi-line header (see `post_process_table_inner`'s header cap) and
/// mis-promotes a lone data row to a fake header. This pass reassembles those
/// fragments after the fact: each fragment's own rows are themselves raw
/// word-wrapped sub-lines of a single logical row (there is no reliable way to
/// tell, post hoc, which fragment "really" had a header split correctly), so
/// stitching column-merges every fragment's rows into exactly one row — the
/// topmost fragment in a chain becomes the header, the rest become data rows —
/// and then attempts to recover any trailing data rows that fell below the
/// last known fragment without ever becoming a table fragment at all (e.g.
/// because the row-gap clustering merged them into an unrelated, rejected
/// region).
///
/// Bounded to avoid quadratic blowup: fragments are grouped by page first (an
/// `O(n)` pass), and each page's fragment list is walked once after an
/// `O(m log m)` sort, with the inner chain-adjacency check bounded by
/// `TABLE_STITCH_MAX_CHAIN_FRAGMENTS`. `oxide::table::MAX_REGIONS_PER_PAGE`
/// already caps how many fragments a single page can contribute.
fn stitch_fragmented_tables(
    tables: Vec<crate::types::Table>,
    all_page_segments: &[Vec<SegmentData>],
) -> Vec<crate::types::Table> {
    let mut by_page: ahash::AHashMap<u32, Vec<crate::types::Table>> = ahash::AHashMap::new();
    let mut unbboxed = Vec::new();
    for table in tables {
        if table.bounding_box.is_some() {
            by_page.entry(table.page_number).or_default().push(table);
        } else {
            unbboxed.push(table);
        }
    }

    let mut result = unbboxed;
    let mut page_numbers: Vec<u32> = by_page.keys().copied().collect();
    page_numbers.sort_unstable();
    for page_number in page_numbers {
        if let Some(page_tables) = by_page.remove(&page_number) {
            result.extend(stitch_page_tables(page_tables, all_page_segments));
        }
    }
    result
}

/// Assign a stable, deterministic `table_id` (and, when missing, `columns`) to
/// every table in `tables`, in the given order.
///
/// Ids are sequential (`"table-1"`, `"table-2"`, ...) rather than derived from
/// randomness or wall-clock time, so the same input document always produces
/// the same ids. Must run over the final, post-dedup set of tables a document
/// will actually emit (see [`prepare_emitted_tables`]) — running it any
/// earlier, e.g. over native tables alone, would leave layout-detected tables
/// that survive dedup without an id.
///
/// Fragments of one physical table that [`stitch_page_tables`] merged into a
/// single [`crate::types::Table`] naturally share one id, since by this point
/// they are already one entry; distinct tables receive distinct ids because
/// they remain distinct entries. Cross-page continuations of one physical
/// table are not linked: [`fragments_are_stitchable`] only merges fragments on
/// the same page, so a table split across a page boundary is intentionally
/// emitted as separate `tables[]` entries with separate ids today. Sharing an
/// id across page-boundary fragments is a known possible future extension,
/// not attempted here.
fn assign_deterministic_table_ids(tables: &mut [crate::types::Table]) {
    for (index, table) in tables.iter_mut().enumerate() {
        table.table_id = Some(format!("table-{}", index + 1));
        if table.columns.is_none() {
            table.columns = table.cells.first().cloned();
        }
    }
}

/// Stitch one page's table fragments. See [`stitch_fragmented_tables`].
fn stitch_page_tables(
    mut fragments: Vec<crate::types::Table>,
    all_page_segments: &[Vec<SegmentData>],
) -> Vec<crate::types::Table> {
    fragments.sort_by(|a, b| {
        let a_top = a.bounding_box.map_or(f64::MIN, |bbox| bbox.y1);
        let b_top = b.bounding_box.map_or(f64::MIN, |bbox| bbox.y1);
        b_top.total_cmp(&a_top)
    });

    let mut output = Vec::with_capacity(fragments.len());
    let mut index = 0;
    while index < fragments.len() {
        let mut chain_end = index + 1;
        while chain_end < fragments.len()
            && chain_end - index < TABLE_STITCH_MAX_CHAIN_FRAGMENTS
            && fragments_are_stitchable(&fragments[chain_end - 1], &fragments[chain_end])
        {
            chain_end += 1;
        }

        if chain_end - index >= 2 {
            let chain = fragments[index..chain_end].to_vec();
            output.push(merge_table_chain(chain, all_page_segments));
        } else {
            output.push(fragments[index].clone());
        }
        index = chain_end;
    }
    output
}

/// Whether `next` is the vertically-adjacent continuation of `prev` within one
/// stitch chain: same page, same column count, near-zero row gap, and matching
/// left/right edges.
fn fragments_are_stitchable(prev: &crate::types::Table, next: &crate::types::Table) -> bool {
    if prev.page_number != next.page_number {
        return false;
    }
    let (Some(a), Some(b)) = (prev.bounding_box, next.bounding_box) else {
        return false;
    };

    let prev_cols = prev.cells.first().map_or(0, Vec::len);
    let next_cols = next.cells.first().map_or(0, Vec::len);
    if prev_cols == 0 || prev_cols != next_cols {
        return false;
    }

    (a.y0 - b.y1).abs() <= TABLE_STITCH_Y_GAP_TOLERANCE_PTS
        && (a.x0 - b.x0).abs() <= TABLE_STITCH_X_TOLERANCE_PTS
        && (a.x1 - b.x1).abs() <= TABLE_STITCH_X_TOLERANCE_PTS
}

/// Merge a chain of >= 2 stitchable fragments into one table.
///
/// The topmost fragment's rows collapse into the header; every other
/// fragment's rows collapse into one data row apiece. See
/// [`stitch_fragmented_tables`] for why a whole-fragment column merge is used
/// instead of trying to re-derive a header/data split.
fn merge_table_chain(chain: Vec<crate::types::Table>, all_page_segments: &[Vec<SegmentData>]) -> crate::types::Table {
    let column_count = chain
        .iter()
        .filter_map(|table| table.cells.first())
        .map(Vec::len)
        .max()
        .unwrap_or(0);

    let page_number = chain[0].page_number;
    let mut bbox = chain
        .iter()
        .find_map(|table| table.bounding_box)
        .unwrap_or(crate::types::BoundingBox {
            x0: 0.0,
            y0: 0.0,
            x1: 0.0,
            y1: 0.0,
        });
    for table in &chain {
        if let Some(b) = table.bounding_box {
            bbox.x0 = bbox.x0.min(b.x0);
            bbox.x1 = bbox.x1.max(b.x1);
            bbox.y0 = bbox.y0.min(b.y0);
            bbox.y1 = bbox.y1.max(b.y1);
        }
    }

    let mut rows: Vec<Vec<String>> = chain
        .iter()
        .map(|table| crate::pdf::table_reconstruct::merge_rows_columnwise(&table.cells, column_count))
        .collect();

    if let Some(page_segments) = all_page_segments.get((page_number.saturating_sub(1)) as usize) {
        recover_trailing_continuation_rows(&mut rows, &mut bbox, column_count, page_segments);
    }

    let markdown = crate::pdf::table_reconstruct::table_to_markdown(&rows);
    let columns = rows.first().cloned();
    crate::types::Table {
        cells: rows,
        markdown,
        page_number,
        bounding_box: Some(bbox),
        columns,
        ..Default::default()
    }
}

/// Recover trailing data rows that never became their own table fragment.
///
/// `oxide::table`'s region clustering sometimes merges the last entities of a
/// fragmented table into a region with unrelated following content (or drops
/// them entirely when the merged region fails `post_process_table`
/// validation), so those rows leak into the document as plain paragraph text
/// instead of table data. This scans the raw page segments strictly below the
/// stitched chain's known bottom edge, within its column span, and — bounded
/// by [`TABLE_STITCH_TRAILING_RECOVERY_MAX_ROWS`] iterations — pulls one
/// row-gap-bounded entity band at a time. A band is only accepted if
/// reconstructing it independently yields the same column count as the
/// stitched table; any mismatch (e.g. the band actually contains an unrelated
/// heading below the table) stops recovery immediately rather than skipping
/// past it, since skipping risks pulling in arbitrary downstream content.
fn recover_trailing_continuation_rows(
    rows: &mut Vec<Vec<String>>,
    bbox: &mut crate::types::BoundingBox,
    column_count: usize,
    page_segments: &[SegmentData],
) {
    if column_count == 0 || page_segments.is_empty() {
        return;
    }

    let page_height = page_segments
        .iter()
        .map(|s| s.y + s.height)
        .fold(0.0_f32, f32::max)
        .max(792.0);
    let x_lo = (bbox.x0 - TABLE_STITCH_X_TOLERANCE_PTS) as f32;
    let x_hi = (bbox.x1 + TABLE_STITCH_X_TOLERANCE_PTS) as f32;
    let mut search_floor = bbox.y0 as f32;

    for _ in 0..TABLE_STITCH_TRAILING_RECOVERY_MAX_ROWS {
        let band_words: Vec<crate::pdf::table_reconstruct::HocrWord> = page_segments
            .iter()
            .filter(|seg| {
                !seg.text.trim().is_empty()
                    && seg.y + seg.height <= search_floor + TABLE_STITCH_Y_GAP_TOLERANCE_PTS as f32
                    && seg.x + seg.width >= x_lo
                    && seg.x <= x_hi
            })
            .flat_map(|seg| crate::pdf::table_reconstruct::split_segment_to_words(seg, page_height))
            .collect();
        if band_words.is_empty() {
            break;
        }

        let Some((entity_words, entity_bottom_image_y)) = take_next_entity_band(&band_words) else {
            break;
        };

        let col_gap = super::regions::tables::compute_adaptive_column_gap(&entity_words, (x_hi - x_lo).max(1.0));
        let grid = crate::pdf::table_reconstruct::reconstruct_table(&entity_words, col_gap, 0.5);
        if grid.is_empty() || grid[0].len() != column_count {
            break;
        }

        let merged_row = crate::pdf::table_reconstruct::merge_rows_columnwise(&grid, column_count);
        if merged_row.iter().all(|cell| cell.trim().is_empty()) {
            break;
        }

        let entity_bottom_pdf_y = page_height - entity_bottom_image_y as f32;
        rows.push(merged_row);
        bbox.y0 = bbox.y0.min(entity_bottom_pdf_y as f64);
        search_floor = entity_bottom_pdf_y;
    }
}

/// Take the topmost row-gap-bounded contiguous band of words from `words`
/// (which may span more than one logical entity), stopping at the first gap
/// larger than `median_height * TABLE_STITCH_TRAILING_ROW_GAP_MULTIPLIER`.
///
/// Returns the band's words and the image-coordinate bottom edge (`top +
/// height`, max across the band) of the last line included.
fn take_next_entity_band(
    words: &[crate::pdf::table_reconstruct::HocrWord],
) -> Option<(Vec<crate::pdf::table_reconstruct::HocrWord>, u32)> {
    if words.is_empty() {
        return None;
    }

    let mut heights: Vec<u32> = words.iter().map(|w| w.height).collect();
    heights.sort_unstable();
    let median_height = heights[heights.len() / 2].max(1);
    let row_gap_split = (median_height as f32 * TABLE_STITCH_TRAILING_ROW_GAP_MULTIPLIER) as u32;
    let row_tolerance = (median_height / 2).max(3);

    let mut sorted: Vec<&crate::pdf::table_reconstruct::HocrWord> = words.iter().collect();
    sorted.sort_by_key(|w| w.top);

    let mut band: Vec<crate::pdf::table_reconstruct::HocrWord> = Vec::new();
    let mut band_bottom = 0u32;
    let mut last_row_yc: Option<u32> = None;
    let mut idx = 0;
    while idx < sorted.len() {
        let row_yc = sorted[idx].top + sorted[idx].height / 2;
        let mut end = idx + 1;
        while end < sorted.len() {
            let yc = sorted[end].top + sorted[end].height / 2;
            if yc.abs_diff(row_yc) <= row_tolerance {
                end += 1;
            } else {
                break;
            }
        }

        if let Some(prev_yc) = last_row_yc
            && row_yc > prev_yc
            && row_yc - prev_yc > row_gap_split
            && !band.is_empty()
        {
            break;
        }

        for word in &sorted[idx..end] {
            band_bottom = band_bottom.max(word.top + word.height);
            band.push((*word).clone());
        }
        last_row_yc = Some(row_yc);
        idx = end;
    }

    if band.is_empty() {
        None
    } else {
        Some((band, band_bottom))
    }
}

/// Select the exact tables that final assembly will emit.
///
/// Suppression must consume this same set so a duplicate or empty table cannot
/// remove source text without contributing a corresponding table element.
fn prepare_emitted_tables(
    native_tables: &[crate::types::Table],
    layout_tables: Vec<crate::types::Table>,
    overlap_preference: crate::core::config::layout::TableOverlapPreference,
) -> Vec<crate::types::Table> {
    let mut emitted_tables: Vec<crate::types::Table> = native_tables.iter().cloned().chain(layout_tables).collect();
    emitted_tables.retain(|table| !table.markdown.trim().is_empty());
    let native_count = native_tables
        .iter()
        .filter(|table| !table.markdown.trim().is_empty())
        .count();
    deduplicate_overlapping_tables(&mut emitted_tables, native_count, overlap_preference);
    normalize_sparse_currency_affix_columns(&mut emitted_tables);
    normalize_wrapped_financial_rows(&mut emitted_tables);
    deduplicate_identical_tables(&mut emitted_tables);
    assign_deterministic_table_ids(&mut emitted_tables);
    emitted_tables
}

const MAX_CURRENCY_AFFIX_CELLS: usize = 3;
const MAX_CURRENCY_AFFIX_OCCUPANCY: f64 = 0.1;
const MIN_FINANCIAL_TARGET_CELLS: usize = 5;
const MIN_FINANCIAL_TARGET_RATIO: f64 = 0.9;
const MIN_WRAPPED_FINANCIAL_VALUE_ROWS: usize = 8;
const FINANCIAL_COLUMN_HEADERS: &[&str] = &[
    "shares",
    "par",
    "principal",
    "quantity",
    "value",
    "market value",
    "cost",
];
const ISO_CURRENCY_CODES: &[&str] = &[
    "AUD", "BRL", "CAD", "CHF", "CNY", "DKK", "EUR", "GBP", "HKD", "INR", "JPY", "KRW", "MXN", "NOK", "NZD", "SEK",
    "SGD", "USD", "ZAR",
];

fn normalize_sparse_currency_affix_columns(tables: &mut [crate::types::Table]) {
    for table in tables {
        normalize_sparse_currency_affix_columns_in_table(table);
    }
}

fn normalize_wrapped_financial_rows(tables: &mut [crate::types::Table]) {
    for table in tables {
        if !is_wrapped_financial_table(&table.cells) {
            continue;
        }
        fold_wrapped_financial_rows(&mut table.cells);
        table.markdown = crate::extractors::frontmatter_utils::cells_to_markdown(&table.cells);
        table.columns = table.cells.first().cloned();
    }
}

fn is_wrapped_financial_table(rows: &[Vec<String>]) -> bool {
    let Some(header) = rows.first() else {
        return false;
    };
    if header.len() < 3
        || rows.len() <= 1
        || !header.iter().skip(1).all(|cell| is_financial_column_header(cell))
        || rows.iter().any(|row| row.len() != header.len())
    {
        return false;
    }

    let body = &rows[1..];
    let value_rows = body.iter().filter(|row| is_value_bearing_financial_row(row)).count();
    let descriptor_rows = body
        .iter()
        .filter(|row| is_descriptor_only_financial_row(row) && !is_financial_section_label(row))
        .count();
    value_rows >= MIN_WRAPPED_FINANCIAL_VALUE_ROWS
        && descriptor_rows > value_rows
        && body
            .iter()
            .all(|row| is_descriptor_only_financial_row(row) || is_value_bearing_financial_row(row))
}

fn is_descriptor_only_financial_row(row: &[String]) -> bool {
    row.first().is_some_and(|cell| !cell.trim().is_empty()) && row.iter().skip(1).all(|cell| cell.trim().is_empty())
}

fn is_value_bearing_financial_row(row: &[String]) -> bool {
    row.first().is_some_and(|cell| !cell.trim().is_empty()) && row.iter().skip(1).all(|cell| is_financial_value(cell))
}

fn is_financial_section_label(row: &[String]) -> bool {
    if !is_descriptor_only_financial_row(row) {
        return false;
    }
    let text = row[0].trim().to_ascii_lowercase();
    text.contains("(continued)") || has_allocation_percentage_suffix(&text)
}

fn has_allocation_percentage_suffix(text: &str) -> bool {
    const MAX_FOOTNOTE_MARKER_CHARS: usize = 4;

    let Some((dash_index, dash)) = text
        .char_indices()
        .rev()
        .find(|(_, character)| matches!(character, '' | ''))
    else {
        return false;
    };
    if text[..dash_index].trim().is_empty() {
        return false;
    }
    let suffix = text[dash_index + dash.len_utf8()..].trim();
    let Some((allocation, remainder)) = suffix.split_once('%') else {
        return false;
    };
    let Ok(allocation) = allocation.trim().parse::<f64>() else {
        return false;
    };
    if !allocation.is_finite() || !(0.0..=100.0).contains(&allocation) {
        return false;
    }

    let remainder = remainder.trim();
    if remainder.is_empty() {
        return true;
    }
    let Some(marker) = remainder.strip_prefix('(').and_then(|value| value.strip_suffix(')')) else {
        return false;
    };
    !marker.is_empty()
        && marker.chars().count() <= MAX_FOOTNOTE_MARKER_CHARS
        && marker.chars().all(char::is_alphanumeric)
}

fn is_financial_value(cell: &str) -> bool {
    let trimmed = cell.trim();
    if is_financial_number(trimmed) {
        return true;
    }
    trimmed
        .split_once(' ')
        .is_some_and(|(marker, value)| is_currency_marker(marker) && is_financial_number(value.trim()))
}

fn fold_wrapped_financial_rows(rows: &mut Vec<Vec<String>>) {
    let mut folded = Vec::with_capacity(rows.len());
    folded.extend(rows.first().cloned());
    let mut pending = Vec::new();
    for mut row in rows.iter().skip(1).cloned() {
        if is_financial_section_label(&row) {
            folded.append(&mut pending);
            folded.push(row);
            continue;
        }
        if is_descriptor_only_financial_row(&row) {
            pending.push(row);
            continue;
        }
        if !pending.is_empty() {
            let prefix = pending
                .drain(..)
                .filter_map(|pending_row| pending_row.into_iter().next())
                .collect::<Vec<_>>()
                .join(" ");
            row[0] = format!("{prefix} {}", row[0]);
        }
        folded.push(row);
    }
    folded.extend(pending);
    *rows = folded;
}

fn normalize_sparse_currency_affix_columns_in_table(table: &mut crate::types::Table) {
    let Some(header) = table.cells.first() else {
        return;
    };
    if table.cells.len() <= 1 || header.len() < 2 {
        return;
    }

    let mut source_columns = (0..header.len() - 1)
        .filter(|&source| {
            header[source].trim().is_empty()
                && header
                    .get(source + 1)
                    .is_some_and(|target| is_financial_column_header(target))
                && is_sparse_currency_affix_column(&table.cells[1..], source, source + 1)
        })
        .collect::<Vec<_>>();
    source_columns.sort_unstable_by(|left, right| right.cmp(left));
    let normalized = !source_columns.is_empty();

    for source in source_columns {
        merge_currency_affix_column(&mut table.cells, source);
    }
    if normalized {
        table.markdown = crate::extractors::frontmatter_utils::cells_to_markdown(&table.cells);
        table.columns = table.cells.first().cloned();
    }
}

fn is_financial_column_header(header: &str) -> bool {
    let normalized = header.trim().to_ascii_lowercase();
    FINANCIAL_COLUMN_HEADERS
        .iter()
        .any(|candidate| normalized == *candidate || normalized.starts_with(&format!("{candidate} ")))
}

fn is_sparse_currency_affix_column(rows: &[Vec<String>], source: usize, target: usize) -> bool {
    let source_cells = rows
        .iter()
        .filter_map(|row| row.get(source))
        .map(|cell| cell.trim())
        .filter(|cell| !cell.is_empty())
        .collect::<Vec<_>>();
    let occupied_limit =
        MAX_CURRENCY_AFFIX_CELLS.min(((rows.len() as f64) * MAX_CURRENCY_AFFIX_OCCUPANCY).ceil() as usize);
    if source_cells.is_empty()
        || source_cells.len() > occupied_limit
        || !source_cells.iter().all(|cell| is_currency_marker(cell))
        || rows.iter().any(|row| {
            row.get(source).is_some_and(|cell| !cell.trim().is_empty())
                && row.get(target).is_none_or(|cell| cell.trim().is_empty())
        })
    {
        return false;
    }

    let target_cells = rows
        .iter()
        .filter_map(|row| row.get(target))
        .map(|cell| cell.trim())
        .filter(|cell| !cell.is_empty())
        .collect::<Vec<_>>();
    target_cells.len() >= MIN_FINANCIAL_TARGET_CELLS
        && target_cells.iter().filter(|cell| is_financial_number(cell)).count() as f64 / target_cells.len() as f64
            >= MIN_FINANCIAL_TARGET_RATIO
}

fn is_currency_marker(cell: &str) -> bool {
    const CURRENCY_SYMBOLS: &[&str] = &["$", "", "£", "¥", "", "", "", "", "", "", "", "", "฿"];
    CURRENCY_SYMBOLS.contains(&cell) || ISO_CURRENCY_CODES.contains(&cell.to_ascii_uppercase().as_str())
}

fn is_financial_number(cell: &str) -> bool {
    let mut has_digit = false;
    cell.chars().all(|character| {
        if character.is_ascii_digit() {
            has_digit = true;
            true
        } else {
            character.is_ascii_whitespace() || matches!(character, ',' | '.' | '-' | '+' | '(' | ')' | '%')
        }
    }) && has_digit
}

fn merge_currency_affix_column(rows: &mut [Vec<String>], source: usize) {
    for row in rows {
        if row.len() <= source {
            continue;
        }
        if let Some(marker) = row.get(source).map(|cell| cell.trim()).filter(|cell| !cell.is_empty())
            && let Some(value) = row
                .get(source + 1)
                .map(|cell| cell.trim())
                .filter(|cell| !cell.is_empty())
        {
            row[source + 1] = format!("{marker} {value}");
        }
        row.remove(source);
    }
}

/// Collapse byte-identical table duplicates on the same page.
///
/// [`deduplicate_overlapping_tables`] only merges a pair when both tables carry
/// a `bounding_box`; a native/layout pair that detects the same physical table
/// but disagrees on bbox presence (e.g. native reconstruction leaves
/// `bounding_box: None` for some heuristic grids) can otherwise escape that
/// pass entirely. This pass is origin- and bbox-agnostic: any two tables on the
/// same page with byte-identical markdown are the same table by definition, so
/// the second (and any further) occurrence is dropped regardless of bbox state.
///
/// Runs in `O(n)` over the page's table count using a hash set keyed on
/// `(page_number, markdown)`.
fn deduplicate_identical_tables(tables: &mut Vec<crate::types::Table>) {
    if tables.len() < 2 {
        return;
    }

    let mut seen: ahash::AHashSet<(u32, &str)> = ahash::AHashSet::with_capacity(tables.len());
    let mut keep = vec![true; tables.len()];
    for (index, table) in tables.iter().enumerate() {
        if !seen.insert((table.page_number, table.markdown.as_str())) {
            keep[index] = false;
        }
    }

    let mut index = 0;
    tables.retain(|_| {
        let keep_this = keep[index];
        index += 1;
        keep_this
    });
}

fn table_bboxes_by_page(tables: &[crate::types::Table]) -> ahash::AHashMap<usize, Vec<crate::types::BoundingBox>> {
    let mut bboxes_by_page: ahash::AHashMap<usize, Vec<crate::types::BoundingBox>> = ahash::AHashMap::new();
    for table in tables {
        if let Some(bbox) = table.bounding_box {
            bboxes_by_page
                .entry(table.page_number.saturating_sub(1) as usize)
                .or_default()
                .push(bbox);
        }
    }
    bboxes_by_page
}

/// Filter out segments that overlap >=50% with any table bounding box.
///
/// Segments with zero area or empty text are always kept.
fn filter_segments_by_table_bboxes(
    segments: Vec<SegmentData>,
    table_bboxes: &[crate::types::BoundingBox],
) -> Vec<SegmentData> {
    if table_bboxes.is_empty() {
        return segments;
    }
    segments
        .into_iter()
        .filter(|seg| {
            let seg_area = seg.width * seg.height;
            if seg_area <= 0.0 || seg.text.trim().is_empty() {
                return true;
            }
            !table_bboxes.iter().any(|bb| {
                let inter_left = seg.x.max(bb.x0 as f32);
                let inter_right = (seg.x + seg.width).min(bb.x1 as f32);
                let inter_bottom = seg.y.max(bb.y0 as f32);
                let inter_top = (seg.y + seg.height).min(bb.y1 as f32);
                if inter_left >= inter_right || inter_bottom >= inter_top {
                    return false;
                }
                let inter_area = (inter_right - inter_left) * (inter_top - inter_bottom);
                inter_area / seg_area >= 0.5
            })
        })
        .collect()
}

/// Apply all 5 text repair passes in a single traversal over a segment's text.
///
/// Returns `Cow::Borrowed` if nothing changed, `Cow::Owned` otherwise.
fn fused_text_repairs(text: &str) -> Cow<'_, str> {
    let t1 = normalize_text_encoding(text);
    let t2 = repair_ligature_spaces(&t1);
    let t3 = expand_ligatures_with_space_absorption(&t2);
    let t3b = collapse_spaced_hyphens(&t3);
    let t4 = normalize_unicode_text(&t3b);
    let t5 = clean_duplicate_punctuation(&t4);
    match (&t1, &t2, &t3, &t3b, &t4, &t5) {
        (
            Cow::Borrowed(_),
            Cow::Borrowed(_),
            Cow::Borrowed(_),
            Cow::Borrowed(_),
            Cow::Borrowed(_),
            Cow::Borrowed(_),
        ) => Cow::Borrowed(text),
        _ => Cow::Owned(t5.into_owned()),
    }
}

/// Deduplicate tables that overlap on the same page.
///
/// When both native oxide detection and layout-based table extraction produce tables
/// for the same region, they can overlap. Tables at index `< native_count` are native;
/// the rest are layout (TATR/SLANeXT) tables. Complete side-by-side layout replacements
/// are selected atomically before ordinary pairwise arbitration. Outside those replacements,
/// `preference` decides mixed native/layout overlaps, while content weight decides same-origin
/// overlaps and [`TableOverlapPreference::Content`].
fn deduplicate_overlapping_tables(
    tables: &mut Vec<crate::types::Table>,
    native_count: usize,
    preference: crate::core::config::layout::TableOverlapPreference,
) {
    use crate::core::config::layout::TableOverlapPreference;

    if tables.len() < 2 {
        return;
    }

    let mut to_remove = ahash::AHashSet::new();
    let mut protected_layout_children = ahash::AHashSet::new();

    if preference != TableOverlapPreference::Native {
        // A complete split cohort is one structural alternative to its native source
        // cohort. Select it atomically for every non-Native preference: pairwise
        // content weighting could otherwise mix incompatible rows from both grids.
        for (parents, children) in side_by_side_layout_replacements(tables, native_count) {
            protected_layout_children.extend(children);
            to_remove.extend(parents);
        }
    }

    for i in 0..tables.len() {
        if to_remove.contains(&i) {
            continue;
        }
        for j in (i + 1)..tables.len() {
            if to_remove.contains(&j) {
                continue;
            }
            if tables[i].page_number != tables[j].page_number {
                continue;
            }
            if let (Some(a), Some(b)) = (&tables[i].bounding_box, &tables[j].bounding_box) {
                let inter_x = (a.x1.min(b.x1) - a.x0.max(b.x0)).max(0.0);
                let inter_y = (a.y1.min(b.y1) - a.y0.max(b.y0)).max(0.0);
                let intersection = inter_x * inter_y;
                let area_a = (a.x1 - a.x0) * (a.y1 - a.y0);
                let area_b = (b.x1 - b.x0) * (b.y1 - b.y0);
                let min_area = area_a.min(area_b);

                if min_area > 0.0 && intersection / min_area > 0.5 {
                    let i_is_native = i < native_count;
                    let j_is_native = j < native_count;
                    let mixed_origin = i_is_native != j_is_native;
                    let i_is_protected = protected_layout_children.contains(&i);
                    let j_is_protected = protected_layout_children.contains(&j);
                    let remove = match (i_is_protected, j_is_protected) {
                        (true, false) => Some(j),
                        (false, true) => Some(i),
                        (true, true) => {
                            let duplicate = intersection / area_a >= LAYOUT_CHILD_DUPLICATE_OVERLAP
                                && intersection / area_b >= LAYOUT_CHILD_DUPLICATE_OVERLAP;
                            duplicate.then(|| lower_content_table(tables, i, j))
                        }
                        (false, false) => Some(match preference {
                            TableOverlapPreference::Native if mixed_origin => {
                                if i_is_native {
                                    j
                                } else {
                                    i
                                }
                            }
                            TableOverlapPreference::Layout if mixed_origin => {
                                if i_is_native {
                                    i
                                } else {
                                    j
                                }
                            }
                            _ => lower_content_table(tables, i, j),
                        }),
                    };
                    let Some(remove) = remove else {
                        continue;
                    };
                    to_remove.insert(remove);
                    if remove == i {
                        break;
                    }
                }
            }
        }
    }

    let surviving_protected: Vec<_> = protected_layout_children
        .iter()
        .copied()
        .filter(|index| !to_remove.contains(index))
        .collect();
    let affected_rows: Vec<_> = surviving_protected
        .iter()
        .filter_map(|&index| tables[index].bounding_box.map(|bbox| (tables[index].page_number, bbox)))
        .collect();

    let mut idx = 0;
    tables.retain(|_| {
        let keep = !to_remove.contains(&idx);
        idx += 1;
        keep
    });
    canonicalize_affected_table_rows(tables, affected_rows);
}

/// Required containment for a layout child and, in one-to-one cohort matching,
/// reciprocal coverage of its corresponding native parent.
const SIDE_BY_SIDE_CHILD_PARENT_OVERLAP: f64 = 0.8;
/// Crop jitter tolerance for reciprocal one-to-one cohort correspondence.
const SIDE_BY_SIDE_CORRESPONDENCE_EPSILON: f64 = 0.005;
/// Both children must describe the same row band, rather than stacked tables.
const SIDE_BY_SIDE_VERTICAL_OVERLAP: f64 = 0.6;
/// The children together must account for most of the parent's horizontal span.
const SIDE_BY_SIDE_PARENT_WIDTH_COVERAGE: f64 = 0.75;
/// Every child must span most of the parent's height, rejecting shallow row fragments.
const SIDE_BY_SIDE_PARENT_HEIGHT_COVERAGE: f64 = 0.75;
/// Disjoint children must jointly explain most of the parent's total area.
const SIDE_BY_SIDE_PARENT_AREA_COVERAGE: f64 = 0.65;
/// Candidate detections that mutually cover nearly all of one another represent
/// the same layout table rather than distinct parts of a split table.
const LAYOUT_CHILD_DUPLICATE_OVERLAP: f64 = 0.9;

fn side_by_side_layout_replacements(
    tables: &[crate::types::Table],
    native_count: usize,
) -> Vec<(Vec<usize>, Vec<usize>)> {
    let native_count = native_count.min(tables.len());
    let rows = native_candidate_rows(tables, native_count);
    let mut used_native = ahash::AHashSet::new();
    let mut used_layout = ahash::AHashSet::new();
    let mut replacements = Vec::new();
    for parent in rows.iter().flatten().copied() {
        let parent_bbox = tables[parent].bounding_box.as_ref().expect("candidate has bbox");
        let mut children = layout_children_for_parent(tables, native_count, tables[parent].page_number, parent_bbox);
        children.retain(|child| !used_layout.contains(child));
        if !used_native.contains(&parent) && is_side_by_side_replacement(tables, parent_bbox, &children) {
            used_native.insert(parent);
            used_layout.extend(children.iter().copied());
            replacements.push((vec![parent], children));
        }
    }
    replacements.extend(side_by_side_native_cohort_replacements(
        tables,
        native_count,
        &rows,
        &mut used_native,
        &mut used_layout,
    ));
    replacements
}

fn side_by_side_native_cohort_replacements(
    tables: &[crate::types::Table],
    native_count: usize,
    rows: &[Vec<usize>],
    used_native: &mut ahash::AHashSet<usize>,
    used_layout: &mut ahash::AHashSet<usize>,
) -> Vec<(Vec<usize>, Vec<usize>)> {
    let mut replacements = Vec::new();
    for pair in rows.iter().flat_map(|row| row.windows(2)) {
        let parents = vec![pair[0], pair[1]];
        if parents.iter().any(|parent| used_native.contains(parent)) {
            continue;
        }
        let Some(parent_bbox) = table_union_bbox(&tables[parents[0]], &tables[parents[1]]) else {
            continue;
        };
        if !is_side_by_side_replacement(tables, &parent_bbox, &parents) {
            continue;
        }
        let mut children =
            layout_children_for_parent(tables, native_count, tables[parents[0]].page_number, &parent_bbox);
        children.retain(|child| !used_layout.contains(child));
        if children.len() != 2
            || !is_side_by_side_replacement(tables, &parent_bbox, &children)
            || !replacement_children_correspond(tables, &parents, &children)
        {
            continue;
        }
        used_native.extend(parents.iter().copied());
        used_layout.extend(children.iter().copied());
        replacements.push((parents, children));
    }
    replacements
}

fn native_candidate_rows(tables: &[crate::types::Table], native_count: usize) -> Vec<Vec<usize>> {
    let mut candidates: Vec<_> = (0..native_count)
        .filter(|&index| tables[index].bounding_box.is_some())
        .collect();
    candidates.sort_by(|&left, &right| {
        tables[left]
            .page_number
            .cmp(&tables[right].page_number)
            .then_with(|| table_top(tables, right).total_cmp(&table_top(tables, left)))
            .then_with(|| table_left(tables, left).total_cmp(&table_left(tables, right)))
    });
    let mut rows: Vec<Vec<usize>> = Vec::new();
    for candidate in candidates {
        let joins_last_row = rows.last().is_some_and(|row| {
            tables[row[0]].page_number == tables[candidate].page_number
                && vertical_overlap_fraction(
                    tables[row[0]].bounding_box.as_ref().expect("candidate has bbox"),
                    tables[candidate].bounding_box.as_ref().expect("candidate has bbox"),
                ) >= SIDE_BY_SIDE_VERTICAL_OVERLAP
        });
        if joins_last_row {
            rows.last_mut().expect("row exists").push(candidate);
        } else {
            rows.push(vec![candidate]);
        }
    }
    for row in &mut rows {
        row.sort_by(|&left, &right| table_left(tables, left).total_cmp(&table_left(tables, right)));
    }
    rows
}

fn replacement_children_correspond(tables: &[crate::types::Table], parents: &[usize], children: &[usize]) -> bool {
    parents
        .iter()
        .zip(children)
        .enumerate()
        .all(|(position, (&parent, &child))| {
            let parent_bbox = tables[parent].bounding_box.as_ref().expect("candidate has bbox");
            let child_bbox = tables[child].bounding_box.as_ref().expect("candidate has bbox");
            let paired_intersection = bbox_intersection_area(parent_bbox, child_bbox);
            let sibling_intersection = children
                .get(1 - position)
                .and_then(|&sibling| tables[sibling].bounding_box.as_ref())
                .map_or(0.0, |sibling_bbox| bbox_intersection_area(parent_bbox, sibling_bbox));
            bbox_center_x(child_bbox) >= parent_bbox.x0
                && bbox_center_x(child_bbox) <= parent_bbox.x1
                && paired_intersection > sibling_intersection
                && bbox_overlap_fraction(child_bbox, parent_bbox) + SIDE_BY_SIDE_CORRESPONDENCE_EPSILON
                    >= SIDE_BY_SIDE_CHILD_PARENT_OVERLAP
                && bbox_overlap_fraction(parent_bbox, child_bbox) + SIDE_BY_SIDE_CORRESPONDENCE_EPSILON
                    >= SIDE_BY_SIDE_CHILD_PARENT_OVERLAP
        })
}

fn bbox_center_x(bbox: &crate::types::BoundingBox) -> f64 {
    (bbox.x0 + bbox.x1) / 2.0
}

fn table_top(tables: &[crate::types::Table], index: usize) -> f64 {
    tables[index]
        .bounding_box
        .as_ref()
        .map_or(f64::NEG_INFINITY, |bbox| bbox.y1)
}

fn layout_children_for_parent(
    tables: &[crate::types::Table],
    native_count: usize,
    page_number: u32,
    parent_bbox: &crate::types::BoundingBox,
) -> Vec<usize> {
    let children = (native_count..tables.len())
        .filter(|&child| {
            tables[child].page_number == page_number
                && tables[child]
                    .bounding_box
                    .as_ref()
                    .is_some_and(|bbox| bbox_overlap_fraction(bbox, parent_bbox) >= SIDE_BY_SIDE_CHILD_PARENT_OVERLAP)
        })
        .collect();
    deduplicate_layout_candidates(tables, children)
}

fn table_union_bbox(left: &crate::types::Table, right: &crate::types::Table) -> Option<crate::types::BoundingBox> {
    let left = left.bounding_box.as_ref()?;
    let right = right.bounding_box.as_ref()?;
    Some(crate::types::BoundingBox {
        x0: left.x0.min(right.x0),
        y0: left.y0.min(right.y0),
        x1: left.x1.max(right.x1),
        y1: left.y1.max(right.y1),
    })
}

fn deduplicate_layout_candidates(tables: &[crate::types::Table], mut candidates: Vec<usize>) -> Vec<usize> {
    candidates.sort_by(|&left, &right| table_left(tables, left).total_cmp(&table_left(tables, right)));
    let mut unique: Vec<usize> = Vec::with_capacity(candidates.len());
    for candidate in candidates {
        let duplicate = unique.iter().position(|&existing| {
            let candidate_bbox = tables[candidate].bounding_box.as_ref().expect("candidate has bbox");
            let existing_bbox = tables[existing].bounding_box.as_ref().expect("candidate has bbox");
            bbox_overlap_fraction(candidate_bbox, existing_bbox) >= LAYOUT_CHILD_DUPLICATE_OVERLAP
                && bbox_overlap_fraction(existing_bbox, candidate_bbox) >= LAYOUT_CHILD_DUPLICATE_OVERLAP
        });
        if let Some(position) = duplicate {
            let existing = unique[position];
            if table_content_weight(&tables[candidate]) > table_content_weight(&tables[existing]) {
                unique[position] = candidate;
            }
        } else {
            unique.push(candidate);
        }
    }
    unique.sort_by(|&left, &right| table_left(tables, left).total_cmp(&table_left(tables, right)));
    unique
}

fn lower_content_table(tables: &[crate::types::Table], left: usize, right: usize) -> usize {
    if table_content_weight(&tables[left]) >= table_content_weight(&tables[right]) {
        right
    } else {
        left
    }
}

fn table_content_weight(table: &crate::types::Table) -> usize {
    table.cells.len() + table.markdown.len()
}

fn is_side_by_side_replacement(
    tables: &[crate::types::Table],
    parent: &crate::types::BoundingBox,
    children: &[usize],
) -> bool {
    let parent_width = parent.x1 - parent.x0;
    let parent_height = parent.y1 - parent.y0;
    if children.len() < 2 || parent_width <= 0.0 || parent_height <= 0.0 {
        return false;
    }
    let horizontally_disjoint = children.windows(2).all(|pair| {
        let left = tables[pair[0]].bounding_box.as_ref().expect("candidate has bbox");
        let right = tables[pair[1]].bounding_box.as_ref().expect("candidate has bbox");
        left.x1 <= right.x0 && vertical_overlap_fraction(left, right) >= SIDE_BY_SIDE_VERTICAL_OVERLAP
    });
    if !horizontally_disjoint {
        return false;
    }
    let covers_parent_height = children.iter().all(|&index| {
        let bbox = tables[index].bounding_box.as_ref().expect("candidate has bbox");
        let covered_height = (bbox.y1.min(parent.y1) - bbox.y0.max(parent.y0)).max(0.0);
        covered_height / parent_height >= SIDE_BY_SIDE_PARENT_HEIGHT_COVERAGE
    });
    if !covers_parent_height {
        return false;
    }
    let covered_width: f64 = children
        .iter()
        .map(|&index| {
            let bbox = tables[index].bounding_box.as_ref().expect("candidate has bbox");
            (bbox.x1.min(parent.x1) - bbox.x0.max(parent.x0)).max(0.0)
        })
        .sum();
    let covered_area: f64 = children
        .iter()
        .map(|&index| bbox_intersection_area(tables[index].bounding_box.as_ref().expect("candidate has bbox"), parent))
        .sum();
    covered_width / parent_width >= SIDE_BY_SIDE_PARENT_WIDTH_COVERAGE
        && covered_area / (parent_width * parent_height) >= SIDE_BY_SIDE_PARENT_AREA_COVERAGE
}

fn bbox_overlap_fraction(child: &crate::types::BoundingBox, parent: &crate::types::BoundingBox) -> f64 {
    let child_area = (child.x1 - child.x0).max(0.0) * (child.y1 - child.y0).max(0.0);
    if child_area == 0.0 {
        return 0.0;
    }
    bbox_intersection_area(child, parent) / child_area
}

fn bbox_intersection_area(a: &crate::types::BoundingBox, b: &crate::types::BoundingBox) -> f64 {
    let intersection_width = (a.x1.min(b.x1) - a.x0.max(b.x0)).max(0.0);
    let intersection_height = (a.y1.min(b.y1) - a.y0.max(b.y0)).max(0.0);
    intersection_width * intersection_height
}

fn vertical_overlap_fraction(a: &crate::types::BoundingBox, b: &crate::types::BoundingBox) -> f64 {
    let overlap = (a.y1.min(b.y1) - a.y0.max(b.y0)).max(0.0);
    let min_height = (a.y1 - a.y0).min(b.y1 - b.y0);
    if min_height <= 0.0 { 0.0 } else { overlap / min_height }
}

fn table_left(tables: &[crate::types::Table], index: usize) -> f64 {
    tables[index]
        .bounding_box
        .as_ref()
        .map_or(f64::INFINITY, |bbox| bbox.x0)
}

fn canonicalize_affected_table_rows(
    tables: &mut Vec<crate::types::Table>,
    affected_rows: Vec<(u32, crate::types::BoundingBox)>,
) {
    let cohorts = affected_row_cohorts(affected_rows);
    if cohorts.is_empty() {
        return;
    }
    let assignments: Vec<_> = tables.iter().map(|table| table_row_cohort(table, &cohorts)).collect();
    let mut cohort_tables: Vec<Vec<_>> = (0..cohorts.len()).map(|_| Vec::new()).collect();
    let mut source: Vec<Option<_>> = std::mem::take(tables).into_iter().map(Some).collect();
    for (index, cohort) in assignments.iter().enumerate() {
        if let Some(cohort) = cohort {
            cohort_tables[*cohort].push(source[index].take().expect("assigned table is present"));
        }
    }
    for cohort in &mut cohort_tables {
        cohort.sort_by(canonical_table_order);
        cohort.reverse();
    }
    for (index, cohort) in assignments.iter().enumerate() {
        if let Some(cohort) = cohort {
            source[index] = Some(
                cohort_tables[*cohort]
                    .pop()
                    .expect("cohort table count matches assigned slots"),
            );
        }
    }
    tables.extend(source.into_iter().flatten());
}

fn affected_row_cohorts(mut rows: Vec<(u32, crate::types::BoundingBox)>) -> Vec<(u32, Vec<crate::types::BoundingBox>)> {
    let mut cohorts = Vec::new();
    while let Some((page, seed)) = rows.pop() {
        let mut cohort = vec![seed];
        let mut changed = true;
        while changed {
            changed = false;
            rows.retain(|(candidate_page, candidate)| {
                let connected = *candidate_page == page
                    && cohort
                        .iter()
                        .any(|member| vertical_overlap_fraction(member, candidate) >= SIDE_BY_SIDE_VERTICAL_OVERLAP);
                if connected {
                    cohort.push(*candidate);
                    changed = true;
                }
                !connected
            });
        }
        cohorts.push((page, cohort));
    }
    cohorts.sort_by(|(left_page, left_rows), (right_page, right_rows)| {
        left_page.cmp(right_page).then_with(|| {
            let left_y = left_rows.iter().map(|row| row.y0).fold(f64::INFINITY, f64::min);
            let right_y = right_rows.iter().map(|row| row.y0).fold(f64::INFINITY, f64::min);
            left_y.total_cmp(&right_y)
        })
    });
    cohorts
}

fn table_row_cohort(table: &crate::types::Table, cohorts: &[(u32, Vec<crate::types::BoundingBox>)]) -> Option<usize> {
    let bbox = table.bounding_box.as_ref()?;
    cohorts
        .iter()
        .enumerate()
        .filter(|(_, (page, _))| *page == table.page_number)
        .map(|(index, (_, rows))| {
            let overlap = rows
                .iter()
                .map(|row| vertical_overlap_fraction(bbox, row))
                .fold(0.0_f64, f64::max);
            (index, overlap)
        })
        .filter(|(_, overlap)| *overlap >= SIDE_BY_SIDE_VERTICAL_OVERLAP)
        .max_by(|left, right| left.1.total_cmp(&right.1).then_with(|| right.0.cmp(&left.0)))
        .map(|(index, _)| index)
}

fn canonical_table_order(left: &crate::types::Table, right: &crate::types::Table) -> std::cmp::Ordering {
    let left_bbox = left.bounding_box.as_ref();
    let right_bbox = right.bounding_box.as_ref();
    left.page_number
        .cmp(&right.page_number)
        .then_with(|| {
            left_bbox
                .map_or(f64::INFINITY, |bbox| bbox.y0)
                .total_cmp(&right_bbox.map_or(f64::INFINITY, |bbox| bbox.y0))
        })
        .then_with(|| {
            left_bbox
                .map_or(f64::INFINITY, |bbox| bbox.x0)
                .total_cmp(&right_bbox.map_or(f64::INFINITY, |bbox| bbox.x0))
        })
        .then_with(|| left.markdown.cmp(&right.markdown))
}

/// Clear `is_page_furniture` on paragraphs whose `layout_class` was set to
/// `PageHeader` or `PageFooter` by the layout model, when the caller has opted
/// in to keeping those regions via `include_headers` / `include_footers`.
///
/// This must run **before** `retain_page_furniture_safely`, which physically
/// removes furniture paragraphs via `.retain()`. Un-marking here ensures that
/// user-opted-in header/footer paragraphs survive that pass.
fn un_mark_layout_furniture_per_config(paragraphs: &mut [PdfParagraph], include_headers: bool, include_footers: bool) {
    if !include_headers && !include_footers {
        return;
    }
    for para in paragraphs.iter_mut() {
        if !para.is_page_furniture {
            continue;
        }
        match para.layout_class {
            Some(super::types::LayoutHintClass::PageHeader) if include_headers => {
                para.is_page_furniture = false;
            }
            Some(super::types::LayoutHintClass::PageFooter) if include_footers => {
                para.is_page_furniture = false;
            }
            _ => {}
        }
    }
}

const FOOTNOTE_MARKER_MAX_CHARS: usize = 3;
const FOOTNOTE_MARKER_MAX_FONT_RATIO: f32 = 0.8;
const FOOTNOTE_MARKER_MAX_GAP_EM: f32 = 0.5;
const FOOTNOTE_MARKER_MIN_VERTICAL_OVERLAP_RATIO: f32 = 0.8;
const FOOTNOTE_MARKER_MIN_RISE_EM: f32 = 0.1;
const FOOTNOTE_RUN_MIN_LENGTH: usize = 3;
const FOOTNOTE_RUN_MAX_FONT_DELTA: f32 = 0.5;
const FOOTNOTE_RUN_MAX_LEFT_DELTA_EM: f32 = 0.5;
const FOOTNOTE_RUN_MAX_VERTICAL_GAP_EM: f32 = 0.5;
const FOOTNOTE_RUN_MAX_GAP_SPREAD_EM: f32 = 0.25;

/// Rejoin a small raised footnote marker that was split from its body.
///
/// Standalone numeric markers are initially classified as page numbers. Only
/// strong same-line geometry can override that classification, so genuine page
/// numbers and numbered list items remain untouched.
fn merge_spatial_footnote_markers(paragraphs: &mut Vec<PdfParagraph>) {
    let mut merged_pairs = vec![false; paragraphs.len()];
    let mut index = 0;
    while index + 1 < paragraphs.len() {
        if !is_spatial_footnote_pair(&paragraphs[index], &paragraphs[index + 1]) {
            index += 1;
            continue;
        }

        let marker = paragraphs.remove(index);
        merged_pairs.remove(index);
        let body = &mut paragraphs[index];
        let mut lines = marker.lines;
        lines.append(&mut body.lines);
        body.lines = lines;
        body.text.clear();
        body.block_bbox = marker.block_bbox.zip(body.block_bbox).map(|(marker_bbox, body_bbox)| {
            (
                marker_bbox.0.min(body_bbox.0),
                marker_bbox.1.min(body_bbox.1),
                marker_bbox.2.max(body_bbox.2),
                marker_bbox.3.max(body_bbox.3),
            )
        });
        body.word_count = PdfParagraph::compute_word_count("", &body.lines);
        body.is_page_furniture = false;
        merged_pairs[index] = true;
        index += 1;
    }
    merge_consecutive_spatial_footnotes(paragraphs, &mut merged_pairs);
}

fn spatial_footnote_number(paragraph: &PdfParagraph) -> Option<u32> {
    if paragraph.lines.len() < 2 || paragraph.heading_level.is_some() || paragraph.is_list_item {
        return None;
    }
    let marker = paragraph.lines.first()?.segments.first()?;
    if marker.font_size > paragraph.dominant_font_size * FOOTNOTE_MARKER_MAX_FONT_RATIO {
        return None;
    }
    marker.text.trim().parse().ok()
}

fn spatial_footnote_gap(upper: &PdfParagraph, lower: &PdfParagraph) -> Option<f32> {
    let (_, upper_bottom, _, _) = upper.block_bbox?;
    let (_, _, _, lower_top) = lower.block_bbox?;
    Some(upper_bottom - lower_top)
}

fn spatial_footnotes_are_adjacent(upper: &PdfParagraph, lower: &PdfParagraph) -> bool {
    let Some(upper_number) = spatial_footnote_number(upper) else {
        return false;
    };
    let Some(lower_number) = spatial_footnote_number(lower) else {
        return false;
    };
    let Some((upper_left, _, _, _)) = upper.block_bbox else {
        return false;
    };
    let Some((lower_left, _, _, _)) = lower.block_bbox else {
        return false;
    };
    let Some(gap) = spatial_footnote_gap(upper, lower) else {
        return false;
    };
    upper_number.checked_add(1) == Some(lower_number)
        && upper.layout_region_path == lower.layout_region_path
        && (upper.dominant_font_size - lower.dominant_font_size).abs() < FOOTNOTE_RUN_MAX_FONT_DELTA
        && (upper_left - lower_left).abs() <= upper.dominant_font_size * FOOTNOTE_RUN_MAX_LEFT_DELTA_EM
        && gap >= 0.0
        && gap <= upper.dominant_font_size * FOOTNOTE_RUN_MAX_VERTICAL_GAP_EM
}

fn spatial_footnote_run_is_regular(run: &[PdfParagraph]) -> bool {
    if run.len() < FOOTNOTE_RUN_MIN_LENGTH
        || !run
            .windows(2)
            .all(|pair| spatial_footnotes_are_adjacent(&pair[0], &pair[1]))
    {
        return false;
    }
    let gaps = run
        .windows(2)
        .filter_map(|pair| spatial_footnote_gap(&pair[0], &pair[1]))
        .collect::<Vec<_>>();
    let minimum = gaps.iter().copied().fold(f32::INFINITY, f32::min);
    let maximum = gaps.iter().copied().fold(f32::NEG_INFINITY, f32::max);
    maximum - minimum <= run[0].dominant_font_size * FOOTNOTE_RUN_MAX_GAP_SPREAD_EM
}

fn merge_spatial_footnote_run(run: Vec<PdfParagraph>) -> PdfParagraph {
    let mut iter = run.into_iter();
    let mut merged = iter.next().expect("footnote run is non-empty");
    for mut paragraph in iter {
        merged.lines.append(&mut paragraph.lines);
        merged.block_bbox = merged.block_bbox.zip(paragraph.block_bbox).map(|(left, right)| {
            (
                left.0.min(right.0),
                left.1.min(right.1),
                left.2.max(right.2),
                left.3.max(right.3),
            )
        });
    }
    merged.text.clear();
    merged.word_count = PdfParagraph::compute_word_count("", &merged.lines);
    merged
}

fn merge_consecutive_spatial_footnotes(paragraphs: &mut Vec<PdfParagraph>, merged_pairs: &mut Vec<bool>) {
    let mut start = 0;
    while start + FOOTNOTE_RUN_MIN_LENGTH <= paragraphs.len() {
        let minimum_end = start + FOOTNOTE_RUN_MIN_LENGTH;
        if !merged_pairs[start..minimum_end].iter().all(|merged| *merged)
            || !spatial_footnote_run_is_regular(&paragraphs[start..minimum_end])
        {
            start += 1;
            continue;
        }

        let mut end = minimum_end;
        while end < paragraphs.len() && merged_pairs[end] && spatial_footnote_run_is_regular(&paragraphs[start..=end]) {
            end += 1;
        }

        let merged = merge_spatial_footnote_run(paragraphs.drain(start..end).collect());
        paragraphs.insert(start, merged);
        merged_pairs.drain(start..end);
        merged_pairs.insert(start, false);
        start += 1;
    }
}

fn is_spatial_footnote_pair(marker: &PdfParagraph, body: &PdfParagraph) -> bool {
    if !marker.is_page_furniture
        || body.is_page_furniture
        || body.heading_level.is_some()
        || body.is_list_item
        || body.is_code_block
        || body.is_formula
        || body.caption_for.is_some()
        || marker.layout_region_path != body.layout_region_path
        || !is_compact_footnote_marker(&paragraph_text_raw(marker))
    {
        return false;
    }

    let Some((marker_left, marker_bottom, marker_right, marker_top)) = marker.block_bbox else {
        return false;
    };
    let Some((body_left, body_bottom, _, body_top)) = body.block_bbox else {
        return false;
    };
    let marker_height = marker_top - marker_bottom;
    let body_height = body_top - body_bottom;
    let overlap = marker_top.min(body_top) - marker_bottom.max(body_bottom);
    let minimum_height = marker_height.min(body_height);
    let horizontal_gap = body_left - marker_right;

    marker_left < body_left
        && horizontal_gap >= 0.0
        && horizontal_gap <= body.dominant_font_size * FOOTNOTE_MARKER_MAX_GAP_EM
        && marker.dominant_font_size <= body.dominant_font_size * FOOTNOTE_MARKER_MAX_FONT_RATIO
        && marker_bottom - body_bottom >= body.dominant_font_size * FOOTNOTE_MARKER_MIN_RISE_EM
        && minimum_height > 0.0
        && overlap >= minimum_height * FOOTNOTE_MARKER_MIN_VERTICAL_OVERLAP_RATIO
}

fn is_compact_footnote_marker(text: &str) -> bool {
    let marker = text.trim();
    let char_count = marker.chars().count();
    char_count > 0
        && char_count <= FOOTNOTE_MARKER_MAX_CHARS
        && (marker.chars().all(|character| character.is_ascii_digit())
            || marker
                .chars()
                .all(|character| matches!(character, '*' | '' | '' | '§')))
}

/// Filter page furniture paragraphs with a safety valve.
///
/// Removes paragraphs marked as page furniture (headers/footers) by layout
/// detection. If removing ALL furniture-marked paragraphs would leave zero
/// content, the furniture markings are cleared instead — better to include
/// headers/footers than to produce empty output. This handles layout models
/// misclassifying body text as page furniture on non-standard document types
/// (e.g., legal transcripts, cover pages).
fn retain_page_furniture_safely(paragraphs: &mut Vec<PdfParagraph>) {
    let total = paragraphs.len();
    let furniture_count = paragraphs.iter().filter(|p| p.is_page_furniture).count();

    if furniture_count == 0 {
        return;
    }

    if furniture_count >= total {
        for para in paragraphs.iter_mut() {
            para.is_page_furniture = false;
        }
        return;
    }

    let total_alphanum: usize = paragraphs.iter().map(paragraph_alphanum_len).sum();

    if total_alphanum > 0 {
        let furniture_alphanum: usize = paragraphs
            .iter()
            .filter(|p| p.is_page_furniture)
            .map(paragraph_alphanum_len)
            .sum();

        if furniture_alphanum * 100 > total_alphanum * 30 {
            for para in paragraphs.iter_mut() {
                para.is_page_furniture = false;
            }
            return;
        }
    }

    const MIN_SUBSTANTIVE_CHARS: usize = 80;

    paragraphs.retain(|p| {
        if !p.is_page_furniture {
            return true;
        }
        paragraph_alphanum_len(p) > MIN_SUBSTANTIVE_CHARS
    });
}

/// Count alphanumeric characters in a paragraph's text content.
fn paragraph_alphanum_len(para: &PdfParagraph) -> usize {
    para.lines
        .iter()
        .flat_map(|line| line.segments.iter())
        .map(|seg| seg.text.bytes().filter(|b| b.is_ascii_alphanumeric()).count())
        .sum()
}

/// Dehyphenate paragraphs by rejoining words split across line boundaries.
///
/// When `has_positions` is true (heuristic extraction path), both explicit
/// trailing hyphens and implicit breaks (no hyphen, full line) are handled.
/// When false (structure tree path with x=0, width=0), only explicit trailing
/// hyphens are rejoined to avoid false positives.
fn dehyphenate_paragraphs(paragraphs: &mut [PdfParagraph], has_positions: bool) {
    for para in paragraphs.iter_mut() {
        if para.is_code_block || para.lines.len() < 2 {
            continue;
        }
        if has_positions {
            dehyphenate_paragraph_lines(para);
        } else {
            dehyphenate_hyphen_only(para);
        }
    }
}

/// High-confidence lexical compounds whose source hyphen must survive a line break.
///
/// A trailing ASCII hyphen is otherwise indistinguishable from a discretionary PDF
/// line-wrap hyphen. Exact pair matching is intentionally narrower than prefix or
/// suffix rules: it protects common compounds without suppressing repairs such as
/// `soft-` + `ware`.
const PRESERVED_LEXICAL_COMPOUNDS: &[(&str, &str)] = &[
    ("cost", "effective"),
    ("evidence", "based"),
    ("high", "level"),
    ("long", "term"),
    ("low", "level"),
    ("real", "time"),
    ("short", "term"),
    ("state", "of-the-art"),
    ("user", "defined"),
    ("well", "known"),
];

fn should_preserve_lexical_hyphen(trailing_word: &str, leading_word: &str) -> bool {
    let trim_non_lexical = |ch: char| !ch.is_alphanumeric() && ch != '-';
    let left = trailing_word.trim_matches(trim_non_lexical);
    let right = leading_word.trim_matches(trim_non_lexical);

    PRESERVED_LEXICAL_COMPOUNDS
        .iter()
        .any(|&(expected_left, expected_right)| {
            left.eq_ignore_ascii_case(expected_left) && right.eq_ignore_ascii_case(expected_right)
        })
}

/// Core dehyphenation with position-based full-line detection.
///
/// For each line boundary, checks whether the line extends close to the right
/// margin. If so, attempts to rejoin the trailing word of one line with the
/// leading word of the next.
fn dehyphenate_paragraph_lines(para: &mut PdfParagraph) {
    let max_right_edge = para
        .lines
        .iter()
        .flat_map(|l| l.segments.iter())
        .map(|s| s.x + s.width)
        .fold(0.0_f32, f32::max);

    if max_right_edge <= 0.0 {
        dehyphenate_hyphen_only(para);
        return;
    }

    let threshold = max_right_edge * FULL_LINE_FRACTION;

    let n = para.lines.len();
    for i in 0..(n - 1) {
        let trailing_right = para.lines[i].segments.last().map(|s| s.x + s.width).unwrap_or(0.0);
        if trailing_right < threshold {
            continue;
        }

        let trailing_text = match para.lines[i].segments.last() {
            Some(s) if !s.text.is_empty() => s.text.clone(),
            _ => continue,
        };
        let leading_text = match para.lines[i + 1].segments.first() {
            Some(s) if !s.text.is_empty() => s.text.clone(),
            _ => continue,
        };

        let has_trailing_hyphen = trailing_text.ends_with('-');
        if !has_trailing_hyphen {
            continue;
        }

        let leading_word = leading_text.split_whitespace().next().unwrap_or("");
        if leading_word.chars().next().is_some_and(|c| c.is_uppercase()) {
            continue;
        }

        let trailing_word = trailing_text
            .trim_end_matches('-')
            .split_whitespace()
            .last()
            .unwrap_or("");
        if trailing_word.chars().last().is_some_and(is_cjk_char) {
            continue;
        }

        let preserved_hyphen = if should_preserve_lexical_hyphen(trailing_word, leading_word) {
            "-"
        } else {
            ""
        };
        let joined_word = format!("{trailing_word}{preserved_hyphen}{leading_word}");

        if let Some(seg) = para.lines[i].segments.last_mut() {
            let text_without_word: String = seg
                .text
                .chars()
                .rev()
                .skip(trailing_word.len() + 1)
                .collect::<String>()
                .chars()
                .rev()
                .collect();
            seg.text = format!("{text_without_word}{joined_word}");
        }

        if let Some(seg) = para.lines[i + 1].segments.first_mut() {
            let after_leading_word = seg.text.trim_start_matches(leading_word).trim_start();
            seg.text = after_leading_word.to_string();
        }
    }
}

/// Hyphen-only dehyphenation (no position data required).
///
/// Only joins lines when the trailing segment ends with an explicit hyphen.
/// Used for structure tree pages where x/width may be zero.
fn dehyphenate_hyphen_only(para: &mut PdfParagraph) {
    let n = para.lines.len();
    for i in 0..(n - 1) {
        let trailing_text = match para.lines[i].segments.last() {
            Some(s) if s.text.ends_with('-') => s.text.clone(),
            _ => continue,
        };
        let leading_text = match para.lines[i + 1].segments.first() {
            Some(s) if !s.text.is_empty() => s.text.clone(),
            _ => continue,
        };

        let leading_word = leading_text.split_whitespace().next().unwrap_or("");
        if leading_word.chars().next().is_some_and(|c| c.is_uppercase()) {
            continue;
        }

        let trailing_word = trailing_text
            .trim_end_matches('-')
            .split_whitespace()
            .last()
            .unwrap_or("");
        if trailing_word.chars().last().is_some_and(is_cjk_char) {
            continue;
        }

        let preserved_hyphen = if should_preserve_lexical_hyphen(trailing_word, leading_word) {
            "-"
        } else {
            ""
        };
        let joined_word = format!("{trailing_word}{preserved_hyphen}{leading_word}");

        if let Some(seg) = para.lines[i].segments.last_mut() {
            let text_without_word: String = seg
                .text
                .chars()
                .rev()
                .skip(trailing_word.len() + 1)
                .collect::<String>()
                .chars()
                .rev()
                .collect();
            seg.text = format!("{text_without_word}{joined_word}");
        }

        if let Some(seg) = para.lines[i + 1].segments.first_mut() {
            let after_leading_word = seg.text.trim_start_matches(leading_word).trim_start();
            seg.text = after_leading_word.to_string();
        }
    }
}

/// Detect whether a set of paragraphs contains any font-size variation.
///
/// Variation is defined as any paragraph whose font size differs from the first
/// non-zero size by more than 0.5pt. Used to decide whether structure-tree pages
/// need font-size clustering for heading assignment.
fn has_font_size_variation(paragraphs: &[PdfParagraph]) -> bool {
    let mut first_size: Option<f32> = None;
    for para in paragraphs {
        let size = para.dominant_font_size;
        if size <= 0.0 {
            continue;
        }
        match first_size {
            None => first_size = Some(size),
            Some(fs) if (size - fs).abs() > 0.5 => return true,
            _ => {}
        }
    }
    false
}

/// Deduplicate paragraphs with identical text within each page.
///
/// Two-pass approach:
/// 1. Consecutive duplicates: remove back-to-back identical paragraphs
///    (catches bold/shadow rendering artifacts).
/// 2. Non-consecutive duplicates: remove body-text paragraphs whose
///    normalized text was already seen on the same page (catches table
///    content rendered as both table and body text).
///
/// Only deduplicates body text — headings, list items, code blocks,
/// formulas, and captions are preserved even if duplicated.
fn deduplicate_paragraphs(all_pages: &mut [Vec<PdfParagraph>]) {
    for page in all_pages.iter_mut() {
        if page.len() < 2 {
            continue;
        }

        let mut i = 0;
        while i + 1 < page.len() {
            let a_text = paragraph_text_normalized(&page[i]);
            let b_text = paragraph_text_normalized(&page[i + 1]);
            if page[i].layout_region_path == page[i + 1].layout_region_path && a_text.len() >= 5 && a_text == b_text {
                page.remove(i + 1);
            } else {
                i += 1;
            }
        }

        let mut seen = ahash::AHashSet::new();
        let mut to_remove = Vec::new();
        for (idx, para) in page.iter().enumerate() {
            if !is_dedup_candidate(para) {
                continue;
            }
            let text = paragraph_text_normalized(para);
            if text.len() < 15 {
                continue;
            }
            if !seen.insert((para.layout_region_path, text)) {
                to_remove.push(idx);
            }
        }

        for &idx in to_remove.iter().rev() {
            page.remove(idx);
        }
    }
}

const DEFAULT_OUTLINE_HEADING_OFFSET: i64 = 2;
const MIN_OUTLINE_CALIBRATION_ANCHORS: usize = 2;
const MIN_MARKDOWN_HEADING_LEVEL: i64 = 1;
const MAX_MARKDOWN_HEADING_LEVEL: i64 = 6;

#[derive(Debug, Clone, Copy)]
struct OutlineParagraphMatch {
    page_index: usize,
    paragraph_index: usize,
    depth: usize,
}

fn recover_headings_from_outline(all_pages: &mut [Vec<PdfParagraph>], outline_entries: &[PdfOutlineEntry]) {
    let matches = collect_unique_outline_matches(all_pages, outline_entries);
    let offset = calibrated_outline_heading_offset(all_pages, &matches);

    for matched in matches {
        let paragraph = &mut all_pages[matched.page_index][matched.paragraph_index];
        if paragraph.heading_level.is_some() || !outline_layout_allows_heading(paragraph) {
            continue;
        }
        let depth = i64::try_from(matched.depth).unwrap_or(i64::MAX);
        let level = depth
            .saturating_add(offset)
            .clamp(MIN_MARKDOWN_HEADING_LEVEL, MAX_MARKDOWN_HEADING_LEVEL);
        paragraph.heading_level = Some(level as u8);
        paragraph.is_list_item = false;
        paragraph.is_page_furniture = false;
    }
}

fn collect_unique_outline_matches(
    all_pages: &[Vec<PdfParagraph>],
    outline_entries: &[PdfOutlineEntry],
) -> Vec<OutlineParagraphMatch> {
    let mut outline_counts = ahash::AHashMap::<(usize, String), usize>::new();
    for entry in outline_entries {
        if let Some(key) = outline_match_key(entry, all_pages.len()) {
            *outline_counts.entry(key).or_default() += 1;
        }
    }
    let paragraph_matches = all_pages
        .iter()
        .map(|page| {
            let mut matches = ahash::AHashMap::<String, (usize, usize)>::new();
            for (index, paragraph) in page.iter().enumerate() {
                let title = normalize_outline_title(&paragraph_text_raw(paragraph));
                let entry = matches.entry(title).or_insert((0, index));
                entry.0 += 1;
            }
            matches
        })
        .collect::<Vec<_>>();

    outline_entries
        .iter()
        .filter_map(|entry| {
            let (page_index, title) = outline_match_key(entry, all_pages.len())?;
            if outline_counts.get(&(page_index, title.clone())) != Some(&1) {
                return None;
            }
            let &(paragraph_count, paragraph_index) = paragraph_matches[page_index].get(&title)?;
            (paragraph_count == 1).then_some(OutlineParagraphMatch {
                page_index,
                paragraph_index,
                depth: entry.depth,
            })
        })
        .collect()
}

fn outline_match_key(entry: &PdfOutlineEntry, page_count: usize) -> Option<(usize, String)> {
    let page_number = entry.page_number?;
    let page_index = usize::try_from(page_number.checked_sub(1)?).ok()?;
    let title = normalize_outline_title(&entry.title);
    (page_index < page_count && !title.is_empty()).then_some((page_index, title))
}

fn calibrated_outline_heading_offset(all_pages: &[Vec<PdfParagraph>], matches: &[OutlineParagraphMatch]) -> i64 {
    let mut counts = ahash::AHashMap::<i64, usize>::new();
    for matched in matches {
        let paragraph = &all_pages[matched.page_index][matched.paragraph_index];
        if !outline_layout_allows_heading(paragraph) {
            continue;
        }
        if let Some(level) = paragraph.heading_level {
            let depth = i64::try_from(matched.depth).unwrap_or(i64::MAX);
            *counts.entry(i64::from(level).saturating_sub(depth)).or_default() += 1;
        }
    }

    let max_count = counts.values().copied().max().unwrap_or_default();
    let mut winners = counts.into_iter().filter(|(_, count)| *count == max_count);
    let winner = winners.next();
    match (winner, winners.next(), max_count) {
        (Some((offset, _)), None, count) if count >= MIN_OUTLINE_CALIBRATION_ANCHORS => offset,
        _ => DEFAULT_OUTLINE_HEADING_OFFSET,
    }
}

fn outline_layout_allows_heading(paragraph: &PdfParagraph) -> bool {
    if paragraph.is_code_block || paragraph.is_formula || paragraph.caption_for.is_some() {
        return false;
    }
    matches!(
        paragraph.layout_class,
        None | Some(super::types::LayoutHintClass::Title)
            | Some(super::types::LayoutHintClass::SectionHeader)
            | Some(super::types::LayoutHintClass::Text)
            | Some(super::types::LayoutHintClass::Other)
    )
}

fn normalize_outline_title(text: &str) -> String {
    let text = strip_section_label(text.trim());
    let mut normalized = String::new();
    let mut pending_space = false;
    for character in text.chars().flat_map(char::to_lowercase) {
        if character.is_alphanumeric() {
            if pending_space && !normalized.is_empty() {
                normalized.push(' ');
            }
            normalized.push(character);
            pending_space = false;
        } else if !normalized.is_empty() {
            pending_space = true;
        }
    }
    normalized
}

fn strip_section_label(text: &str) -> &str {
    let Some((first, rest)) = text.split_once(char::is_whitespace) else {
        return text;
    };
    let punctuated = first
        .chars()
        .next()
        .is_some_and(|character| matches!(character, '(' | '['))
        || first
            .chars()
            .last()
            .is_some_and(|character| matches!(character, '.' | ')' | ']' | ':'));
    let core = first.trim_matches(|character| matches!(character, '(' | '[' | '.' | ')' | ']' | ':'));
    let decimal_parts = core.split('.').collect::<Vec<_>>();
    let decimal = !decimal_parts.is_empty()
        && decimal_parts
            .iter()
            .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()));
    let decimal_label = decimal && (punctuated || decimal_parts.len() > 1 || core.len() <= 3);
    let roman_label = punctuated
        && !core.is_empty()
        && core
            .chars()
            .all(|character| matches!(character.to_ascii_uppercase(), 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M'));
    let letter_label = punctuated && core.len() == 1 && core.chars().all(|character| character.is_ascii_alphabetic());

    if decimal_label || roman_label || letter_label {
        rest.trim_start()
    } else {
        text
    }
}

fn paragraph_text_raw(para: &PdfParagraph) -> String {
    if para.text.is_empty() {
        para.lines
            .iter()
            .flat_map(|line| line.segments.iter())
            .map(|segment| segment.text.as_str())
            .collect::<Vec<_>>()
            .join(" ")
    } else {
        para.text.clone()
    }
}

/// Normalize paragraph text for deduplication comparison.
///
/// Uses `para.text` when populated (heuristic path), otherwise assembles text
/// from segment data (structure tree path, used in tests).
fn paragraph_text_normalized(para: &PdfParagraph) -> String {
    paragraph_text_raw(para)
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_lowercase()
}

/// Check if a paragraph is a candidate for non-consecutive deduplication.
fn is_dedup_candidate(p: &PdfParagraph) -> bool {
    p.heading_level.is_none()
        && !p.is_list_item
        && !p.is_code_block
        && !p.is_formula
        && !p.is_page_furniture
        && p.caption_for.is_none()
}

/// Minimum word count for the lead sentence before a run-in list's anchor
/// colon; guards against matching short labels (`"Note:"`, abbreviations)
/// that happen to be followed by a semicolon elsewhere in the text.
const RUN_IN_LIST_MIN_LEAD_WORDS: usize = 4;
/// Minimum semicolon-delimited clauses required to call a colon-introduced
/// run a "list" — a single clause is just a qualified sentence, not an
/// enumeration.
const RUN_IN_LIST_MIN_ITEMS: usize = 2;
/// Minimum word count per clause; guards against matching stray short
/// fragments (e.g. an abbreviation followed by `;`) as list items.
const RUN_IN_LIST_MIN_ITEM_WORDS: usize = 3;

/// Split a colon-introduced, semicolon-delimited "run-in" list — a prose
/// convention common in legal/contract text, e.g. "...is authorised to
/// exclude subscription rights: to exclude fractional amounts...; where the
/// new shares...;" — out of a single assembled paragraph into a lead
/// paragraph plus one list-item paragraph per clause.
///
/// These enumerations are frequently rendered with no distinguishing
/// indentation or line break from the surrounding prose (the source document
/// never used a real list, just semicolon-separated clauses within one
/// paragraph flow), so geometry-based list detection
/// (`classify::detect_indentation_based_lists`) never sees them — that pass
/// only promotes paragraphs already indented relative to the page's modal
/// left margin. This pass instead recognizes the enumeration from paragraph
/// text alone, after normal paragraph assembly, and works for both the
/// heuristic and structure-tree paragraph paths via [`paragraph_text_raw`].
///
/// xberg-io/xberg#1301.
fn split_colon_semicolon_run_in_lists(all_page_paragraphs: &mut [Vec<PdfParagraph>]) {
    for page_paragraphs in all_page_paragraphs.iter_mut() {
        let mut index = 0;
        while index < page_paragraphs.len() {
            match try_split_run_in_list(&page_paragraphs[index]) {
                Some(replacement) => {
                    let inserted = replacement.len();
                    page_paragraphs.splice(index..=index, replacement);
                    index += inserted;
                }
                None => index += 1,
            }
        }
    }
}

/// Attempt to split one paragraph into a lead paragraph plus run-in list
/// items. Returns `None` when the paragraph does not match the pattern, in
/// which case it is left untouched.
fn try_split_run_in_list(para: &PdfParagraph) -> Option<Vec<PdfParagraph>> {
    if para.heading_level.is_some()
        || para.is_list_item
        || para.is_code_block
        || para.is_formula
        || para.is_page_furniture
    {
        return None;
    }

    let normalized: String = paragraph_text_raw(para)
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let colon_byte = normalized.rfind(':')?;
    let lead = normalized[..=colon_byte].trim();
    if lead.split_whitespace().count() < RUN_IN_LIST_MIN_LEAD_WORDS {
        return None;
    }

    let tail = normalized[colon_byte + 1..].trim_start();
    if tail.is_empty() {
        return None;
    }

    let items: Vec<&str> = tail
        .split_inclusive(';')
        .map(str::trim)
        .filter(|segment| !segment.is_empty())
        .collect();
    if items.len() < RUN_IN_LIST_MIN_ITEMS || !items.iter().all(|item| is_probable_run_in_list_item(item)) {
        return None;
    }

    let mut split = Vec::with_capacity(items.len() + 1);
    split.push(run_in_list_fragment(para, lead.to_string(), false));
    for item in items {
        split.push(run_in_list_fragment(para, item.to_string(), true));
    }
    Some(split)
}

/// Whether one semicolon-delimited clause reads as a genuine list item:
/// substantial (several words), a lowercase continuation of the lead
/// sentence (real clauses read as "to exclude...", "where...", not a new
/// capitalized sentence), and clause-terminated.
fn is_probable_run_in_list_item(item: &str) -> bool {
    item.split_whitespace().count() >= RUN_IN_LIST_MIN_ITEM_WORDS
        && item.chars().next().is_some_and(char::is_lowercase)
        && matches!(item.chars().last(), Some(';' | '.'))
}

/// Build one split-off fragment, inheriting the source paragraph's
/// non-textual attributes (font size, boldness, page association, etc.).
fn run_in_list_fragment(source: &PdfParagraph, text: String, is_list_item: bool) -> PdfParagraph {
    let word_count = text.split_whitespace().count();
    PdfParagraph {
        text,
        lines: Vec::new(),
        heading_level: None,
        is_list_item,
        is_code_block: false,
        is_formula: false,
        layout_class: if is_list_item {
            Some(super::types::LayoutHintClass::ListItem)
        } else {
            source.layout_class
        },
        word_count,
        ..source.clone()
    }
}

fn apply_text_repair_to_structure_tree_paragraphs(paragraphs: &mut Vec<PdfParagraph>, has_positions: bool) {
    apply_to_all_segments(paragraphs, fused_text_repairs);
    dehyphenate_paragraphs(paragraphs, has_positions);
    split_embedded_list_items(paragraphs);
    synchronize_paragraph_text_metadata(paragraphs);
}

/// Invalidate cached paragraph text after mutating segments and refresh derived metadata.
///
/// Assembly derives both the emitted text and inline annotation byte ranges from segments
/// when `text` is empty. Keeping that cache empty prevents repaired segment text from
/// diverging from the stale pre-repair string used by the heuristic path.
fn synchronize_paragraph_text_metadata(paragraphs: &mut [PdfParagraph]) {
    for paragraph in paragraphs {
        paragraph.text.clear();
        paragraph.word_count = PdfParagraph::compute_word_count("", &paragraph.lines);
    }
}

fn compact_final_heading_hierarchy(all_pages: &mut [Vec<PdfParagraph>]) {
    let headings = all_pages
        .iter()
        .flat_map(|page| page.iter())
        .filter_map(|paragraph| paragraph.heading_level);
    let (h1_count, has_h2, has_deeper) = headings.fold((0usize, false, false), |state, level| {
        (
            state.0 + usize::from(level == 1),
            state.1 || level == 2,
            state.2 || level >= 3,
        )
    });
    if h1_count != 1 || has_h2 || !has_deeper {
        return;
    }

    for paragraph in all_pages.iter_mut().flat_map(|page| page.iter_mut()) {
        if let Some(level @ 3..) = paragraph.heading_level {
            paragraph.heading_level = Some(level - 1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pdf::hierarchy::SegmentData;
    use crate::pdf::structure::types::{PdfLine, PdfParagraph};

    #[cfg(feature = "layout-detection")]
    #[test]
    fn table_model_preflight_uses_selected_slanet_variant() {
        use crate::core::config::layout::TableModel;

        assert_eq!(
            slanet_variant_for_table_model(TableModel::SlanetWired),
            Some("slanet_wired")
        );
        assert_eq!(
            slanet_variant_for_table_model(TableModel::SlanetWireless),
            Some("slanet_wireless")
        );
        assert_eq!(
            slanet_variant_for_table_model(TableModel::SlanetPlus),
            Some("slanet_plus")
        );
        assert_eq!(
            slanet_variant_for_table_model(TableModel::SlanetAuto),
            Some("slanet_wired")
        );
        assert_eq!(slanet_variant_for_table_model(TableModel::Tatr), None);
        assert_eq!(slanet_variant_for_table_model(TableModel::Disabled), None);
    }

    /// Helper: a table at `bbox` on `page` whose only content is `markdown`
    /// (so content weight == markdown length; empty cells).
    fn ov_table(page: u32, bbox: (f64, f64, f64, f64), markdown: &str) -> crate::types::Table {
        let (x0, y0, x1, y1) = bbox;
        crate::types::Table {
            cells: Vec::new(),
            markdown: markdown.to_string(),
            page_number: page,
            bounding_box: Some(crate::types::BoundingBox { x0, y0, x1, y1 }),
            ..Default::default()
        }
    }

    /// Helper: a table fragment with real cell content (needed to satisfy
    /// `fragments_are_stitchable`'s column-count check) at `bbox` on `page`.
    fn cell_table(page: u32, bbox: (f64, f64, f64, f64), cells: &[&[&str]]) -> crate::types::Table {
        let (x0, y0, x1, y1) = bbox;
        let cells: Vec<Vec<String>> = cells
            .iter()
            .map(|row| row.iter().map(|s| s.to_string()).collect())
            .collect();
        let markdown = cells.iter().map(|row| row.join("|")).collect::<Vec<_>>().join("\n");
        crate::types::Table {
            cells,
            markdown,
            page_number: page,
            bounding_box: Some(crate::types::BoundingBox { x0, y0, x1, y1 }),
            ..Default::default()
        }
    }

    /// Run the same id/columns assignment the real pipeline performs: stitch
    /// same-page fragments, then run the final, post-dedup assignment pass in
    /// `prepare_emitted_tables` (see issue #1297 code review: assigning ids
    /// inside `stitch_fragmented_tables` alone misses layout-detected tables).
    fn stitch_and_emit(
        native_tables: Vec<crate::types::Table>,
        layout_tables: Vec<crate::types::Table>,
        all_page_segments: &[Vec<SegmentData>],
    ) -> Vec<crate::types::Table> {
        use crate::core::config::layout::TableOverlapPreference;
        let stitched = stitch_fragmented_tables(native_tables, all_page_segments);
        prepare_emitted_tables(&stitched, layout_tables, TableOverlapPreference::Content)
    }

    /// Issue #1297: fragments of one physical table (stitched into a single
    /// chain) collapse into one `tables[]` entry, which naturally carries one
    /// `table_id`. A separate, non-adjacent table gets a distinct id.
    #[test]
    fn stitched_fragments_share_one_table_id_distinct_tables_differ() {
        let frag_top = cell_table(1, (0.0, 90.0, 100.0, 110.0), &[&["H1", "H2"]]);
        let frag_bottom = cell_table(1, (0.0, 70.0, 100.0, 89.0), &[&["a", "b"]]);
        let other_page_table = cell_table(2, (0.0, 0.0, 100.0, 20.0), &[&["X", "Y"]]);

        let all_page_segments: Vec<Vec<SegmentData>> = Vec::new();
        let result = stitch_and_emit(
            vec![frag_top, frag_bottom, other_page_table],
            Vec::new(),
            &all_page_segments,
        );

        assert_eq!(result.len(), 2, "the two page-1 fragments must stitch into one table");

        let page_1_table = result
            .iter()
            .find(|t| t.page_number == 1)
            .expect("page 1 table present");
        let page_2_table = result
            .iter()
            .find(|t| t.page_number == 2)
            .expect("page 2 table present");

        assert_eq!(page_1_table.cells.len(), 2, "stitched chain has both fragments' rows");
        assert!(page_1_table.table_id.is_some(), "stitched table must have a table_id");
        assert!(page_2_table.table_id.is_some(), "unrelated table must have a table_id");
        assert_ne!(
            page_1_table.table_id, page_2_table.table_id,
            "distinct physical tables must have distinct ids"
        );
    }

    /// Issue #1297: `table_id` assignment must be deterministic across runs
    /// for the same input (no randomness, no wall-clock dependence).
    #[test]
    fn table_id_assignment_is_deterministic_across_runs() {
        let build_input = || {
            vec![
                cell_table(2, (0.0, 0.0, 100.0, 20.0), &[&["X", "Y"]]),
                cell_table(1, (0.0, 0.0, 100.0, 20.0), &[&["A", "B"]]),
            ]
        };
        let all_page_segments: Vec<Vec<SegmentData>> = Vec::new();

        let first_run = stitch_and_emit(build_input(), Vec::new(), &all_page_segments);
        let second_run = stitch_and_emit(build_input(), Vec::new(), &all_page_segments);

        let first_ids: Vec<_> = first_run.iter().map(|t| (t.page_number, t.table_id.clone())).collect();
        let second_ids: Vec<_> = second_run.iter().map(|t| (t.page_number, t.table_id.clone())).collect();
        assert_eq!(first_ids, second_ids, "table_id assignment must be deterministic");
    }

    /// Issue #1297: every emitted table fragment carries `columns` (its own
    /// header row), even a fragment that stitching left untouched.
    #[test]
    fn stitching_populates_columns_on_merged_and_standalone_fragments() {
        let frag_top = cell_table(1, (0.0, 90.0, 100.0, 110.0), &[&["H1", "H2"]]);
        let frag_bottom = cell_table(1, (0.0, 70.0, 100.0, 89.0), &[&["a", "b"]]);
        let standalone = cell_table(3, (0.0, 0.0, 100.0, 20.0), &[&["Name", "Age"], &["Alice", "30"]]);

        let all_page_segments: Vec<Vec<SegmentData>> = Vec::new();
        let result = stitch_and_emit(vec![frag_top, frag_bottom, standalone], Vec::new(), &all_page_segments);

        let stitched = result.iter().find(|t| t.page_number == 1).unwrap();
        assert_eq!(
            stitched.columns,
            Some(vec!["H1".to_string(), "H2".to_string()]),
            "stitched table's columns come from the topmost fragment's header row"
        );

        let standalone_result = result.iter().find(|t| t.page_number == 3).unwrap();
        assert_eq!(
            standalone_result.columns,
            Some(vec!["Name".to_string(), "Age".to_string()]),
            "a standalone fragment's columns come from its own first row"
        );
    }

    /// Issue #1297 code review (Finding 1): a layout-detected table (never
    /// passed through `stitch_fragmented_tables`, only appended in
    /// `prepare_emitted_tables`) must still receive a `table_id` and
    /// `columns` once it survives dedup into the final emitted set.
    #[test]
    fn layout_detected_table_surviving_dedup_gets_table_id_and_columns() {
        let native = cell_table(1, (0.0, 0.0, 100.0, 20.0), &[&["A", "B"]]);
        let layout_only = cell_table(2, (0.0, 0.0, 100.0, 20.0), &[&["Layout1", "Layout2"], &["x", "y"]]);

        let all_page_segments: Vec<Vec<SegmentData>> = Vec::new();
        let result = stitch_and_emit(vec![native], vec![layout_only], &all_page_segments);

        assert_eq!(
            result.len(),
            2,
            "both the native and layout-detected tables must be emitted"
        );
        let layout_result = result
            .iter()
            .find(|t| t.page_number == 2)
            .expect("layout-detected table survives into the emitted set");

        assert!(
            layout_result.table_id.is_some(),
            "a layout-detected table must receive a table_id, not just native tables"
        );
        assert_eq!(
            layout_result.columns,
            Some(vec!["Layout1".to_string(), "Layout2".to_string()]),
            "a layout-detected table must receive columns from its own header row"
        );
    }

    #[test]
    fn identical_markdown_tables_collapse_despite_missing_bbox() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![crate::types::Table {
            cells: vec![vec!["a".into(), "b".into()]],
            markdown: "| a | b |".to_string(),
            page_number: 1,
            bounding_box: None,
            ..Default::default()
        }];
        let layout = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "| a | b |")];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.len(),
            1,
            "byte-identical markdown on the same page collapses even when one table has no bbox"
        );
    }

    #[test]
    fn sparse_currency_affix_columns_merge_into_financial_values() {
        use crate::core::config::layout::TableOverlapPreference;

        let mut cells = vec![vec![
            "Security".into(),
            String::new(),
            "Par (000)".into(),
            String::new(),
            "Value".into(),
        ]];
        for index in 0..12 {
            cells.push(vec![
                format!("Bond {index}"),
                if index == 0 { "USD".into() } else { String::new() },
                format!("{},000", index + 1),
                if index == 0 { "$".into() } else { String::new() },
                format!("{},500", index + 1),
            ]);
        }
        let table = crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            page_number: 1,
            ..Default::default()
        };

        let emitted = prepare_emitted_tables(&[table], Vec::new(), TableOverlapPreference::Content);

        assert_eq!(emitted[0].cells[0], ["Security", "Par (000)", "Value"]);
        assert_eq!(emitted[0].cells[1], ["Bond 0", "USD 1,000", "$ 1,500"]);
        assert_eq!(
            emitted[0].columns,
            Some(vec!["Security".into(), "Par (000)".into(), "Value".into()])
        );
        assert!(emitted[0].markdown.starts_with("| Security | Par (000) | Value |"));
    }

    #[test]
    fn wrapped_financial_rows_fold_into_value_bearing_records() {
        let mut cells = vec![
            vec!["Security".into(), "Par (000)".into(), "Value".into()],
            vec!["Region (continued)".into(), String::new(), String::new()],
        ];
        for index in 0..8 {
            cells.push(vec![format!("Asset {index}, Series"), String::new(), String::new()]);
            cells.push(vec!["Class A, variable rate".into(), String::new(), String::new()]);
            cells.push(vec![
                "maturing in 2035".into(),
                format!("{},000", index + 1),
                format!("$ {},500", index + 1),
            ]);
        }
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_wrapped_financial_rows(&mut tables);

        assert_eq!(tables[0].cells.len(), 10);
        assert_eq!(
            tables[0].cells[1],
            ["Region (continued)", "", ""],
            "the first descriptor-only section label must remain its own row"
        );
        assert_eq!(
            tables[0].cells[2],
            [
                "Asset 0, Series Class A, variable rate maturing in 2035",
                "1,000",
                "$ 1,500"
            ]
        );
        assert!(
            tables[0]
                .markdown
                .contains("| Asset 7, Series Class A, variable rate maturing in 2035 | 8,000 | $ 8,500 |")
        );
    }

    #[test]
    fn wrapped_financial_rows_preserve_interior_section_boundaries() {
        let mut cells = vec![
            vec!["Security".into(), "Par".into(), "Value".into()],
            vec!["Region A (continued)".into(), String::new(), String::new()],
        ];
        for index in 0..4 {
            cells.push(vec![format!("Wrapped asset {index}"), String::new(), String::new()]);
            cells.push(vec!["final line".into(), String::new(), String::new()]);
            cells.push(vec![
                "matures 2035".into(),
                format!("{}", index + 1),
                format!("{}", index + 101),
            ]);
        }
        cells.push(vec![
            "Unanchored text before section".into(),
            String::new(),
            String::new(),
        ]);
        cells.push(vec!["Region B — 2.0%".into(), String::new(), String::new()]);
        for index in 4..8 {
            cells.push(vec![format!("Wrapped asset {index}"), String::new(), String::new()]);
            cells.push(vec!["final line".into(), String::new(), String::new()]);
            cells.push(vec![
                "matures 2035".into(),
                format!("{}", index + 1),
                format!("{}", index + 101),
            ]);
        }
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_wrapped_financial_rows(&mut tables);

        let section_index = tables[0]
            .cells
            .iter()
            .position(|row| row[0] == "Region B — 2.0%")
            .expect("interior section label");
        assert_eq!(
            tables[0].cells[section_index - 1],
            ["Unanchored text before section", "", ""],
            "pending descriptors must flush unchanged before a new section"
        );
        assert_eq!(tables[0].cells[section_index], ["Region B — 2.0%", "", ""]);
        assert_eq!(
            tables[0].cells[section_index + 1],
            ["Wrapped asset 4 final line matures 2035", "5", "105"],
            "folding may resume after the section boundary"
        );
    }

    #[test]
    fn financial_section_label_accepts_allocation_with_footnote() {
        let row = vec!["Regional allocation — 0.6%(b)".into(), String::new(), String::new()];

        assert!(is_financial_section_label(&row));
    }

    #[test]
    fn financial_section_label_rejects_coupon_description_after_percentage() {
        let row = vec!["ACME notes — 5.0% senior notes".into(), String::new(), String::new()];

        assert!(!is_financial_section_label(&row));
    }

    #[test]
    fn wrapped_financial_rows_fold_without_a_section_label() {
        let mut cells = vec![vec!["Security".into(), "Par".into(), "Value".into()]];
        for index in 0..8 {
            cells.push(vec![format!("Asset {index}, Series"), String::new(), String::new()]);
            cells.push(vec!["Class A, variable rate".into(), String::new(), String::new()]);
            cells.push(vec![
                "maturing in 2035".into(),
                format!("{},000", index + 1),
                format!("{},500", index + 1),
            ]);
        }
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_wrapped_financial_rows(&mut tables);

        assert_eq!(tables[0].cells.len(), 9);
        assert_eq!(
            tables[0].cells[1],
            [
                "Asset 0, Series Class A, variable rate maturing in 2035",
                "1,000",
                "1,500"
            ]
        );
    }

    #[test]
    fn wrapped_financial_row_folding_preserves_tokens_and_trailing_text() {
        let mut cells = vec![
            vec!["Security".into(), "Par".into(), "Value".into()],
            vec!["Region".into(), String::new(), String::new()],
        ];
        for index in 0..8 {
            cells.push(vec![format!("Wrapped asset {index}"), String::new(), String::new()]);
            cells.push(vec![
                "final line".into(),
                format!("{}", index + 1),
                format!("{}", index + 101),
            ]);
        }
        cells.push(vec!["Unanchored trailing note".into(), String::new(), String::new()]);
        let before_tokens = cells
            .iter()
            .flatten()
            .flat_map(|cell| cell.split_whitespace())
            .map(str::to_string)
            .collect::<Vec<_>>();
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_wrapped_financial_rows(&mut tables);

        let after_tokens = tables[0]
            .cells
            .iter()
            .flatten()
            .flat_map(|cell| cell.split_whitespace())
            .map(str::to_string)
            .collect::<Vec<_>>();
        assert_eq!(after_tokens, before_tokens);
        assert_eq!(
            tables[0].cells.last().expect("trailing row"),
            &["Unanchored trailing note", "", ""],
            "descriptor-only text without an immediately following value row must not fold"
        );
    }

    #[test]
    fn wrapped_financial_row_folding_requires_strict_financial_density() {
        let build_cells = |header: [&str; 3], continuation_rows: usize| {
            let mut cells = vec![
                header.map(str::to_string).to_vec(),
                vec!["Section".into(), String::new(), String::new()],
            ];
            for index in 0..8 {
                if index < continuation_rows {
                    cells.push(vec![format!("Wrapped {index}"), String::new(), String::new()]);
                }
                cells.push(vec![
                    format!("Asset {index}"),
                    format!("{}", index + 1),
                    format!("{}", index + 101),
                ]);
            }
            cells
        };
        let non_financial = build_cells(["Name", "Owner", "Status"], 8);
        let balanced = build_cells(["Security", "Par", "Value"], 7);
        let mut tables = vec![
            crate::types::Table {
                markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&non_financial),
                cells: non_financial.clone(),
                ..Default::default()
            },
            crate::types::Table {
                markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&balanced),
                cells: balanced.clone(),
                ..Default::default()
            },
        ];

        normalize_wrapped_financial_rows(&mut tables);

        assert_eq!(tables[0].cells, non_financial);
        assert_eq!(
            tables[1].cells, balanced,
            "descriptor-only rows must outnumber value-bearing rows after the section label"
        );
    }

    #[test]
    fn named_or_non_currency_columns_are_not_collapsed() {
        let build_table = |source_header: &str, source_value: &str| {
            let mut cells = vec![vec!["Security".into(), source_header.into(), "Value".into()]];
            for index in 0..12 {
                cells.push(vec![
                    format!("Asset {index}"),
                    if index == 0 { source_value.into() } else { String::new() },
                    format!("{index},000"),
                ]);
            }
            crate::types::Table {
                markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
                cells,
                ..Default::default()
            }
        };
        let mut tables = vec![build_table("Currency", "USD"), build_table("", "kg")];

        normalize_sparse_currency_affix_columns(&mut tables);

        assert_eq!(
            tables[0].cells[0].len(),
            3,
            "an explicitly named Currency column is semantic"
        );
        assert_eq!(
            tables[1].cells[0].len(),
            3,
            "an arbitrary sparse unit is not a currency marker"
        );
    }

    #[test]
    fn dense_currency_columns_are_not_collapsed() {
        let mut cells = vec![vec!["Security".into(), String::new(), "Value".into()]];
        for index in 0..10 {
            cells.push(vec![
                format!("Asset {index}"),
                if index < 2 { "USD".into() } else { String::new() },
                format!("{index},000"),
            ]);
        }
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_sparse_currency_affix_columns(&mut tables);

        assert_eq!(tables[0].cells[0].len(), 3);
    }

    #[test]
    fn currency_marker_without_target_value_is_preserved() {
        let mut cells = vec![vec!["Security".into(), String::new(), "Value".into()]];
        cells.push(vec!["Currency declaration".into(), "USD".into(), String::new()]);
        for index in 0..11 {
            cells.push(vec![format!("Asset {index}"), String::new(), format!("{index},000")]);
        }
        let mut tables = vec![crate::types::Table {
            markdown: crate::extractors::frontmatter_utils::cells_to_markdown(&cells),
            cells,
            ..Default::default()
        }];

        normalize_sparse_currency_affix_columns(&mut tables);

        assert_eq!(tables[0].cells[0].len(), 3);
        assert_eq!(tables[0].cells[1][1], "USD");
    }

    #[test]
    fn dedup_content_preference_keeps_larger_table() {
        use crate::core::config::layout::TableOverlapPreference;
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "a"),
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "bbbbbbbbbb"),
        ];
        deduplicate_overlapping_tables(&mut tables, 1, TableOverlapPreference::Content);
        assert_eq!(tables.len(), 1);
        assert_eq!(
            tables[0].markdown, "bbbbbbbbbb",
            "Content keeps the larger (layout) table"
        );
    }

    #[test]
    fn dedup_native_preference_keeps_native_even_when_smaller() {
        use crate::core::config::layout::TableOverlapPreference;
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "a"),
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "bbbbbbbbbb"),
        ];
        deduplicate_overlapping_tables(&mut tables, 1, TableOverlapPreference::Native);
        assert_eq!(tables.len(), 1);
        assert_eq!(
            tables[0].markdown, "a",
            "Native preference keeps native over a larger layout table"
        );
    }

    #[test]
    fn dedup_layout_preference_keeps_layout_even_when_smaller() {
        use crate::core::config::layout::TableOverlapPreference;
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "aaaaaaaaaa"),
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "b"),
        ];
        deduplicate_overlapping_tables(&mut tables, 1, TableOverlapPreference::Layout);
        assert_eq!(tables.len(), 1);
        assert_eq!(
            tables[0].markdown, "b",
            "Layout preference keeps layout over a larger native table"
        );
    }

    #[test]
    fn dedup_native_preference_falls_back_to_content_for_same_origin() {
        use crate::core::config::layout::TableOverlapPreference;
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "a"),
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "bbbbbbbbbb"),
        ];
        deduplicate_overlapping_tables(&mut tables, 2, TableOverlapPreference::Native);
        assert_eq!(tables.len(), 1);
        assert_eq!(
            tables[0].markdown, "bbbbbbbbbb",
            "same-origin overlap falls back to content"
        );
    }

    #[test]
    fn dedup_non_overlapping_tables_both_kept() {
        use crate::core::config::layout::TableOverlapPreference;
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "a"),
            ov_table(1, (200.0, 200.0, 300.0, 300.0), "b"),
        ];
        deduplicate_overlapping_tables(&mut tables, 1, TableOverlapPreference::Native);
        assert_eq!(tables.len(), 2, "non-overlapping tables are both kept");
    }

    #[test]
    fn side_by_side_layout_children_replace_content_heavy_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["left", "right"]
        );
    }

    #[test]
    fn side_by_side_layout_cohort_replaces_two_content_heavy_native_parents() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"native left".repeat(100)),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), &"native right".repeat(100)),
        ];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "layout left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "layout right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["layout left", "layout right"]
        );
    }

    #[test]
    fn native_preference_keeps_two_parents_over_side_by_side_layout_cohort() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "native left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "native right"),
        ];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"layout left".repeat(100)),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), &"layout right".repeat(100)),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Native);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["native left", "native right"]
        );
    }

    #[test]
    fn one_layout_child_does_not_replace_two_native_parents() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"native left".repeat(100)),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), &"native right".repeat(100)),
        ];
        let layout = vec![ov_table(1, (0.0, 0.0, 95.0, 100.0), "layout left")];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 2);
        assert!(emitted.iter().all(|table| table.markdown.starts_with("native")));
    }

    #[test]
    fn stacked_native_parents_do_not_form_side_by_side_replacement_cohort() {
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 200.0, 45.0), "native top"),
            ov_table(1, (0.0, 55.0, 200.0, 100.0), "native bottom"),
        ];
        tables.extend([
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "layout left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "layout right"),
        ]);

        assert!(side_by_side_layout_replacements(&tables, 2).is_empty());
    }

    #[test]
    fn weakly_overlapping_layout_children_do_not_replace_two_native_parents() {
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "native left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "native right"),
        ];
        tables.extend([
            ov_table(1, (-70.0, 0.0, 80.0, 100.0), "layout left"),
            ov_table(1, (120.0, 0.0, 270.0, 100.0), "layout right"),
        ]);

        assert!(side_by_side_layout_replacements(&tables, 2).is_empty());
    }

    #[test]
    fn layout_cohort_rejects_child_that_does_not_cover_corresponding_parent() {
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "native left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "native right"),
        ];
        tables.extend([
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "layout left"),
            ov_table(1, (105.0, 0.0, 175.0, 100.0), "layout right"),
        ]);

        assert!(side_by_side_layout_replacements(&tables, 2).is_empty());
    }

    #[test]
    fn layout_cohort_accepts_reciprocal_crop_within_tolerance() {
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "native left"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "native right"),
        ];
        tables.extend([
            ov_table(1, (0.0, 0.0, 79.6, 100.0), "layout left"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "layout right"),
        ]);

        assert_eq!(side_by_side_layout_replacements(&tables, 2), [(vec![0, 1], vec![2, 3])]);
    }

    #[test]
    fn layout_cohort_rejects_reciprocal_crop_below_tolerance() {
        let mut tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "native left"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "native right"),
        ];
        tables.extend([
            ov_table(1, (0.0, 0.0, 79.4, 100.0), "layout left"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "layout right"),
        ]);

        assert!(side_by_side_layout_replacements(&tables, 2).is_empty());
    }

    #[test]
    fn layout_cohort_rejects_child_owned_by_sibling_parent() {
        let tables = vec![
            ov_table(1, (0.0, 0.0, 100.0, 100.0), "native left"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "native right"),
            ov_table(1, (90.0, 0.0, 210.0, 100.0), "layout crossing"),
            ov_table(1, (110.0, 0.0, 210.0, 100.0), "layout right"),
        ];

        assert!(!replacement_children_correspond(&tables, &[0, 1], &[2, 3]));
    }

    #[test]
    fn three_native_candidates_select_one_disjoint_adjacent_cohort() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (105.0, 0.0, 200.0, 100.0), &"native middle".repeat(100)),
            ov_table(1, (210.0, 0.0, 305.0, 100.0), &"native right".repeat(100)),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"native left".repeat(100)),
        ];
        let layout = vec![
            ov_table(1, (210.0, 0.0, 305.0, 100.0), "layout right"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "layout left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "layout middle"),
        ];
        let mut candidates = native.clone();
        candidates.extend(layout.clone());

        let replacements = side_by_side_layout_replacements(&candidates, native.len());
        assert_eq!(replacements, [(vec![2, 0], vec![4, 5])]);

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);
        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["layout left", "layout middle", &"native right".repeat(100)]
        );
    }

    #[test]
    fn side_by_side_replacement_is_atomic_against_native_duplicate() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100)),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"native duplicate".repeat(100)),
        ];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["left", "right"]
        );
    }

    #[test]
    fn side_by_side_replacement_is_atomic_against_earlier_layout_duplicate() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let better_left = "layout duplicate with more content";
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), better_left),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            [better_left, "right"]
        );
    }

    #[test]
    fn side_by_side_replacement_is_atomic_against_later_layout_duplicate() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let better_left = "layout duplicate with more content";
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), better_left),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            [better_left, "right"]
        );
    }

    #[test]
    fn overlapping_protected_replacement_groups_survive() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 200.0, 100.0), "upper parent"),
            ov_table(1, (0.0, 40.0, 200.0, 140.0), "lower parent"),
        ];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "upper left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "upper right"),
            ov_table(1, (0.0, 40.0, 95.0, 140.0), "lower left"),
            ov_table(1, (105.0, 40.0, 200.0, 140.0), "lower right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["upper left", "upper right", "lower left", "lower right"]
        );
    }

    #[test]
    fn partially_shared_replacement_groups_keep_canonical_table_order() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 200.0, 100.0), "parent a"),
            ov_table(1, (105.0, 0.0, 305.0, 100.0), "parent b"),
        ];
        let layout = vec![
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "shared"),
            ov_table(1, (210.0, 0.0, 305.0, 100.0), "right"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["left", "shared", "right"]
        );
    }

    #[test]
    fn side_by_side_replacement_orders_complete_affected_row_cohort() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), "parent")];
        let layout = vec![
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
            ov_table(1, (300.0, 0.0, 350.0, 100.0), "unrelated"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["left", "right", "unrelated"]
        );
    }

    #[test]
    fn side_by_side_replacement_preserves_interleaved_different_row_slot() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), "parent")];
        let layout = vec![
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
            ov_table(1, (300.0, -100.0, 350.0, -10.0), "different row"),
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["left", "different row", "right"]
        );
    }

    #[test]
    fn one_layout_child_does_not_replace_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![ov_table(1, (0.0, 0.0, 95.0, 100.0), "left")];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 1);
        assert!(emitted[0].markdown.starts_with("parent"));
    }

    #[test]
    fn overlapping_layout_children_do_not_replace_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 120.0, 100.0), "left"),
            ov_table(1, (80.0, 0.0, 200.0, 100.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 1);
        assert!(emitted[0].markdown.starts_with("parent"));
    }

    #[test]
    fn stacked_layout_children_do_not_replace_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 200.0, 45.0), "top"),
            ov_table(1, (0.0, 55.0, 200.0, 100.0), "bottom"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 1);
        assert!(emitted[0].markdown.starts_with("parent"));
    }

    #[test]
    fn shallow_layout_children_do_not_replace_tall_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 20.0), "left"),
            ov_table(1, (105.0, 0.0, 200.0, 20.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 1);
        assert!(emitted[0].markdown.starts_with("parent"));
    }

    #[test]
    fn weakly_overlapping_layout_children_do_not_replace_parent() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100))];
        let layout = vec![
            ov_table(1, (-70.0, 0.0, 80.0, 100.0), "left"),
            ov_table(1, (120.0, 0.0, 270.0, 100.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(emitted.len(), 1);
        assert!(emitted[0].markdown.starts_with("parent"));
    }

    #[test]
    fn side_by_side_replacement_preserves_unrelated_table() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![
            ov_table(1, (0.0, 0.0, 200.0, 100.0), &"parent".repeat(100)),
            ov_table(2, (10.0, 10.0, 80.0, 80.0), "unrelated"),
        ];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), "left"),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), "right"),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Content);

        assert_eq!(
            emitted.iter().map(|table| table.markdown.as_str()).collect::<Vec<_>>(),
            ["unrelated", "left", "right"]
        );
    }

    #[test]
    fn native_preference_keeps_parent_over_side_by_side_children() {
        use crate::core::config::layout::TableOverlapPreference;
        let native = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), "parent")];
        let layout = vec![
            ov_table(1, (0.0, 0.0, 95.0, 100.0), &"left".repeat(100)),
            ov_table(1, (105.0, 0.0, 200.0, 100.0), &"right".repeat(100)),
        ];

        let emitted = prepare_emitted_tables(&native, layout, TableOverlapPreference::Native);

        assert_eq!(emitted.len(), 1);
        assert_eq!(emitted[0].markdown, "parent");
    }

    #[test]
    fn dropped_duplicate_table_does_not_suppress_text() {
        use crate::core::config::layout::TableOverlapPreference;

        let native_tables = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "native table content")];
        let layout_tables = vec![ov_table(1, (0.0, 0.0, 200.0, 100.0), "x")];
        let emitted_tables = prepare_emitted_tables(&native_tables, layout_tables, TableOverlapPreference::Content);
        let bboxes_by_page = table_bboxes_by_page(&emitted_tables);

        assert_eq!(emitted_tables.len(), 1);
        assert_eq!(emitted_tables[0].bounding_box.expect("kept table bbox").x1, 100.0);

        let segment = SegmentData {
            x: 150.0,
            y: 10.0,
            width: 20.0,
            height: 12.0,
            ..seg("text outside the emitted table", 150.0, 20.0)
        };
        let filtered = filter_segments_by_table_bboxes(
            vec![segment],
            bboxes_by_page.get(&0).map(Vec::as_slice).unwrap_or_default(),
        );
        assert_eq!(filtered.len(), 1, "a discarded duplicate bbox must not remove text");
    }

    #[test]
    fn empty_table_does_not_suppress_text() {
        use crate::core::config::layout::TableOverlapPreference;

        let native_tables = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "  \n")];
        let emitted_tables = prepare_emitted_tables(&native_tables, Vec::new(), TableOverlapPreference::Content);
        let bboxes_by_page = table_bboxes_by_page(&emitted_tables);

        assert!(
            emitted_tables.is_empty(),
            "assembly would not emit whitespace-only markdown"
        );
        assert!(
            bboxes_by_page.is_empty(),
            "non-emitted tables must not contribute suppression boxes"
        );

        let segment = SegmentData {
            x: 10.0,
            y: 10.0,
            width: 20.0,
            height: 12.0,
            ..seg("text under an empty table", 10.0, 20.0)
        };
        let filtered = filter_segments_by_table_bboxes(
            vec![segment],
            bboxes_by_page.get(&0).map(Vec::as_slice).unwrap_or_default(),
        );
        assert_eq!(filtered.len(), 1);
    }

    #[test]
    fn empty_table_does_not_displace_valid_overlap() {
        use crate::core::config::layout::TableOverlapPreference;

        let native_tables = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "  \n")];
        let layout_tables = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "| valid |")];

        let emitted_tables = prepare_emitted_tables(&native_tables, layout_tables, TableOverlapPreference::Native);

        assert_eq!(emitted_tables.len(), 1);
        assert_eq!(emitted_tables[0].markdown, "| valid |");
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn missing_wrapper_validation_is_treated_as_skipped() {
        use super::super::regions::layout_validation::RegionValidation;

        let hint = |class_name| LayoutHint {
            class_name,
            confidence: 0.9,
            left: 0.0,
            bottom: 0.0,
            right: 100.0,
            top: 100.0,
        };
        let hints = vec![
            hint(LayoutHintClass::Picture),
            hint(LayoutHintClass::Form),
            hint(LayoutHintClass::Text),
        ];
        let ownership = wrapper_ownership_by_hint(&hints, &[RegionValidation::Empty]);
        assert_eq!(ownership, [false, true, true]);
    }

    #[test]
    fn emitted_table_still_suppresses_covered_text() {
        use crate::core::config::layout::TableOverlapPreference;

        let native_tables = vec![ov_table(1, (0.0, 0.0, 100.0, 100.0), "| value |")];
        let emitted_tables = prepare_emitted_tables(&native_tables, Vec::new(), TableOverlapPreference::Content);
        let bboxes_by_page = table_bboxes_by_page(&emitted_tables);
        let segment = SegmentData {
            x: 10.0,
            y: 10.0,
            width: 20.0,
            height: 12.0,
            ..seg("duplicated table text", 10.0, 20.0)
        };

        let filtered = filter_segments_by_table_bboxes(
            vec![segment],
            bboxes_by_page.get(&0).map(Vec::as_slice).unwrap_or_default(),
        );
        assert!(
            filtered.is_empty(),
            "an emitted table must continue to suppress duplicate text"
        );
    }

    /// Helper: segment with font metadata for title-promotion tests.
    fn role_seg(text: &str, font_size: f32, is_bold: bool, assigned_role: Option<u8>) -> SegmentData {
        SegmentData {
            text: text.to_string(),
            x: 72.0,
            y: 700.0,
            width: 200.0,
            height: font_size,
            font_size,
            is_bold,
            is_italic: false,
            is_monospace: false,
            baseline_y: 700.0,
            assigned_role,
        }
    }

    /// A bold, first-page, larger-than-any-tagged-heading tier must be promoted
    /// to h1 with the tagged hierarchy shifted down one level.
    #[test]
    fn promote_title_shifts_tagged_heading_levels_down() {
        let pages = vec![vec![
            role_seg("Titre du document", 28.0, true, None),
            role_seg("Titre 1", 18.0, true, Some(1)),
            role_seg("Titre 2", 16.0, true, Some(2)),
            role_seg("body text", 12.0, false, None),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(promote_untagged_document_title(&mut map, &pages));

        let level_of = |font: f32| map.iter().find(|(f, _)| (*f - font).abs() < 0.05).and_then(|(_, l)| *l);
        assert_eq!(level_of(28.0), Some(1), "title tier must become h1");
        assert_eq!(level_of(18.0), Some(2), "tagged H1 must demote to h2");
        assert_eq!(level_of(16.0), Some(3), "tagged H2 must demote to h3");
        assert_eq!(level_of(12.0), None, "body must stay body");
    }

    /// No untagged tier above the largest tagged heading → no promotion.
    #[test]
    fn promote_title_no_candidate_leaves_map_unchanged() {
        let pages = vec![vec![
            role_seg("Heading", 18.0, true, Some(1)),
            role_seg("body", 12.0, false, None),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        let before = map.clone();
        assert!(!promote_untagged_document_title(&mut map, &pages));
        assert_eq!(map, before);
    }

    /// A non-bold large tier (e.g. a pull quote) must not be mistaken for a title.
    #[test]
    fn promote_title_requires_bold() {
        let pages = vec![vec![
            role_seg("large quote", 28.0, false, None),
            role_seg("Heading", 18.0, true, Some(1)),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(!promote_untagged_document_title(&mut map, &pages));
    }

    /// A large tier appearing only after page 0 is not a document title.
    #[test]
    fn promote_title_requires_first_page() {
        let pages = vec![
            vec![role_seg("Heading", 18.0, true, Some(1))],
            vec![role_seg("Big banner later", 28.0, true, None)],
        ];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(!promote_untagged_document_title(&mut map, &pages));
    }

    /// A mid-word split (e.g. "Text" extracted as "Te" + "xt", same role and
    /// font size, immediately adjacent) must count as one logical block, not
    /// two — otherwise a font-encoding artifact inflates the apparent
    /// document size past the sparsity floor.
    #[test]
    fn count_logical_blocks_merges_same_role_same_size_runs() {
        let pages = vec![vec![
            role_seg("Big", 24.0, false, Some(1)),
            role_seg("Small Text", 12.0, true, Some(2)),
            role_seg("Te", 24.0, false, Some(1)),
            role_seg("xt", 24.0, false, Some(1)),
        ]];
        assert_eq!(
            count_logical_blocks(&pages),
            3,
            "the split \"Te\"+\"xt\" run must collapse into a single block"
        );
    }

    /// Segments with different assigned roles never merge, even at the same
    /// font size.
    #[test]
    fn count_logical_blocks_does_not_merge_different_roles() {
        let pages = vec![vec![
            role_seg("Heading", 18.0, true, Some(1)),
            role_seg("more heading text", 18.0, true, Some(2)),
        ]];
        assert_eq!(count_logical_blocks(&pages), 2);
    }

    /// Sparse document where the structure tree tags every block as a heading
    /// with no body tier at all (a document with just a couple of heading-tagged
    /// lines and nothing else) must have every role suppressed rather than trusted.
    #[test]
    fn suppress_all_heading_roles_fires_when_sparse_and_all_tagged() {
        let mut pages = vec![vec![
            role_seg("Big", 24.0, false, Some(1)),
            role_seg("Small Text", 12.0, true, Some(2)),
            role_seg("Te xt", 24.0, false, Some(1)),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(suppress_all_heading_roles_when_sparse_and_untrusted(
            &mut map, &mut pages
        ));

        assert!(
            map.iter().all(|(_, level)| level.is_none()),
            "heading map must be fully suppressed; got: {map:?}"
        );
        for page in &pages {
            for seg in page {
                assert_eq!(
                    seg.assigned_role, None,
                    "assigned_role must be cleared on every segment"
                );
            }
        }
    }

    /// A sparse document with one tagged heading and one untagged body
    /// paragraph (the `issue-987-test.pdf` shape: "Big"/"Te xt" tagged,
    /// "Small Text" untagged — 3 total blocks) must ALSO be suppressed: a mix
    /// of heading and body tiers on that few blocks is not enough evidence
    /// that the tagging is trustworthy, matching GT for that fixture (plain
    /// "Big Text"/"Small Text", no headings at all).
    #[test]
    fn suppress_all_heading_roles_fires_when_sparse_with_body_tier() {
        let mut pages = vec![vec![
            role_seg("Title", 24.0, true, Some(1)),
            role_seg("body text", 12.0, false, None),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(suppress_all_heading_roles_when_sparse_and_untrusted(
            &mut map, &mut pages
        ));
        assert_eq!(pages[0][0].assigned_role, None, "tagged role must be cleared");
    }

    /// A sparse document with no heading roles at all must not be touched —
    /// there is nothing to suppress.
    #[test]
    fn suppress_all_heading_roles_does_not_fire_with_no_headings() {
        let mut pages = vec![vec![
            role_seg("body text one", 12.0, false, None),
            role_seg("body text two", 12.0, false, None),
        ]];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(!suppress_all_heading_roles_when_sparse_and_untrusted(
            &mut map, &mut pages
        ));
    }

    /// At or above the sparsity floor, an all-heading-tagged document is left
    /// alone even with no body tier — larger documents are trusted.
    #[test]
    fn suppress_all_heading_roles_does_not_fire_at_or_above_floor() {
        // Alternate heading/body role so each segment is a distinct logical
        // block under `count_logical_blocks` rather than collapsing into one. ~keep
        let mut pages = vec![
            (0..MIN_BLOCKS_FOR_FONT_HEADING)
                .map(|i| {
                    if i % 2 == 0 {
                        role_seg(&format!("Heading {i}"), 18.0, true, Some(1))
                    } else {
                        role_seg(&format!("Body paragraph {i}."), 12.0, false, None)
                    }
                })
                .collect(),
        ];
        let mut map = build_heading_map_from_assigned_roles(&pages);
        assert!(!suppress_all_heading_roles_when_sparse_and_untrusted(
            &mut map, &mut pages
        ));
        assert_eq!(
            pages[0][0].assigned_role,
            Some(1),
            "role must be untouched at/above the floor"
        );
    }

    /// Role demotion mirrors the map shift on segments (bridge.rs reads roles directly).
    #[test]
    fn demote_assigned_roles_shifts_and_caps() {
        let mut pages = vec![vec![
            role_seg("h1", 18.0, true, Some(1)),
            role_seg("h6", 8.0, true, Some(6)),
            role_seg("body", 12.0, false, None),
        ]];
        demote_assigned_roles(&mut pages);
        assert_eq!(pages[0][0].assigned_role, Some(2));
        assert_eq!(pages[0][1].assigned_role, Some(6), "level 6 must cap, not overflow");
        assert_eq!(pages[0][2].assigned_role, None);
    }

    #[test]
    fn assigned_sal_annotation_role_is_demoted() {
        let paragraphs = process_heuristic_segments(vec![role_seg("__inout_bcount_full(n)", 12.0, false, Some(2))]);
        assert_eq!(paragraphs[0].heading_level, None);
    }

    #[test]
    fn assigned_identifier_heading_role_is_preserved() {
        let paragraphs = blocks_to_paragraphs(
            vec![role_seg("__in_section", 12.0, false, Some(2))],
            &[(12.0, None)],
            &[],
        );
        assert_eq!(paragraphs[0].heading_level, Some(2));
    }

    /// Helper: create a segment with positional data.
    fn seg(text: &str, x: f32, width: f32) -> SegmentData {
        SegmentData {
            text: text.to_string(),
            x,
            y: 0.0,
            width,
            height: 12.0,
            font_size: 12.0,
            is_bold: false,
            is_italic: false,
            is_monospace: false,
            baseline_y: 0.0,
            assigned_role: None,
        }
    }

    fn inline_seg(text: &str, x: f32, baseline_y: f32, is_bold: bool) -> SegmentData {
        let mut segment = seg(text, x, 20.0);
        segment.baseline_y = baseline_y;
        segment.y = baseline_y - segment.height;
        segment.is_bold = is_bold;
        segment
    }

    #[test]
    fn inline_bold_runs_stay_in_one_paragraph() {
        let segments = vec![
            inline_seg("plain", 10.0, 100.0, false),
            inline_seg("bold", 31.0, 100.0, true),
            inline_seg("tail", 52.0, 100.0, false),
        ];

        let paragraphs = blocks_to_paragraphs(segments, &[], &[]);

        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraphs[0].lines.len(), 1);
        assert_eq!(paragraphs[0].lines[0].segments.len(), 3);
        assert!(paragraphs[0].lines[0].segments[1].is_bold);
        assert_eq!(paragraph_text(&paragraphs[0]), "plain bold tail");

        let document = crate::pdf::structure::assembly::assemble_internal_document(vec![paragraphs], &[], None, &[]);
        let element = &document.elements[0];
        let bold = element
            .annotations
            .iter()
            .find(|annotation| matches!(annotation.kind, crate::types::AnnotationKind::Bold))
            .expect("inline bold annotation should be preserved");
        assert_eq!(element.text, "plain bold tail");
        assert_eq!((bold.start, bold.end), (6, 10));
    }

    #[test]
    fn inline_typographic_dash_does_not_split_a_paragraph() {
        let segments = vec![
            inline_seg("Figures 6", 10.0, 100.0, false),
            inline_seg("– 8 show the results", 31.0, 100.0, false),
        ];

        let paragraphs = blocks_to_paragraphs(segments, &[], &[]);

        assert_eq!(paragraphs.len(), 1);
        assert!(!paragraphs[0].is_list_item);
    }

    #[test]
    fn typographic_dash_on_a_new_line_still_starts_a_list() {
        let segments = vec![
            inline_seg("Introduction", 10.0, 100.0, false),
            inline_seg("– first item", 10.0, 80.0, false),
        ];

        let paragraphs = blocks_to_paragraphs(segments, &[], &[]);

        assert_eq!(paragraphs.len(), 2);
        assert!(paragraphs[1].is_list_item);
    }

    #[test]
    fn split_typographic_dash_and_same_line_body_stay_a_list() {
        let segments = vec![
            inline_seg("Introduction", 10.0, 100.0, false),
            inline_seg("", 10.0, 80.0, false),
            inline_seg("quoted body", 31.0, 80.0, false),
        ];

        let paragraphs = blocks_to_paragraphs(segments, &[], &[]);

        assert_eq!(paragraphs.len(), 2);
        assert!(paragraphs[1].is_list_item);
    }

    #[test]
    fn split_typographic_dash_and_different_line_body_are_not_a_list() {
        let segments = vec![
            inline_seg("Figures 6", 10.0, 100.0, false),
            inline_seg("", 31.0, 100.0, false),
            inline_seg("8 show the results", 10.0, 80.0, false),
        ];

        let paragraphs = blocks_to_paragraphs(segments, &[], &[]);

        assert!(paragraphs.iter().all(|paragraph| !paragraph.is_list_item));
    }

    #[test]
    fn cross_line_bold_transition_remains_a_boundary() {
        let segments = vec![
            inline_seg("Heading", 10.0, 100.0, true),
            inline_seg("body", 10.0, 80.0, false),
        ];

        assert_eq!(blocks_to_paragraphs(segments, &[], &[]).len(), 2);
    }

    #[test]
    fn tagged_heading_and_body_stay_separate_on_the_same_line() {
        let mut heading = inline_seg("Heading", 10.0, 100.0, true);
        heading.assigned_role = Some(1);
        let body = inline_seg("body", 31.0, 100.0, false);

        let paragraphs = blocks_to_paragraphs(vec![heading, body], &[], &[]);

        assert_eq!(paragraphs.len(), 2);
        assert_eq!(paragraph_text(&paragraphs[0]), "Heading");
        assert_eq!(paragraphs[0].heading_level, Some(1));
        assert_eq!(paragraph_text(&paragraphs[1]), "body");
        assert_eq!(paragraphs[1].heading_level, None);
    }

    #[test]
    fn different_tagged_heading_levels_stay_separate_on_the_same_line() {
        let mut first = inline_seg("First", 10.0, 100.0, true);
        first.assigned_role = Some(1);
        let mut second = inline_seg("Second", 31.0, 100.0, false);
        second.assigned_role = Some(2);

        let paragraphs = blocks_to_paragraphs(vec![first, second], &[], &[]);

        assert_eq!(paragraphs.len(), 2);
        assert_eq!(paragraph_text(&paragraphs[0]), "First");
        assert_eq!(paragraphs[0].heading_level, Some(1));
        assert_eq!(paragraph_text(&paragraphs[1]), "Second");
        assert_eq!(paragraphs[1].heading_level, Some(2));
    }

    #[test]
    fn same_tagged_heading_role_keeps_inline_style_transitions_together() {
        let mut first = inline_seg("First", 10.0, 100.0, true);
        first.assigned_role = Some(1);
        let mut second = inline_seg("Second", 31.0, 100.0, false);
        second.assigned_role = Some(1);

        let paragraphs = blocks_to_paragraphs(vec![first, second], &[], &[]);

        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraph_text(&paragraphs[0]), "First Second");
        assert_eq!(paragraphs[0].heading_level, Some(1));
    }

    #[test]
    fn distant_same_line_bold_transition_remains_a_boundary() {
        let segments = vec![
            inline_seg("left", 10.0, 100.0, false),
            inline_seg("right", 100.0, 100.0, true),
        ];

        assert_eq!(blocks_to_paragraphs(segments, &[], &[]).len(), 2);
    }

    #[test]
    fn overlapping_or_reverse_bold_transition_remains_a_boundary() {
        let overlapping = vec![
            inline_seg("first", 30.0, 100.0, false),
            inline_seg("second", 40.0, 100.0, true),
        ];
        let reversed = vec![
            inline_seg("first", 30.0, 100.0, false),
            inline_seg("second", 5.0, 100.0, true),
        ];

        assert_eq!(blocks_to_paragraphs(overlapping, &[], &[]).len(), 2);
        assert_eq!(blocks_to_paragraphs(reversed, &[], &[]).len(), 2);
    }

    #[test]
    fn slight_metric_overlap_is_still_inline() {
        let segments = vec![
            inline_seg("plain", 30.0, 100.0, false),
            inline_seg("bold", 49.0, 100.0, true),
        ];

        assert_eq!(blocks_to_paragraphs(segments, &[], &[]).len(), 1);
    }

    #[test]
    fn invalid_inline_geometry_remains_a_boundary() {
        let plain = inline_seg("plain", 10.0, 100.0, false);
        let mut zero_font = inline_seg("bold", 31.0, 100.0, true);
        zero_font.font_size = 0.0;
        let mut non_finite_x = inline_seg("bold", 31.0, 100.0, true);
        non_finite_x.x = f32::NAN;
        let mut non_finite_baseline = inline_seg("bold", 31.0, 100.0, true);
        non_finite_baseline.baseline_y = f32::NAN;

        assert_eq!(blocks_to_paragraphs(vec![plain.clone(), zero_font], &[], &[]).len(), 2);
        assert_eq!(
            blocks_to_paragraphs(vec![plain.clone(), non_finite_x], &[], &[]).len(),
            2
        );
        assert_eq!(
            blocks_to_paragraphs(vec![plain, non_finite_baseline], &[], &[]).len(),
            2
        );
    }

    #[test]
    fn later_line_inline_style_transition_does_not_absorb_prior_lines() {
        let segments = vec![
            inline_seg("first line", 10.0, 120.0, false),
            inline_seg("plain", 10.0, 100.0, false),
            inline_seg("bold", 31.0, 100.0, true),
        ];

        assert_eq!(blocks_to_paragraphs(segments, &[], &[]).len(), 2);
    }

    #[test]
    fn monospace_style_transition_remains_a_boundary() {
        let mut plain = inline_seg("let value =", 10.0, 100.0, false);
        plain.is_monospace = true;
        let mut bold = inline_seg("42", 31.0, 100.0, true);
        bold.is_monospace = true;

        assert_eq!(blocks_to_paragraphs(vec![plain, bold], &[], &[]).len(), 2);
    }

    fn line(segments: Vec<SegmentData>) -> PdfLine {
        PdfLine {
            segments,
            baseline_y: 0.0,
            dominant_font_size: 12.0,
            is_bold: false,
            is_monospace: false,
        }
    }

    fn para(lines: Vec<PdfLine>) -> PdfParagraph {
        let word_count = PdfParagraph::compute_word_count("", &lines);
        PdfParagraph {
            text: String::new(),
            lines,
            dominant_font_size: 12.0,
            heading_level: None,
            is_bold: false,
            is_list_item: false,
            is_code_block: false,
            is_formula: false,
            is_page_furniture: false,
            layout_class: None,
            layout_region_path: None,
            caption_for: None,
            block_bbox: None,
            word_count,
        }
    }

    fn outline_para(text: &str) -> PdfParagraph {
        let mut paragraph = para(vec![line(vec![seg(text, 0.0, 100.0)])]);
        paragraph.text = text.to_string();
        paragraph.word_count = text.split_whitespace().count();
        paragraph
    }

    fn outline_heading(text: &str, level: u8) -> PdfParagraph {
        let mut paragraph = outline_para(text);
        paragraph.heading_level = Some(level);
        paragraph
    }

    fn table_with_body_rows(body_rows: usize, cell: &str) -> crate::types::Table {
        let mut cells = vec![vec!["Column".to_string()]];
        cells.extend((0..body_rows).map(|_| vec![cell.to_string()]));
        crate::types::Table {
            cells,
            page_number: 1,
            bounding_box: Some(crate::types::BoundingBox {
                x0: 0.0,
                y0: 100.0,
                x1: 500.0,
                y1: 700.0,
            }),
            ..Default::default()
        }
    }

    #[test]
    fn table_dominant_page_removes_spill_but_preserves_annotations() {
        let mut heading = outline_heading("Decorative title", 1);
        heading.block_bbox = Some((10.0, 650.0, 200.0, 680.0));
        let mut spill =
            outline_para("AB Carval Euro CLO Series Class D three month EURIBOR at 3.75 percent 02/15/37 2,350");
        spill.block_bbox = Some((10.0, 350.0, 490.0, 390.0));
        let mut short_prose = outline_para("Rates shown are unaudited.");
        short_prose.block_bbox = Some((10.0, 300.0, 250.0, 320.0));
        let expected_side_prose = "This explanatory sidebar remains because it sits entirely beside the detected table despite sharing its vertical band.";
        let mut side_prose = outline_para(expected_side_prose);
        side_prose.block_bbox = Some((520.0, 300.0, 700.0, 340.0));
        let mut note = outline_para("Note: values are unaudited");
        note.block_bbox = Some((10.0, 250.0, 250.0, 270.0));
        let mut caption = outline_para("Source: annual filing");
        caption.layout_class = Some(LayoutHintClass::Caption);
        caption.block_bbox = Some((10.0, 200.0, 250.0, 220.0));
        let mut pages = vec![vec![heading, spill, short_prose, side_prose, note, caption]];
        let tables = vec![table_with_body_rows(
            TABLE_DOMINANT_MIN_BODY_ROWS,
            "long-table-value-1234567890-long-table-value-1234567890-long-table-value-1234567890",
        )];

        suppress_table_dominant_paragraph_spill(&mut pages, &tables);

        assert_eq!(pages[0].len(), 5);
        assert_eq!(paragraph_text_raw(&pages[0][0]), "Decorative title");
        assert_eq!(paragraph_text_raw(&pages[0][1]), "Rates shown are unaudited.");
        assert_eq!(paragraph_text_raw(&pages[0][2]), expected_side_prose);
        assert_eq!(paragraph_text_raw(&pages[0][3]), "Note: values are unaudited");
        assert_eq!(paragraph_text_raw(&pages[0][4]), "Source: annual filing");
    }

    #[test]
    fn table_dominant_cleanup_preserves_mixed_prose_pages() {
        let prose =
            "This explanatory paragraph is intentionally much longer than the compact table values. ".repeat(12);
        let mut pages = vec![vec![outline_para(&prose)]];
        let tables = vec![table_with_body_rows(TABLE_DOMINANT_MIN_BODY_ROWS, "1")];

        suppress_table_dominant_paragraph_spill(&mut pages, &tables);

        assert_eq!(pages[0].len(), 1);
        assert_eq!(paragraph_text_raw(&pages[0][0]), prose);
    }

    #[test]
    fn table_dominant_cleanup_requires_minimum_body_rows() {
        let mut pages = vec![vec![outline_heading("Keep this title", 1)]];
        let tables = vec![table_with_body_rows(
            TABLE_DOMINANT_MIN_BODY_ROWS - 1,
            "long-table-value-1234567890",
        )];

        suppress_table_dominant_paragraph_spill(&mut pages, &tables);

        assert_eq!(pages[0].len(), 1);
        assert_eq!(paragraph_text_raw(&pages[0][0]), "Keep this title");
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn deferred_layout_caption_survives_table_dominant_cleanup() {
        let caption_text = "2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036";
        let mut caption = outline_para(caption_text);
        caption.block_bbox = Some((10.0, 350.0, 490.0, 390.0));
        let mut pages = vec![vec![caption]];
        let hints = vec![LayoutHint {
            class_name: LayoutHintClass::Caption,
            confidence: 0.99,
            left: 0.0,
            bottom: 340.0,
            right: 500.0,
            top: 400.0,
        }];
        let tables = vec![table_with_body_rows(
            TABLE_DOMINANT_MIN_BODY_ROWS,
            "long-table-value-1234567890-long-table-value-1234567890-long-table-value-1234567890",
        )];

        crate::pdf::structure::layout_classify::annotate_layout_classes(&mut pages[0], &hints, 0.5, 0.2);
        suppress_table_dominant_paragraph_spill(&mut pages, &tables);

        assert_eq!(pages[0].len(), 1);
        assert_eq!(paragraph_text_raw(&pages[0][0]), caption_text);
        assert_eq!(pages[0][0].layout_class, Some(LayoutHintClass::Caption));
    }

    #[test]
    fn final_heading_compaction_changes_rendered_markdown_levels() {
        let mut pages = vec![vec![
            outline_heading("Title", 1),
            outline_heading("Section", 3),
            outline_heading("Subsection", 4),
            outline_para("Body text"),
        ]];

        compact_final_heading_hierarchy(&mut pages);
        let document = crate::pdf::structure::assembly::assemble_internal_document(pages, &[], None, &[]);
        let markdown = crate::rendering::render_markdown(&document);
        let headings = markdown
            .lines()
            .filter(|line| line.starts_with('#'))
            .collect::<Vec<_>>();

        assert_eq!(headings, ["# Title", "## Section", "### Subsection"]);
        assert!(markdown.find("# Title").unwrap() < markdown.find("Body text").unwrap());
    }

    #[test]
    fn final_heading_compaction_is_conservatively_gated() {
        let cases = [
            vec![Some(1), Some(1), Some(3)],
            vec![Some(1), Some(2), Some(3), Some(5)],
            vec![Some(1), None],
            vec![Some(3), None],
        ];

        for expected in cases {
            let mut pages = vec![
                expected
                    .iter()
                    .enumerate()
                    .map(|(index, level)| {
                        let mut paragraph = outline_para(&format!("Block {index}"));
                        paragraph.heading_level = *level;
                        paragraph
                    })
                    .collect::<Vec<_>>(),
            ];

            compact_final_heading_hierarchy(&mut pages);

            let actual = pages[0]
                .iter()
                .map(|paragraph| paragraph.heading_level)
                .collect::<Vec<_>>();
            assert_eq!(actual, expected);
        }
    }

    /// Regression test for xberg-io/xberg#1301 (mode a): a colon-introduced,
    /// semicolon-delimited run-in list with no distinguishing indentation or
    /// line break — exactly how it is rendered from unstyled HTML — is split
    /// into a lead paragraph plus one list item per clause.
    #[test]
    fn run_in_colon_semicolon_list_is_split_into_lead_and_items() {
        let text = "Article 1. The management board is authorised to exclude subscription rights: \
to exclude fractional amounts from the shareholders' subscription right; \
where the new shares are issued against cash contributions at market price;";
        let mut pages = vec![vec![outline_para(text)]];

        split_colon_semicolon_run_in_lists(&mut pages);

        assert_eq!(pages[0].len(), 3, "lead paragraph + 2 list items");
        assert!(!pages[0][0].is_list_item);
        assert!(
            pages[0][0].text.ends_with("authorised to exclude subscription rights:"),
            "lead keeps everything up to and including the anchor colon: {}",
            pages[0][0].text
        );
        assert!(pages[0][1].is_list_item);
        assert_eq!(
            pages[0][1].text,
            "to exclude fractional amounts from the shareholders' subscription right;"
        );
        assert!(pages[0][2].is_list_item);
        assert_eq!(
            pages[0][2].text,
            "where the new shares are issued against cash contributions at market price;"
        );
    }

    #[test]
    fn run_in_list_split_requires_at_least_two_clauses() {
        let mut pages = vec![vec![outline_para("Note: see the appendix for full details.")]];

        split_colon_semicolon_run_in_lists(&mut pages);

        assert_eq!(
            pages[0].len(),
            1,
            "a single clause after the colon is not an enumeration"
        );
        assert!(!pages[0][0].is_list_item);
    }

    #[test]
    fn run_in_list_split_leaves_unrelated_paragraphs_untouched_and_in_order() {
        let list_text = "The board is authorised to exclude rights: to exclude fractional amounts; \
where new shares are issued;";
        let decoy = "- a bare dash-prefixed clause outside a list, unit #06-18 Tower 2, Singapore.";
        let mut pages = vec![vec![outline_para(list_text), outline_para(decoy)]];

        split_colon_semicolon_run_in_lists(&mut pages);

        assert_eq!(pages[0].len(), 4, "lead + 2 items + the untouched trailing paragraph");
        assert_eq!(
            pages[0][3].text, decoy,
            "trailing paragraph keeps its text and reading-order position"
        );
    }

    #[test]
    fn outline_recovery_is_page_scoped_and_uses_root_h2() {
        let mut intro = outline_para("1. Introduction");
        intro.is_list_item = true;
        intro.is_page_furniture = true;
        let mut pages = vec![vec![intro, outline_para("Methods")], vec![outline_para("Introduction")]];
        let entries = vec![
            PdfOutlineEntry::test_entry("Introduction", 0, 1),
            PdfOutlineEntry::test_entry("Methods", 1, 1),
        ];

        recover_headings_from_outline(&mut pages, &entries);

        assert_eq!(pages[0][0].heading_level, Some(2));
        assert_eq!(pages[0][1].heading_level, Some(3));
        assert_eq!(pages[1][0].heading_level, None);
        assert!(!pages[0][0].is_list_item);
        assert!(!pages[0][0].is_page_furniture);
    }

    #[test]
    fn outline_recovery_calibrates_from_two_consistent_anchors() {
        let mut first = outline_para("First anchor");
        first.heading_level = Some(1);
        let mut second = outline_para("Second anchor");
        second.heading_level = Some(2);
        let mut pages = vec![vec![first, second, outline_para("Recovered")]];
        let entries = vec![
            PdfOutlineEntry::test_entry("First anchor", 0, 1),
            PdfOutlineEntry::test_entry("Second anchor", 1, 1),
            PdfOutlineEntry::test_entry("Recovered", 2, 1),
        ];

        recover_headings_from_outline(&mut pages, &entries);

        assert_eq!(pages[0][2].heading_level, Some(3));
    }

    #[test]
    fn outline_recovery_ignores_singleton_bad_calibration_anchor() {
        let mut anchor = outline_para("Bad anchor");
        anchor.heading_level = Some(5);
        let mut pages = vec![vec![anchor, outline_para("Recovered")]];
        let entries = vec![
            PdfOutlineEntry::test_entry("Bad anchor", 0, 1),
            PdfOutlineEntry::test_entry("Recovered", 1, 1),
        ];

        recover_headings_from_outline(&mut pages, &entries);

        assert_eq!(pages[0][1].heading_level, Some(3));
    }

    #[test]
    fn outline_recovery_rejects_ambiguous_titles() {
        let mut pages = vec![vec![
            outline_para("Duplicate outline"),
            outline_para("Duplicate paragraph"),
            outline_para("Duplicate paragraph"),
        ]];
        let entries = vec![
            PdfOutlineEntry::test_entry("Duplicate outline", 0, 1),
            PdfOutlineEntry::test_entry("Duplicate outline", 1, 1),
            PdfOutlineEntry::test_entry("Duplicate paragraph", 0, 1),
        ];

        recover_headings_from_outline(&mut pages, &entries);

        assert!(pages[0].iter().all(|paragraph| paragraph.heading_level.is_none()));
    }

    #[test]
    fn outline_recovery_rejects_semantic_non_headings() {
        let mut header = outline_para("Header");
        header.layout_class = Some(LayoutHintClass::PageHeader);
        let mut list = outline_para("List");
        list.layout_class = Some(LayoutHintClass::ListItem);
        let mut formula = outline_para("Formula");
        formula.is_formula = true;
        let mut pages = vec![vec![header, list, formula]];
        let entries = vec![
            PdfOutlineEntry::test_entry("Header", 0, 1),
            PdfOutlineEntry::test_entry("List", 0, 1),
            PdfOutlineEntry::test_entry("Formula", 0, 1),
        ];

        recover_headings_from_outline(&mut pages, &entries);

        assert!(pages[0].iter().all(|paragraph| paragraph.heading_level.is_none()));
    }

    #[test]
    fn outline_title_normalization_handles_labels_without_aliasing_prose() {
        assert_eq!(
            normalize_outline_title("1. Introduction"),
            normalize_outline_title("Introduction")
        );
        assert_eq!(
            normalize_outline_title("IV. Results"),
            normalize_outline_title("Results")
        );
        assert_ne!(
            normalize_outline_title("A quick example"),
            normalize_outline_title("quick example")
        );
        assert_ne!(
            normalize_outline_title("2024 Report"),
            normalize_outline_title("Report")
        );
        assert_ne!(normalize_outline_title("v2 API"), normalize_outline_title("API"));
    }

    fn paragraph_text(paragraph: &PdfParagraph) -> String {
        paragraph
            .lines
            .iter()
            .flat_map(|line| line.segments.iter())
            .map(|segment| segment.text.as_str())
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn heuristic_segment(text: &str, baseline_y: f32, width: f32, is_monospace: bool) -> SegmentData {
        let mut segment = seg(text, 10.0, width);
        segment.y = baseline_y - segment.height;
        segment.baseline_y = baseline_y;
        segment.is_monospace = is_monospace;
        segment
    }

    fn process_heuristic_segments(segments: Vec<SegmentData>) -> Vec<PdfParagraph> {
        process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: segments,
                page_hints: None,
                table_bboxes: Vec::new(),
                preserve_native_semantics: false,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: Vec::new(),
                #[cfg(feature = "layout-detection")]
                page_width_pts: None,
                needs_classify: false,
                paragraph_gap_ys: Vec::new(),
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        )
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn empty_or_ineligible_layout_hints_use_legacy_page_processing() {
        let segments = vec![
            heuristic_segment("First paragraph.", 700.0, 220.0, false),
            heuristic_segment("Second paragraph.", 600.0, 220.0, false),
        ];
        let paragraph_gap_ys = compute_paragraph_gap_ys(&segments);
        let process = |page_hints| {
            process_single_page(
                PageInput {
                    page_index: 0,
                    struct_paragraphs: None,
                    heuristic_segments: segments.clone(),
                    page_hints,
                    table_bboxes: Vec::new(),
                    preserve_native_semantics: false,
                    use_layout_reading_order: false,
                    hint_validations: Vec::new(),
                    page_width_pts: None,
                    needs_classify: false,
                    paragraph_gap_ys: paragraph_gap_ys.clone(),
                    include_headers: true,
                    include_footers: true,
                },
                &[],
                None,
            )
        };

        let legacy = process(None);
        let empty = process(Some(Vec::new()));
        let invalid = process(Some(vec![LayoutHint {
            class_name: crate::pdf::structure::types::LayoutHintClass::Text,
            confidence: 0.9,
            left: 0.0,
            bottom: 0.0,
            right: f32::INFINITY,
            top: 100.0,
        }]));
        let non_overlapping = process(Some(vec![LayoutHint {
            class_name: crate::pdf::structure::types::LayoutHintClass::Text,
            confidence: 0.9,
            left: 400.0,
            bottom: 0.0,
            right: 500.0,
            top: 100.0,
        }]));

        assert_eq!(format!("{empty:?}"), format!("{legacy:?}"));
        assert_eq!(format!("{invalid:?}"), format!("{legacy:?}"));
        assert_eq!(format!("{non_overlapping:?}"), format!("{legacy:?}"));
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn page_width_reaches_layout_reading_order_graph() {
        let positioned_segment = |text: &str, x: f32, y: f32| {
            let mut segment = heuristic_segment(text, y + 10.0, 10.0, false);
            segment.x = x;
            segment.y = y;
            segment.height = 10.0;
            segment
        };
        let mut segments = vec![
            positioned_segment("bottom-left", 10.0, 205.0),
            positioned_segment("top-left", 90.0, 305.0),
            positioned_segment("top-right", 200.0, 305.0),
            positioned_segment("bottom-right", 250.0, 205.0),
        ];
        for (index, segment) in segments.iter_mut().enumerate() {
            segment.assigned_role = Some(if index % 2 == 0 { 2 } else { 3 });
        }
        let hint = |left, bottom, right, top| LayoutHint {
            class_name: crate::pdf::structure::types::LayoutHintClass::Text,
            confidence: 0.95,
            left,
            bottom,
            right,
            top,
        };
        let hints = vec![
            hint(0.0, 200.0, 120.0, 220.0),
            hint(80.0, 300.0, 160.0, 320.0),
            hint(120.0, 300.0, 240.0, 320.0),
            hint(160.0, 200.0, 280.0, 220.0),
        ];
        let process = |page_width_pts, table_bboxes, _has_emitted_table| {
            let mut pages = vec![process_single_page(
                PageInput {
                    page_index: 0,
                    struct_paragraphs: None,
                    heuristic_segments: segments.clone(),
                    page_hints: Some(hints.clone()),
                    table_bboxes,
                    preserve_native_semantics: true,
                    use_layout_reading_order: true,
                    hint_validations: Vec::new(),
                    page_width_pts,
                    needs_classify: false,
                    paragraph_gap_ys: Vec::new(),
                    include_headers: true,
                    include_footers: true,
                },
                &[],
                None,
            )];
            reorder_pages_by_layout_region(&mut pages);
            pages[0].iter().map(paragraph_text).collect::<Vec<_>>()
        };

        assert_eq!(
            process(None, Vec::new(), false),
            ["top-left", "bottom-left", "top-right", "bottom-right"]
        );
        assert_eq!(
            process(Some(400.0), Vec::new(), false),
            ["top-left", "top-right", "bottom-left", "bottom-right"],
            "the actual page width must reach layout graph dilation"
        );
        assert_eq!(
            process(
                Some(400.0),
                vec![crate::types::BoundingBox {
                    x0: 0.0,
                    y0: 0.0,
                    x1: 50.0,
                    y1: 50.0,
                }],
                true,
            ),
            ["top-left", "top-right", "bottom-left", "bottom-right"],
            "an emitted table must not disable layout reading order for surrounding prose"
        );
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn stacked_layout_groups_preserve_native_paragraph_assembly() {
        let segments = vec![
            heuristic_segment("One continuous", 700.0, 120.0, false),
            heuristic_segment("paragraph.", 688.0, 100.0, false),
        ];
        let hints = vec![
            LayoutHint {
                class_name: LayoutHintClass::Text,
                confidence: 0.99,
                left: 0.0,
                bottom: 685.0,
                right: 200.0,
                top: 705.0,
            },
            LayoutHint {
                class_name: LayoutHintClass::Text,
                confidence: 0.99,
                left: 0.0,
                bottom: 673.0,
                right: 200.0,
                top: 693.0,
            },
        ];
        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: segments,
                page_hints: Some(hints),
                table_bboxes: Vec::new(),
                preserve_native_semantics: true,
                use_layout_reading_order: false,
                hint_validations: Vec::new(),
                page_width_pts: Some(612.0),
                needs_classify: false,
                paragraph_gap_ys: Vec::new(),
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );

        assert_eq!(output.len(), 1);
        assert_eq!(paragraph_text(&output[0]), "One continuous paragraph.");
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn bboxless_emitted_table_page_preserves_native_semantics_and_layout_class() {
        let segment = heuristic_segment("Ordinary prose.", 700.0, 220.0, false);
        let paragraph_gap_ys = compute_paragraph_gap_ys(std::slice::from_ref(&segment));
        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: vec![segment],
                page_hints: Some(vec![LayoutHint {
                    class_name: LayoutHintClass::Title,
                    confidence: 0.99,
                    left: 0.0,
                    bottom: 680.0,
                    right: 300.0,
                    top: 720.0,
                }]),
                table_bboxes: Vec::new(),
                preserve_native_semantics: true,
                use_layout_reading_order: true,
                hint_validations: Vec::new(),
                page_width_pts: Some(612.0),
                needs_classify: false,
                paragraph_gap_ys,
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );

        assert_eq!(output.len(), 1);
        assert_eq!(paragraph_text(&output[0]), "Ordinary prose.");
        assert_eq!(output[0].heading_level, None);
        assert_eq!(output[0].layout_class, Some(LayoutHintClass::Title));
    }

    #[cfg(feature = "layout-detection")]
    #[test]
    fn emitted_table_page_annotates_caption_without_overriding_native_semantics() {
        let segment = heuristic_segment("Source: annual filing", 100.0, 220.0, false);
        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: vec![segment],
                page_hints: Some(vec![LayoutHint {
                    class_name: LayoutHintClass::Caption,
                    confidence: 0.99,
                    left: 0.0,
                    bottom: 80.0,
                    right: 300.0,
                    top: 120.0,
                }]),
                table_bboxes: Vec::new(),
                preserve_native_semantics: true,
                use_layout_reading_order: true,
                hint_validations: Vec::new(),
                page_width_pts: Some(612.0),
                needs_classify: false,
                paragraph_gap_ys: Vec::new(),
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );

        assert_eq!(output.len(), 1);
        assert_eq!(paragraph_text(&output[0]), "Source: annual filing");
        assert_eq!(output[0].heading_level, None);
        assert_eq!(output[0].layout_class, Some(LayoutHintClass::Caption));
    }

    #[test]
    fn test_heuristic_path_runs_fused_text_repairs() {
        let mut segment = heuristic_segment("Intro\u{00AD}duction, , body", 700.0, 320.0, false);
        segment.is_bold = true;

        let output = process_heuristic_segments(vec![segment]);

        assert_eq!(output.len(), 1);
        assert_eq!(paragraph_text(&output[0]), "Introduction, body");
        assert!(
            output[0].text.is_empty(),
            "repaired segments must remain the text source of truth"
        );
        assert_eq!(output[0].word_count, 2);

        let document = assemble_internal_document(vec![output], &[], None, &[]);
        let element = &document.elements[0];
        assert_eq!(element.text, "Introduction, body");
        assert_eq!(element.annotations.len(), 1);
        assert_eq!(element.annotations[0].start, 0);
        assert_eq!(element.annotations[0].end as usize, element.text.len());
    }

    #[test]
    fn test_heuristic_path_dehyphenates_wrapped_word() {
        let output = process_heuristic_segments(vec![
            heuristic_segment("Reliable soft-", 700.0, 490.0, false),
            heuristic_segment("ware handles load", 680.0, 200.0, false),
        ]);

        assert_eq!(output.len(), 1);
        assert_eq!(paragraph_text(&output[0]), "Reliable software handles load");
        assert_eq!(output[0].word_count, 4);
    }

    #[test]
    fn test_heuristic_path_preserves_compound_and_code_hyphens() {
        let compound = process_heuristic_segments(vec![
            heuristic_segment("A cost-", 700.0, 490.0, false),
            heuristic_segment("effective design", 680.0, 200.0, false),
        ]);
        assert_eq!(paragraph_text(&compound[0]), "A cost-effective design");

        let document = assemble_internal_document(vec![compound], &[], None, &[]);
        assert_eq!(document.elements[0].text, "A cost-effective design");

        let code = process_heuristic_segments(vec![
            heuristic_segment("let value = soft-", 700.0, 490.0, true),
            heuristic_segment("ware;", 680.0, 100.0, true),
        ]);
        assert!(code[0].is_code_block);
        assert_eq!(paragraph_text(&code[0]), "let value = soft- ware;");
    }

    #[test]
    fn test_structure_tree_page_runs_text_repair_before_assembly() {
        let paragraphs = vec![para(vec![line(vec![seg(
            "Intro\u{00AD}duction, , body • first item • second item",
            10.0,
            320.0,
        )])])];

        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: Some(paragraphs),
                heuristic_segments: Vec::new(),
                page_hints: None,
                table_bboxes: Vec::new(),
                preserve_native_semantics: false,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: Vec::new(),
                #[cfg(feature = "layout-detection")]
                page_width_pts: None,
                needs_classify: false,
                paragraph_gap_ys: Vec::new(),
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );

        assert_eq!(output.len(), 3);
        assert_eq!(paragraph_text(&output[0]), "Introduction, body");
        assert!(output[1].is_list_item);
        assert_eq!(paragraph_text(&output[1]), "first item");
        assert!(output[2].is_list_item);
        assert_eq!(paragraph_text(&output[2]), "second item");
    }

    #[test]
    fn assigned_sal_heading_survives_merge_when_layout_confirms_it() {
        let mut body = role_seg("unterminated body", 12.0, false, None);
        body.y = 688.0;
        body.baseline_y = 700.0;
        let mut annotation = role_seg("__in", 12.0, false, Some(2));
        annotation.y = 638.0;
        annotation.baseline_y = 650.0;

        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: vec![body, annotation],
                page_hints: Some(vec![LayoutHint {
                    class_name: LayoutHintClass::SectionHeader,
                    confidence: 0.99,
                    left: 70.0,
                    bottom: 635.0,
                    right: 275.0,
                    top: 655.0,
                }]),
                table_bboxes: Vec::new(),
                preserve_native_semantics: false,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: Vec::new(),
                #[cfg(feature = "layout-detection")]
                page_width_pts: Some(612.0),
                needs_classify: false,
                paragraph_gap_ys: Vec::new(),
                include_headers: true,
                include_footers: true,
            },
            &[],
            Some(12.0),
        );

        assert_eq!(output.len(), 2);
        assert_eq!(paragraph_text(&output[1]), "__in");
        assert_eq!(output[1].heading_level, Some(2));
        assert_eq!(output[1].layout_class, Some(LayoutHintClass::SectionHeader));
    }

    /// Full-width line at x=10, width=490 → right edge 500.
    fn full_line_seg(text: &str) -> SegmentData {
        seg(text, 10.0, 490.0)
    }

    /// Short line at x=10, width=100 → right edge 110 (well below 500*0.85=425).
    fn short_line_seg(text: &str) -> SegmentData {
        seg(text, 10.0, 100.0)
    }

    #[test]
    fn test_case1_trailing_hyphen_full_line() {
        let mut p = para(vec![
            line(vec![full_line_seg("some soft-")]),
            line(vec![seg("ware is great", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "some software");
        assert_eq!(p.lines[1].segments[0].text, "is great");
    }

    #[test]
    fn test_case2_no_hyphen_full_line_no_join() {
        let mut p = para(vec![
            line(vec![full_line_seg("the soft")]),
            line(vec![seg("ware is great", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "the soft");
        assert_eq!(p.lines[1].segments[0].text, "ware is great");
    }

    #[test]
    fn test_short_line_no_join() {
        let mut p = para(vec![
            line(vec![short_line_seg("hello")]),
            line(vec![full_line_seg("world and more")]),
        ]);
        let original_trailing = p.lines[0].segments[0].text.clone();
        let original_leading = p.lines[1].segments[0].text.clone();
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, original_trailing);
        assert_eq!(p.lines[1].segments[0].text, original_leading);
    }

    #[test]
    fn test_code_block_not_joined() {
        let mut p = para(vec![
            line(vec![full_line_seg("some soft-")]),
            line(vec![seg("ware is code", 10.0, 200.0)]),
        ]);
        p.is_code_block = true;
        let mut paragraphs = vec![p];
        dehyphenate_paragraphs(&mut paragraphs, true);
        assert_eq!(paragraphs[0].lines[0].segments[0].text, "some soft-");
    }

    #[test]
    fn test_uppercase_leading_not_joined() {
        let mut p = para(vec![
            line(vec![full_line_seg("some text")]),
            line(vec![seg("Next sentence here", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "some text");
        assert_eq!(p.lines[1].segments[0].text, "Next sentence here");
    }

    #[test]
    fn test_cjk_not_joined() {
        let mut p = para(vec![
            line(vec![full_line_seg("some \u{4E00}-")]),
            line(vec![seg("text here", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "some \u{4E00}-");
    }

    #[test]
    fn test_real_world_software_no_join_without_hyphen() {
        let mut p = para(vec![
            line(vec![full_line_seg("advanced soft")]),
            line(vec![seg("ware development", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "advanced soft");
        assert_eq!(p.lines[1].segments[0].text, "ware development");
    }

    #[test]
    fn test_real_world_hardware_no_join_without_hyphen() {
        let mut p = para(vec![
            line(vec![full_line_seg("modern hard")]),
            line(vec![seg("ware components", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "modern hard");
        assert_eq!(p.lines[1].segments[0].text, "ware components");
    }

    #[test]
    fn test_leading_word_with_trailing_punctuation_no_join() {
        let mut p = para(vec![
            line(vec![full_line_seg("the soft")]),
            line(vec![seg("ware, which is great", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "the soft");
        assert_eq!(p.lines[1].segments[0].text, "ware, which is great");
    }

    #[test]
    fn test_hyphen_only_fallback() {
        let mut p = para(vec![
            line(vec![seg("some soft-", 0.0, 0.0)]),
            line(vec![seg("ware is great", 0.0, 0.0)]),
        ]);
        dehyphenate_hyphen_only(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "some software");
        assert_eq!(p.lines[1].segments[0].text, "is great");
    }

    #[test]
    fn test_hyphen_only_uppercase_not_joined() {
        let mut p = para(vec![
            line(vec![seg("some well-", 0.0, 0.0)]),
            line(vec![seg("Known thing", 0.0, 0.0)]),
        ]);
        dehyphenate_hyphen_only(&mut p);
        assert_eq!(p.lines[0].segments[0].text, "some well-");
    }

    #[test]
    fn test_single_line_paragraph_skipped() {
        let mut paragraphs = vec![para(vec![line(vec![full_line_seg("single line")])])];
        dehyphenate_paragraphs(&mut paragraphs, true);
        assert_eq!(paragraphs[0].lines[0].segments[0].text, "single line");
    }

    #[test]
    fn test_multi_segment_line_no_join_without_hyphen() {
        let mut p = para(vec![
            line(vec![seg("first part", 10.0, 200.0), seg("soft", 220.0, 280.0)]),
            line(vec![seg("ware next words", 10.0, 200.0)]),
        ]);
        dehyphenate_paragraph_lines(&mut p);
        assert_eq!(p.lines[0].segments[1].text, "soft");
        assert_eq!(p.lines[1].segments[0].text, "ware next words");
    }

    fn para_with_font_size(font_size: f32) -> PdfParagraph {
        let lines = vec![line(vec![seg("text", 0.0, 100.0)])];
        let word_count = PdfParagraph::compute_word_count("", &lines);
        PdfParagraph {
            text: String::new(),
            lines,
            dominant_font_size: font_size,
            heading_level: None,
            is_bold: false,
            is_list_item: false,
            is_code_block: false,
            is_formula: false,
            is_page_furniture: false,
            layout_class: None,
            layout_region_path: None,
            caption_for: None,
            block_bbox: None,
            word_count,
        }
    }

    #[test]
    fn test_has_font_size_variation_empty() {
        assert!(!has_font_size_variation(&[]));
    }

    #[test]
    fn test_has_font_size_variation_single_size() {
        let paragraphs = vec![para_with_font_size(12.0), para_with_font_size(12.0)];
        assert!(!has_font_size_variation(&paragraphs));
    }

    #[test]
    fn test_has_font_size_variation_different_sizes() {
        let paragraphs = vec![para_with_font_size(12.0), para_with_font_size(18.0)];
        assert!(has_font_size_variation(&paragraphs));
    }

    #[test]
    fn test_has_font_size_variation_small_difference_ignored() {
        let paragraphs = vec![para_with_font_size(12.0), para_with_font_size(12.3)];
        assert!(!has_font_size_variation(&paragraphs));
    }

    #[test]
    fn test_has_font_size_variation_zero_sizes_ignored() {
        let paragraphs = vec![para_with_font_size(0.0), para_with_font_size(0.0)];
        assert!(!has_font_size_variation(&paragraphs));
    }

    use crate::pdf::structure::types::LayoutHintClass;

    fn furniture_para_with_class(class: LayoutHintClass) -> PdfParagraph {
        let lines = vec![line(vec![seg("ACME", 0.0, 50.0)])];
        let word_count = PdfParagraph::compute_word_count("", &lines);
        PdfParagraph {
            text: String::new(),
            lines,
            dominant_font_size: 10.0,
            heading_level: None,
            is_bold: false,
            is_list_item: false,
            is_code_block: false,
            is_formula: false,
            is_page_furniture: true,
            layout_class: Some(class),
            layout_region_path: None,
            caption_for: None,
            block_bbox: None,
            word_count,
        }
    }

    #[test]
    fn test_include_headers_clears_page_header_furniture() {
        let mut paras = vec![furniture_para_with_class(LayoutHintClass::PageHeader)];
        un_mark_layout_furniture_per_config(&mut paras, true, false);
        assert!(
            !paras[0].is_page_furniture,
            "PageHeader furniture must be cleared when include_headers=true"
        );
    }

    #[test]
    fn test_include_footers_clears_page_footer_furniture() {
        let mut paras = vec![furniture_para_with_class(LayoutHintClass::PageFooter)];
        un_mark_layout_furniture_per_config(&mut paras, false, true);
        assert!(
            !paras[0].is_page_furniture,
            "PageFooter furniture must be cleared when include_footers=true"
        );
    }

    #[test]
    fn test_include_headers_false_preserves_page_header_furniture() {
        let mut paras = vec![furniture_para_with_class(LayoutHintClass::PageHeader)];
        un_mark_layout_furniture_per_config(&mut paras, false, false);
        assert!(
            paras[0].is_page_furniture,
            "PageHeader furniture must remain when include_headers=false"
        );
    }

    #[test]
    fn test_include_headers_does_not_clear_page_footer_furniture() {
        let mut paras = vec![furniture_para_with_class(LayoutHintClass::PageFooter)];
        un_mark_layout_furniture_per_config(&mut paras, true, false);
        assert!(
            paras[0].is_page_furniture,
            "PageFooter furniture must remain when only include_headers=true"
        );
    }

    #[test]
    fn test_include_headers_does_not_clear_non_layout_furniture() {
        let mut para = para(vec![line(vec![seg("repeating", 0.0, 80.0)])]);
        para.is_page_furniture = true;
        para.layout_class = None;
        let mut paras = vec![para];
        un_mark_layout_furniture_per_config(&mut paras, true, true);
        assert!(
            paras[0].is_page_furniture,
            "Heuristic furniture (no layout_class) must not be cleared"
        );
    }

    #[test]
    fn test_un_mark_is_noop_when_both_flags_false() {
        let mut paras = vec![
            furniture_para_with_class(LayoutHintClass::PageHeader),
            furniture_para_with_class(LayoutHintClass::PageFooter),
        ];
        un_mark_layout_furniture_per_config(&mut paras, false, false);
        assert!(paras[0].is_page_furniture);
        assert!(paras[1].is_page_furniture);
    }

    #[test]
    fn test_deduplicate_paragraphs_removes_consecutive_duplicates() {
        let p1 = para(vec![line(vec![full_line_seg("Brand loses market share")])]);
        let p2 = para(vec![line(vec![full_line_seg("Brand loses market share")])]);
        let p3 = para(vec![line(vec![full_line_seg("Different content here")])]);
        let mut pages = vec![vec![p1, p2, p3]];
        deduplicate_paragraphs(&mut pages);
        assert_eq!(pages[0].len(), 2, "consecutive duplicate should be removed");
    }

    #[test]
    fn test_deduplicate_paragraphs_removes_non_consecutive_body_duplicates() {
        let p1 = para(vec![line(vec![full_line_seg("Brand loses market share in volume")])]);
        let p2 = para(vec![line(vec![full_line_seg("Some intervening paragraph")])]);
        let p3 = para(vec![line(vec![full_line_seg("Brand loses market share in volume")])]);
        let mut pages = vec![vec![p1, p2, p3]];
        deduplicate_paragraphs(&mut pages);
        assert_eq!(pages[0].len(), 2, "non-consecutive body duplicate should be removed");
    }

    #[test]
    fn test_deduplicate_paragraphs_preserves_non_consecutive_headings() {
        let mut h = para(vec![line(vec![full_line_seg("Brand loses market share in volume")])]);
        h.heading_level = Some(2);
        let filler = para(vec![line(vec![full_line_seg("Some other content between them")])]);
        let mut h2 = para(vec![line(vec![full_line_seg("Brand loses market share in volume")])]);
        h2.heading_level = Some(2);
        let mut pages = vec![vec![h, filler, h2]];
        deduplicate_paragraphs(&mut pages);
        assert_eq!(
            pages[0].len(),
            3,
            "non-consecutive heading duplicates must be preserved"
        );
    }

    fn positioned_footnote_paragraph(
        text: &str,
        bbox: (f32, f32, f32, f32),
        font_size: f32,
        is_page_furniture: bool,
    ) -> PdfParagraph {
        let mut segment = seg_at(text, bbox.0, bbox.1, font_size, false);
        segment.width = bbox.2 - bbox.0;
        let mut paragraph = para(vec![line(vec![segment])]);
        paragraph.dominant_font_size = font_size;
        paragraph.is_page_furniture = is_page_furniture;
        paragraph.block_bbox = Some(bbox);
        paragraph
    }

    fn positioned_numeric_footnote_run<const N: usize>(
        numbers: [u32; N],
        body_bottoms: [f32; N],
        body_fonts: [f32; N],
    ) -> Vec<PdfParagraph> {
        let mut paragraphs = Vec::new();
        for ((number, body_bottom), body_font) in numbers.into_iter().zip(body_bottoms).zip(body_fonts) {
            paragraphs.push(positioned_footnote_paragraph(
                &number.to_string(),
                (72.0, body_bottom + 3.7947, 75.3369, body_bottom + 9.7947),
                6.0,
                true,
            ));
            paragraphs.push(positioned_footnote_paragraph(
                "estimate",
                (78.1142, body_bottom, 140.9093, body_bottom + body_font),
                body_font,
                false,
            ));
        }
        paragraphs
    }

    #[test]
    fn consecutive_spatial_footnotes_merge_into_one_paragraph() {
        let pairs = [
            ("1", "2021 estimate", 101.0221, 97.2274),
            ("2", "2020 estimate", 89.5231, 85.7284),
            ("3", "2020 estimate", 78.024, 74.2294),
        ];
        let mut paragraphs = Vec::new();
        for (marker, body, marker_bottom, body_bottom) in pairs {
            paragraphs.push(positioned_footnote_paragraph(
                marker,
                (72.0, marker_bottom, 75.3369, marker_bottom + 6.0),
                6.0,
                true,
            ));
            paragraphs.push(positioned_footnote_paragraph(
                body,
                (78.1142, body_bottom, 140.9093, body_bottom + 10.0),
                10.0,
                false,
            ));
        }

        merge_spatial_footnote_markers(&mut paragraphs);
        retain_page_furniture_safely(&mut paragraphs);
        let mut pages = vec![paragraphs];
        deduplicate_paragraphs(&mut pages);

        assert_eq!(
            pages[0].iter().map(paragraph_text_raw).collect::<Vec<_>>(),
            ["1 2021 estimate 2 2020 estimate 3 2020 estimate"]
        );
        assert_eq!(pages[0][0].lines.len(), 6);
        assert_eq!(pages[0][0].block_bbox, Some((72.0, 74.2294, 140.9093, 107.2274)));
    }

    #[test]
    fn spatial_footnote_run_rejects_sequence_gap_path_and_style_changes() {
        let regular_bottoms = [97.2274, 85.7284, 74.2294];

        let mut nonsequential = positioned_numeric_footnote_run([1, 3, 4], regular_bottoms, [10.0, 10.0, 10.0]);
        merge_spatial_footnote_markers(&mut nonsequential);
        assert_eq!(nonsequential.len(), 3);

        let mut large_gap = positioned_numeric_footnote_run([1, 2, 3], [97.2274, 80.0, 68.5], [10.0, 10.0, 10.0]);
        merge_spatial_footnote_markers(&mut large_gap);
        assert_eq!(large_gap.len(), 3);

        let mut mismatched_path = positioned_numeric_footnote_run([1, 2, 3], regular_bottoms, [10.0, 10.0, 10.0]);
        let other_path = super::super::types::LayoutRegionPath {
            root: super::super::types::LayoutRegionTag {
                id: 1,
                class_name: Some(super::super::types::LayoutHintClass::Footnote),
            },
            child: None,
        };
        mismatched_path[2].layout_region_path = Some(other_path);
        mismatched_path[3].layout_region_path = Some(other_path);
        merge_spatial_footnote_markers(&mut mismatched_path);
        assert_eq!(mismatched_path.len(), 3);

        let mut style_change = positioned_numeric_footnote_run([1, 2, 3], regular_bottoms, [10.0, 12.0, 10.0]);
        merge_spatial_footnote_markers(&mut style_change);
        assert_eq!(style_change.len(), 3);
    }

    #[test]
    fn spatial_footnote_run_rejects_overflowing_marker_sequence() {
        let make_paragraph = |marker: &str, body_bottom: f32| {
            let marker = positioned_footnote_paragraph(
                marker,
                (72.0, body_bottom + 3.7947, 75.3369, body_bottom + 9.7947),
                6.0,
                false,
            );
            let body = positioned_footnote_paragraph(
                "estimate",
                (78.1142, body_bottom, 140.9093, body_bottom + 10.0),
                10.0,
                false,
            );
            let mut paragraph = para(vec![marker.lines[0].clone(), body.lines[0].clone()]);
            paragraph.dominant_font_size = 10.0;
            paragraph.block_bbox = Some((72.0, body_bottom, 140.9093, body_bottom + 10.0));
            paragraph
        };
        let upper = make_paragraph(&u32::MAX.to_string(), 97.2274);
        let lower = make_paragraph("0", 85.7284);

        assert!(!spatial_footnotes_are_adjacent(&upper, &lower));
    }

    #[test]
    fn spatial_footnote_run_requires_marker_pair_provenance() {
        let paragraphs = positioned_numeric_footnote_run([1, 2, 3], [97.2274, 85.7284, 74.2294], [10.0; 3]);
        let mut preexisting = paragraphs
            .chunks_exact(2)
            .map(|pair| {
                let mut paragraph = pair.to_vec();
                merge_spatial_footnote_markers(&mut paragraph);
                paragraph.pop().expect("marker and body merge")
            })
            .collect::<Vec<_>>();

        merge_spatial_footnote_markers(&mut preexisting);

        assert_eq!(preexisting.len(), 3);
        assert_eq!(
            preexisting.iter().map(paragraph_text_raw).collect::<Vec<_>>(),
            ["1 estimate", "2 estimate", "3 estimate"]
        );
    }

    #[test]
    fn spatial_footnote_run_keeps_regular_prefix_before_irregular_fourth() {
        let mut paragraphs =
            positioned_numeric_footnote_run([1, 2, 3, 4], [97.2274, 85.7284, 74.2294, 59.5], [10.0; 4]);

        merge_spatial_footnote_markers(&mut paragraphs);

        assert_eq!(paragraphs.len(), 2);
        assert_eq!(
            paragraphs.iter().map(paragraph_text_raw).collect::<Vec<_>>(),
            ["1 estimate 2 estimate 3 estimate", "4 estimate"]
        );
    }

    #[test]
    fn spatial_footnote_merge_rejects_page_numbers_and_list_markers() {
        let page_number = positioned_footnote_paragraph("1", (300.0, 20.0, 303.0, 26.0), 6.0, true);
        let distant_body = positioned_footnote_paragraph("Following paragraph", (72.0, 40.0, 180.0, 50.0), 10.0, false);
        let list_number = positioned_footnote_paragraph("2", (72.0, 80.0, 75.0, 90.0), 10.0, true);
        let list_body = positioned_footnote_paragraph("List body", (78.0, 80.0, 130.0, 90.0), 10.0, false);
        let small_list_number = positioned_footnote_paragraph("3", (72.0, 60.0, 75.0, 66.0), 6.0, true);
        let aligned_list_body =
            positioned_footnote_paragraph("Small list body", (78.0, 60.0, 150.0, 70.0), 10.0, false);
        let mut paragraphs = vec![
            page_number,
            distant_body,
            list_number,
            list_body,
            small_list_number,
            aligned_list_body,
        ];

        merge_spatial_footnote_markers(&mut paragraphs);

        assert_eq!(paragraphs.len(), 6);
        assert_eq!(
            paragraphs.iter().map(paragraph_text_raw).collect::<Vec<_>>(),
            ["1", "Following paragraph", "2", "List body", "3", "Small list body"]
        );
    }

    #[test]
    fn spatial_footnote_merge_requires_compatible_geometry_and_layout_path() {
        let marker = positioned_footnote_paragraph("12", (72.0, 100.0, 76.0, 106.0), 6.0, true);
        let large_gap_body = positioned_footnote_paragraph("Large gap", (90.0, 96.0, 140.0, 106.0), 10.0, false);
        let weak_overlap_body = positioned_footnote_paragraph("Weak overlap", (78.0, 104.0, 140.0, 114.0), 10.0, false);
        let mut mismatched_path_body =
            positioned_footnote_paragraph("Other region", (78.0, 96.0, 140.0, 106.0), 10.0, false);
        mismatched_path_body.layout_region_path = Some(super::super::types::LayoutRegionPath {
            root: super::super::types::LayoutRegionTag {
                id: 1,
                class_name: Some(super::super::types::LayoutHintClass::Footnote),
            },
            child: None,
        });

        for body in [large_gap_body, weak_overlap_body, mismatched_path_body] {
            let mut paragraphs = vec![marker.clone(), body];
            merge_spatial_footnote_markers(&mut paragraphs);
            assert_eq!(paragraphs.len(), 2);
        }
    }

    #[test]
    fn spatial_footnote_merge_accepts_conventional_symbol_marker() {
        let marker = positioned_footnote_paragraph("", (72.0, 100.0, 75.0, 106.0), 6.0, true);
        let body = positioned_footnote_paragraph("Source note", (78.0, 96.0, 140.0, 106.0), 10.0, false);
        let mut paragraphs = vec![marker, body];

        merge_spatial_footnote_markers(&mut paragraphs);

        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraph_text_raw(&paragraphs[0]), "† Source note");
    }

    /// Verify that the index offset formula used for image mapping is correct.
    #[test]
    fn test_image_index_offset_mapping() {
        let indices: Vec<usize> = vec![50, 52, 54];
        let indices_set: ahash::AHashSet<usize> = indices.iter().copied().collect();
        let first_idx_on_page = indices.iter().copied().min().unwrap_or(0);

        let mut matched: Vec<usize> = Vec::new();
        for current_image in 0..5usize {
            let global_idx = first_idx_on_page + current_image;
            if indices_set.contains(&global_idx) {
                matched.push(global_idx);
            }
        }

        assert_eq!(
            matched,
            vec![50, 52, 54],
            "offset formula must yield exactly the requested global indices"
        );

        assert!(
            !indices_set.contains(&49usize),
            "index 49 is before the page range and must not match"
        );

        assert!(
            !indices_set.contains(&55usize),
            "index 55 was not requested and must not match"
        );
    }

    /// Helper: build a minimal SegmentData for heading-map tests.
    fn seg_with_font(text: &str, font_size: f32) -> SegmentData {
        SegmentData {
            text: text.to_string(),
            x: 10.0,
            y: 700.0,
            width: 200.0,
            height: font_size,
            font_size,
            is_bold: false,
            is_italic: false,
            is_monospace: false,
            baseline_y: 700.0,
            assigned_role: None,
        }
    }

    fn seg_at(text: &str, x: f32, y: f32, height: f32, monospace: bool) -> SegmentData {
        SegmentData {
            text: text.to_string(),
            x,
            y,
            width: 200.0,
            height,
            font_size: height,
            is_bold: false,
            is_italic: false,
            is_monospace: monospace,
            baseline_y: y,
            assigned_role: None,
        }
    }

    #[test]
    fn test_compute_paragraph_gap_ys_detects_blank_line_gap() {
        let segments = vec![
            seg_at("line one", 10.0, 700.0, 12.0, false),
            seg_at("line two", 10.0, 684.0, 12.0, false),
            seg_at("new paragraph", 10.0, 644.0, 12.0, false),
        ];
        let gaps = compute_paragraph_gap_ys(&segments);
        assert_eq!(gaps.len(), 1, "only the blank-line jump is a paragraph gap");
        assert!(
            gaps[0] > 656.0 && gaps[0] < 684.0,
            "gap midpoint between the paragraphs, got {}",
            gaps[0]
        );
    }

    #[test]
    fn test_compute_paragraph_gap_ys_ignores_same_line_runs_and_tight_lines() {
        let segments = vec![
            seg_at("run a", 10.0, 700.0, 12.0, false),
            seg_at("run b", 80.0, 700.0, 12.0, false),
            seg_at("next line", 10.0, 685.0, 12.0, false),
        ];
        assert_eq!(compute_paragraph_gap_ys(&segments), Vec::<f32>::new());
    }

    #[test]
    fn test_compute_paragraph_gap_ys_immune_to_column_major_stream_order() {
        let segments = vec![
            seg_at("A top", 10.0, 700.0, 12.0, false),
            seg_at("A mid", 10.0, 685.0, 12.0, false),
            seg_at("A bot", 10.0, 670.0, 12.0, false),
            seg_at("B top", 300.0, 700.0, 12.0, false),
            seg_at("B mid", 300.0, 685.0, 12.0, false),
            seg_at("B bot", 300.0, 670.0, 12.0, false),
        ];
        assert_eq!(compute_paragraph_gap_ys(&segments), Vec::<f32>::new());
    }

    #[test]
    fn test_finalize_paragraph_page_number_is_furniture_not_heading() {
        let heading_map = vec![(12.0, Some(2)), (9.0, None)];
        let gap_info = crate::pdf::structure::classify::precompute_gap_info(&heading_map);
        let seg = seg_at("1", 300.0, 50.0, 12.0, false);
        let para = finalize_paragraph(&[&seg], &heading_map, &gap_info).expect("paragraph");
        assert_eq!(para.heading_level, None, "page number must not become a heading");
        assert!(para.is_page_furniture, "page number must be marked furniture");
    }

    #[test]
    fn test_compute_paragraph_gap_ys_skips_blank_lines_inside_code_blocks() {
        let segments = vec![
            seg_at("let x = 1;", 10.0, 700.0, 12.0, true),
            seg_at("let y = 2;", 10.0, 660.0, 12.0, true),
            seg_at("Prose resumes here.", 10.0, 620.0, 12.0, false),
        ];
        let gaps = compute_paragraph_gap_ys(&segments);
        assert_eq!(gaps.len(), 1, "only the code→prose boundary is a gap");
        assert!(
            gaps[0] > 632.0 && gaps[0] < 660.0,
            "gap sits between code and prose, got {}",
            gaps[0]
        );
    }

    /// 5-paragraph doc (1 title at 14pt + 4 body at 11pt) with k_clusters=4.
    /// The adaptive clamp should reduce clusters to max(2, 5/4)=max(2,1)=2,
    /// and then the font-size difference (14 vs 11, ratio≈1.27 ≥ 1.2) should
    /// produce a heading_level=1 for the 14pt entry.
    #[test]
    fn test_build_heading_map_short_doc_title_gets_heading_level_1() {
        let title_seg = seg_with_font("My Title", 14.0);
        let body_seg1 = seg_with_font("Body paragraph one.", 11.0);
        let body_seg2 = seg_with_font("Body paragraph two.", 11.0);
        let body_seg3 = seg_with_font("Body paragraph three.", 11.0);
        let body_seg4 = seg_with_font("Body paragraph four.", 11.0);

        let all_page_segments = vec![vec![title_seg, body_seg1, body_seg2, body_seg3, body_seg4]];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];
        let k_clusters = 4;

        let (heading_map, _) =
            build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, k_clusters)
                .expect("build_heading_map must succeed");

        let title_entry = heading_map.iter().find(|(fs, _)| (*fs - 14.0).abs() < 0.5);
        assert!(
            title_entry.is_some(),
            "heading_map must contain an entry near 14pt; got: {heading_map:?}"
        );
        assert_eq!(
            title_entry.unwrap().1,
            Some(1),
            "14pt title in a 5-paragraph doc must get heading_level=1; got: {heading_map:?}"
        );
    }

    /// Verify that the adaptive k clamp doesn't over-reduce for larger documents
    /// (≥20 paragraphs keeps k_clusters unchanged).
    #[test]
    fn test_build_heading_map_large_doc_k_not_reduced() {
        let mut segs: Vec<SegmentData> = (0..4).map(|i| seg_with_font(&format!("Heading {i}"), 18.0)).collect();
        segs.extend((0..20).map(|i| seg_with_font(&format!("Body text paragraph {i}."), 12.0)));

        let all_page_segments = vec![segs];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        let heading_entry = heading_map.iter().find(|(fs, _)| (*fs - 18.0).abs() < 1.0);
        assert!(
            heading_entry.is_some_and(|(_, level)| level.is_some()),
            "18pt entries in a 24-paragraph doc must have a heading level; got: {heading_map:?}"
        );
    }

    /// Uniform-font short document: when all paragraphs share the same font size,
    /// no heading cluster is found by k-means. The fallback must detect the first-page
    /// segment as a title when its font is ≥ 1.2× median — but here all fonts are equal
    /// so no fallback should fire.
    #[test]
    fn test_build_heading_map_uniform_font_no_spurious_heading() {
        let segs: Vec<SegmentData> = (0..5).map(|i| seg_with_font(&format!("Para {i}"), 12.0)).collect();

        let all_page_segments = vec![segs];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        assert!(
            heading_map.iter().all(|(_, level)| level.is_none()),
            "uniform-font doc must produce no headings; got: {heading_map:?}"
        );
    }

    /// Fallback title detection: 5-paragraph doc where first segment is 14pt,
    /// others are 11pt. Ratio 14/11 ≈ 1.27 ≥ 1.2 — fallback must fire only when
    /// k-means would fail to assign a heading.  This exercises the same fixture as
    /// `test_build_heading_map_short_doc_title_gets_heading_level_1` but specifically
    /// with k=1 (no clustering possible) to force the fallback path.
    #[test]
    fn test_build_heading_map_fallback_title_when_k_equals_1() {
        let title_seg = seg_with_font("Document Title", 14.0);
        let body_segs: Vec<SegmentData> = (0..4)
            .map(|i| seg_with_font(&format!("Body paragraph {i}."), 11.0))
            .collect();

        let mut segs = vec![title_seg];
        segs.extend(body_segs);

        let all_page_segments = vec![segs];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 1)
            .expect("build_heading_map must succeed");

        let title_entry = heading_map.iter().find(|(fs, _)| (*fs - 14.0).abs() < 0.5);
        let _ = title_entry;
    }

    /// Sparsity gate: a three-block, single-page document with one clearly larger
    /// first line must NOT promote that line to a heading. A larger opening line
    /// in a tiny document is display prose, not necessarily a title.
    #[test]
    fn test_build_heading_map_sparse_single_page_doc_no_heading_promotion() {
        let all_page_segments = vec![vec![
            seg_with_font("Display Text", 24.0),
            seg_with_font("Body paragraph one.", 12.0),
            seg_with_font("Body paragraph two.", 12.0),
        ]];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        assert!(
            heading_map.iter().all(|(_, level)| level.is_none()),
            "3-block doc must not promote the larger first line to a heading; got: {heading_map:?}"
        );
    }

    /// A sparse multi-page document has stronger evidence than a cover or title
    /// page when the same large-font tier repeats on separate pages and a smaller
    /// body tier is also present. This is the `hello_structure.pdf` shape.
    #[test]
    fn test_build_heading_map_sparse_multi_page_repeated_tier_promotes_headings() {
        let all_page_segments = vec![
            vec![seg_with_font("Hello World", 24.0)],
            vec![
                seg_with_font("Goodbye Cruel World...", 24.0),
                seg_with_font("I'll be back shortly!", 12.0),
            ],
        ];
        let struct_tree_results = vec![None, None];
        let heuristic_pages = vec![0usize, 1usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        let repeated_tier = heading_map
            .iter()
            .find(|(font_size, _)| (*font_size - 24.0).abs() < 0.5);
        assert!(
            repeated_tier.is_some_and(|(_, level)| *level == Some(2)),
            "a repeated 24pt tier across pages with a 12pt body tier must be promoted to H2; got: {heading_map:?}"
        );
    }

    #[test]
    fn test_build_heading_map_sparse_multi_page_does_not_promote_non_repeated_intermediate_tier() {
        use crate::pdf::structure::classify::{find_heading_level, precompute_gap_info};

        let all_page_segments = vec![
            vec![seg_with_font("Repeated Heading One", 22.0)],
            vec![
                seg_with_font("Repeated Heading Two", 22.0),
                seg_with_font("Display prose", 21.0),
                seg_with_font("Body paragraph.", 12.0),
            ],
        ];
        let struct_tree_results = vec![None, None];
        let heuristic_pages = vec![0usize, 1usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");
        let gap_info = precompute_gap_info(&heading_map);

        assert_eq!(
            find_heading_level(21.0, &heading_map, &gap_info),
            None,
            "a non-repeated intermediate font tier must remain prose; got: {heading_map:?}"
        );
    }

    #[test]
    fn test_build_heading_map_sparse_multi_page_does_not_promote_repeated_mid_page_display_text() {
        let all_page_segments = vec![
            vec![
                seg_with_font("Body paragraph one.", 12.0),
                seg_with_font("Repeated display text", 24.0),
            ],
            vec![
                seg_with_font("Body paragraph two.", 12.0),
                seg_with_font("Repeated pull quote", 24.0),
            ],
        ];
        let struct_tree_results = vec![None, None];
        let heuristic_pages = vec![0usize, 1usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        assert!(
            heading_map.iter().all(|(_, level)| level.is_none()),
            "repeated mid-page display text must remain prose in sparse documents; got: {heading_map:?}"
        );
    }

    /// Sparsity gate: a two-block document (the `issue-987-test.pdf` shape) with
    /// a larger first line must NOT promote either line to a heading.
    #[test]
    fn test_build_heading_map_two_block_doc_no_heading_promotion() {
        let all_page_segments = vec![vec![seg_with_font("Big Text", 24.0), seg_with_font("Small Text", 12.0)]];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        assert!(
            heading_map.iter().all(|(_, level)| level.is_none()),
            "2-block doc must not promote either line to a heading; got: {heading_map:?}"
        );
    }

    /// The sparsity gate must fire strictly below `MIN_BLOCKS_FOR_FONT_HEADING`:
    /// a document at exactly the floor (five blocks) still promotes its title,
    /// so genuine short documents keep their heading.
    #[test]
    fn test_build_heading_map_at_block_floor_still_promotes() {
        let mut segs = vec![seg_with_font("Section Title", 18.0)];
        segs.extend(
            (0..(MIN_BLOCKS_FOR_FONT_HEADING - 1)).map(|i| seg_with_font(&format!("Body paragraph {i}."), 11.0)),
        );

        let all_page_segments = vec![segs];
        let struct_tree_results = vec![None];
        let heuristic_pages = vec![0usize];

        let (heading_map, _) = build_heading_map(&all_page_segments, &struct_tree_results, &heuristic_pages, 4)
            .expect("build_heading_map must succeed");

        let title_entry = heading_map.iter().find(|(fs, _)| (*fs - 18.0).abs() < 0.5);
        assert_eq!(
            title_entry.and_then(|(_, level)| *level),
            Some(1),
            "at the block floor the title must still be promoted; got: {heading_map:?}"
        );
    }

    /// Segment with explicit font_size and baseline_y for heuristic-path tests.
    fn seg_heuristic(text: &str, font_size: f32, baseline_y: f32) -> SegmentData {
        SegmentData {
            text: text.to_string(),
            x: 10.0,
            y: baseline_y,
            width: 200.0,
            height: font_size,
            font_size,
            is_bold: false,
            is_italic: false,
            is_monospace: false,
            baseline_y,
            assigned_role: None,
        }
    }

    /// Heuristic path: two segments at different font sizes (triggering a split in
    /// blocks_to_paragraphs) that are a sentence continuation should be re-joined
    /// by merge_continuation_paragraphs.
    #[test]
    fn test_heuristic_path_merges_font_split_continuation() {
        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: vec![
                    seg_heuristic("een indicative", 12.0, 700.0),
                    seg_heuristic("van toenemende merkbekendheid", 13.8, 680.0),
                ],
                page_hints: None,
                table_bboxes: vec![],
                preserve_native_semantics: false,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: vec![],
                #[cfg(feature = "layout-detection")]
                page_width_pts: None,
                needs_classify: false,
                paragraph_gap_ys: vec![],
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );
        assert_eq!(
            output.len(),
            1,
            "continuation paragraph split by font change should be merged on heuristic path"
        );
        assert!(
            output[0].text.is_empty(),
            "merged paragraph must have cleared text so assembly joins from segments"
        );
        let all_text: String = output[0]
            .lines
            .iter()
            .flat_map(|l| l.segments.iter())
            .map(|s| s.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            all_text.contains("een indicative"),
            "first fragment must survive in merged segments; got: {all_text:?}"
        );
        assert!(
            all_text.contains("van toenemende merkbekendheid"),
            "second fragment must survive in merged segments; got: {all_text:?}"
        );
    }

    /// Heuristic path: a sentence-terminating paragraph followed by an
    /// uppercase-starting paragraph must NOT be merged.
    #[test]
    fn test_heuristic_path_does_not_merge_terminated_sentences() {
        let output = process_single_page(
            PageInput {
                page_index: 0,
                struct_paragraphs: None,
                heuristic_segments: vec![
                    seg_heuristic("The first sentence ends here.", 12.0, 700.0),
                    seg_heuristic("New sentence starts uppercase.", 13.8, 680.0),
                ],
                page_hints: None,
                table_bboxes: vec![],
                preserve_native_semantics: false,
                use_layout_reading_order: false,
                #[cfg(feature = "layout-detection")]
                hint_validations: vec![],
                #[cfg(feature = "layout-detection")]
                page_width_pts: None,
                needs_classify: false,
                paragraph_gap_ys: vec![],
                include_headers: true,
                include_footers: true,
            },
            &[],
            None,
        );
        assert_eq!(
            output.len(),
            2,
            "terminated sentence followed by uppercase must not be merged"
        );
    }

    /// Verify that non-contiguous index ranges across pages are handled correctly.
    #[test]
    fn test_image_index_offset_non_contiguous_pages() {
        let page1_indices: Vec<usize> = vec![0, 1];
        let page2_indices: Vec<usize> = vec![100, 101];

        for (indices, expected_first) in [(&page1_indices, 0usize), (&page2_indices, 100usize)] {
            let first_idx = indices.iter().copied().min().unwrap_or(0);
            assert_eq!(
                first_idx, expected_first,
                "first_idx_on_page must equal the minimum index in the slice"
            );

            let set: ahash::AHashSet<usize> = indices.iter().copied().collect();
            for current_image in 0..2usize {
                let global_idx = first_idx + current_image;
                assert!(
                    set.contains(&global_idx),
                    "global index {global_idx} must be found for page with first_idx={first_idx}"
                );
            }
        }
    }
}

#[cfg(test)]
mod list_marker_tests {
    use super::{is_bare_list_marker, looks_like_list_item};

    #[test]
    fn bare_markers_are_detected() {
        assert!(is_bare_list_marker("1."));
        assert!(is_bare_list_marker("12)"));
        assert!(is_bare_list_marker("a."));
        assert!(is_bare_list_marker("a)"));
        assert!(is_bare_list_marker("I."));
        assert!(is_bare_list_marker("(1)"));
        assert!(is_bare_list_marker("(2)"));
        assert!(is_bare_list_marker("[1]"));
        assert!(is_bare_list_marker(""));
    }

    #[test]
    fn prose_fragments_are_not_bare_markers() {
        assert!(!is_bare_list_marker("etc."));
        assert!(!is_bare_list_marker("Inc."));
        assert!(!is_bare_list_marker("(appendix)"));
        assert!(!is_bare_list_marker("Item"));
        assert!(!is_bare_list_marker(""));
    }

    #[test]
    fn newline_separated_marker_and_text_is_a_list_item() {
        assert!(looks_like_list_item("1.\nÉnumération 1"));
        assert!(looks_like_list_item("1. First point"));
        assert!(looks_like_list_item("123. One hundred twenty-third point"));
        assert!(looks_like_list_item("999. Nine hundred ninety-ninth point"));
        assert!(!looks_like_list_item("1000. Four-digit identifier"));
        assert!(looks_like_list_item("viii. eighth item"));
        assert!(looks_like_list_item("(2)\nsecond item"));
        assert!(looks_like_list_item("[1] bracketed item"));
    }

    #[test]
    fn four_digit_year_is_not_a_list_item() {
        assert!(!looks_like_list_item("2023. A total of 3 trucks were used"));
    }

    #[test]
    fn section_headings_are_not_list_items() {
        assert!(!looks_like_list_item("3.2 Methods"));
        assert!(!looks_like_list_item("IV. Results"));
        assert!(!looks_like_list_item("1. INTRODUCTION"));
    }

    #[test]
    fn prose_words_ending_with_period_are_not_list_markers() {
        assert!(!looks_like_list_item("tua. At vero eos et accusam"));
        assert!(!looks_like_list_item("etc. and more prose"));
        assert!(looks_like_list_item("a. first item"));
        assert!(looks_like_list_item("iv. fourth item"));
    }

    #[test]
    fn typographic_dash_requires_an_inline_body() {
        assert!(looks_like_list_item("– first item"));
        assert!(looks_like_list_item("\tsecond item"));
        assert!(looks_like_list_item("– “quoted item”"));
        assert!(looks_like_list_item("— (parenthesized item)"));
        assert!(!looks_like_list_item("\n457"));
        assert!(!looks_like_list_item("\n457"));
        assert!(!looks_like_list_item("\t\nbody"));
        assert!(!looks_like_list_item("\n8 show the remaining figures"));
        assert!(!looks_like_list_item("—continuation"));
    }

    #[test]
    fn author_initials_are_not_list_markers() {
        assert!(!looks_like_list_item(
            "O. Sanni, A.P.I. Popoola / Data in Brief 22 (2019) 451"
        ));
        assert!(!looks_like_list_item("O. Sanni, A. Popoola / Data in Brief"));
        assert!(looks_like_list_item("A. First item"));
        assert!(looks_like_list_item("a. first item"));
        assert!(looks_like_list_item("A. Compare input, output / behavior"));
    }
}