flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
//! Merge selected pages from multiple PDF documents into a new document.
//!
//! qpdf correspondence: `QPDF::copyForeignObject` and page-insertion primitives.
//!
//! Production `QPDFJob::handlePageSpecs` keeps the primary document in place in
//! [`super::page_specs`]; this module's [`merge_documents`] is a separate
//! fresh-target Rust API.
//!
//! [`merge_documents`] copies selected pages from N source documents into one
//! fresh target. `inputs[0]` is the primary: its Catalog/trailer state is the
//! document base, with page-tree, PageLabels, and AcroForm fields updated by
//! the merge-specific consumers; later inputs contribute pages and form fields
//! only. Shared resources within one input are de-duplicated; form-field name
//! collisions are resolved by qpdf's `<name>+<N>` renaming rule.
//!
//! `/PageLabels` is the one document-level structure that is **not**
//! primary-only: it is reconstructed from every input's own labels, one entry
//! per selected page in output order, matching qpdf's `handlePageSpecs`
//! (which calls `getLabelsForPageRange` for each selected page regardless of
//! which input file it came from). No input's named destinations or outline
//! items are copied at all beyond the primary — those structures are not
//! part of any page's object closure, and qpdf's own page-copy mechanism
//! (`addPage` / `copyForeignObject`) never reaches a source document's
//! catalog-level `/Names /Dests`, legacy `/Dests`, or `/Outlines`.
//! Consequently no named-destination "collision" between inputs is possible
//! here (there is nothing from a secondary input to collide with).
//!
//! The target document is built via [`Pdf::empty`] (qpdf's
//! `QPDF::emptyPDF()`). Its merge-specific union copy retains the primary
//! Catalog/trailer graph and the AcroForm handling needed by
//! `QPDFJob::handlePageSpecs`; the primary source is flattened by the
//! qpdf-shaped `removePage` route before its selected pages are copied, while
//! foreign sources are prepared through
//! [`PageDocumentHelper::push_inherited_attributes_to_pages`]. Each copied
//! leaf is reparented through a live destination handle, matching qpdf's
//! `insertPage` boundary. Neither the empty-document construction nor this
//! page preparation touches PDF version, so the returned document keeps
//! `emptyPDF()`'s own header version (`"1.3"`) rather than any input's version.
//! Propagating an input's version, as the qpdf CLI's `--pages` does, is
//! `QPDFJob` orchestration layered on top of these library primitives — a
//! distinct responsibility this function does not implement.

use super::acroform_field_prune::DEFAULT_MAX_ACROFORM_DEPTH;
use super::resource_pruning::{should_remove_unreferenced_resources, RemoveUnreferencedResources};
use crate::object_copy::{
    copy_foreign_object_for_preserve, copy_foreign_object_with_stale_generation_policy,
    copy_foreign_value_with_stale_generation_policy,
};
use crate::page_extract::{append_selection_kids, null_copied_removed_pages, target_pages_root};
use crate::page_label_document_helper::{
    copy_raw_page_label_entries, merge_adjacent_raw_page_labels, record_primary_label_provenance,
    RawPageLabelEntry,
};
use crate::pages::page_refs;
use crate::pdf::WriterObjectOrderKey;
use crate::pdf_string::{new_unicode_string, utf8_value};
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::{
    AcroFormDocumentHelper, Error, ObjectHandle, ObjectRef, ObjectStreamMode, PageDocumentHelper,
    PageObjectHelper, Pdf, Result, XrefEntry,
};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Read, Seek};

/// One merge input: an opened source document and the 0-based page indices to
/// take from it (arbitrary order, duplicates allowed).
pub struct MergeInput<'a, R: Read + Seek + 'static> {
    /// The opened source document.
    ///
    /// The borrow lasts only for the merge call, but a provider-backed stream
    /// copied from this source remains lazy in the returned document and is
    /// re-read from this source on every later write or read of the returned
    /// document, not only the first. Keep the source [`Pdf`] alive for as
    /// long as the returned document may still access that copied stream, or
    /// call [`Pdf::set_immediate_copy_from`] on the source before merging when
    /// it must be released earlier. Parsed file-backed streams capture their
    /// input source separately and do not require this `Pdf` to remain alive.
    pub source: &'a mut Pdf<R>,
    /// 0-based page indices to copy, in output order.
    pub pages: Vec<usize>,
}

/// Project the persistent qpdf raw foreign-copy map at the page-merge
/// consumers that operate on parser-valid source references. Raw entries stay
/// in the canonical map owned by Pdf; this view is deliberately lossy only at
/// the public page/field ObjectRef boundary.
fn project_foreign_object_map(
    raw_map: &BTreeMap<QpdfObjGen, ObjectRef>,
) -> BTreeMap<ObjectRef, ObjectRef> {
    raw_map
        .iter()
        .filter_map(|(object_gen, target_ref)| {
            object_gen
                .to_object_ref()
                .map(|source_ref| (source_ref, *target_ref))
        })
        .collect()
}

// Primary Catalog and trailer values are copied directly through the canonical
// ObjectHandle foreign copier below. qpdf keeps the primary document in place
// during `handlePageSpecs`; no legacy closure snapshot is needed here.

/// Copy every non-`/Pages` primary Catalog value through the destination's
/// persistent qpdf-shaped foreign copier. qpdf keeps the primary Catalog in
/// place while `handlePageSpecs` mutates its page-owned `/Pages` key
/// (`QPDFJob.cc:2462-2472`); the fresh target supplies that one key itself.
fn wire_primary_catalog<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
    source_id: u64,
    remove_stale_generations: bool,
) -> Result<()> {
    // qpdf's `getRoot()` accepts both an indirect reference and an inline
    // Catalog. Use the resolved handle for the semantic Catalog operation;
    // `root_ref()` is only an optional identity projection and cannot represent
    // a direct trailer value.
    let source_catalog = source.root_handle()?;
    let target_catalog = target.root_handle()?;

    for key in source_catalog.try_get_keys()? {
        if key == b"/Pages" {
            continue;
        }
        let value = source_catalog.try_get_key(&key)?;
        let copied = copy_foreign_value_with_stale_generation_policy(
            target,
            source_id,
            &value,
            remove_stale_generations,
        )?; // cov:ignore: qpdf primary Catalog copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
        target_catalog.replace_key(&key, copied)?;
    }
    Ok(())
}

/// Copy the primary root `/Pages` dictionary's non-structural values into the
/// fresh target root. qpdf keeps this root in place while `removePage` and
/// `addPage` replace only `/Kids` and `/Count`; unknown root keys therefore
/// remain visible to the writer (`QPDF_pages.cc:166-177,239-250`).
fn wire_primary_pages_root<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
    source_id: u64,
    target_pages_ref: ObjectRef,
    remove_stale_generations: bool,
) -> Result<()> {
    let source_catalog = source.root_handle()?;
    let source_pages = source_catalog.try_get_key(b"/Pages")?;
    source_pages.try_dereference()?;
    let target_pages = target.get_object_handle(target_pages_ref);
    target_pages.try_dereference()?;

    for key in source_pages.try_get_keys()? {
        if matches!(
            key.as_slice(),
            b"/Type"
                | b"/Parent"
                | b"/Kids"
                | b"/Count"
                | b"/MediaBox"
                | b"/CropBox"
                | b"/Resources"
                | b"/Rotate"
        ) {
            continue;
        }
        let value = source_pages.try_get_key(&key)?;
        let copied = copy_foreign_value_with_stale_generation_policy(
            target,
            source_id,
            &value,
            remove_stale_generations,
        )?; // cov:ignore: qpdf primary /Pages copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
        target_pages.replace_key(&key, copied)?;
    }
    Ok(())
}

/// Preserve a direct primary trailer `/Root` after the fresh target has
/// finished its Catalog mutations. qpdf writes a direct Catalog value
/// directly from the trailer, while `Pdf::empty()` starts with an indirect
/// Catalog; remove that temporary target slot so preserve-unreferenced cannot
/// emit an extra unreachable Catalog (`QPDF.cc:2349-2358`; `QPDFWriter.cc:
/// 1144-1155,2907-2925`).
fn preserve_primary_root_shape<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
) -> Result<()> {
    if source.root_ref().is_some() {
        return Ok(());
    }
    let temporary_root_ref = target.root_ref();
    let target_root = target.root_handle()?;
    target_root.try_dereference()?;
    let direct_root = target_root.shallow_copy()?;
    target.trailer().replace_key(b"/Root", direct_root)?;
    if let Some(temporary_root_ref) = temporary_root_ref {
        target.remove_object_handle(temporary_root_ref)?; // cov:ignore: direct-root unit and CLI tests execute this cleanup; LLVM attributes the generic call body to reader.rs.
    } // cov:ignore: the direct-root cleanup branch is exercised; LLVM maps its generic call terminator to the block exit.
    Ok(())
}

/// Copy the primary trailer's non-writer-owned values through the same
/// persistent foreign copier. qpdf rebuilds `/Root`, `/Size`, encryption,
/// and xref-history keys at the writer boundary; `/Info`, `/ID`, and unknown
/// trailer entries remain primary-owned (`QPDFWriter.cc:2907-2913`).
fn wire_primary_trailer<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
    source_id: u64,
    remove_stale_generations: bool,
) -> Result<()> {
    let source_trailer = source.trailer();
    let target_trailer = target.trailer();
    // cov:ignore-start: this helper is called with Pdf::empty(), whose
    // construction contract always supplies a target catalog root.
    let Some(root_ref) = target.root_ref() else {
        return Ok(());
    };
    // cov:ignore-end
    for key in source_trailer.try_get_keys()? {
        if matches!(
            key.as_slice(),
            b"/Root"
                | b"/Size"
                | b"/Prev"
                | b"/Encrypt"
                | b"/Type"
                | b"/W"
                | b"/Index"
                | b"/XRefStm"
                | b"/Length"
                | b"/Filter"
                | b"/DecodeParms"
        ) {
            continue;
        }
        let value = source_trailer.try_get_key(&key)?;
        let copied = copy_foreign_value_with_stale_generation_policy(
            target,
            source_id,
            &value,
            remove_stale_generations,
        )?; // cov:ignore: qpdf primary trailer copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
        target_trailer.replace_key(&key, copied)?;
    }
    target_trailer.replace_key(b"/Root", target.get_object_handle(root_ref))?;
    Ok(())
}

/// Recreate qpdf's primary source-ObjStm ownership on a fresh merge target.
///
/// `QPDFJob::handlePageSpecs` keeps the primary QPDF in place, so the writer's
/// `preserveObjectStreams` sees its original type-2 xref rows. flpdf's
/// canonical foreign copier correctly transfers the logical member objects,
/// but the fresh target needs an equivalent target-owned placeholder for each
/// source container and a type-2 row for each copied member before the plain
/// Preserve planner runs (`QPDFWriter.cc:1939-1967`). The placeholder stream
/// carries only the source `/Extends` chain; the writer rebuilds its body from
/// the copied member handles, as qpdf does (`QPDFWriter.cc:1621-1740`).
///
/// `source_object_stream_membership` is the source's own
/// `QPDF::getObjectStreamData` snapshot (`crates/flpdf/src/reader.rs::
/// Pdf::get_object_stream_data`), taken at the same pre-mutation instant as
/// `source_xref_entries`; it drives which members belong to which container.
/// `source_xref_entries` is consulted only for each member's stream `index`,
/// a field `getObjectStreamData`'s own `std::map<int, int>` does not carry
/// (`libqpdf/QPDF.cc:2381-2390`) and which the writer recomputes from its own
/// object-stream-to-objects order rather than reading back
/// (`QPDFWriter.cc:2163-2168`); reusing the source's original value here
/// keeps the placeholder row's shape faithful to a real type-2 entry without
/// fabricating one.
fn install_primary_object_stream_membership<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
    source_object_stream_membership: &BTreeMap<u32, u32>,
    source_xref_entries: &BTreeMap<ObjectRef, XrefEntry>,
    copied: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
    let mut target_containers = BTreeMap::new();
    for (&source_member_number, &stream) in source_object_stream_membership {
        // A type-2 xref row is always registered at generation 0
        // (`crates/flpdf/src/xref.rs`'s xref-stream parser maps object type
        // `0 | 2` to generation 0), matching qpdf's own compressed-object
        // invariant, so `source_xref_entries` always has an entry at this key.
        let source_member = ObjectRef::new(source_member_number, 0);
        let Some(&target_member) = copied.get(&source_member) else {
            continue;
        };
        let Some(XrefEntry::Compressed { index, .. }) = source_xref_entries.get(&source_member)
        else {
            continue; // cov:ignore: source_object_stream_membership is derived from source_xref_entries, so this row is always Compressed
        };
        let target_container = ensure_object_stream_container(
            source,
            target,
            ObjectRef::new(stream, 0),
            &mut target_containers,
            copied,
        )?; // cov:ignore: malformed source ObjStm container errors propagate at this boundary
        target.install_object_stream_member(target_member, target_container, *index);
    }
    Ok(())
}

/// Allocate one target-owned source-container placeholder and preserve its
/// indirect `/Extends` chain. The body, `/N`, `/First`, and filter are emitted
/// by the plain writer from the retained members rather than copied here.
fn ensure_object_stream_container<RS: Read + Seek, RT: Read + Seek>(
    source: &mut Pdf<RS>,
    target: &mut Pdf<RT>,
    source_container: ObjectRef,
    target_containers: &mut BTreeMap<ObjectRef, ObjectRef>,
    copied: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<ObjectRef> {
    // Walk the `/Extends` chain iteratively. The chain is only bounded by the
    // number of containers in the source, and a recursive walk would grow the
    // stack with it, which `.claude/rules/pdf-rust-review-patterns.md` section 4
    // rules out. qpdf has no counterpart to walk: it follows `/Extends` a single
    // hop while unparsing the container dictionary
    // (`QPDFWriter.cc:1727-1737`).
    let mut chain = Vec::new();
    let mut current = Some(source_container);
    while let Some(container) = current {
        if target_containers.contains_key(&container) || chain.contains(&container) {
            break;
        }
        // The canonical foreign copier may already own this container: a source
        // ObjStm without `/Type /ObjStm` is not skipped by the preserve loop,
        // and qpdf identifies containers by the type-2 xref row rather than the
        // dictionary key (`QPDF.cc:2381-2390`). Reusing that copy keeps one
        // identity per container, as qpdf does — `writeObjectStream` knows a
        // single `old_og` (`QPDFWriter.cc:1626-1629`).
        if let Some(&already_copied) = copied.get(&container) {
            target_containers.insert(container, already_copied);
            break;
        }
        chain.push(container);
        current = {
            let source_stream = source.get_object_handle(container);
            source_stream.try_dereference()?;
            source_stream
                .as_stream_dict()
                .map(|dictionary| dictionary.try_get_key(b"/Extends"))
                .transpose()?
                .and_then(|extends| extends.object_ref())
        };
    }

    // Copy the containers themselves rather than allocating empty streams. A
    // container whose members are all retained is rewritten from its members by
    // the writer, but one with no retained member stays an ordinary stream in
    // qpdf's output: `writeObjectStream` only runs for streams present in
    // `object_stream_to_objects` (`QPDFWriter.cc:2163-2170`), so an
    // `/Extends`-only target keeps its original `/Type /ObjStm`, `/N`, `/First`
    // and body. Allocating a data-less stream instead both blanked that object
    // and left routes that bypass the plain writer (`--qdf`,
    // `--normalize-content`) with a stream that has no data to pipe.
    for &container in chain.iter().rev() {
        let source_stream = source.get_object_handle(container);
        source_stream.try_dereference()?;
        let target_stream = copy_foreign_object_for_preserve(target, &source_stream)?;
        let target_container = target_stream.object_ref().ok_or(Error::Internal(
            "copied ObjStm container lost its object identity".to_owned(),
        ))?;
        target_containers.insert(container, target_container);
    }

    target_containers
        .get(&source_container)
        .copied()
        .ok_or(Error::Internal(
            "ObjStm container copy did not register its source identity".to_owned(),
        ))
}

/// Resolve qpdf's `--pages` form-field name collision: return `base` when it is
/// not yet present in `used`, otherwise the first unused `base+1`, `base+2`, …
///
/// This reproduces qpdf 11.9.0's observed renaming: `name`+`name` →
/// `name`, `name+1`; a three-way collision → `name`, `name+1`, `name+2`; and a
/// candidate that itself collides is re-resolved (a field originally named
/// `name+1` whose `name+1` is already taken becomes `name+1+1`).
pub(crate) fn unique_field_name(base: &[u8], used: &BTreeSet<Vec<u8>>) -> Vec<u8> {
    if !used.contains(base) {
        return base.to_vec();
    }
    for n in 1u32.. {
        let mut candidate = base.to_vec();
        candidate.extend_from_slice(format!("+{n}").as_bytes());
        if !used.contains(&candidate) {
            return candidate;
        }
    }
    unreachable!("u32 candidate space exhausted") // cov:ignore: 2^32 colliding names is unreachable
}

/// A top-level AcroForm field copied into the target, paired with the partial
/// name (`/T`) read from its source. `partial_name` is `None` for a field with
/// no direct `/T` (such a field is appended without a name-collision check).
struct KeptField {
    /// The field's object ref in the merged target document.
    target_ref: ObjectRef,
    /// The field's `/T` partial name as read from the source (resolved).
    partial_name: Option<Vec<u8>>,
    /// Whether the field came from the primary input (`inputs[0]`).
    is_primary: bool,
}

/// The primary input's inherited `/AcroForm` defaults, captured before copying
/// and remapped onto the merged output's `/AcroForm`.
#[derive(Default)]
struct PrimaryAcroForm {
    /// Whether the primary has a `/DR` default-resource entry. The Catalog
    /// copier carries the value itself; this flag preserves qpdf's decision to
    /// retain an otherwise field-less `/AcroForm`.
    has_dr: bool,
    /// Whether the primary has a `/DA` default-appearance entry.
    has_da: bool,
    /// Whether the primary has an `/AcroForm` dictionary whose `/Fields`
    /// resolves to an array (qpdf's `hasAcroForm() && fields.isArray()`
    /// gate, `QPDFJob.cc:2609-2610`). Drives [`build_merged_acroform`]'s
    /// decision to rebuild or remove `/AcroForm`, independent of `/DR`/`/DA`.
    had_fields_array: bool,
    /// Whether the primary's original `/Fields` array was held indirectly.
    /// qpdf preserves that holder shape when it installs the filtered array
    /// (`QPDFJob.cc:2615-2618`).
    fields_are_indirect: bool,
    /// Original names of every primary top-level field, including fields on
    /// pages that are not selected. qpdf keeps those fields in its collision
    /// index until the final page-pruning pass (`QPDFJob.cc:2516-2521,
    /// 2600-2629`), so later inputs must not reuse their names or suffixes.
    original_field_names: BTreeSet<Vec<u8>>,
}

/// Read the primary input's AcroForm shape through canonical handles. The
/// Catalog copy below owns the actual `/DR` and `/DA` graph transfer; this
/// snapshot only carries the qpdf field-rebuild gates.
fn discover_primary_acroform<R: Read + Seek>(source: &mut Pdf<R>) -> Result<PrimaryAcroForm> {
    // `QPDFJob::handlePageSpecs` constructs the primary AcroForm helper only
    // after it has removed every primary page (`QPDFJob.cc:2514-2521`). The
    // pre-removal snapshot therefore must read the field tree without running
    // the helper's page-based orphan-widget pass; otherwise a direct Widget
    // on the still-present primary page is warned before qpdf would ever scan
    // that page set.
    let had_fields_array = {
        let mut acroform = AcroFormDocumentHelper::new_for_field_tree(source)?;
        acroform.has_fields_array()?
    };
    let mut out = PrimaryAcroForm {
        had_fields_array,
        ..Default::default()
    };
    let root = source.root_handle()?;
    let acroform = root.try_get_key(b"/AcroForm")?;
    acroform.try_dereference()?;
    if acroform.try_is_dictionary()? {
        let dr = acroform.try_get_key(b"/DR")?;
        let da = acroform.try_get_key(b"/DA")?;
        out.has_dr = !dr.try_is_null()?;
        out.has_da = !da.try_is_null()?;
        let fields = acroform.try_get_key(b"/Fields")?;
        out.fields_are_indirect = fields.is_indirect() && fields.try_is_array()?;
    }
    Ok(out)
}

/// Read the partial names (`/T`, resolved) of `source`'s top-level AcroForm
/// fields, in `/Fields` order, paired with the source field ref so a caller can
/// map the ref through that input's copy map. A field whose `/T` is absent
/// yields `None`.
pub(crate) fn source_top_level_field_names<R: Read + Seek>(
    source: &mut Pdf<R>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
    let top_fields = source.acroform()?.top_level_fields()?;
    source_top_level_field_names_from_refs(source, top_fields)
}

/// Read top-level field names through qpdf's field-tree-only construction.
///
/// The page job uses this before removing the primary page tree. qpdf does not
/// construct the primary's full `QPDFAcroFormDocumentHelper` until after that
/// removal (`QPDFJob.cc:2514-2521`), so this snapshot must not run the eager
/// page-based orphan-widget scan.
fn source_top_level_field_names_without_page_scan<R: Read + Seek>(
    source: &mut Pdf<R>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
    let top_fields = {
        let mut acroform = AcroFormDocumentHelper::new_for_field_tree(source)?;
        acroform.top_level_fields()?
    };
    source_top_level_field_names_from_refs(source, top_fields)
}

fn source_top_level_field_names_from_refs<R: Read + Seek>(
    source: &mut Pdf<R>,
    top_fields: Vec<ObjectRef>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
    let mut out = Vec::with_capacity(top_fields.len());
    for field_ref in top_fields {
        // A top-level `/Fields` element may be a holder chain (a ref to a ref to
        // the field dict). The copy map keys the field by its TERMINAL ref, so
        // normalize to the terminal before recording it — otherwise `map.get` on
        // the holder ref misses and the field is dropped from the merged form. The
        // terminal also feeds the `/T` lookup so a name behind a holder is read.
        let field_handle = source.get_object_handle(field_ref);
        let terminal = field_handle.object_ref().unwrap_or(field_ref);
        field_handle.try_dereference()?;
        let name = resolve_field_partial_name(source, terminal)?;
        out.push((terminal, name));
    }
    Ok(out)
}

/// Resolve a field's `/T` partial name, decoded to qpdf's UTF-8 view. `/T`
/// may be an indirect reference (review rule 2); a resolved non-string or
/// absent `/T` yields `None`.
///
/// qpdf's collision index compares `getFullyQualifiedName()`, itself built
/// from `getUTF8Value()`-decoded `/T` segments
/// (`QPDFFormFieldObjectHelper::getFullyQualifiedName`,
/// `QPDFAcroFormDocumentHelper.cc:82-103`) — never the raw stored bytes. A
/// `/T` stored as UTF-16BE (or PDFDocEncoded with non-ASCII bytes) must
/// therefore be decoded before it is stored or compared here, or an ASCII
/// collision candidate could byte-mismatch a semantically identical reserved
/// name and collide with it in the output.
fn resolve_field_partial_name<R: Read + Seek>(
    source: &mut Pdf<R>,
    field_ref: ObjectRef,
) -> Result<Option<Vec<u8>>> {
    let field_handle = source.get_object_handle(field_ref);
    field_handle.try_dereference()?;
    let field = field_handle;
    if !field.try_is_dictionary()? {
        return Ok(None);
    }
    let t_value = field.try_get_key(b"/T")?;
    if t_value.try_is_null()? {
        return Ok(None);
    }
    // `/T` may be stored through more than one indirect hop; follow the whole
    // chain (not a one-hop resolve) so a multi-hop name string is read and
    // used for collision renaming rather than yielding `None`.
    let resolved = t_value.clone();
    resolved.try_dereference()?;
    Ok(resolved.as_string().map(|raw| utf8_value(&raw)))
}

/// Remove `/AcroForm` from the target's catalog, if present.
///
/// The canonical primary Catalog copier places the primary's `/AcroForm`
/// on the target verbatim (unpruned) before [`build_merged_acroform`] runs.
/// qpdf removes `/AcroForm` entirely once the filtered field count reaches 0
/// (`QPDFJob.cc:2626-2629`, `pdf.getRoot().removeKey("/AcroForm")`); this
/// mirrors that removal for the case where nothing else rebuilds the key.
fn remove_target_acroform<R: Read + Seek>(target: &mut Pdf<R>) -> Result<()> {
    let Some(catalog_ref) = target.root_ref() else {
        return Ok(()); // cov:ignore: the seed target always has a /Root catalog
    };
    let catalog_handle = target.get_object_handle(catalog_ref);
    catalog_handle.try_dereference()?;
    let catalog = catalog_handle;
    if !catalog.try_is_dictionary()? {
        return Ok(()); // cov:ignore: the seed catalog is always a dict
    }
    catalog.remove_key(b"/AcroForm");
    Ok(())
}

/// Build the merged output's `/AcroForm` from the primary's inherited `/DR` /
/// `/DA` base plus every kept top-level field, applying qpdf's `+N` name
/// collision renaming to fields from later inputs.
///
/// Primary fields keep their names verbatim (they seed the `used` set); a later
/// input's field name is resolved through [`unique_field_name`] and written
/// back onto the copied field as a direct `/T` string. No `/AcroForm` is created
/// when there are no kept fields and the primary carried no `/DR` / `/DA`, so a
/// form-free merge gains no empty `/AcroForm`.
fn build_merged_acroform<R: Read + Seek>(
    target: &mut Pdf<R>,
    primary: &PrimaryAcroForm,
    kept: &[KeptField],
) -> Result<()> {
    // qpdf's final field-prune gate is the original `/Fields` array, not the
    // presence of `/DR` or `/DA` (`QPDFJob.cc:2609-2614`). If that key was
    // absent and no selected foreign field requires `addFormField`, retain the
    // primary AcroForm exactly as the Catalog copier installed it.
    if kept.is_empty() && !primary.had_fields_array {
        return Ok(());
    }
    if kept.is_empty() && !primary.has_dr && !primary.has_da {
        if primary.had_fields_array {
            // The primary had a /Fields array (so the generic catalog copy
            // placed a real, now-stale /AcroForm on the target) but every
            // field's page was dropped from the selection. Remove it to
            // match qpdf instead of leaving the unpruned copy in place.
            remove_target_acroform(target)?;
        }
        return Ok(());
    }

    // The target is still a transient grouped copy here: repeated-page
    // annotations have not yet gone through the qpdf `fixCopiedAnnotations`
    // replay. Construct only the field-tree cache so that those pending
    // annotations are not reported as source-document orphans.
    let acroform =
        AcroFormDocumentHelper::new_for_field_tree(target)?.canonical_get_or_create_acroform()?;
    if !acroform.try_is_dictionary()? {
        return Ok(()); // cov:ignore: ensure_acroform_ref always yields a dictionary
    }

    // Seed `used` with the primary's field names (verbatim — the primary is the
    // base document and is never renamed), then append every kept field, in
    // order, renaming later inputs' colliding names via the qpdf `+N` rule.
    let mut used = primary.original_field_names.clone();
    for field in kept {
        if field.is_primary {
            if let Some(name) = &field.partial_name {
                used.insert(name.clone());
            }
        }
    }

    let mut fields = Vec::with_capacity(kept.len());
    for field in kept {
        if !field.is_primary {
            if let Some(name) = &field.partial_name {
                let unique = unique_field_name(name, &used);
                used.insert(unique.clone());
                // qpdf only rewrites `/T` when an actual collision produced a
                // suffix (`if (!append.empty())`,
                // `QPDFAcroFormDocumentHelper.cc:97-102`); a field whose name
                // was already unique keeps its original `/T` bytes/encoding
                // untouched.
                if unique != *name {
                    rename_field(target, field.target_ref, unique)?;
                }
            }
        }
        fields.push(target.get_object_handle(field.target_ref));
    }
    let replacement = ObjectHandle::array(fields);
    let replacement = if primary.fields_are_indirect {
        target.make_indirect_object_handle(replacement)?
    } else {
        replacement
    };
    acroform.replace_key(b"/Fields", replacement)?;

    Ok(())
}

/// Overwrite the copied field's `/T` with `name` (qpdf's UTF-8-decoded,
/// collision-suffixed name), re-encoded through
/// [`new_unicode_string`] to match qpdf's own rename write
/// (`QPDFObjectHandle::newUnicodeString`, `QPDFAcroFormDocumentHelper.cc:99-102`).
fn rename_field<R: Read + Seek>(
    target: &mut Pdf<R>,
    field_ref: ObjectRef,
    name: Vec<u8>,
) -> Result<()> {
    let field_handle = target.get_object_handle(field_ref);
    field_handle.try_dereference()?;
    let field = field_handle;
    if !field.try_is_dictionary()? {
        return Ok(()); // cov:ignore: a copied field ref always resolves to a dictionary
    }
    field.replace_key(b"/T", ObjectHandle::string(new_unicode_string(&name)))?;
    Ok(())
}

/// Read a field's direct `/Kids` as the source-space refs they point at, or
/// `None` when the field has no `/Kids` (a terminal field — the widget IS the
/// field). `/Kids` itself may be an indirect reference (review rule 2); a
/// resolved non-array yields an empty list (treated as "no widget kids").
fn field_kid_refs<R: Read + Seek>(
    source: &mut Pdf<R>,
    field_ref: ObjectRef,
) -> Result<Option<Vec<ObjectRef>>> {
    let field_handle = source.get_object_handle(field_ref);
    field_handle.try_dereference()?;
    let field = field_handle;
    if !field.try_is_dictionary()? {
        return Ok(None);
    }
    let kids_value = field.try_get_key(b"/Kids")?;
    if kids_value.try_is_null()? {
        return Ok(None);
    }
    let resolved = kids_value.clone();
    resolved.try_dereference()?;
    let Some(items) = resolved.try_as_array()? else {
        return Ok(Some(Vec::new())); // cov:ignore: a /Kids value resolves to an array in practice
    };
    let mut refs = Vec::with_capacity(items.len());
    for item in items {
        let terminal_ref = item.object_ref();
        item.try_dereference()?;
        if let Some(r) = terminal_ref {
            // A `/Kids` element may be a reference to a reference to the field/
            // widget; resolve the holder chain to the terminal ref so trimming
            // compares the same ref that retained-`/Annots` membership records.
            refs.push(r);
        } // cov:ignore: llvm-cov gap-region artifact on the brace closing a `?`-bearing block; the body (the `refs.push`) is covered
    }
    Ok(Some(refs))
}

/// Collect the widget annotation refs that appear directly in the selected
/// pages' `/Annots` arrays (the "retained widget refs"). A widget that is a
/// member of a selected page's `/Annots` is on a surviving page and must be kept
/// by [`trim_field_kids`], whether or not it carries the optional `/P`
/// back-pointer (`/P` is not required by ISO 32000-2 §12.5.2 — it is a
/// convenience pointer, so it cannot be the survival signal).
///
/// `/Annots` may be an inline array or an indirect reference to one; each element
/// is an indirect reference to (or an inline) annotation dict. Only the direct
/// annotation refs are recorded — that is what extract uses to decide a widget
/// survives. Reference-holder traversal keeps each source identity before
/// resolving its canonical handle.
fn collect_retained_widget_refs<R: Read + Seek>(
    source: &mut Pdf<R>,
    selected_pages: &BTreeSet<ObjectRef>,
    retained: &mut BTreeSet<ObjectRef>,
) -> Result<()> {
    for &page_ref in selected_pages {
        let page_handle = source.get_object_handle(page_ref);
        page_handle.try_dereference()?;
        let page = page_handle;
        if !page.try_is_dictionary()? {
            continue; // cov:ignore: a selected page ref always resolves to a dictionary
        }
        let annots_val = page.try_get_key(b"/Annots")?;
        if annots_val.try_is_null()? {
            continue;
        }
        // /Annots: an inline array or an indirect reference to one.
        let concrete = annots_val.clone();
        concrete.try_dereference()?;
        let Some(elems) = concrete.try_as_array()? else {
            continue; // cov:ignore: a non-array /Annots is malformed
        };
        for elem in elems {
            let terminal_ref = elem.object_ref();
            elem.try_dereference()?;
            if let Some(r) = terminal_ref {
                // An `/Annots` element may be a reference to a reference to the
                // widget; resolve the holder chain to the terminal widget ref so it
                // matches the field-tree kid ref recorded by `field_kid_refs`.
                retained.insert(r);
            }
        }
    }
    Ok(())
}

/// Resolve a widget's `/P` page reference (review rule 2: `/P` may be indirect),
/// returning the final page `ObjectRef` of the reference chain, or `None` when
/// the widget carries no `/P`.
fn widget_page_ref<R: Read + Seek>(
    source: &mut Pdf<R>,
    widget_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
    let widget_handle = source.get_object_handle(widget_ref);
    widget_handle.try_dereference()?;
    let widget = widget_handle;
    if !widget.try_is_dictionary()? {
        return Ok(None);
    }
    let p_value = widget.try_get_key(b"/P")?;
    if p_value.try_is_null()? {
        // `/P` is optional (ISO 32000-2 §12.5.2): a widget may omit it. Such
        // a widget's survival is decided by retained-`/Annots` membership in
        // trim_field_kids, not by this back-pointer.
        return Ok(None);
    }
    let last_ref = p_value.object_ref();
    p_value.try_dereference()?;
    Ok(last_ref)
}

/// Trim a non-terminal AcroForm field's widget `/Kids` to only the widgets whose
/// `/P` page survived into the output (is in `surviving_pages`), recursing into
/// intermediate sub-fields (fields that themselves carry `/Kids`). Returns:
///
/// - `None` — the field is terminal (no `/Kids`, the widget IS the field); the
///   caller leaves it untouched. This is what protects flat-form fields and the
///   `+N` rename tests, whose widgets carry no `/Kids`.
/// - `Some(survivors)` — the trimmed list of direct kid source-refs to keep. A
///   leaf-widget kid is kept iff it is a `retained_widgets` member (it appears in
///   a selected page's `/Annots`) OR its `/P` resolves to a page in
///   `surviving_pages`; an intermediate sub-field kid is kept iff it has at least
///   one surviving descendant (recursion). An empty `survivors` means no widget
///   survived, so the field should be dropped (top level) or pruned from its
///   parent's `/Kids` (nested).
///
/// The retained-`/Annots` membership is the primary survival signal because a
/// widget's `/P` page back-pointer is optional (ISO 32000-2 §12.5.2); a
/// selected-page widget that omits `/P` must still be kept. The `/P` path is a
/// fallback for a widget reachable through the field tree but not directly listed
/// in a scanned `/Annots`.
///
/// Side effects: rewrites each kept intermediate sub-field's `/Kids` in `target`
/// (mapped through `map`), and records each dropped widget's unselected `/P`
/// page (source-space) into `orphan_pages` so the caller can null it (a dropped
/// widget that also omits `/P` carries no page to null).
///
/// Bounded by `DEFAULT_MAX_ACROFORM_DEPTH` and a `visited` cycle guard (review
/// rule 4): a hostile field tree cannot drive unbounded recursion.
#[allow(clippy::too_many_arguments)]
fn trim_field_kids<R: Read + Seek, T: Read + Seek>(
    source: &mut Pdf<R>,
    target: &mut Pdf<T>,
    field_ref: ObjectRef,
    surviving_pages: &BTreeSet<ObjectRef>,
    retained_widgets: &BTreeSet<ObjectRef>,
    map: &BTreeMap<ObjectRef, ObjectRef>,
    orphan_pages: &mut BTreeSet<ObjectRef>,
    depth: usize,
    visited: &mut BTreeSet<ObjectRef>,
) -> Result<Option<Vec<ObjectRef>>> {
    if depth > DEFAULT_MAX_ACROFORM_DEPTH {
        return Err(Error::Unsupported(format!(
            "AcroForm field tree depth exceeds maximum of {DEFAULT_MAX_ACROFORM_DEPTH}"
        )));
    }
    if !visited.insert(field_ref) {
        return Ok(Some(Vec::new()));
    }
    let Some(kids) = field_kid_refs(source, field_ref)? else {
        return Ok(None); // terminal field — nothing to trim
    };

    let mut survivors: Vec<ObjectRef> = Vec::with_capacity(kids.len());
    for kid_ref in kids {
        let kid_kind = trim_field_kids(
            source,
            target,
            kid_ref,
            surviving_pages,
            retained_widgets,
            map,
            orphan_pages,
            depth + 1,
            visited,
        )?;
        match kid_kind {
            // The kid is itself a non-terminal sub-field.
            Some(sub_survivors) => {
                if sub_survivors.is_empty() {
                    // Whole sub-field is off-tree — prune it from this field's
                    // `/Kids`. Its widgets' orphan pages were recorded by the
                    // recursive call.
                    continue;
                }
                rewrite_field_kids(target, kid_ref, &sub_survivors, map)?;
                survivors.push(kid_ref);
            }
            // The kid is a leaf widget (no `/Kids`). It survives iff it is a
            // retained widget (a member of a selected page's `/Annots`) — the
            // signal extract uses — OR its optional `/P` resolves to a surviving
            // page (a fallback for a widget reached through the field tree but not
            // directly in a scanned `/Annots`). A non-surviving widget's `/P`
            // page, if any, is an off-tree orphan to null; a `/P`-less dropped
            // widget carries no page to null.
            None => {
                if retained_widgets.contains(&kid_ref) {
                    survivors.push(kid_ref);
                } else {
                    match widget_page_ref(source, kid_ref)? {
                        Some(page_ref) if surviving_pages.contains(&page_ref) => {
                            survivors.push(kid_ref)
                        }
                        Some(page_ref) => {
                            orphan_pages.insert(page_ref);
                        }
                        None => {}
                    }
                }
            }
        }
    }
    Ok(Some(survivors))
}

/// Overwrite the copied field's `/Kids` with the surviving source kid-refs
/// mapped through this input's copy map. A survivor missing from `map` is
/// skipped (it was not copied); the rewrite never inserts a dangling ref.
fn rewrite_field_kids<R: Read + Seek>(
    target: &mut Pdf<R>,
    src_field_ref: ObjectRef,
    survivors: &[ObjectRef],
    map: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
    let Some(target_field_ref) = map.get(&src_field_ref).copied() else {
        return Ok(()); // cov:ignore: a survivor's parent field is always in the copy map
    };
    let field_handle = target.get_object_handle(target_field_ref);
    field_handle.try_dereference()?;
    let field = field_handle;
    if !field.try_is_dictionary()? {
        return Ok(()); // cov:ignore: a copied field ref always resolves to a dictionary
    }
    let mut kids = Vec::with_capacity(survivors.len());
    for src in survivors {
        if let Some(&target_ref) = map.get(src) {
            kids.push(target.get_object_handle(target_ref));
        }
    }
    field.replace_key(b"/Kids", ObjectHandle::array(kids))?;
    Ok(())
}

/// Merge selected pages from N sources into one fresh document.
///
/// Each [`MergeInput`] pairs an opened source document with the page indices to
/// take from it. Returns an owned in-memory [`Pdf`] whose catalog has a
/// single-level `/Pages` tree containing the selected pages from every input,
/// concatenated
/// in input order and, within each input, in the order given by that input's
/// `pages`. Each input is copied in a single pass with one renumbering map, so
/// objects shared between selected pages of the same input (fonts, images,
/// content streams) appear once per input in the output.
///
/// Inherited page attributes (`/Resources`, `/MediaBox`, `/CropBox`,
/// `/Rotate`) are materialized onto each copied page from its source page
/// tree, and a page selected more than once within an input becomes a shallow
/// clone of its first copy, matching [`extract_pages`](crate::extract_pages).
///
/// Each source is left unmodified, unless [`Pdf::set_immediate_copy_from`] was
/// enabled on it beforehand: that opt-in materializes each provider-backed
/// stream into the source itself as a side effect of copying it. Each selected
/// page is copied with the persistent [`Pdf::copy_foreign_object`] route; the
/// result mirrors [`extract_pages`](crate::extract_pages) for a single input.
/// Write the result with [`crate::PdfWriter`] to produce one fresh qpdf-style
/// output.
///
/// Provider-backed streams reachable from selected pages or from the primary
/// Catalog/trailer metadata remain lazy and are re-read from their source on
/// every later write or read of the returned document, not only the first.
/// As with qpdf's `QPDF::copyForeignObject`, keep the corresponding source
/// [`Pdf`] alive for as long as the returned document may still access that
/// stream, or call [`Pdf::set_immediate_copy_from`] on that source before
/// this function when early release is required. This rule applies to
/// provider-backed streams only; parsed file-backed streams retain a separate
/// captured input source and can be written after their source `Pdf` is
/// dropped.
///
/// An input may select **no pages** (`pages: vec![]`): it contributes nothing
/// and is not an error. A blank document passed as `inputs[0]` with an empty
/// selection is the qpdf `--empty` analog — the merge then starts from an empty
/// base and inherits no document-level information (a blank primary has none).
///
/// The primary input (`inputs[0]`) remains the document base: its Catalog and
/// trailer metadata (including `/Info`, `/ID`, unknown trailer entries, and
/// unrelated Catalog keys) are copied with indirect references remapped, while
/// the merged page tree and writer-owned trailer structure are rebuilt in the
/// target. Its `/Outlines` tree, `/Names /Dests` named destinations (and the
/// legacy `/Catalog /Dests` dictionary), and `/OpenAction` therefore remain
/// primary-only as part of that Catalog graph. Later inputs contribute pages
/// and selected form fields only — their Catalog/trailer metadata, outlines,
/// and named destinations are not merged. A direct (inline) `/Names /Dests`
/// name-tree root is inherited
/// in either ISO 32000-2 §7.9.6 shape: a `/Names` leaf has its destinations
/// remapped, and a `/Kids` root has its sub-leaves copied and its `/Kids`
/// references remapped to those copies, so the named destinations survive in
/// both forms.
///
/// A destination (annotation `/Dest`, an `/A` or `/AA` `/GoTo` action, including
/// `/Next` continuations and `/GoTo /SD` structure destinations, plus the
/// primary's inherited outline / named / `/OpenAction` destinations) that points
/// at a page not selected from its input keeps its reference, which resolves to
/// a `null` page object in the output.
///
/// A page reached only through a back-pointer from an unselected page — a thread
/// bead's `/P`, a structure element's `/Pg`, or (on malformed input) an
/// annotation's `/P` that names an unselected page rather than the page it sits
/// on — is not yet pruned: it stays out of the output page tree (`/Pages`
/// `/Kids`) but remains a live object in the output, reachable through that
/// surviving back-pointer.
///
/// Interactive form (AcroForm) fields are merged: the primary's `/AcroForm`
/// `/DR` default resources and `/DA` default appearance are the base, and every
/// selected page's top-level field (reached from its widget annotations) is
/// added to the output `/AcroForm /Fields`. A field whose widget is on an
/// unselected page is dropped (qpdf form subset). A non-terminal field whose
/// widget `/Kids` span several pages keeps only the widgets whose page is
/// selected — its `/Kids` are trimmed to those, and the field is dropped
/// entirely only if no widget survives. Top-level field-name (`/T`)
/// collisions are resolved by qpdf's `<name>+<N>` rule: the primary keeps its
/// names and a later input's colliding name becomes the first unused
/// `<name>+1`, `<name>+2`, … . Collision handling is limited to **top-level
/// partial names** (flat forms where the partial name equals the fully-qualified
/// name); nested field-tree fully-qualified-path collisions, and merging later
/// inputs' `/DR` resources, are not handled. A merge of form-free inputs adds no
/// `/AcroForm`.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::{merge_documents, MergeInput, Pdf, PdfWriter};
///
/// let mut a = Pdf::open(BufReader::new(File::open("a.pdf")?))?;
/// let mut b = Pdf::open(BufReader::new(File::open("b.pdf")?))?;
/// let mut inputs = [
///     MergeInput { source: &mut a, pages: vec![0, 1] }, // a's first two pages
///     MergeInput { source: &mut b, pages: vec![0] },    // then b's first page
/// ];
/// let mut merged = merge_documents(&mut inputs)?;
///
/// let mut writer = PdfWriter::new(&mut merged);
/// writer.set_output_file("merged.pdf")?;
/// writer.write()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Errors
///
/// - [`Error::Unsupported`] if the `inputs` slice is empty (an *input* with an
///   empty page selection is permitted; see above), or if a requested page
///   index is out of range for its input.
/// - Propagates resolve/copy errors from the underlying primitives.
pub fn merge_documents<R: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    merge_documents_with_resource_mode(inputs, RemoveUnreferencedResources::No)
}

/// Merge selected pages while applying qpdf's page-job resource mode to the
/// first copy of each selected source page.
///
/// The public [`merge_documents`] library primitive intentionally retains its
/// historical library-level behaviour: resource pruning belongs to
/// `QPDFJob::handlePageSpecs`, not to the generic page insertion primitive.
/// The job route calls this bounded variant so that qpdf's
/// `--remove-unreferenced-resources={auto,yes,no}` decision is made per source
/// before a page enters the canonical foreign-object copier.
pub(crate) fn merge_documents_with_resource_mode<R: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    resource_mode: RemoveUnreferencedResources,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    merge_documents_with_resource_mode_and_preserve_primary(inputs, resource_mode, false)
}

/// Merge selected pages while optionally retaining primary-source objects that
/// are not reachable from its trailer roots.
///
/// qpdf keeps the primary QPDF in place while `QPDFJob::handlePageSpecs`
/// copies foreign pages (`libqpdf/QPDFJob.cc:2360-2632`). When the writer's
/// `preserve_unreferenced_objects` option is enabled, those primary objects
/// remain available to `QPDFWriter::enqueueObjectsStandard` (`QPDFWriter.cc:
/// 2907-2913`). The fresh merge target normally has no way to see them, so the
/// job-level page-spec route adds the primary's unreachable live references to
/// the same persistent foreign-object map as its selected pages.
pub(crate) fn merge_documents_with_resource_mode_and_preserve_primary<R: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    resource_mode: RemoveUnreferencedResources,
    preserve_primary_unreferenced: bool,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    // qpdf computes this decision once per source in QPDFJob before entering
    // the page-copy loop. Generic callers do not have a QPDFJob report
    // boundary, so retain this wrapper's existing silent decision path.
    let remove_resources: Vec<bool> = inputs
        .iter_mut()
        .map(|input| match resource_mode {
            RemoveUnreferencedResources::No => Ok(false),
            RemoveUnreferencedResources::Yes => Ok(true),
            RemoveUnreferencedResources::Auto => should_remove_unreferenced_resources(input.source),
        })
        .collect::<Result<_>>()?;
    merge_documents_with_resource_decisions_and_preserve_primary(
        inputs,
        &remove_resources,
        preserve_primary_unreferenced,
    )
}

/// Merge selected pages using decisions already made by qpdf's job-level
/// resource heuristic.
///
/// `QPDFJob::handlePageSpecs` performs the Auto scan and its verbose side
/// effects before entering the copy loop (`libqpdf/QPDFJob.cc:2442-2455`).
/// Accepting the resulting per-source booleans here keeps that scan single and
/// leaves this function responsible only for page copying and page-local
/// mutation.
pub(crate) fn merge_documents_with_resource_decisions_and_preserve_primary<R: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
    preserve_primary_unreferenced: bool,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    let target = Pdf::empty()?;
    merge_documents_with_resource_decisions_and_preserve_primary_into(
        inputs,
        remove_resources,
        preserve_primary_unreferenced,
        target,
    )
}

/// Merge selected pages into a caller-provided target document.
///
/// The public library primitive uses qpdf's canonical in-memory empty target,
/// while `QPDFJob::createQPDF` supplies its erased job document here. Keeping
/// the copy and page-rebuild body shared is important: the target reader type
/// is an ownership detail, not a second page-selection implementation.
pub(crate) fn merge_documents_with_resource_decisions_and_preserve_primary_into<
    R: Read + Seek,
    T: Read + Seek,
>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
    preserve_primary_unreferenced: bool,
    target: Pdf<T>,
) -> Result<Pdf<T>> {
    merge_documents_with_resource_decisions_and_preserve_primary_into_impl(
        inputs,
        remove_resources,
        preserve_primary_unreferenced,
        target,
        false,
        ObjectStreamMode::Preserve,
    )
}

/// Exercise the old fresh-target page merge in unit tests.
///
/// Production `QPDFJob::handlePageSpecs` now mutates the primary document and
/// copies foreign pages in occurrence order. This wrapper remains only for
/// focused tests of the lower-level grouped merge implementation.
#[cfg(test)]
pub(crate) fn merge_documents_for_page_specs_into<R: Read + Seek, T: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
    preserve_primary_unreferenced: bool,
    target: Pdf<T>,
    object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
    merge_documents_with_resource_decisions_and_preserve_primary_into_impl(
        inputs,
        remove_resources,
        preserve_primary_unreferenced,
        target,
        true,
        object_stream_mode,
    )
}

fn merge_documents_with_resource_decisions_and_preserve_primary_into_impl<
    R: Read + Seek,
    T: Read + Seek,
>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
    preserve_primary_unreferenced: bool,
    mut target: Pdf<T>,
    defer_foreign_acroform_fields: bool,
    object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
    if inputs.is_empty() {
        return Err(Error::Unsupported(
            "merge requires at least one input".to_string(),
        ));
    }
    if inputs.len() != remove_resources.len() {
        return Err(Error::Internal(
            "page merge resource decisions do not match source count".to_owned(),
        ));
    }

    // The primary page tree is flattened and emptied below to mirror
    // qpdf::handlePageSpecs. Keep the original source page identities before
    // that mutation so later AcroForm and removed-page bookkeeping can still
    // address the source pages that qpdf retains in its object cache.
    let original_page_refs: Vec<Vec<ObjectRef>> = inputs
        .iter_mut()
        .enumerate()
        .map(|(input_index, input)| {
            if input_index != 0 && input.pages.is_empty() {
                // Keep the documented unused-secondary fast path below: qpdf
                // never opens or walks a source that contributes no selected
                // pages, so its malformed page tree cannot abort this merge.
                Ok(Vec::new())
            } else {
                page_refs(input.source)
            }
        })
        .collect::<Result<_>>()?;

    let pages_root_ref = target_pages_root(&mut target)?;
    let mut writer_object_order: BTreeMap<ObjectRef, WriterObjectOrderKey> = BTreeMap::new();
    // qpdf keeps the primary QPDF object-number allocator alive while it
    // copies foreign page graphs. Foreign copies therefore receive the next
    // object numbers after the primary cache *after page removal*, not the
    // fresh target's local references. Page removal can itself promote a
    // direct inherited `/Pages` value into a newly allocated object
    // (`QPDF_optimization.cc:179-190`), so these values are initialized at
    // the primary mutation boundary below rather than from the pre-mutation
    // xref table (`QPDF.cc:1271-1283,2019-2213`).
    let mut primary_max_object = 0;
    // This is assigned before the first non-primary input is processed. The
    // initial value only keeps the variable initialized for Rust's definite
    // assignment rules; qpdf always processes the primary input first.
    let mut next_foreign_original = 1;

    // Output `/Kids`, accumulated across inputs in input/selection order.
    let mut kids: Vec<ObjectRef> = Vec::new();
    // Copied page objects already placed in `kids`, so a page selected more
    // than once becomes a shallow clone rather than a duplicated reference.
    let mut used: BTreeSet<ObjectRef> = BTreeSet::new();

    // AcroForm merge state. `kept_fields` accumulates each input's kept
    // top-level fields (orphan fields on unselected pages are absent from the
    // selected-page map and so never appear). `primary_acroform` holds only the
    // primary's qpdf field-rebuild gates; the Catalog copier carries `/DR` and
    // `/DA` through the canonical foreign map.
    let mut kept_fields: Vec<KeptField> = Vec::new();
    let mut primary_acroform = PrimaryAcroForm::default();
    // /PageLabels merge state (qpdf `handlePageSpecs` parity). Unlike outlines
    // and named destinations, which are inherited from the primary input
    // only, page labels accumulate across EVERY input: qpdf calls
    // `getLabelsForPageRange` once per selected page regardless of which
    // source file it came from, gating only the final `/PageLabels` install
    // on whether ANY input's own tree carried real labels.
    // One entry per selected page across all inputs, upper-bounded by the
    // total selection count; pre-allocate to avoid repeated regrowth on
    // large merges.
    let total_selected: usize = inputs.iter().map(|i| i.pages.len()).sum();
    let mut label_entries: Vec<RawPageLabelEntry> = Vec::with_capacity(total_selected);
    let mut any_page_labels = false;
    let mut out_pageno: i64 = 0;

    for (input_index, input) in inputs.iter_mut().enumerate() {
        // Document-level structures (outlines, named dests, /OpenAction) are
        // inherited from the PRIMARY input only (qpdf `--pages` parity).
        let is_primary = input_index == 0;

        // A non-primary input that selects no pages contributes nothing (it adds
        // no pages and, with no selected pages, no fields). Skip it before any
        // source read so a malformed but unused secondary (e.g. a broken
        // `/AcroForm /Fields` or `/Pages` tree) cannot abort the whole merge.
        // The primary is always processed: it carries the inherited document-level
        // state even when it contributes no pages of its own.
        if !is_primary && input.pages.is_empty() {
            continue;
        }

        // Capture the primary's physical type-2 rows before page mutation.
        // qpdf keeps this source xref ownership on the primary QPDF until the
        // writer's Preserve setup; the fresh target will install the copied
        // rows after its canonical member map is complete.
        let primary_source_xref_entries = if is_primary {
            input.source.source_xref_entries()
        } else {
            BTreeMap::new()
        };
        // Same snapshot instant as `primary_source_xref_entries`: qpdf's own
        // `QPDF::getObjectStreamData` (`libqpdf/QPDF.cc:2381-2390`) member ->
        // container mapping, taken before page mutation for the same reason.
        // `install_primary_object_stream_membership` derives its member set
        // from this canonical map instead of re-matching `XrefEntry::
        // Compressed` rows itself.
        let mut primary_object_stream_membership = BTreeMap::new();
        if is_primary {
            input
                .source
                .get_object_stream_data(&mut primary_object_stream_membership);
        }
        let source_has_object_streams = primary_source_xref_entries
            .values()
            .any(|entry| matches!(entry, XrefEntry::Compressed { .. }));
        // qpdf's `getCompressibleObjGens` runs during Generate for every
        // source and during Preserve only when source ObjStms are retained.
        // Disable and Preserve+`--preserve-unreferenced` skip that walk, so a
        // missing lower generation remains an indirect null in those modes.
        let remove_stale_generations = is_primary
            && (!preserve_primary_unreferenced || object_stream_mode == ObjectStreamMode::Generate)
            && match object_stream_mode {
                ObjectStreamMode::Disable => false,
                ObjectStreamMode::Preserve => source_has_object_streams,
                ObjectStreamMode::Generate => true,
            };

        // Capture qpdf's original page list before the primary page tree is
        // cleared. `handlePageSpecs` calls `removePage` for every primary page
        // before it adds the selected pages back; that first removal flattens
        // the tree with skipped-key warnings enabled. Foreign sources are not
        // removed from, so they take the ordinary `copyForeignObject`-
        // preparation path instead.
        let all = original_page_refs[input_index].clone();
        // qpdf's page-copy boundary prepares every source through
        // `pushInheritedAttributesToPage` before the selected pages are
        // copied. This promotes shared non-scalar inherited values (such as a
        // direct `/MediaBox` on `/Pages`) once, and only writes a leaf key when
        // an ancestor actually supplies it. In particular, an absent
        // `/Rotate` must stay absent rather than becoming `/Rotate 0`.
        PageDocumentHelper::new(input.source).push_inherited_attributes_to_pages()?;

        // Reconstruct this input's page-label contribution, one entry per
        // selected page (in selection order, duplicates included), before any
        // other per-input processing — purely a `/PageLabels`-tree read,
        // independent of the page-copy/dest/AcroForm machinery below.
        // An input that contributes no pages contributes no labels either —
        // otherwise a primary carrying /PageLabels but pages: vec![] would
        // set `any_page_labels` (and thereby install fabricated labels for
        // every later input's pages) even though none of its own pages are
        // in the output.
        if !input.pages.is_empty() {
            let source_id = input.source.unique_id();
            let mut src_labels = input.source.page_labels();
            if src_labels.has_page_labels()? {
                any_page_labels = true;
            }
            let src_indices: Vec<i64> = input.pages.iter().map(|&i| i as i64).collect();
            label_entries.extend(
                src_labels
                    .labels_for_selection_raw(&src_indices, out_pageno)?
                    .into_iter()
                    .map(|(index, label)| RawPageLabelEntry {
                        index,
                        source_id,
                        source_is_primary: is_primary,
                        label,
                    }),
            );
            out_pageno = out_pageno.saturating_add(input.pages.len() as i64);
        }

        // The primary's `/AcroForm /DR` and `/DA` are the merged form's base; a
        // later input contributes form fields only (its `/DR` / `/DA` are not
        // merged). Read the primary's field-rebuild gates before copying.
        if is_primary {
            primary_acroform = discover_primary_acroform(input.source)?;
        }
        // Source top-level field names, read before the copy severs numbering;
        // each is mapped through this input's copy map below.
        // qpdf constructs the primary AcroForm helper only after the primary
        // page tree has been removed, while a selected secondary helper is
        // constructed at the foreign-copy boundary after that same removal
        // (`QPDFJob.cc:2514-2524`). Preserve those analysis points: the
        // primary snapshot reads only the field tree, and a secondary snapshot
        // keeps the normal eager orphan-widget scan.
        let source_fields = if is_primary {
            source_top_level_field_names_without_page_scan(input.source)?
        } else {
            source_top_level_field_names(input.source)?
        };
        if is_primary {
            primary_acroform.original_field_names.extend(
                source_fields
                    .iter()
                    .filter_map(|(_, name)| name.as_ref().cloned()),
            );
        }

        // Resolve the selected source page refs (range-checked, duplicates
        // allowed), in selection order.
        let mut selected: Vec<ObjectRef> = Vec::with_capacity(input.pages.len());
        for &idx in &input.pages {
            let page_ref = *all.get(idx).ok_or_else(|| {
                Error::Unsupported(format!(
                    "page index {idx} out of range (input document has {} pages)",
                    all.len()
                ))
            })?;
            selected.push(page_ref);
        }

        // Unique source pages in first-occurrence order; duplicates re-use the
        // same copied object and are shallow-cloned when building /Kids.
        let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
        let mut unique: Vec<ObjectRef> = Vec::with_capacity(selected.len());
        for &page_ref in &selected {
            if seen.insert(page_ref) {
                unique.push(page_ref);
            }
        }

        // qpdf removes resources from each unique source page immediately
        // before its first foreign copy. A later duplicate is a shallow page
        // copy and must not run the resource pass a second time. The source
        // inherited-attribute push above is intentionally before this call:
        // qpdf's page helper sees the effective page attributes at the copy
        // boundary, while the Auto decision above was made against the
        // original page tree.
        if remove_resources[input_index] {
            for &page_ref in &unique {
                PageObjectHelper::new(page_ref, input.source).remove_unreferenced_resources()?;
            }
        }

        if is_primary {
            for &page_ref in &all {
                PageDocumentHelper::new(input.source).remove_page(page_ref)?;
            }
            primary_max_object = input.source.get_object_count()?;
            // cov:ignore-start: a source object-number universe ending at
            // u32::MAX cannot allocate the next foreign identity in a
            // representable PDF object space.
            next_foreign_original = primary_max_object.checked_add(1).ok_or_else(|| {
                Error::Unsupported("foreign QDF object identity overflows u32".to_owned())
            })?;
            // cov:ignore-end
        }

        // qpdf's QPDFPageDocumentHelper::addPage delegates foreign page
        // insertion to QPDF::copyForeignObject. Keep the primary Catalog and
        // `/Pages` identities in the persistent per-source ObjCopier before
        // copying selected pages, matching qpdf's in-place primary document
        // ownership (`QPDF.cc:2019-2093`).
        let source_id = input.source.unique_id();
        let mut copy_seed = target.take_foreign_object_map(source_id);
        if is_primary {
            let target_catalog_ref = target
                .root_ref()
                .expect("Pdf::empty always populates a root catalog");
            let primary_catalog = input.source.root_handle()?;
            let primary_pages_ref = primary_catalog
                .try_get_key(b"/Pages")?
                .object_ref()
                .expect("page_refs above already required an indirect primary /Pages");
            // A direct Catalog has no source-space ObjectRef to reserve. Its
            // direct child values are copied by `wire_primary_catalog`; only
            // an indirect Catalog participates in the identity map.
            if let Some(primary_catalog_ref) = input.source.root_ref() {
                copy_seed.insert(
                    QpdfObjGen::try_from_object_ref(primary_catalog_ref)?,
                    target_catalog_ref,
                );
            }
            copy_seed.insert(
                QpdfObjGen::try_from_object_ref(primary_pages_ref)?,
                pages_root_ref,
            );
        }
        target.set_foreign_object_map(source_id, copy_seed);
        for &page_ref in &unique {
            // qpdf's ObjCopier records newly reserved foreign objects in the
            // depth-first `to_copy` order from `reserveObjects`, not in source
            // object-number or destination-map order (`QPDF.cc:2071-2089,
            // 2101-2155`). The resolver's allocation log is the canonical
            // destination-side equivalent of that event sequence. Capture its
            // delta at the copy boundary so page-spec provenance can retain
            // the exact discovery order for QDF Original object IDs.
            let allocation_checkpoint = target.allocation_checkpoint();
            let source_page = input.source.get_object_handle(page_ref);
            let copied_page = if is_primary {
                copy_foreign_object_with_stale_generation_policy(
                    &mut target,
                    &source_page,
                    remove_stale_generations,
                )? // cov:ignore: qpdf primary page copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
            } else {
                target.copy_foreign_object(&source_page)?
            };
            // cov:ignore-start: QPDF::copyForeignObject returns an indirect
            // destination handle for an indirect page root; this guard protects
            // the contract if the allocator ever regresses.
            if copied_page.object_ref().is_none() {
                return Err(Error::Missing("merged page missing from foreign copy map"));
            }
            // cov:ignore-end
            if !is_primary {
                let new_objects = target.allocated_object_refs_after(allocation_checkpoint);
                target
                    .foreign_page_copy_orders
                    .entry(source_id)
                    .or_default()
                    .push((page_ref, new_objects));
            }
        }
        let page_copy_map_before_catalog =
            project_foreign_object_map(&target.foreign_object_map_snapshot(source_id));
        // qpdf keeps the primary Catalog and trailer in the same QPDF while
        // `handlePageSpecs` mutates its page tree. Copy their values through
        // the destination-owned ObjectHandle copier, reusing the selected-page
        // map and preserving direct arrays/dictionaries without materializing
        // a legacy Object snapshot.
        if is_primary {
            wire_primary_catalog(
                input.source,
                &mut target,
                source_id,
                remove_stale_generations,
            )?; // cov:ignore: qpdf primary Catalog copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
            wire_primary_pages_root(
                input.source,
                &mut target,
                source_id,
                pages_root_ref,
                remove_stale_generations,
            )?; // cov:ignore: qpdf primary /Pages copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
            wire_primary_trailer(
                input.source,
                &mut target,
                source_id,
                remove_stale_generations,
            )?; // cov:ignore: qpdf primary trailer copy is exercised by the edge differential; LLVM maps this multiline call continuation separately.
        }
        let page_copy_map = if is_primary && defer_foreign_acroform_fields {
            project_foreign_object_map(&target.foreign_object_map_snapshot(source_id))
        } else {
            page_copy_map_before_catalog
        };

        // `--preserve-unreferenced` mirrors qpdf's writer-side
        // `enqueueObjectsStandard` over the primary's complete live object
        // cache. Copy every non-ObjStm object through the preserve-specific
        // traversal, which treats `/Pages` containers as ordinary graph nodes
        // just as qpdf's writer enqueue does. ObjStm containers are writer-owned
        // compression artifacts and are intentionally regenerated by the
        // target writer rather than copied as source streams
        // (`QPDFWriter.cc:1093-1103,1955-2003`).
        if is_primary && preserve_primary_unreferenced {
            for source_object in input.source.canonical_live_object_handles()? {
                if source_object.try_is_stream_of_type(b"ObjStm", b"")? {
                    continue;
                }
                copy_foreign_object_for_preserve(&mut target, &source_object)?;
            }
        }

        // Keep the completed source map as the local identity view for field
        // trimming, removed-page nulling, and page-tree assembly. The map has
        // been populated only by the canonical foreign copier above.
        let raw_map = target.take_foreign_object_map(source_id);
        let map = project_foreign_object_map(&raw_map);

        if is_primary {
            install_primary_object_stream_membership(
                input.source,
                &mut target,
                &primary_object_stream_membership,
                &primary_source_xref_entries,
                &map,
            )?; // cov:ignore: malformed source xref errors propagate at this boundary
        }

        // qpdf keeps primary objects in their source object-number order and
        // assigns foreign objects in copy-discovery order. The destination
        // references alone cannot express that distinction after this route
        // has copied both sources into a fresh target, so retain the ordering
        // key for the linearization planner. Newly created merge objects are
        // intentionally absent and use the planner's fresh-object fallback.
        let mut foreign_originals = BTreeMap::new();
        if !is_primary {
            let mut target_refs: Vec<ObjectRef> = map.values().copied().collect();
            target_refs.sort_unstable();
            for target_ref in target_refs {
                foreign_originals.insert(target_ref, ObjectRef::new(next_foreign_original, 0));
                // cov:ignore-start: allocating more than the u32 PDF object
                // space is infeasible for an in-memory page merge.
                next_foreign_original = next_foreign_original.checked_add(1).ok_or_else(|| {
                    Error::Unsupported("foreign QDF object identity overflows u32".to_owned())
                })?;
                // cov:ignore-end
            }
        }
        for (&source_ref, &target_ref) in &map {
            let order_key = if is_primary {
                WriterObjectOrderKey::primary(source_ref)
            } else {
                WriterObjectOrderKey::foreign_with_allocation_identity(
                    target_ref,
                    foreign_originals
                        .get(&target_ref)
                        .copied()
                        .unwrap_or(target_ref),
                )
            };
            writer_object_order.insert(target_ref, order_key);
        }

        null_copied_removed_pages(&mut target, &all, &seen, &map)?;

        // qpdf replaces each copied page's `/Parent` with the destination
        // `/Pages` handle during insertion. Keep the same live-handle boundary
        // after the source-side inherited-attribute push and foreign copy.
        let pages_handle = target.get_object_handle(pages_root_ref);
        for &src_ref in &unique {
            let copied_page_ref = *map
                .get(&src_ref)
                .ok_or(Error::Missing("merged page missing from copy map"))?;
            let page = target.get_object_handle(copied_page_ref);
            page.try_dereference()?;
            page.replace_key(b"/Parent", pages_handle.clone())?;
        }

        // Record this input's kept top-level fields (those whose source ref was
        // copied — orphan fields on unselected pages are absent from `map` and
        // so dropped, matching qpdf's form subset). The primary's `map` also
        // carries the Catalog-copied AcroForm graph.
        //
        // A NON-TERMINAL field (whose `/Kids` are widget annotations, possibly
        // on different pages) reaches the copy map whenever any one of its
        // widgets is on a selected page; the canonical page map's `/Parent` →
        // sibling-`/Kids` traversal then pulls in the field's widgets on
        // UNSELECTED pages too (and, via each such widget's `/P`, those pages as
        // off-tree orphans). Trim the field's `/Kids` to only the widgets whose
        // `/P` page survived; a field left with zero surviving widgets is
        // dropped entirely (the surrounding `map.get` guard already drops fields
        // never reached, so a zero-survivor trim only happens for malformed
        // shapes where a field ref sits directly in a page `/Annots`). Each
        // dropped widget's unselected page is collected and nulled below, so the
        // output never carries a live orphan `/Type /Page` outside `/Kids`.
        let mut orphan_pages: BTreeSet<ObjectRef> = BTreeSet::new();
        // A widget survives the field-tree trim iff it is a member of a selected
        // page's `/Annots` (or its optional `/P` resolves to a surviving page).
        // Build that retained-widget set once per input from the selected pages'
        // `/Annots`, in source space, so a `/P`-less selected-page widget is kept.
        let mut retained_widgets: BTreeSet<ObjectRef> = BTreeSet::new();
        collect_retained_widget_refs(input.source, &seen, &mut retained_widgets)?;
        for (src_field_ref, partial_name) in source_fields {
            // The qpdf page job creates foreign fields only in the
            // occurrence-ordered fixCopiedAnnotations pass. Do not mutate the
            // grouped foreign field copy here: it is the object-map source
            // that the later replay must reuse with its original `/T` value.
            if defer_foreign_acroform_fields && !is_primary {
                continue;
            }
            if page_copy_map.contains_key(&src_field_ref) {
                if let Some(&target_ref) = map.get(&src_field_ref) {
                    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
                    let trimmed = trim_field_kids(
                        input.source,
                        &mut target,
                        src_field_ref,
                        &seen,
                        &retained_widgets,
                        &map,
                        &mut orphan_pages,
                        0,
                        &mut visited,
                    )?; // cov:ignore: `?` Err arm — trim_field_kids errors only on the depth guard, unreachable on well-formed input
                    if let Some(survivors) = trimmed {
                        if survivors.is_empty() {
                            // No widget survived: drop the whole field (do not record
                            // it). Its widgets' orphan pages are nulled below.
                            continue;
                        }
                        rewrite_field_kids(&mut target, src_field_ref, &survivors, &map)?;
                    }
                    kept_fields.push(KeptField {
                        target_ref,
                        partial_name,
                        is_primary,
                    });
                }
            }
        }

        // Null the copied placeholder body of each off-tree orphan page reached
        // only through a dropped widget's `/P`. This mirrors the removed-dest
        // null-out above: the page never appears in `/Kids`, and nulling its
        // body (rather than leaving a live `/Type /Page`) keeps the merged form
        // internally consistent. The merge-only reachability sweep later GCs
        // the placeholder once no surviving reference points at it.
        for src_page_ref in &orphan_pages {
            if let Some(&new_ref) = map.get(src_page_ref) {
                target.replace_object(new_ref, ObjectHandle::null())?;
            }
        }
        // Append this input's pages to /Kids in selection order, with each
        // input resolved through its own copy map.
        append_selection_kids(
            &mut target,
            &selected,
            &map,
            &mut used,
            &mut kids,
            &mut writer_object_order,
            &mut next_foreign_original,
        )?; // cov:ignore: malformed page-copy map errors propagate at this boundary

        // QPDF::copyForeignObject keeps the per-source ObjCopier alive after
        // page insertion. QPDFJob::handlePageSpecs then reuses that same map
        // when fixCopiedAnnotations makes each page occurrence independent
        // (`QPDFJob.cc:2517-2585`, `QPDF.cc:2019-2272`). Keep the complete
        // graph map on the target until the job-level AcroForm replay has
        // finished; retaining only the page-ref projection would copy every
        // field, annotation, appearance stream, and resource a second time.
        target.set_foreign_object_map(source_id, raw_map);

        if is_primary && !preserve_primary_unreferenced && !all.is_empty() {
            // qpdf keeps the primary QPDF's complete xref object-number
            // universe alive while it imports the next page source, including
            // unselected page/content objects that are nulled only after all
            // `fixCopiedAnnotations` calls (`QPDFJob.cc:2390-2469,2596-2608`).
            // The fresh Rust target has copied only the primary graph that is
            // reachable at this boundary, so fill the unused portion of that
            // primary number space with destination-owned null slots before a
            // foreign ObjCopier can allocate its first object. The slots are
            // unreachable and therefore omitted by the ordinary writer, but
            // they preserve qpdf's diagnostic object identities and allocator
            // ordering for the subsequent foreign copy.
            let target_max = target
                .canonical_live_object_refs()
                .into_iter()
                .map(|object| object.number)
                .max()
                .unwrap_or(0);
            // Raising the ceiling is what matters here, not owning every slot
            // below it: the next allocation is `max + 1` either way, and the
            // reserved slots are unreachable and never written. Claim only the
            // top slot instead of one object per gap -- the gap is attacker
            // controlled (a single dangling `100000000 0 R` in a 351-byte file
            // reaches `get_object_count`), so filling it would let a tiny input
            // allocate unboundedly.
            if target_max < primary_max_object {
                target
                    .replace_object(ObjectRef::new(primary_max_object, 0), ObjectHandle::null())?;
            }
        }
    }

    // Build the fresh single-level /Pages root over the accumulated kids
    // through the canonical live-handle mutation boundary.
    let root = target.get_object_handle(pages_root_ref);
    root.try_dereference()?;
    // cov:ignore-start: Pdf::empty() owns the target /Pages dictionary and no
    // merge operation replaces that slot with another value before this point.
    if !root.try_is_dictionary()? {
        return Err(Error::Unsupported(
            "target /Pages is not a dictionary".to_owned(),
        ));
    }
    // cov:ignore-end
    let kid_handles = kids
        .iter()
        .map(|&kid| target.get_object_handle(kid))
        .collect();
    root.replace_key(b"/Kids", ObjectHandle::array(kid_handles))?;
    root.replace_key(b"/Count", ObjectHandle::integer(kids.len() as i64))?;

    // Build the merged `/AcroForm`: the primary's `/DR` / `/DA` base plus every
    // kept top-level field, with later inputs' colliding `/T` names renamed by
    // qpdf's `+N` rule. Done BEFORE the sweep so the `/DR` fonts (reachable only
    // through `/AcroForm`) are not garbage-collected.
    build_merged_acroform(&mut target, &primary_acroform, &kept_fields)?;

    // Install the merged `/PageLabels`, folding away entries that turn out
    // redundant with the running sequence (qpdf's own accumulating
    // `getLabelsForPageRange` redundancy check). A no-op when no input ever
    // carried real page labels — the target then keeps its fresh, label-less
    // catalog, matching qpdf's `emptyPDF()`-based output.
    target.set_writer_object_order(writer_object_order);
    if any_page_labels {
        let folded = merge_adjacent_raw_page_labels(label_entries)?;
        let copied = copy_raw_page_label_entries(&mut target, &folded)?;
        record_primary_label_provenance(&mut target, &folded);
        target
            .page_labels()
            .write_reconstructed_labels_raw(&copied)?;
    }

    preserve_primary_root_shape(inputs[0].source, &mut target)?;

    Ok(target)
}

#[cfg(test)]
mod tests {
    use super::super::resource_pruning::RemoveUnreferencedResources;
    use super::{
        collect_retained_widget_refs, discover_primary_acroform, field_kid_refs,
        install_primary_object_stream_membership, merge_documents,
        merge_documents_with_resource_decisions_and_preserve_primary,
        merge_documents_with_resource_mode_and_preserve_primary, preserve_primary_root_shape,
        resolve_field_partial_name, rewrite_field_kids, trim_field_kids, unique_field_name,
        widget_page_ref, MergeInput, DEFAULT_MAX_ACROFORM_DEPTH,
    };
    use crate::{Error, ObjectHandle, ObjectRef, Pdf};
    use std::collections::{BTreeMap, BTreeSet};

    fn build_pdf(objects: &[(u32, &str)], root: u32) -> Vec<u8> {
        let mut out: Vec<u8> = b"%PDF-1.7\n".to_vec();
        let mut offsets: BTreeMap<u32, u64> = BTreeMap::new();
        let max = objects.iter().map(|(number, _)| *number).max().unwrap_or(0);
        for (number, body) in objects {
            offsets.insert(*number, out.len() as u64);
            out.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
        }
        let xref_start = out.len() as u64;
        let size = max + 1;
        out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes());
        out.extend_from_slice(b"0000000000 65535 f \n");
        for number in 1..=max {
            match offsets.get(&number) {
                Some(offset) => {
                    out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes())
                }
                None => out.extend_from_slice(b"0000000000 65535 f \n"),
            }
        }
        out.extend_from_slice(
            format!(
                "trailer\n<< /Size {size} /Root {root} 0 R >>\nstartxref\n{xref_start}\n%%EOF\n"
            )
            .as_bytes(),
        );
        out
    }

    fn used(names: &[&[u8]]) -> BTreeSet<Vec<u8>> {
        names.iter().map(|n| n.to_vec()).collect()
    }

    fn decode_hex_fixture(hex: &str) -> Vec<u8> {
        let digits: Vec<u8> = hex.bytes().filter(u8::is_ascii_hexdigit).collect();
        digits
            .chunks(2)
            .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
            .collect()
    }

    #[test]
    fn primary_objstm_membership_preserves_an_extends_chain() {
        let mut source = Pdf::open_mem_owned(decode_hex_fixture(include_str!(
            "../../../../tests/fixtures/compat/objstm-extends-chain.pdf.hex"
        )))
        .expect("open ObjStm source");
        let mut target = Pdf::empty().expect("empty target");
        let source_xref_entries = source.source_xref_entries();
        let mut source_object_stream_membership = BTreeMap::new();
        source.get_object_stream_data(&mut source_object_stream_membership);
        let mut copied = BTreeMap::new();
        for source_member in [ObjectRef::new(2, 0), ObjectRef::new(3, 0)] {
            let copied_handle = target
                .make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
                .expect("allocate copied member");
            copied.insert(source_member, copied_handle.object_ref().unwrap());
        }

        install_primary_object_stream_membership(
            &mut source,
            &mut target,
            &source_object_stream_membership,
            &source_xref_entries,
            &copied,
        )
        .expect("install source membership");

        let member = *copied.values().next().expect("copied member");
        let mut target_membership = BTreeMap::new();
        target.get_object_stream_data(&mut target_membership);
        let target_container = *target_membership
            .get(&member.number)
            .expect("copied member must have a compressed source row");
        let stream_handle = target.get_object_handle(ObjectRef::new(target_container, 0));
        stream_handle.try_is_scalar().unwrap();
        let extends = stream_handle
            .as_stream_dict()
            .unwrap()
            .try_get_key(b"/Extends")
            .unwrap()
            .object_ref()
            .expect("source ObjStm /Extends must remain indirect");
        assert_ne!(ObjectRef::new(target_container, 0), extends);
    }

    #[test]
    fn direct_primary_root_removes_the_temporary_target_catalog() {
        let mut source = Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/direct-root-one-page.pdf").to_vec(),
        )
        .expect("open direct-root source");
        assert_eq!(source.root_ref(), None);

        let mut target = Pdf::empty().expect("empty merge target");
        assert!(target.root_ref().is_some());

        preserve_primary_root_shape(&mut source, &mut target)
            .expect("preserve direct primary root shape");

        assert_eq!(target.root_ref(), None);
        assert!(target
            .root_handle()
            .expect("direct target Catalog")
            .try_has_key(b"/Pages")
            .expect("direct target Catalog keys"));
    }

    #[test]
    fn page_merge_production_route_has_no_legacy_borrowed_resolution() {
        let source = include_str!("page_merge.rs").replace("\r\n", "\n");
        let production = source
            .split_once("#[cfg(test)]\nmod tests")
            .expect("page_merge test module marker")
            .0;
        assert_eq!(
            production.matches("resolve_borrowed").count(),
            0,
            "page_merge production must use the canonical ObjectHandle resolver"
        );
    }

    #[test]
    fn install_primary_object_stream_membership_routes_through_get_object_stream_data() {
        let source = include_str!("page_merge.rs").replace("\r\n", "\n");
        let production = source
            .split_once("#[cfg(test)]\nmod tests")
            .expect("page_merge test module marker")
            .0;
        let body = production
            .split_once("fn install_primary_object_stream_membership")
            .expect("install_primary_object_stream_membership signature")
            .1
            .split_once("\nfn ")
            .expect("next production fn boundary")
            .0;
        // route matrix D9 (`docs/qpdf-route-matrix/d-writer.md`): the
        // member -> container mapping must come from the same
        // `get_object_stream_data` (`QPDF::getObjectStreamData`,
        // `libqpdf/QPDF.cc:2381-2390`) call every other Preserve consumer
        // uses, not a private re-match of `XrefEntry::Compressed` rows.
        assert!(
            body.contains("in source_object_stream_membership"),
            "install_primary_object_stream_membership must iterate the \
             canonical get_object_stream_data snapshot (route matrix D9) \
             rather than reconstructing member -> container itself"
        );
        assert!(
            !body.contains("for (&source_member, entry) in source_xref_entries"),
            "install_primary_object_stream_membership must not re-match \
             XrefEntry::Compressed rows off the raw xref table to find \
             membership itself; that computation belongs to \
             get_object_stream_data alone (route matrix D9)"
        );
        assert!(
            production.contains("get_object_stream_data(&mut primary_object_stream_membership)"),
            "the primary's get_object_stream_data snapshot feeding \
             install_primary_object_stream_membership must actually be \
             computed by calling get_object_stream_data (route matrix D9)"
        );
    }

    #[test]
    fn primary_field_snapshot_does_not_scan_pages_before_page_job_removes_them() {
        let bytes = build_pdf(
            &[
                (
                    1,
                    "<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>",
                ),
                (2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
                (
                    3,
                    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [<< /Type /Annot /Subtype /Widget /T (Direct) /Rect [0 0 10 10] >>] >>",
                ),
                (5, "<< /Fields [] >>"),
            ],
            1,
        );
        let mut source = Pdf::open_mem_owned(bytes).expect("open source");

        discover_primary_acroform(&mut source).expect("snapshot primary AcroForm");

        assert!(source.repair_diagnostics().entries().is_empty());
    }

    #[test]
    fn merge_skips_page_reads_for_an_unused_secondary() {
        let primary = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
            1,
        );
        let mut primary = Pdf::open_mem_owned(primary).expect("open primary");
        let mut secondary = Pdf::empty().expect("open unused secondary");
        secondary.trailer().remove_key(b"/Root");
        let mut inputs = [
            MergeInput {
                source: &mut primary,
                pages: vec![0],
            },
            MergeInput {
                source: &mut secondary,
                pages: Vec::new(),
            },
        ];

        let mut merged = merge_documents(&mut inputs).expect("unused secondary is ignored");
        assert_eq!(
            crate::pages::page_refs(&mut merged)
                .expect("read merged pages")
                .len(),
            1
        );
    }

    #[test]
    fn precomputed_resource_decisions_must_cover_every_merge_input() {
        let mut source = Pdf::empty().expect("empty source");
        let mut inputs = [MergeInput {
            source: &mut source,
            pages: vec![0],
        }];

        assert!(matches!(
            merge_documents_with_resource_decisions_and_preserve_primary(
                &mut inputs,
                &[],
                false,
            ),
            Err(Error::Internal(message))
                if message == "page merge resource decisions do not match source count"
        ));
    }

    #[test]
    fn resource_mode_wrapper_evaluates_yes_and_auto_decisions() {
        for mode in [
            RemoveUnreferencedResources::Yes,
            RemoveUnreferencedResources::Auto,
        ] {
            let mut source = Pdf::open_mem_owned(build_pdf(
                &[
                    (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                    (2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
                    (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
                ],
                1,
            ))
            .expect("one-page source");
            let mut inputs = [MergeInput {
                source: &mut source,
                pages: vec![0],
            }];

            let mut merged =
                merge_documents_with_resource_mode_and_preserve_primary(&mut inputs, mode, false)
                    .expect("resource mode merge");
            assert_eq!(crate::pages::page_refs(&mut merged).unwrap().len(), 1);
        }
    }

    #[test]
    fn unique_field_name_keeps_unused_base() {
        assert_eq!(unique_field_name(b"name", &used(&[])), b"name".to_vec());
        assert_eq!(
            unique_field_name(b"name", &used(&[b"email"])),
            b"name".to_vec()
        );
    }

    #[test]
    fn unique_field_name_appends_plus_one_on_collision() {
        assert_eq!(
            unique_field_name(b"name", &used(&[b"name"])),
            b"name+1".to_vec()
        );
    }

    #[test]
    fn unique_field_name_finds_first_unused_in_sequence() {
        // name, name+1 taken → name+2 (the three-way collision tail).
        assert_eq!(
            unique_field_name(b"name", &used(&[b"name", b"name+1"])),
            b"name+2".to_vec()
        );
    }

    #[test]
    fn unique_field_name_reresolves_colliding_candidate() {
        // A field originally named `name+1` whose `name+1` is already used must
        // re-resolve to `name+1+1` (qpdf 11.9.0 observed behaviour).
        assert_eq!(
            unique_field_name(b"name+1", &used(&[b"name", b"name+1"])),
            b"name+1+1".to_vec()
        );
    }

    fn resolved_handle<R: std::io::Read + std::io::Seek>(
        pdf: &mut Pdf<R>,
        object_ref: ObjectRef,
    ) -> ObjectHandle {
        let handle = pdf.get_object_handle(object_ref);
        handle.try_is_scalar().expect("resolve object");
        handle
    }

    /// A malformed indirect document-level root may itself be an unselected
    /// page. It is still copied so the catalog carrier can point at a null page
    /// boundary, but generic root traversal must stop there rather than pulling
    /// the page's `/Contents` into the foreign copier map.
    #[test]
    fn doc_level_page_root_is_null_boundary_without_contents_in_closure() {
        let bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /OpenAction 4 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
                (
                    4,
                    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 10 0 R >>",
                ),
                (10, "<< /Length 4 >>\nstream\nDROP\nendstream"),
            ],
            1,
        );

        let mut merge_source = Pdf::open_mem_owned(bytes.clone()).unwrap();
        let mut inputs = [MergeInput {
            source: &mut merge_source,
            pages: vec![0],
        }];
        let mut merged = merge_documents(&mut inputs).unwrap();
        let catalog_ref = merged.root_ref().unwrap();
        let catalog = resolved_handle(&mut merged, catalog_ref);
        assert!(
            catalog.as_dictionary().is_some(),
            "catalog must be a dictionary"
        );
        let open_action_ref = catalog
            .try_get_key(b"/OpenAction")
            .unwrap()
            .object_ref()
            .expect("indirect /OpenAction carrier is retained");
        assert!(
            resolved_handle(&mut merged, open_action_ref).is_null(),
            "the unselected page root is copied and nulled"
        );
    }

    /// [`merge_documents`] is a public library primitive
    /// (`pub use page_merge::merge_documents` in `lib.rs`), independently
    /// callable without the CLI `--pages` job's later
    /// `rebuild_acroform_in_final_page_order` correction pass
    /// (`job/page_specs.rs`), which redoes the per-occurrence field copy
    /// through a route that already decodes reserved names. This test
    /// exercises [`build_merged_acroform`]'s own collision avoidance
    /// directly, matching qpdf's `addAndRenameFormFields`
    /// (`QPDFAcroFormDocumentHelper.cc:62-103`): the primary's unselected
    /// field reserves `F+1` even though it is stored as a UTF-16BE text
    /// string (`<FEFF0046002B0031>`, BOM-prefixed), so the secondary's `F`
    /// must resolve to `F+2`, not byte-collide past the undecoded
    /// reservation and reuse `F+1`.
    #[test]
    fn merge_documents_reserves_unselected_primary_names_regardless_of_string_encoding() {
        let primary_bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 6 0 R >>"),
                (2, "<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>"),
                (
                    3,
                    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R] >>",
                ),
                (
                    4,
                    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [7 0 R] >>",
                ),
                (
                    5,
                    "<< /Type /Annot /Subtype /Widget /FT /Tx /T (F) /Rect [0 0 10 10] /P 3 0 R >>",
                ),
                (6, "<< /Fields [5 0 R 7 0 R] >>"),
                (
                    7,
                    "<< /Type /Annot /Subtype /Widget /FT /Tx /T <FEFF0046002B0031> \
                     /Rect [0 0 10 10] /P 4 0 R >>",
                ),
            ],
            1,
        );
        let secondary_bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>"),
                (2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
                (
                    3,
                    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>",
                ),
                (
                    4,
                    "<< /Type /Annot /Subtype /Widget /FT /Tx /T (F) /Rect [0 0 10 10] /P 3 0 R >>",
                ),
                (5, "<< /Fields [4 0 R] >>"),
            ],
            1,
        );

        let mut primary = Pdf::open_mem_owned(primary_bytes).unwrap();
        let mut secondary = Pdf::open_mem_owned(secondary_bytes).unwrap();
        let mut inputs = [
            MergeInput {
                source: &mut primary,
                pages: vec![0],
            },
            MergeInput {
                source: &mut secondary,
                pages: vec![0],
            },
        ];
        let mut merged = merge_documents(&mut inputs).unwrap();

        let catalog_ref = merged.root_ref().unwrap();
        let catalog = resolved_handle(&mut merged, catalog_ref);
        assert!(
            catalog.as_dictionary().is_some(),
            "catalog must be a dictionary"
        );
        let acroform_ref = catalog
            .try_get_key(b"/AcroForm")
            .unwrap()
            .object_ref()
            .expect("/AcroForm");
        let acroform = resolved_handle(&mut merged, acroform_ref);
        assert!(
            acroform.as_dictionary().is_some(),
            "AcroForm must be a dictionary"
        );
        let fields = acroform
            .try_get_key(b"/Fields")
            .unwrap()
            .as_array()
            .expect("/Fields array");
        let names: Vec<Vec<u8>> = fields
            .iter()
            .map(|field| {
                let field_ref = field.object_ref().expect("field is an indirect ref");
                let field_dict = resolved_handle(&mut merged, field_ref);
                assert!(
                    field_dict.as_dictionary().is_some(),
                    "field must be a dictionary"
                );
                let name = field_dict.try_get_key(b"/T").unwrap();
                name.try_is_scalar().expect("resolve /T");
                name.as_string().expect("/T string")
            })
            .collect();

        assert_eq!(
            names,
            vec![b"F".to_vec(), b"F+2".to_vec()],
            "the secondary's colliding field must resolve to F+2, matching qpdf's \
             getUTF8Value()-decoded collision index, not F+1 from an undecoded byte \
             comparison against the UTF-16BE-encoded reservation"
        );
    }

    #[test]
    fn field_kid_and_widget_page_routes_use_resolved_handle_refs() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat/form-fields-and-annotations-p-and-inline.pdf");
        let mut source = Pdf::open_mem_owned(std::fs::read(path).expect("fixture exists")).unwrap();

        let kids = field_kid_refs(&mut source, ObjectRef::new(5, 0))
            .expect("field kids")
            .expect("non-terminal field");
        assert_eq!(
            kids,
            vec![
                ObjectRef::new(12, 0),
                ObjectRef::new(13, 0),
                ObjectRef::new(14, 0)
            ]
        );
        assert_eq!(
            widget_page_ref(&mut source, ObjectRef::new(3, 0)).expect("widget page"),
            Some(ObjectRef::new(10, 0))
        );

        let mut retained = BTreeSet::new();
        collect_retained_widget_refs(
            &mut source,
            &BTreeSet::from([ObjectRef::new(10, 0)]),
            &mut retained,
        )
        .expect("retained widgets");
        assert!(retained.contains(&ObjectRef::new(12, 0)));

        let mut target = Pdf::empty().expect("empty target");
        let target_field = target
            .make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
            .expect("target field");
        let target_kid = target
            .make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
            .expect("target kid");
        let target_field_ref = target_field.object_ref().expect("target field ref");
        let target_kid_ref = target_kid.object_ref().expect("target kid ref");
        let map = BTreeMap::from([
            (ObjectRef::new(5, 0), target_field_ref),
            (kids[0], target_kid_ref),
        ]);
        rewrite_field_kids(&mut target, ObjectRef::new(5, 0), &[kids[0]], &map)
            .expect("rewrite copied field kids");
        target_field
            .try_is_scalar()
            .expect("resolve rewritten field");
        assert_eq!(
            target_field
                .try_get_key(b"/Kids")
                .expect("kids key")
                .as_array()
                .expect("kids array")
                .len(),
            1
        );
    }

    #[test]
    fn field_helpers_return_none_for_a_non_dictionary_reference() {
        let mut source = Pdf::empty().expect("empty source");
        let non_dict = source
            .make_indirect_object_handle(ObjectHandle::integer(42))
            .expect("non-dictionary indirect object");
        let non_dict_ref = non_dict.object_ref().expect("non-dictionary ref");

        assert_eq!(
            resolve_field_partial_name(&mut source, non_dict_ref).unwrap(),
            None,
            "a field ref that resolves to a non-dictionary must yield no /T"
        );
        assert_eq!(
            field_kid_refs(&mut source, non_dict_ref).unwrap(),
            None,
            "a field ref that resolves to a non-dictionary must yield no kids"
        );
        assert_eq!(
            widget_page_ref(&mut source, non_dict_ref).unwrap(),
            None,
            "a widget ref that resolves to a non-dictionary must yield no page"
        );
    }

    #[test]
    fn trim_field_kids_propagates_the_depth_guard_through_recursion() {
        let bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R >>"),
                (4, "<< /Fields [5 0 R] >>"),
                (5, "<< /FT /Tx /T (Parent) /Kids [6 0 R] >>"),
                (6, "<< /FT /Tx /T (Child) >>"),
            ],
            1,
        );
        let mut source = Pdf::open_mem_owned(bytes).expect("open source");
        let mut target = Pdf::empty().expect("empty target");
        let mut orphan_pages = BTreeSet::new();
        let mut visited = BTreeSet::new();

        // Starting at the cap itself so the single recursive step into the
        // child (5's only /Kids entry) lands one level past it.
        let err = trim_field_kids(
            &mut source,
            &mut target,
            ObjectRef::new(5, 0),
            &BTreeSet::new(),
            &BTreeSet::new(),
            &BTreeMap::new(),
            &mut orphan_pages,
            DEFAULT_MAX_ACROFORM_DEPTH,
            &mut visited,
        )
        .unwrap_err();

        assert!(
            matches!(err, crate::Error::Unsupported(ref message)
                if message.contains("AcroForm field tree depth exceeds maximum")),
            "recursing past the depth cap must surface the guard's error, not swallow it: {err:?}"
        );
    }

    #[test]
    fn trim_field_kids_treats_a_kids_cycle_as_no_survivors() {
        let bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R >>"),
                (4, "<< /Fields [5 0 R] >>"),
                (5, "<< /FT /Tx /T (Cyclic) /Kids [5 0 R] >>"),
            ],
            1,
        );
        let mut source = Pdf::open_mem_owned(bytes).expect("open source");
        let mut target = Pdf::empty().expect("empty target");
        let mut orphan_pages = BTreeSet::new();
        let mut visited = BTreeSet::new();

        let survivors = trim_field_kids(
            &mut source,
            &mut target,
            ObjectRef::new(5, 0),
            &BTreeSet::new(),
            &BTreeSet::new(),
            &BTreeMap::new(),
            &mut orphan_pages,
            0,
            &mut visited,
        )
        .expect("a self-referential /Kids must not hang or error");

        assert_eq!(
            survivors,
            Some(Vec::new()),
            "the cyclic re-entry must be treated as a childless sub-field, not retried"
        );
    }

    #[test]
    fn trim_field_kids_drops_a_dangling_widget_without_a_page_to_null() {
        let bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R >>"),
                (4, "<< /Fields [5 0 R] >>"),
                (5, "<< /FT /Tx /T (Field) /Kids [6 0 R] >>"),
                (6, "<< /Subtype /Widget >>"),
            ],
            1,
        );
        let mut source = Pdf::open_mem_owned(bytes).expect("open source");
        let mut target = Pdf::empty().expect("empty target");
        let mut orphan_pages = BTreeSet::new();
        let mut visited = BTreeSet::new();

        let survivors = trim_field_kids(
            &mut source,
            &mut target,
            ObjectRef::new(5, 0),
            &BTreeSet::new(),
            &BTreeSet::new(),
            &BTreeMap::new(),
            &mut orphan_pages,
            0,
            &mut visited,
        )
        .expect("trim must not error");

        assert_eq!(
            survivors,
            Some(Vec::new()),
            "a widget with no /P and no /Annots retention must not survive"
        );
        assert!(
            orphan_pages.is_empty(),
            "a /P-less dropped widget carries no page to null"
        );
    }
}