flpdf-cli 0.5.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
#![forbid(unsafe_code)]

mod arg_parser;

use clap::{ArgGroup, Args as ClapArgs, CommandFactory, Parser, Subcommand, ValueEnum};
use flpdf::fix_qdf;
use flpdf::job::{
    apply_rotate_to_pages, flatten_rotation_on_pages, remap_outline_and_dests,
    should_remove_unreferenced_resources, AttachmentAddOptions, AttachmentCopyOptions, CheckError,
    JobExitCode, JsonJobError, JsonJobOptions, JsonJobOutput, JsonStreamData, PageSpecInput,
    QPDFJob, RemoveUnreferencedResources, SplitPageOptions,
};
use flpdf::pipeline::PipelineHandle;
use flpdf::qutil::same_file as qpdf_same_file;
use flpdf::writer::DecodeLevel as StreamDecodeLevel;
use flpdf::{
    collate,
    objr_obj_annot_p::drop_objr_obj_annot_dangling_p,
    pages::tree_rebuild::{rebuild_page_tree, RebuildResult},
    struct_tree_pg::drop_struct_elem_dangling_pg,
    thread_bead_p::drop_thread_bead_dangling_p,
    CombinedPage, CombinedPlan, InputSpec, PageRange, RotateSpec,
};
use flpdf::{
    json_inspect::{DecodeLevel, JsonKey, JsonObjectSelector},
    linearization::{show_linearization_path_with_warnings, ShowLinearizationError},
    normalize_content_stream, pages, parse_pdf_version, AcroFormDocumentHelper, CompressStreams,
    CopyEncryptionSource, EncryptMethod, EncryptParams, Error, NewlineBeforeEndstream,
    ObjectHandle, ObjectKeyAlg, ObjectRef, ObjectStreamMode, PageDocumentHelper, PageObjectHelper,
    PasswordMode, Pdf, PdfOpenOptions, PdfVersion, PdfWriter, PermissionsConfig, PrintPermission,
    QPDFLogger, StreamDataMode, UsageError, WriterConfiguration,
};
use std::collections::{BTreeMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

type CliResult<T> = Result<T, Box<dyn std::error::Error>>;

struct PipelineWriter {
    pipeline: PipelineHandle,
}

impl Write for PipelineWriter {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        self.pipeline.write(data).map_err(std::io::Error::other)?;
        Ok(data.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// CLI-owned writer configuration. The library's lower-level option bridge is
/// intentionally private; all CLI output is configured through PdfWriter.
#[derive(Debug, Clone)]
struct WriterOptions {
    object_streams: ObjectStreamMode,
    /// Explicit `--compress-streams` value; `None` preserves qpdf's default
    /// without overriding an explicitly selected stream-data mode.
    compress_streams: Option<CompressStreams>,
    content_normalization: bool,
    content_normalization_set: bool,
    qdf: bool,
    preserve_unreferenced_objects: bool,
    newline_before_endstream: NewlineBeforeEndstream,
    stream_data: Option<StreamDataMode>,
    decode_level: StreamDecodeLevel,
    decode_level_set: bool,
    recompress_flate: bool,
    static_id: bool,
    deterministic_id: bool,
    static_aes_iv: bool,
    no_original_object_ids: bool,
    min_version: Option<String>,
    min_extension_level: Option<i64>,
    force_version: Option<String>,
    force_extension_level: Option<i64>,
    encrypt: Option<EncryptParams>,
    copy_encryption: Option<CopyEncryptionSource>,
    preserve_encryption: bool,
}

impl Default for WriterOptions {
    fn default() -> Self {
        Self {
            object_streams: ObjectStreamMode::Preserve,
            compress_streams: None,
            content_normalization: false,
            content_normalization_set: false,
            qdf: false,
            preserve_unreferenced_objects: false,
            newline_before_endstream: NewlineBeforeEndstream::Never,
            stream_data: None,
            decode_level: StreamDecodeLevel::None,
            decode_level_set: false,
            recompress_flate: false,
            static_id: false,
            deterministic_id: false,
            static_aes_iv: false,
            no_original_object_ids: false,
            min_version: None,
            min_extension_level: None,
            force_version: None,
            force_extension_level: None,
            encrypt: None,
            copy_encryption: None,
            preserve_encryption: true,
        }
    }
}

#[derive(Debug, Clone, Default)]
struct CliVersionOptions {
    min: Option<(String, i64)>,
    force: Option<(String, i64)>,
}

fn parse_cli_version_options(
    min: Option<&str>,
    force: Option<&str>,
) -> CliResult<CliVersionOptions> {
    let parse = |name: &str, value: Option<&str>| -> CliResult<Option<(String, i64)>> {
        value
            .map(|value| {
                flpdf::parse_pdf_version_spec(value)
                    .ok_or_else(|| format!("invalid {name} value: {value:?}").into())
            })
            .transpose()
    };
    Ok(CliVersionOptions {
        min: parse("--min-version", min)?,
        force: parse("--force-version", force)?,
    })
}

fn apply_cli_version_options(options: &mut WriterOptions, versions: &CliVersionOptions) {
    if let Some((version, extension_level)) = &versions.min {
        options.min_version = Some(version.clone());
        options.min_extension_level = Some(*extension_level);
    }
    if let Some((version, extension_level)) = &versions.force {
        options.force_version = Some(version.clone());
        options.force_extension_level = Some(*extension_level);
    }
}

fn apply_cli_decode_level(options: &mut WriterOptions, decode_level: Option<CliDecodeLevel>) {
    if let Some(level) = decode_level {
        options.decode_level = level.into();
        options.decode_level_set = true;
    }
}

/// Translate the CLI's effective writer options into the reusable library
/// configuration that qpdf reapplies to every split-page output writer.
fn writer_configuration(options: &WriterOptions, linearize: bool) -> WriterConfiguration {
    let mut configuration = WriterConfiguration::default();
    configuration.set_object_stream_mode(options.object_streams);
    if let Some(mode) = options.stream_data {
        configuration.set_stream_data_mode(mode);
    }
    if let Some(mode) = options.compress_streams {
        configuration.set_compress_streams(matches!(mode, CompressStreams::Yes));
    }
    if options.decode_level_set {
        configuration.set_decode_level(options.decode_level);
    }
    configuration.set_recompress_flate(options.recompress_flate);
    configuration.set_qdf_mode(options.qdf && !linearize);
    if options.content_normalization_set {
        configuration.set_content_normalization(options.content_normalization);
    }
    configuration.set_preserve_unreferenced_objects(options.preserve_unreferenced_objects);
    configuration.set_newline_before_endstream(matches!(
        options.newline_before_endstream,
        NewlineBeforeEndstream::Yes
    ));
    configuration.set_static_id(options.static_id);
    configuration.set_deterministic_id(options.deterministic_id);
    configuration.set_static_aes_iv(options.static_aes_iv);
    configuration.set_suppress_original_object_ids(options.no_original_object_ids);
    configuration.set_preserve_encryption(options.preserve_encryption);
    if let Some(version) = options.min_version.as_deref() {
        configuration.set_minimum_pdf_version(version, options.min_extension_level.unwrap_or(0));
    }
    if let Some(version) = options.force_version.as_deref() {
        configuration.force_pdf_version(version, options.force_extension_level.unwrap_or(0));
    }
    if let Some(params) = options.encrypt.clone() {
        configuration.set_encryption_parameters(params);
    }
    if let Some(source) = options.copy_encryption.clone() {
        configuration.copy_encryption_parameters(source);
    }
    configuration
}

fn configure_pdf_writer<R: Read + Seek + 'static>(
    writer: &mut PdfWriter<'_, R>,
    options: &WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
) -> CliResult<()> {
    writer_configuration(options, linearize).apply_to(writer);
    writer.set_linearization(linearize);
    if let Some(path) = linearize_pass1 {
        writer.set_linearization_pass1_filename(path.to_path_buf());
    }
    Ok(())
}

fn write_with_pdf_writer<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    output: &Path,
    standard_output: &mut Option<PipelineWriter>,
    options: &WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
) -> CliResult<()> {
    let mut writer = PdfWriter::new(pdf);
    configure_pdf_writer(&mut writer, options, linearize, linearize_pass1)?;
    if let Some(sink) = standard_output.take() {
        writer.set_output_writer(sink)?;
    } else {
        writer.set_output_file(output)?;
    }
    writer.write()?;
    Ok(())
}

fn write_qpdf_to_memory<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
) -> CliResult<Vec<u8>> {
    let mut writer = PdfWriter::new(pdf);
    configure_pdf_writer(&mut writer, options, false, None)?;
    writer.set_output_memory()?;
    writer.write()?;
    Ok(writer.get_buffer()?)
}

// ---------------------------------------------------------------------------
// qpdf-compatible exit-code infrastructure (flpdf-9hc.23.2)
//
// Source: qpdf manual §"Exit Status"
//   https://qpdf.readthedocs.io/en/stable/cli.html#exit-status
// Confirmed by qpdf C header (qpdf/include/qpdf/Constants.h):
//   qpdf_exit_success  = 0   (no errors or warnings)
//   qpdf_exit_error    = 2   (errors found)
//   qpdf_exit_warning  = 3   (warnings found, no errors)
//
// Note: exit code 1 is intentionally unused by qpdf (shells use it for
// command-not-found); flpdf follows the same convention.
//
// Future subtasks (e.g. flpdf-9hc.3.17) should express their own
// exit-code semantics by constructing a `CliExitError` with the appropriate
// `ExitCode` variant — the enum is generic enough for `--is-encrypted` (0/2)
// and `--requires-password` (0/2/3) once those subcommands are added.
// ---------------------------------------------------------------------------

/// qpdf-compatible CLI exit codes.
///
/// Matches `qpdf_exit_code_e` from `qpdf/include/qpdf/Constants.h`:
/// - `Ok` = 0: success, no errors or warnings
/// - `Errors` = 2: errors detected (file invalid / unprocessable)
/// - `Warnings` = 3: warnings found but no errors (recoverable issues)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    /// 0 — no errors or warnings detected.
    Ok = 0,
    /// 2 — errors found; file could not be fully processed.
    Errors = 2,
    /// 3 — warnings found (recoverable issues) but no hard errors.
    Warnings = 3,
}

impl ExitCode {
    pub fn as_i32(self) -> i32 {
        self as i32
    }
}

/// An error type that carries an explicit [`ExitCode`] so that `main()` can
/// use that code rather than defaulting to 2.
///
/// Use this (instead of a plain string error) whenever a CLI path needs to
/// communicate a specific exit code to the shell (e.g. `--check` warning-only
/// result → 3).  All other `CliResult::Err` values fall back to exit 2 via
/// the existing generic handler in `main()`.
#[derive(Debug)]
pub struct CliExitError {
    /// The exit code to pass to `std::process::exit`.
    pub code: ExitCode,
    /// Human-readable message printed to stderr.
    pub message: String,
}

impl std::fmt::Display for CliExitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for CliExitError {}

#[derive(Debug, Parser)]
#[command(name = "flpdf")]
#[command(about = "Pure Rust qpdf-style PDF tool")]
// Top-level option flags (--json, --check, --linearize, …) are mutually
// exclusive with subcommands. Without this, `flpdf --json rewrite in out`
// would parse as the rewrite subcommand while silently keeping --json,
// never reaching the JSON branch. Conflicting instead surfaces the
// ambiguity as a clean usage error.
#[command(args_conflicts_with_subcommands = true)]
// The five attachment operations are dispatched by an ordered `else if`
// chain in `main`, so supplying two at once would silently run only the
// first. Make them mutually exclusive at the parser level: clap rejects
// e.g. `--add-attachment … -- --copy-attachments-from …` with a usage
// error instead of discarding the second operation. (`--verbose` is a
// sub-modifier, not an operation, so it is intentionally NOT a member of
// this group.)
#[command(group(
    ArgGroup::new("attachment_op")
        .multiple(false)
        .args([
            "add_attachment",
            "remove_attachment",
            "list_attachments",
            "show_attachment",
            "copy_attachments_from",
        ])
))]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    // Legacy options kept for compatibility.
    #[arg(long, conflicts_with = "output")]
    check: bool,
    /// Suppress warning delivery while retaining qpdf's warning exit status.
    #[arg(long)]
    no_warn: bool,
    /// Check whether the input's linearization hint tables are correct
    /// (qpdf --check-linearization).
    #[arg(
        long = "check-linearization",
        conflicts_with_all = [
            "check",
            "show_object",
            "show_npages",
            "show_pages",
            "show_xref",
            "show_linearization",
            "show_encryption",
            "job_json_file",
            "json",
            "json_input",
            "update_from_json",
            "json_output",
            "json_key",
            "json_object",
            "json_stream_data",
            "json_stream_prefix",
            "linearize",
            "static_id",
            "deterministic_id",
            "static_aes_iv",
            "remove_restrictions",
            "decrypt",
            "qdf",
            "preserve_unreferenced",
            "coalesce_contents",
            "pages",
            "rotate",
            "split_pages",
            "collate",
            "empty",
            "overlay",
            "underlay",
            "add_attachment",
            "remove_attachment",
            "list_attachments",
            "show_attachment",
            "copy_attachments_from",
            "encrypt",
            "copy_encryption",
            "encryption_file_password",
            "output",
        ]
    )]
    check_linearization: bool,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
    #[arg(long, conflicts_with = "output")]
    show_object: Option<String>,
    /// Emit stored stream bytes for `--show-object` (qpdf --raw-stream-data).
    #[arg(long = "raw-stream-data", requires = "show_object")]
    raw_stream_data: bool,
    /// Emit decoded stream bytes for `--show-object` (qpdf --filtered-stream-data).
    #[arg(long = "filtered-stream-data", requires = "show_object")]
    filtered_stream_data: bool,
    #[arg(long, conflicts_with = "output")]
    show_npages: bool,
    #[arg(long, conflicts_with = "output")]
    show_pages: bool,
    #[arg(long, conflicts_with = "output")]
    show_xref: bool,
    #[arg(long, conflicts_with = "output")]
    show_linearization: bool,
    /// Show encryption parameters on the qpdf-compatible top-level surface.
    /// This is the argv form used by qtest (`qpdf --show-encryption FILE`);
    /// the native `show-encryption` subcommand dispatches to the same
    /// inspection implementation below.
    ///
    /// qpdf marks `showEncryption()` as `require_outfile = false`
    /// (`QPDFJob_config.cc:554-559`), so `checkConfiguration()`
    /// (`QPDFJob.cc:593-594`) rejects an output file argument outright with
    /// "no output file may be given for this option", regardless of what
    /// other flags accompany it.
    #[arg(long = "show-encryption", conflicts_with = "output")]
    show_encryption: bool,

    /// Include the derived encryption key in JSON's `encrypt.parameters.key`
    /// field (qpdf `--show-encryption-key`).
    #[arg(long = "show-encryption-key")]
    show_encryption_key: bool,

    /// Run a complete qpdf job JSON file through the production QPDFJob
    /// lifecycle (qpdf `--job-json-file`).
    #[arg(long = "job-json-file", value_name = "PATH", require_equals = true)]
    job_json_file: Option<PathBuf>,

    // ── JSON inspection flags ─────────────────────────────────────────────
    // These mirror qpdf's --json / --json-output / --json-key / --json-object
    // / --json-stream-data / --json-stream-prefix flags.
    /// Enable qpdf JSON output mode. Pass `--json` alone or `--json=1|2`.
    /// The value, when given, must be supplied with an equals sign to avoid
    /// ambiguity with the positional input argument.
    // JSON mode is exclusive with the other top-level inspection / write
    // modes and with the OUTPUT positional. Without these conflicts, e.g.
    // `flpdf --json --check in` or `flpdf --json in out` would silently
    // ignore the second mode (run_json wins in main's dispatch chain).
    // Listing them as clap conflicts surfaces the mistake as a usage error
    // instead of doing one thing while the user asked for two.
    #[arg(long, num_args = 0..=1, default_missing_value = "2",
          require_equals = true,
          value_name = "VERSION", value_parser = ["1", "2", "latest"],
          conflicts_with_all = [
              "check", "linearize", "static_id", "deterministic_id", "static_aes_iv",
              "show_object",
              "show_npages", "show_pages", "show_xref", "show_linearization",
              "show_encryption",
              "compress_streams", "linearize_pass1", "remove_restrictions",
              "decrypt", "encrypt", "copy_encryption",
              "add_attachment", "remove_attachment", "list_attachments",
              "show_attachment", "copy_attachments_from",
              "no_original_object_ids", "qdf", "coalesce_contents",
              "preserve_unreferenced",
          ],
          help = "Generate JSON v2 output (qpdf --json compatible)")]
    json: Option<String>,

    /// Treat INPUT as a qpdf JSON v2 document instead of a PDF
    /// (qpdf `--json-input`). The imported document then follows the same
    /// rewrite, page-operation, or JSON-output job routes as a PDF input.
    #[arg(
        long = "json-input",
        conflicts_with_all = [
            "show_object",
            "show_linearization", "list_attachments", "show_attachment",
            "remove_attachment", "add_attachment", "copy_attachments_from",
        ],
        help = "Treat INPUT as qpdf JSON v2 (qpdf --json-input)"
    )]
    json_input: bool,

    /// Apply a partial qpdf JSON v2 update to INPUT before any other job
    /// transformations (qpdf `--update-from-json`). qpdf requires the equals
    /// form so the JSON path cannot be confused with the PDF input path.
    #[arg(
        long = "update-from-json",
        value_name = "QPDF-JSON",
        require_equals = true,
        conflicts_with_all = [
            "show_object",
            "show_linearization", "list_attachments", "show_attachment",
            "remove_attachment", "add_attachment", "copy_attachments_from",
        ],
        help = "Apply a qpdf JSON update before processing (qpdf --update-from-json)"
    )]
    update_from_json: Option<PathBuf>,

    /// Write JSON output to PATH instead of stdout.
    #[arg(
        long = "json-output",
        num_args = 0..=1,
        default_missing_value = "2",
        require_equals = true,
        value_name = "VERSION",
        value_parser = ["1", "2", "latest"],
        help = "Generate qpdf JSON output; VERSION defaults to 2 and the output file is positional"
    )]
    json_output: Option<String>,

    /// Validate generated JSON against qpdf's own output schema. This is a
    /// testing option used by qpdf's qtest suite.
    #[arg(long = "test-json-schema")]
    test_json_schema: bool,

    /// Limit JSON output to the specified top-level key (repeatable).
    /// Valid JSON v2 keys: acroform, attachments, encrypt, outlines,
    /// pagelabels, pages, qpdf.
    #[arg(
        long = "json-key",
        value_name = "KEY",
        help = "This option is repeatable. If given, only the specified \
                top-level keys will be included in the JSON output. \
                Otherwise, all keys will be included."
    )]
    json_key: Vec<String>,

    /// Restrict JSON qpdf section to a single object (repeatable).
    /// Format: `trailer`, `N`, or `N,G`.
    #[arg(
        long = "json-object",
        value_name = "SELECTOR",
        help = "This option is repeatable. If given, only specified objects \
                will be shown in the \"qpdf\" key of the JSON output. \
                Otherwise, all objects will be shown. Format: trailer, N, \
                or N,G."
    )]
    json_object: Vec<String>,

    /// How to include stream data in JSON output.
    /// `none` (default) omits data; `inline` base64-encodes it; `file` writes
    /// side files named `<prefix>-NNN`.
    #[arg(
        long = "json-stream-data",
        value_name = "MODE",
        help = "When used with --json, this option controls whether streams \
                in json output should be omitted, written inline \
                (base64-encoded), or written to a file. If \"file\" is \
                chosen, the file name is the --json-stream-prefix value \
                appended with -nnn where nnn is the object number. The \
                default is \"none\"."
    )]
    json_stream_data: Option<String>,

    /// Prefix for side-file names when --json-stream-data=file.
    /// With --json-output, defaults to the JSON output path. With JSON on
    /// stdout, file stream data requires an explicit non-empty prefix.
    #[arg(
        long = "json-stream-prefix",
        value_name = "PREFIX",
        help = "Prefix for side files with --json-stream-data=file. With --json-output, \
                defaults to the JSON output path; with JSON on stdout, an explicit \
                non-empty prefix is required. An empty prefix is treated as absent."
    )]
    json_stream_prefix: Option<String>,

    // qpdf-style top-level write flags. When `--linearize` is set together
    // with INPUT and OUTPUT, behave as if `flpdf rewrite --linearize ...`
    // had been invoked. This exists so the qpdf qtest acceptance harness
    // (PATH-shimmed `qpdf` → `flpdf`) can issue qpdf-shaped commands
    // without an arg-translating wrapper.
    /// Produce a linearized ("fast web view") output PDF (top-level alias
    /// of `flpdf rewrite --linearize`).
    #[arg(long)]
    linearize: bool,

    /// Set a minimum PDF version for the output header. An optional third
    /// component is qpdf's Adobe extension level, e.g. `1.7.3`.
    #[arg(long = "min-version")]
    min_version: Option<String>,

    /// Force the output PDF version and optional Adobe extension level,
    /// ignoring the input version (qpdf `--force-version`).
    #[arg(long = "force-version")]
    force_version: Option<String>,

    /// Use a fixed value for the trailer /ID's changing identifier
    /// (top-level alias of `flpdf rewrite --static-id`). Testing only;
    /// never for production output. This qpdf-shaped alias mirrors qpdf,
    /// which is silent for `--static-id`, so it emits no warning; the
    /// test-only diagnostic lives on the native `rewrite --static-id`
    /// surface instead.
    #[arg(long = "static-id")]
    static_id: bool,
    /// Generate a deterministic trailer /ID[1] from an MD5 of the rewritten
    /// output body instead of a random value (top-level alias of `flpdf rewrite
    /// --deterministic-id`; qpdf `--deterministic-id` equivalent). The permanent
    /// identifier /ID[0] is preserved from the input. Implies a full rewrite.
    /// Mutually exclusive with `--static-id`, and incompatible with encrypted
    /// output (the /ID feeds the encryption key).
    #[arg(long = "deterministic-id", conflicts_with = "static_id")]
    deterministic_id: bool,
    /// Force every AES CBC IV to all-zero bytes instead of a random value
    /// (top-level alias of `flpdf rewrite --static-aes-iv`).
    /// **Testing only; produces insecure deterministic IVs, NOT for
    /// production.** Mirrors `qpdf --static-aes-iv`.
    #[arg(long = "static-aes-iv", hide = true)]
    static_aes_iv: bool,
    /// Strip encryption and advisory permission restrictions from the output
    /// (top-level alias of `flpdf rewrite --remove-restrictions`; qpdf
    /// `--remove-restrictions` equivalent). Does NOT bypass authentication.
    // This is a rewrite-path modifier. main()'s dispatch chain runs the
    // inspection modes (--check / --show-object / --show-*) before the
    // rewrite branch, so without these conflicts `flpdf --check
    // --remove-restrictions in out` would silently ignore the flag (and the
    // OUTPUT positional). Listing the inspection modes as clap conflicts
    // surfaces the mistake as a usage error instead. (--json already lists
    // remove_restrictions in its own conflicts_with_all; rewrite/linearize/
    // static_id/output are compatible rewrite modifiers and intentionally
    // excluded here.)
    #[arg(long = "remove-restrictions",
          conflicts_with_all = [
              "check", "show_object",
              "show_npages", "show_pages", "show_xref", "show_linearization",
              "show_encryption",
          ])]
    remove_restrictions: bool,
    /// Strip the `/Encrypt` dictionary from the output (top-level alias of
    /// `flpdf rewrite --decrypt`; qpdf `--decrypt` equivalent). On
    /// encrypted input requires `--password` to authenticate; on plaintext
    /// input it is a no-op pass-through. Silent in both cases (matching
    /// qpdf), unlike `--remove-restrictions` which prints a one-line
    /// diagnostic when an encrypted input was de-restricted.
    ///
    /// Relationship with `--remove-restrictions`: both select the same
    /// unencrypted output bytes; this flag is silent while
    /// `--remove-restrictions` prints its diagnostic.
    // Same conflict semantics as --remove-restrictions: this is a
    // rewrite-path modifier and must be rejected against the inspection
    // subcommands so `flpdf --check --decrypt in out` is a usage error
    // rather than silently ignoring the flag (and OUTPUT).
    #[arg(long = "decrypt",
          conflicts_with_all = [
              "check", "show_object",
              "show_npages", "show_pages", "show_xref", "show_linearization",
              "show_encryption",
          ])]
    decrypt: bool,
    /// `qpdf --compress-streams=y|n` compatibility flag.  Accepted but
    /// currently a no-op: flpdf does not re-encode stream contents on
    /// rewrite.  Provided so qtest commands parse cleanly.
    #[arg(long = "compress-streams")]
    compress_streams: Option<String>,
    /// Control which qpdf stream filters are decoded during rewrite.
    /// Values are ordered from least to most decoding: none, generalized,
    /// specialized, and all.
    #[arg(long = "decode-level", value_enum)]
    decode_level: Option<CliDecodeLevel>,
    /// Control what qpdf does regarding object streams. `preserve` preserves
    /// original object streams (the default), `disable` creates output with no
    /// object streams, and `generate` creates object streams and compresses
    /// objects when possible.
    #[arg(
        long = "object-streams",
        value_enum,
        default_value_t = CliObjectStreamMode::Preserve
    )]
    object_streams: CliObjectStreamMode,
    /// Control how streams are compressed in the output. `compress` is the
    /// same as `--compress-streams=y --decode-level=generalized`, `preserve`
    /// is the same as `--compress-streams=n --decode-level=none`, and
    /// `uncompress` is the same as `--compress-streams=n --decode-level=generalized`.
    #[arg(long = "stream-data", value_enum)]
    stream_data: Option<CliStreamDataMode>,
    /// `qpdf --linearize-pass1=PATH` compatibility flag. Writes the
    /// linearization writer's distinct pass-1 intermediate file.
    #[arg(long = "linearize-pass1")]
    linearize_pass1: Option<PathBuf>,
    /// Omit the `%% Original object ID: N M` comments that QDF output would
    /// otherwise carry (top-level alias of `flpdf rewrite
    /// --no-original-object-ids`; qpdf `--no-original-object-ids`
    /// equivalent). A compatible rewrite/QDF modifier — like `--static-id` it
    /// does not conflict with the rewrite-mode positionals.
    #[arg(long = "no-original-object-ids")]
    no_original_object_ids: bool,
    /// Create a PDF in QDF form: uncompressed, normalized,
    /// human-readable/editable; pair with the qdf-fix subcommand after manual
    /// edits (qpdf --qdf equivalent). Top-level alias of `flpdf rewrite
    /// --qdf`. Like `--static-id`/`--no-original-object-ids` it is a
    /// compatible rewrite/QDF modifier and does not conflict with the
    /// rewrite-mode positionals.
    #[arg(long = "qdf")]
    qdf: bool,

    /// Preserve input objects that are not reachable from trailer roots
    /// (qpdf `--preserve-unreferenced`). The default is disabled.
    #[arg(
        long = "preserve-unreferenced",
        help = "Preserve unreferenced input objects in writer output"
    )]
    preserve_unreferenced: bool,

    /// Normalize PDF page content streams (qpdf --normalize-content=y|n).
    ///
    /// The absence of this option is distinct from an explicit `n`: qpdf
    /// enables normalization by default in QDF mode, but an explicit `n`
    /// overrides that QDF default.
    #[arg(
        long = "normalize-content",
        value_enum,
        help = "Normalize page content streams (qpdf default: n; --qdf default: y)"
    )]
    normalize_content: Option<CliYesNo>,

    /// Coalesce multiple /Contents streams into a single stream per page
    /// (top-level alias of `flpdf rewrite --coalesce-contents`; qpdf
    /// `--coalesce-contents` equivalent). Requires a full rewrite of the
    /// document. Rejected against inspection, attachment, `--linearize`,
    /// and page-operation modes: the linearize branch of `run_rewrite`
    /// and the page-op dispatch never read `args.coalesce_contents`, so
    /// without these conflicts the flag would be silently dropped and the
    /// user's requested coalescing would not appear in the output.
    #[arg(long = "coalesce-contents",
          conflicts_with_all = [
              "check", "show_object",
              "show_npages", "show_pages", "show_xref", "show_linearization",
              "show_encryption",
              "list_attachments", "show_attachment", "remove_attachment",
              "add_attachment", "copy_attachments_from",
              "linearize", "pages", "rotate", "split_pages", "empty",
          ])]
    coalesce_contents: bool,

    // ── Page-operation flags (flpdf-9hc.8.12) ─────────────────────────────
    // These mirror qpdf's page-selection / page-transformation surface.
    // Observed against /usr/bin/qpdf 11.9.0:
    //   qpdf --help=--pages / --rotate / --split-pages / --collate
    //   qpdf in.pdf --pages . a.pdf b.pdf 1-z:even -- out.pdf
    #[command(flatten)]
    page_ops: PageOpArgs,

    // ── Overlay / underlay flags (flpdf-9hc.16), top-level alias ──────────
    // Mirror qpdf's top-level `qpdf in --overlay f -- out` form. Like the
    // `rewrite` subcommand fields, the per-group boundaries are extracted from
    // raw argv by `preprocess_qpdf_args` before clap parses; these fields
    // exist only for `--help` documentation and to accept a leaked token.
    /// Overlay pages from another file on top of the output (qpdf `--overlay`;
    /// top-level alias of `rewrite --overlay`). Repeatable; terminate each
    /// group with `--`.
    #[arg(
        long = "overlay",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "[--file=]FILE [sub-flags]",
        help = "Overlay pages from FILE on top of the output (qpdf --overlay); \
                repeatable, terminate each group with --"
    )]
    overlay: Vec<String>,

    /// Underlay pages from another file beneath the output (qpdf `--underlay`;
    /// top-level alias of `rewrite --underlay`). Repeatable; terminate each
    /// group with `--`.
    #[arg(
        long = "underlay",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "[--file=]FILE [sub-flags]",
        help = "Underlay pages from FILE beneath the output (qpdf --underlay); \
                repeatable, terminate each group with --"
    )]
    underlay: Vec<String>,

    // ── Attachment flags (flpdf-9hc.10.9) ────────────────────────────────
    // Five qpdf-compatible attachment operations.  Each is a top-level flag
    // dispatched before the default rewrite branch.
    //
    // --add-attachment and --copy-attachments-from use value_terminator="--"
    // and allow_hyphen_values=true so that their sub-flags (--key, --filename,
    // --prefix, --password, …) are captured verbatim in the token Vec rather
    // than being parsed as global clap flags.
    /// Add an attachment to the input PDF (qpdf --add-attachment compatible).
    ///
    /// Syntax: `--add-attachment FILE [--key=K] [--filename=F] [--mimetype=M]
    ///           [--description=D] [--creationdate=D] [--moddate=D]
    ///           [--replace] --`
    ///
    /// The `--` terminator ends the sub-flag segment. The token after `--` is
    /// the OUTPUT positional.
    #[arg(
        long = "add-attachment",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "FILE [sub-flags]",
        help = "Add a file attachment (qpdf --add-attachment compatible); \
                terminate segment with --"
    )]
    add_attachment: Vec<String>,

    /// Remove an attachment by key (qpdf --remove-attachment compatible).
    ///
    /// KEY is the name-tree key used when the attachment was added.
    #[arg(
        long = "remove-attachment",
        value_name = "KEY",
        help = "Remove the embedded file with the given key (qpdf --remove-attachment)"
    )]
    remove_attachment: Option<String>,

    /// List all embedded-file attachments (qpdf --list-attachments compatible).
    #[arg(
        long = "list-attachments",
        conflicts_with = "output",
        help = "List all embedded-file attachments (qpdf --list-attachments)"
    )]
    list_attachments: bool,

    /// Print verbose progress and diagnostic messages (mirrors qpdf --verbose).
    #[arg(
        long = "verbose",
        help = "Print verbose progress and diagnostic messages \
                (mirrors qpdf --verbose)"
    )]
    verbose: bool,

    /// Extract an attachment by key (qpdf --show-attachment compatible).
    ///
    /// KEY is the name-tree key used when the attachment was added. The raw
    /// bytes are written to stdout.
    #[arg(
        long = "show-attachment",
        conflicts_with = "output",
        value_name = "KEY",
        help = "Extract the embedded file with the given key to stdout \
                (qpdf --show-attachment)"
    )]
    show_attachment: Option<String>,

    /// Copy attachments from another PDF (qpdf --copy-attachments-from compatible).
    ///
    /// Syntax: `--copy-attachments-from FILE [--password=P] [--prefix=X] --`
    ///
    /// The `--` terminator ends the sub-flag segment.
    #[arg(
        long = "copy-attachments-from",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "FILE [sub-flags]",
        help = "Copy attachments from another PDF (qpdf --copy-attachments-from compatible); \
                terminate segment with --"
    )]
    copy_attachments_from: Vec<String>,

    /// Encrypt the output (qpdf `--encrypt` compatible).
    ///
    /// Syntax: `--encrypt USER-PW OWNER-PW KEY-LEN [sub-flags] --`
    ///
    /// USER-PW / OWNER-PW are the two password strings; KEY-LEN selects the
    /// qpdf Standard security handler family (`40`, `128`, or `256`). The
    /// AES, R=5, weak-crypto, and permission sub-flags follow qpdf's
    /// compatibility rules and are validated before writing.
    ///
    /// The `--` terminator ends the sub-flag segment. The tokens after
    /// `--` are the INPUT / OUTPUT positionals.
    #[arg(
        long = "encrypt",
        num_args = 3..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "USER-PW OWNER-PW KEY-LEN [sub-flags]",
        // Reject combinations that don't make sense on the rewrite path.
        // --remove-restrictions / --decrypt overlap with --encrypt and are
        // rejected because they imply contradictory output forms; --check /
        // --show-object / --show-* are inspection paths that don't produce an
        // output file at all. --linearize is NOT rejected: qpdf itself
        // supports `--linearize --encrypt ...` (verified: `qpdf --linearize
        // --encrypt "" "" 128 --use-aes=y --` produces a valid,
        // `qpdf --check`-clean linearized+encrypted file), and
        // `write_linearized` threads `options.encrypt` through correctly.
        conflicts_with_all = [
            "check", "show_object",
            "show_npages", "show_pages", "show_xref", "show_linearization",
            "show_encryption",
            "remove_restrictions", "decrypt",
            "copy_encryption",
        ],
        help = "Encrypt output (qpdf --encrypt compatible): \
                USER-PW OWNER-PW KEY-LEN [sub-flags] --"
    )]
    encrypt: Vec<String>,

    /// Copy the /Encrypt dictionary from a donor PDF and use its passwords for
    /// output encryption (qpdf --copy-encryption equivalent).
    ///
    /// Supply the donor's password via `--encryption-file-password` (empty
    /// string if the donor has no user password).  Only V=4 AES-128 donors are
    /// supported; other schemes are rejected
    /// with a "not yet supported" diagnostic.
    ///
    /// Mutually exclusive with `--encrypt`. `--linearize` may be combined with
    /// this option; qpdf supports copying encryption into a linearized output.
    #[arg(
        long = "copy-encryption",
        value_name = "FILE",
        conflicts_with_all = [
            "encrypt",
            "check", "show_object",
            "show_npages", "show_pages", "show_xref", "show_linearization",
            "show_encryption",
            "remove_restrictions", "decrypt",
        ],
        help = "Copy /Encrypt from donor PDF (qpdf --copy-encryption); \
                pair with --encryption-file-password"
    )]
    copy_encryption: Option<PathBuf>,

    /// Password to open the donor PDF specified by `--copy-encryption`.
    ///
    /// Omit (or pass an empty string) if the donor has no user password.
    /// This is the *donor's* password, not the output file's password
    /// (the output inherits the donor's passwords exactly).
    #[arg(
        long = "encryption-file-password",
        value_name = "PW",
        requires = "copy_encryption",
        help = "User password to open the donor PDF for --copy-encryption"
    )]
    encryption_file_password: Option<String>,

    input: Option<PathBuf>,
    output: Option<PathBuf>,
}

/// qpdf-compatible page-operation flags, shared by the top-level CLI and the
/// `rewrite` subcommand.
///
/// `--pages SPEC... --` captures the raw multi-input page-selection segment
/// verbatim (clap `value_terminator = "--"`, `allow_hyphen_values = true`) so
/// the embedded `--password=` / `--file=` / `--range=` tokens reach the
/// hand-written segment parser rather than being eaten as global flags. This
/// was verified empirically: with this attribute set, the top-level
/// `--password` field stays `None` while the segment vec captures
/// `["--password=x", …]`.
#[derive(Debug, Clone, Default, ClapArgs)]
struct PageOpArgs {
    /// Select pages from one or more input files (qpdf `--pages`).
    ///
    /// Syntax (qpdf 11.9.0 `--help=page-selection`):
    ///   `--pages [--file=]file [--password=pw] [page-range] [...] -- out.pdf`
    /// `.` is a shorthand for the primary input file. An omitted page-range
    /// selects all pages of that file. The `--` terminator ends the segment;
    /// the token after it is the OUTPUT positional.
    ///
    /// Distinct source files are opened and copied through the qpdf-shaped
    /// `QPDFJob::handle_page_specs` boundary; JSON-created primaries retain
    /// their separate single-document restriction until their source heap is
    /// implemented.
    #[arg(
        long = "pages",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "SPEC",
        help = "Select pages from input files: --pages [--file=]f [--password=p] \
                [range] [...] -- (qpdf-compatible). '.' = primary input; omitted \
                range = all pages."
    )]
    pages: Vec<String>,

    /// Rotate pages by a multiple of 90 degrees (qpdf `--rotate`).
    ///
    /// Form: `[+|-]angle[:page-range]` where angle ∈ {0,90,180,270}.
    /// Repeatable; specs are applied in argument order. In `--pages` mode the
    /// page-range refers to OUTPUT page numbers (qpdf 11.9.0-observed:
    /// `qpdf in --pages . 2-3 -- --rotate=+90:1 out` rotates the first
    /// extracted page).
    #[arg(
        long = "rotate",
        action = clap::ArgAction::Append,
        value_name = "[+|-]angle[:range]",
        help = "Rotate pages by 0/90/180/270 degrees (qpdf --rotate); repeatable"
    )]
    rotate: Vec<String>,

    /// Write one output file per N-page group instead of a single file
    /// (qpdf `--split-pages[=n]`, default n=1).
    ///
    /// File names follow qpdf's `doSplitPages` naming: a `-first-last`
    /// suffix is inserted before the `.pdf` extension. Compatible with
    /// `--pages`.
    #[arg(
        long = "split-pages",
        num_args = 0..=1,
        default_missing_value = "1",
        require_equals = true,
        value_name = "N",
        help = "Split output into N-page files (qpdf --split-pages[=n], default 1)"
    )]
    split_pages: Option<String>,

    /// Collate (interleave) pages selected with `--pages` instead of
    /// concatenating (qpdf `--collate[=n[,m,...]]`, default n=1).
    ///
    /// Only meaningful together with `--pages`; qpdf 11.9.0 accepts it as a
    /// no-op otherwise (exit 0), and flpdf matches that.
    #[arg(
        long = "collate",
        num_args = 0..=1,
        default_missing_value = "1",
        require_equals = true,
        value_name = "N",
        help = "Collate --pages selections in groups of N (qpdf --collate[=n], default 1)"
    )]
    collate: Option<String>,

    /// `qpdf --empty` — start from an empty document. Parsed for qpdf-script
    /// compatibility but NOT implemented at this layer (would silently
    /// produce wrong output if ignored), so it errors actionably.
    #[arg(
        long = "empty",
        help = "(qpdf --empty) start from an empty document — NOT yet implemented"
    )]
    empty: bool,
}

// The RewriteCommand variant is large by design (it holds many optional flags).
// Boxing it would require matching `Commands::Rewrite(cmd)` with a deref in
// every match arm — a larger refactor than warranted for this lint.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Subcommand)]
enum Commands {
    #[command(about = "Validate PDF structure and report diagnostics")]
    Check(CheckCommand),
    #[command(
        name = "check-linearization",
        about = "Validate linearization structure (param dict, hint stream, offsets)"
    )]
    CheckLinearization(CheckLinearizationCommand),
    #[command(name = "dump-object", about = "Dump one indirect object as PDF syntax")]
    DumpObject(DumpObjectCommand),
    #[command(about = "Show page structure summary or detail")]
    Pages(PagesCommand),
    #[command(about = "Create a PDF in QDF form (alias of `rewrite --qdf`)")]
    Qdf(QdfCommand),
    #[command(
        name = "qdf-fix",
        about = "Repair stream /Length, xref offsets, /Size and startxref in a hand-edited QDF file (qpdf fix-qdf equivalent)"
    )]
    QdfFix(QdfFixCommand),
    #[command(about = "Rewrite the input PDF to a normalized output")]
    Rewrite(RewriteCommand),
    #[command(
        name = "show-stream",
        about = "Show a stream object's decoded (or raw) data"
    )]
    ShowStream(ShowStreamCommand),
    #[command(
        name = "show-encryption",
        about = "Show encryption parameters (qpdf --show-encryption compatible)",
        long_about = "\
Print a parseable, greppable encryption report for FILE.

The qpdf `--show-encryption` lines are emitted verbatim (`R = `, `P = `,
the `extract/print/modify ...: allowed|not allowed` block, and the
`stream/string/file encryption method:` lines for V>=4) so scripts that
including `User password = ...` and V<5 owner-password recovery. If the
password is wrong, qpdf's `Incorrect password supplied` line is emitted
before the parsed encryption report. If FILE is not encrypted, prints qpdf's
`File is not encrypted` and exits 0."
    )]
    ShowEncryption(EncryptionInspectCommand),
    #[command(
        name = "is-encrypted",
        about = "Exit 0 if FILE is encrypted, 2 if not (qpdf --is-encrypted)",
        long_about = "\
Silently exit 0 if FILE is encrypted, 2 if it is not encrypted. Works for
password-protected files even without the password. Mirrors qpdf
`--is-encrypted` (qpdf_exit_is_not_encrypted=2)."
    )]
    IsEncrypted(IsEncryptedCommand),
    #[command(
        name = "requires-password",
        about = "Exit 0/2/3 reporting whether a password is required (qpdf --requires-password)",
        long_about = "\
Silently exit reporting FILE's password requirement (qpdf
--requires-password):
  0 = encrypted and a password other than the one supplied is required
  2 = not encrypted (qpdf_exit_is_not_encrypted)
  3 = encrypted and the supplied/empty password opens it
      (qpdf_exit_correct_password)"
    )]
    RequiresPassword(EncryptionInspectCommand),
    #[command(
        name = "show-encryption-key",
        about = "Print the file encryption key as lowercase hex (qpdf --show-encryption-key)",
        long_about = "\
Authenticate FILE with the supplied/empty password, then print the
derived file encryption key as lowercase hex. Mirrors qpdf
`--show-encryption-key`. Errors (exit 2) if FILE is not encrypted or the
password is incorrect."
    )]
    ShowEncryptionKey(EncryptionInspectCommand),
}

/// Args for inspection subcommands that authenticate the document
/// (`show-encryption`, `requires-password`, `show-encryption-key`).
#[derive(Debug, ClapArgs)]
struct EncryptionInspectCommand {
    input: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
}

/// Args for `is-encrypted`. No password: qpdf detects encryption without
/// authenticating, so a password would be meaningless here.
#[derive(Debug, ClapArgs)]
struct IsEncryptedCommand {
    input: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    recovery: RecoveryArgs,
}

#[derive(Debug, ClapArgs)]
struct CheckCommand {
    input: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
}

#[derive(Debug, ClapArgs)]
struct CheckLinearizationCommand {
    /// Input PDF file to validate.
    input: PathBuf,
}

#[derive(Debug, ClapArgs)]
struct DumpObjectCommand {
    object_ref: String,
    input: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
}

#[derive(Debug, ClapArgs)]
struct ShowStreamCommand {
    /// Object reference, e.g. "7 0" or "7 0 R".
    object_ref: String,
    input: PathBuf,
    /// Emit unfiltered stored bytes instead of decoding (qpdf --raw-stream-data).
    #[arg(long = "raw-stream-data")]
    raw_stream_data: bool,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
}

#[derive(Debug, ClapArgs)]
struct PagesCommand {
    input: PathBuf,
    /// Print only the page count (qpdf --show-npages).
    #[arg(long = "show-npages")]
    show_npages: bool,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
}

#[derive(Debug, ClapArgs)]
struct QdfCommand {
    input: PathBuf,
    output: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
    /// Preserve input objects that are not reachable from trailer roots
    /// (qpdf `--preserve-unreferenced`).
    #[arg(long = "preserve-unreferenced")]
    preserve_unreferenced: bool,
}

/// Args for `qdf-fix` (qpdf `fix-qdf` equivalent). No password / no Pdf
/// open: fix_qdf operates byte-for-byte on a (possibly hand-edited) QDF file
/// and must not reparse or reformat it.
#[derive(Debug, ClapArgs)]
struct QdfFixCommand {
    input: PathBuf,
    output: PathBuf,
}

#[derive(Debug, ClapArgs)]
struct RewriteCommand {
    input: PathBuf,
    output: PathBuf,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
    /// Produce a linearized ("fast web view") output PDF.
    #[arg(long)]
    linearize: bool,
    /// Use a fixed value for the trailer /ID's changing identifier (qpdf
    /// --static-id equivalent). Testing only; not for production output.
    /// Emits a stderr warning when used (suppress with the
    /// FLPDF_STATIC_ID_QUIET env var).
    #[arg(long = "static-id")]
    static_id: bool,
    /// Generate a deterministic trailer /ID[1] from an MD5 of the rewritten
    /// output body instead of a random value (qpdf `--deterministic-id`
    /// equivalent).
    ///
    /// The changing identifier /ID[1] is an MD5 over the rewritten output body;
    /// the permanent identifier /ID[0] is preserved from the input (matching
    /// `--static-id` and ISO 32000-1 §14.4). Uses the canonical writer. Mutually
    /// exclusive with `--static-id`, and incompatible with encrypted output (the
    /// /ID feeds the encryption key). Unlike `--static-id` it is a production-safe
    /// flag and emits no testing-only warning.
    #[arg(long = "deterministic-id", conflicts_with = "static_id")]
    deterministic_id: bool,
    /// Force every AES CBC IV to all-zero bytes instead of a random value.
    /// **Testing only; produces insecure deterministic IVs, NOT for
    /// production.** Mirrors `qpdf --static-aes-iv`.
    #[arg(long = "static-aes-iv", hide = true)]
    static_aes_iv: bool,
    /// Strip encryption and advisory permission restrictions from the output
    /// (qpdf `--remove-restrictions` equivalent).
    ///
    /// A normal rewrite preserves authenticated source encryption. This flag
    /// explicitly disables that preservation, removes `/Encrypt` (and its
    /// advisory `/P` permissions), and prints a one-line diagnostic when an
    /// encrypted input was de-restricted. It does NOT bypass authentication.
    ///
    /// See `--decrypt` for the silent qpdf-compatible variant; on the current
    /// rewrite path the two flags produce identical output bytes.
    #[arg(long = "remove-restrictions")]
    remove_restrictions: bool,
    /// Strip the `/Encrypt` dictionary from the output (qpdf `--decrypt`
    /// equivalent). On encrypted input requires `--password` to
    /// authenticate; on plaintext input it is a no-op pass-through. Silent
    /// in both cases, matching qpdf `--decrypt`.
    ///
    /// Relationship with `--remove-restrictions`: both select the same
    /// unencrypted output bytes; this flag is silent while
    /// `--remove-restrictions` prints its diagnostic.
    #[arg(long = "decrypt")]
    decrypt: bool,
    /// Encrypt the output (qpdf `--encrypt` compatible). See the top-level
    /// `--encrypt` documentation for the full syntax and supported modes.
    /// `--linearize` is not rejected: qpdf itself supports
    /// `--linearize --encrypt ...`, and `write_linearized` threads
    /// `options.encrypt` through correctly.
    #[arg(
        long = "encrypt",
        num_args = 3..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "USER-PW OWNER-PW KEY-LEN [sub-flags]",
        conflicts_with_all = [
            "remove_restrictions", "decrypt",
            "copy_encryption",
        ]
    )]
    encrypt: Vec<String>,
    /// Copy the /Encrypt dictionary from a donor PDF and use its passwords for
    /// output encryption (qpdf --copy-encryption equivalent).
    ///
    /// Supply the donor's password via `--encryption-file-password` (empty
    /// string if the donor has no user password).  Only V=4 AES-128 donors are
    /// supported; other schemes are rejected
    /// with a "not yet supported" diagnostic.
    ///
    /// Mutually exclusive with `--encrypt`. `--linearize` may be combined with
    /// this option; qpdf supports copying encryption into a linearized output.
    #[arg(
        long = "copy-encryption",
        value_name = "FILE",
        conflicts_with_all = [
            "encrypt",
            "remove_restrictions", "decrypt",
        ],
        help = "Copy /Encrypt from donor PDF (qpdf --copy-encryption); \
                pair with --encryption-file-password"
    )]
    copy_encryption: Option<PathBuf>,
    /// Password to open the donor PDF specified by `--copy-encryption`.
    ///
    /// Omit (or pass an empty string) if the donor has no user password.
    #[arg(
        long = "encryption-file-password",
        value_name = "PW",
        requires = "copy_encryption",
        help = "User password to open the donor PDF for --copy-encryption"
    )]
    encryption_file_password: Option<String>,
    /// Set a minimum PDF version for the output header.
    ///
    /// The effective version is `max(source_version, min_version)`.
    /// Mirrors `qpdf --min-version`.
    #[arg(long = "min-version")]
    min_version: Option<String>,
    /// Force the output PDF version header to exactly this value.
    ///
    /// Overrides source version and the linearize 1.2 floor.
    /// Mirrors `qpdf --force-version`.
    #[arg(long = "force-version")]
    force_version: Option<String>,
    /// Omit the `%% Original object ID: N M` comments that QDF output would
    /// otherwise carry. Mirrors `qpdf --no-original-object-ids`.
    ///
    /// Observed (qpdf 11.9.0): this flag changes only QDF output; qpdf JSON
    /// v1/v2 is byte-identical with or without it, so flpdf does not wire it
    /// into any JSON path. flpdf's QDF writer does not yet emit these
    /// comments; the flag is
    /// accepted and plumbed for forward-compatibility, so today it is a
    /// byte-level no-op.
    #[arg(long = "no-original-object-ids")]
    no_original_object_ids: bool,
    /// Create a PDF in QDF form: uncompressed, normalized,
    /// human-readable/editable; pair with the qdf-fix subcommand after manual
    /// edits (qpdf --qdf equivalent).
    ///
    /// Uses the canonical writer and preserves the explicit --object-streams mode. Cannot be
    /// combined with --linearize (QDF is inherently non-linearized).
    #[arg(long = "qdf")]
    qdf: bool,
    /// Preserve input objects that are not reachable from trailer roots
    /// (qpdf `--preserve-unreferenced`). The default is disabled.
    #[arg(long = "preserve-unreferenced")]
    preserve_unreferenced: bool,
    /// Object stream behaviour for the output. Mirrors qpdf
    /// `--object-streams=preserve|disable|generate`. Default: `preserve`.
    ///
    /// - `preserve` (default): reuse the source document's existing ObjStm
    ///   grouping.
    /// - `disable`: emit every eligible object as a plain indirect object.
    /// - `generate`: pack eligible objects into freshly generated ObjStm
    ///   containers.
    ///
    /// Applies to the canonical qpdf writer output.
    #[arg(long = "object-streams", value_enum, default_value_t = CliObjectStreamMode::Preserve)]
    object_streams: CliObjectStreamMode,

    /// Apply FlateDecode compression to output streams (qpdf --compress-streams=y|n).
    ///
    /// `y` (default): decode each source stream and re-emit with a single /FlateDecode
    /// filter, matching qpdf's default behaviour.
    /// `n`: decode each source stream and emit raw bytes without any filter.
    ///
    /// Only affects the full-rewrite path.
    #[arg(
        long = "compress-streams",
        value_enum,
        help = "Compress output streams with FlateDecode (qpdf default: y)"
    )]
    compress_streams: Option<CliYesNo>,

    /// Control which qpdf stream filters are decoded during rewrite.
    #[arg(long = "decode-level", value_enum)]
    decode_level: Option<CliDecodeLevel>,

    /// Normalize PDF content streams (qpdf --normalize-content=y|n).
    ///
    /// `y`: re-tokenize each page content stream and emit a canonical whitespace-
    /// normalized form, matching qpdf's `--normalize-content=y`.
    /// `n` (default): leave content streams untouched (qpdf default).
    ///
    /// When enabled, each page's content stream is updated in-place before writing,
    /// which requires a full rewrite of the document.
    #[arg(
        long = "normalize-content",
        value_enum,
        help = "Normalize page content streams (qpdf default: n)"
    )]
    normalize_content: Option<CliYesNo>,

    /// Coalesce multiple /Contents streams into a single stream per page
    /// (qpdf --coalesce-contents).
    ///
    /// When a page's /Contents is an array of two or more stream references,
    /// merge them into a single stream. Default: off (qpdf default: off).
    ///
    /// Requires a full rewrite of the document when enabled.
    #[arg(
        long = "coalesce-contents",
        help = "Merge per-page /Contents arrays into a single stream (qpdf default: off)"
    )]
    coalesce_contents: bool,

    /// Remove unreferenced /Resources entries from each page
    /// (qpdf --remove-unreferenced-resources=auto|yes|no).
    ///
    /// - `auto` (default): prune only pages whose /Resources are not shared with
    ///   another page — safe heuristic, qpdf-compatible.
    /// - `yes`: prune on a per-page basis regardless of sharing (union of
    ///   all referencing pages' used names is kept to avoid breakage).
    /// - `no`: leave all /Resources entries untouched.
    ///
    /// Requires a full rewrite when set to `yes` or `auto`.
    #[arg(long = "remove-unreferenced-resources", value_enum,
          default_value_t = CliRemoveUnreferencedResources::Auto,
          help = "Remove unreferenced /Resources entries (qpdf default: auto)")]
    remove_unreferenced_resources: CliRemoveUnreferencedResources,

    /// Insert a newline before each `endstream` keyword
    /// (qpdf --newline-before-endstream=y|n|never).
    ///
    /// `never` (default): never insert a newline, so exactly `/Length` bytes sit
    /// between `stream` and `endstream`. Reproduces qpdf's default output and is
    /// required for byte-identical qpdf-equivalent rewrites.
    /// `y` and `n`: enable qpdf's boolean option and always write exactly one
    /// `\n` before `endstream`. qpdf 11.9.0 accepts both value spellings as
    /// the presence of the flag.
    /// Unrecognized attached values are also treated as flag presence, as in
    /// qpdf's bare-option parser.
    ///
    /// Only affects the full-rewrite path.
    #[arg(long = "newline-before-endstream", value_enum, num_args = 0..=1,
          require_equals = true, default_missing_value = "y",
          default_value_t = CliNewlineBeforeEndstream::Never,
          help = "Insert newline before endstream keyword (qpdf default: never)")]
    newline_before_endstream: CliNewlineBeforeEndstream,

    /// Stream data mode (qpdf --stream-data={preserve,uncompress,compress}).
    ///
    /// Higher-level policy that sets stream decode behavior before an explicitly
    /// supplied --compress-streams value, matching qpdf's writer setter order.
    /// - `preserve`: pass streams through verbatim — no decode or re-encode.
    /// - `uncompress`: decode streams and emit raw bytes (no /Filter).
    /// - `compress`: decode streams and re-encode with /FlateDecode.
    ///
    /// Default: not set (falls back to --compress-streams).
    /// When both are supplied explicitly, --compress-streams wins.
    /// Only affects the full-rewrite path.
    #[arg(long = "stream-data", value_enum)]
    stream_data: Option<CliStreamDataMode>,

    /// Re-encode streams that are already a lone /FlateDecode (default: preserve
    /// them verbatim, matching qpdf). Mirrors `qpdf --recompress-flate`.
    #[arg(long = "recompress-flate")]
    recompress_flate: bool,

    /// Flatten annotations into page content (qpdf `--flatten-annotations`).
    ///
    /// MODE is `all`, `screen`, or `print`:
    /// - `all`: bake every visible annotation into the page content stream.
    /// - `screen`: annotations that render on screen, including printable annotations.
    /// - `print`: only annotations flagged for printing.
    ///
    /// Combine with `--generate-appearances` to first synthesize missing
    /// form-field appearance streams; generation always runs before
    /// flattening. Requires a full rewrite of the document.
    #[arg(
        long = "flatten-annotations",
        value_enum,
        value_name = "MODE",
        help = "Flatten annotations into page content; MODE is all, screen, or print"
    )]
    flatten_annotations: Option<CliFlattenMode>,

    /// Generate appearance streams for form fields that lack them
    /// (qpdf `--generate-appearances`).
    ///
    /// Only runs if the document's `/AcroForm` indicates its appearances are
    /// out of date (`/NeedAppearances true`); otherwise this is a no-op.
    /// When it runs, form fields whose widgets have no `/AP` `/N` appearance
    /// are rendered from their current value (`/V`) and default appearance
    /// (`/DA`). Useful before `--flatten-annotations` so value-only fields
    /// are not dropped. Requires a full rewrite of the document.
    #[arg(
        long = "generate-appearances",
        help = "Generate appearance streams for form fields that lack them"
    )]
    generate_appearances: bool,

    /// Flatten page rotation by baking `/Rotate` into page content
    /// (qpdf `--flatten-rotation`).
    ///
    /// Removes each page's `/Rotate` entry and rewrites its content,
    /// `/MediaBox`, and annotation rectangles so the visible orientation is
    /// unchanged. Requires a full rewrite of the document.
    #[arg(
        long = "flatten-rotation",
        help = "Flatten page rotation by baking /Rotate into content"
    )]
    flatten_rotation: bool,

    /// qpdf-compatible page-operation flags (--pages / --rotate /
    /// --split-pages / --collate / --empty). See [`PageOpArgs`].
    #[command(flatten)]
    page_ops: PageOpArgs,

    // ── Overlay / underlay flags (flpdf-9hc.16) ───────────────────────────
    // qpdf --overlay / --underlay impose pages from another file on top of
    // (overlay) or beneath (underlay) the destination pages. Both are
    // REPEATABLE and each group is terminated by a bare `--`. Within a group
    // the file token and sub-options may appear in any order:
    //   {--overlay|--underlay} [--file=]f [--password=p] [--to=R] [--from=R]
    //                          [--repeat=R] --
    //
    // The repeated occurrences and their per-group boundaries are extracted
    // from the raw argv by `preprocess_qpdf_args` BEFORE clap parses (clap's
    // derive flattens repeated `Vec<String>` occurrences, losing the group
    // boundary and the per-group declaration order needed for byte-identical
    // composition). These two fields exist only so `--help` documents the
    // flags and so a leaked token is accepted; the value vectors are not read.
    /// Overlay pages from another file on top of the destination pages (qpdf
    /// `--overlay`). Repeatable; terminate each group with `--`.
    ///
    /// Syntax: `--overlay [--file=]FILE [--password=PW] [--to=R] [--from=R]
    ///          [--repeat=R] --`. Within a group the file token and sub-options
    /// may appear in any order. Pages are stacked in order of appearance: first
    /// underlays, then the original page, then overlays.
    #[arg(
        long = "overlay",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "[--file=]FILE [sub-flags]",
        help = "Overlay pages from FILE on top of the output (qpdf --overlay); \
                repeatable, terminate each group with --"
    )]
    overlay: Vec<String>,

    /// Underlay pages from another file beneath the destination pages (qpdf
    /// `--underlay`). Repeatable; terminate each group with `--`.
    ///
    /// Syntax: `--underlay [--file=]FILE [--password=PW] [--to=R] [--from=R]
    ///          [--repeat=R] --`. Within a group the file token and sub-options
    /// may appear in any order. Pages are stacked in order of appearance: first
    /// underlays, then the original page, then overlays.
    #[arg(
        long = "underlay",
        num_args = 1..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "[--file=]FILE [sub-flags]",
        help = "Underlay pages from FILE beneath the output (qpdf --underlay); \
                repeatable, terminate each group with --"
    )]
    underlay: Vec<String>,

    /// Print verbose progress and diagnostic messages (mirrors qpdf --verbose).
    #[arg(
        long = "verbose",
        help = "Print verbose progress and diagnostic messages \
                (mirrors qpdf --verbose)"
    )]
    verbose: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
enum CliObjectStreamMode {
    #[default]
    Preserve,
    Disable,
    Generate,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliDecodeLevel {
    None,
    Generalized,
    Specialized,
    All,
}

impl From<CliDecodeLevel> for StreamDecodeLevel {
    fn from(value: CliDecodeLevel) -> Self {
        match value {
            CliDecodeLevel::None => Self::None,
            CliDecodeLevel::Generalized => Self::Generalized,
            CliDecodeLevel::Specialized => Self::Specialized,
            CliDecodeLevel::All => Self::All,
        }
    }
}

impl From<CliDecodeLevel> for DecodeLevel {
    fn from(value: CliDecodeLevel) -> Self {
        match value {
            CliDecodeLevel::None => Self::None,
            CliDecodeLevel::Generalized => Self::Generalized,
            CliDecodeLevel::Specialized => Self::Specialized,
            CliDecodeLevel::All => Self::All,
        }
    }
}

impl From<CliObjectStreamMode> for ObjectStreamMode {
    fn from(value: CliObjectStreamMode) -> Self {
        match value {
            CliObjectStreamMode::Preserve => ObjectStreamMode::Preserve,
            CliObjectStreamMode::Disable => ObjectStreamMode::Disable,
            CliObjectStreamMode::Generate => ObjectStreamMode::Generate,
        }
    }
}

/// Stream data mode for `--stream-data` (qpdf-compatible).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliStreamDataMode {
    /// Pass streams through verbatim — no decode or re-encode.
    Preserve,
    /// Decode streams and emit raw bytes (no /Filter).
    Uncompress,
    /// Decode streams and re-encode with /FlateDecode.
    Compress,
}

impl From<CliStreamDataMode> for StreamDataMode {
    fn from(v: CliStreamDataMode) -> Self {
        match v {
            CliStreamDataMode::Preserve => StreamDataMode::Preserve,
            CliStreamDataMode::Uncompress => StreamDataMode::Uncompress,
            CliStreamDataMode::Compress => StreamDataMode::Compress,
        }
    }
}

/// `--flatten-annotations=all|screen|print` (qpdf-compatible).
///
/// Selects which annotations are baked into page content by
/// [`flatten_annotations`]:
/// - `all`: every visible annotation.
/// - `screen`: annotations that render on screen, including printable annotations.
/// - `print`: annotations flagged for printing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliFlattenMode {
    All,
    Screen,
    Print,
}

impl CliFlattenMode {
    /// qpdf's `QPDFJob::Config::flattenAnnotations` mapping. Every CLI mode
    /// rejects Invisible and Hidden; `screen` additionally rejects NoView,
    /// while `print` requires the Print bit.
    fn flags(self) -> (i64, i64) {
        match self {
            CliFlattenMode::All => (0, 0x3),
            CliFlattenMode::Screen => (0, 0x3 | 0x20),
            CliFlattenMode::Print => (0x4, 0x3),
        }
    }
}

/// y|n toggle used by --compress-streams, --normalize-content.
/// Clap variant names are `y` and `n` (lowercase single letter, qpdf-compatible).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliYesNo {
    #[clap(name = "y")]
    Yes,
    #[clap(name = "n")]
    No,
}

/// Resolve qpdf's two-bit content-normalization state.
///
/// qpdf's `QPDFJob` only calls its content-normalization setter for an
/// explicit `--normalize-content` option. The writer then enables normalization
/// for QDF only when no explicit value was set, so `--qdf
/// --normalize-content=n` must remain distinguishable from an absent option.
fn normalize_content_enabled(setting: Option<CliYesNo>, qdf: bool) -> bool {
    match setting {
        Some(CliYesNo::Yes) => true,
        Some(CliYesNo::No) => false,
        None => qdf,
    }
}

/// `--newline-before-endstream=y|n|never` (qpdf default: never).
///
/// `never` requests qpdf's default framing (no newline between the stream
/// payload and `endstream`); `y` and `n` both enable qpdf's boolean option.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliNewlineBeforeEndstream {
    #[clap(name = "y")]
    Yes,
    #[clap(name = "n")]
    No,
    #[clap(name = "never")]
    Never,
}

/// `--remove-unreferenced-resources=auto|yes|no` (qpdf-compatible).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
enum CliRemoveUnreferencedResources {
    #[default]
    Auto,
    Yes,
    No,
}

impl From<CliRemoveUnreferencedResources> for RemoveUnreferencedResources {
    fn from(v: CliRemoveUnreferencedResources) -> Self {
        match v {
            CliRemoveUnreferencedResources::Auto => RemoveUnreferencedResources::Auto,
            CliRemoveUnreferencedResources::Yes => RemoveUnreferencedResources::Yes,
            CliRemoveUnreferencedResources::No => RemoveUnreferencedResources::No,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, ClapArgs)]
struct RecoveryArgs {
    /// Ignore any cross-reference streams in the file, falling back to
    /// cross-reference tables or triggering document recovery.
    #[arg(long = "ignore-xref-streams")]
    ignore_xref_streams: bool,
    /// Avoid attempting to recover when errors are found in a file's
    /// cross reference table or stream lengths.
    #[arg(long = "suppress-recovery", conflicts_with = "repair")]
    suppress_recovery: bool,
}

#[derive(Debug, Clone, Default, ClapArgs)]
struct PasswordArgs {
    #[command(flatten)]
    recovery: RecoveryArgs,
    /// Password bytes for encrypted PDFs.
    #[arg(long, conflicts_with = "password_file")]
    password: Option<String>,
    /// File containing password bytes. One trailing LF or CRLF is stripped.
    #[arg(long = "password-file", value_name = "PATH")]
    password_file: Option<PathBuf>,
    /// How qpdf-style password modes interpret --password bytes. On read
    /// paths, only `hex-bytes` transforms the bytes; `auto`, `bytes`, and
    /// `unicode` pass them through unchanged. Mirrors qpdf's flag.
    #[arg(long = "password-mode", value_enum, default_value_t = CliPasswordMode::Auto)]
    password_mode: CliPasswordMode,
    /// Permit creating deprecated RC4-backed handlers and revision 5
    /// encryption. Reading existing weakly encrypted PDFs does not require it.
    #[arg(long = "allow-weak-crypto")]
    allow_weak_crypto: bool,
    /// Interpret --password as the precomputed file encryption key in hex,
    /// not a user/owner password (qpdf --password-is-hex-key).
    #[arg(
        long = "password-is-hex-key",
        long_help = "Interpret the --password value as the precomputed file \
encryption key encoded as hex, NOT a user or owner password. All \
password→key derivation (Algorithm 2 / 2.A / 2.B / 6 / 7) is skipped and the \
decoded bytes are used directly as the file key for stream/string \
decryption. Upper- or lower-case hex and embedded whitespace are accepted; \
the decoded key must be at most 32 bytes. Mirrors qpdf \
--password-is-hex-key. Pair with `show-encryption-key` to recover the key \
from a known password, then reopen the file with that key."
    )]
    password_is_hex_key: bool,
    /// Disable qpdf's alternate password-encoding recovery attempts.
    #[arg(
        long = "suppress-password-recovery",
        long_help = "Accepted for qpdf script compatibility. qpdf retries \
alternate password encodings (UTF-8 / PDFDocEncoding) when authentication \
fails; this flag disables that recovery."
    )]
    suppress_password_recovery: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
enum CliPasswordMode {
    #[default]
    Auto,
    Bytes,
    #[clap(name = "hex-bytes")]
    HexBytes,
    Unicode,
}

impl From<CliPasswordMode> for PasswordMode {
    fn from(value: CliPasswordMode) -> Self {
        match value {
            CliPasswordMode::Auto => PasswordMode::Auto,
            CliPasswordMode::Bytes => PasswordMode::Bytes,
            CliPasswordMode::HexBytes => PasswordMode::HexBytes,
            CliPasswordMode::Unicode => PasswordMode::Unicode,
        }
    }
}

/// Env var that suppresses the `--static-id` "testing only" warning.
///
/// `--static-id` exists purely so test/parity harnesses can produce a
/// byte-stable trailer `/ID`; it must never be used for production output.
/// flpdf's *native* surface (`rewrite --static-id`) therefore emits a stderr
/// warning whenever the flag is requested. The top-level
/// qpdf-shaped alias (`flpdf --static-id …`) exists solely to mirror qpdf's
/// command surface, and qpdf emits no such warning — so the alias stays
/// silent to honour that contract and keep the qtest parity suite green.
///
/// This env var opts the *native* surface out of the diagnostic: harnesses
/// that exercise `rewrite --static-id` and assert on a clean stderr set it.
/// It is deliberately *not* a CLI flag (the qpdf-shaped alias has no such
/// switch).
const STATIC_ID_QUIET_ENV: &str = "FLPDF_STATIC_ID_QUIET";

/// Returns true when `--static-id` was requested via flpdf's native
/// `rewrite` subcommand. The top-level qpdf-shaped alias deliberately does
/// *not* count here: it mirrors qpdf, which is silent for `--static-id`.
fn static_id_warning_applies(args: &Cli) -> bool {
    matches!(&args.command, Some(Commands::Rewrite(cmd)) if cmd.static_id)
}

/// Emit the test-only warning for `--static-id` exactly once, unless
/// suppressed via [`STATIC_ID_QUIET_ENV`]. Writes to stderr only and never
/// changes the process exit code. Only the native `rewrite` surface warns;
/// the top-level qpdf-shaped alias stays silent for qpdf parity.
fn warn_if_static_id(args: &Cli) {
    if !static_id_warning_applies(args) {
        return;
    }
    if std::env::var_os(STATIC_ID_QUIET_ENV).is_some() {
        return;
    }
    eprintln!(
        "flpdf: warning: --static-id is for testing only and must not be \
         used for production output"
    );
}

fn preprocess_qpdf_args(args: Vec<String>) -> CliResult<PreprocessedArgs> {
    let parsed = arg_parser::ArgParser::from_command(Cli::command()).parse(args)?;
    let mut overlay_specs = Vec::new();
    let mut attachment_segments = Vec::new();

    for segment in parsed.named_segments {
        match segment.option.as_str() {
            "overlay" => overlay_specs.push(parse_overlay_segment(
                OverlayKind::Overlay,
                &segment.tokens,
            )?),
            "underlay" => overlay_specs.push(parse_overlay_segment(
                OverlayKind::Underlay,
                &segment.tokens,
            )?),
            "add-attachment" => attachment_segments.push(segment.tokens),
            _ => {}
        }
    }

    Ok(PreprocessedArgs {
        residual_args: parsed.residual_args,
        overlay_specs,
        attachment_segments,
    })
}

/// Print qpdf's sole-option version response (`QPDFJob_argv.cc:99-105`).
fn print_qpdf_version() {
    println!(
        "qpdf version {}\nRun qpdf --copyright to see copyright and license information.",
        flpdf::qpdf_version()
    );
}

/// Print qpdf's sole-option copyright response (`QPDFJob_argv.cc:108-135`).
fn print_qpdf_copyright() {
    println!(
        "qpdf version {}\n\n\
Copyright (c) 2005-2024 Jay Berkenbilt\n\
QPDF is licensed under the Apache License, Version 2.0 (the \"License\");\n\
you may not use this file except in compliance with the License.\n\
You may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\n\
Unless required by applicable law or agreed to in writing, software\n\
distributed under the License is distributed on an \"AS IS\" BASIS,\n\
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\
See the License for the specific language governing permissions and\n\
limitations under the License.\n\n\
Versions of qpdf prior to version 7 were released under the terms\n\
of version 2.0 of the Artistic License. At your option, you may\n\
continue to consider qpdf to be licensed under those terms. Please\n\
see the manual for additional information.",
        flpdf::qpdf_version()
    );
}

fn main() {
    // One private qpdf-style logger owns all document routes for this
    // invocation. It is deliberately distinct from the library process
    // default so later save/info routing can be configured as one unit.
    let _ = cli_logger();
    // Parse qpdf's argv grammar before clap parses feature values. The parser
    // preserves named segment boundaries and returns feature-neutral raw
    // tokens to the existing semantic consumers below.
    let raw_args: Vec<String> = std::env::args().collect();
    if raw_args.len() == 2 {
        match raw_args[1].as_str() {
            "--version" | "-version" => {
                print_qpdf_version();
                return;
            }
            "--copyright" | "-copyright" => {
                print_qpdf_copyright();
                return;
            }
            _ => {}
        }
    }

    let PreprocessedArgs {
        residual_args,
        overlay_specs,
        attachment_segments,
    } = match preprocess_qpdf_args(raw_args) {
        Ok(parsed) => parsed,
        Err(error) => {
            eprintln!("flpdf: {error}");
            std::process::exit(2);
        }
    };
    let args = Cli::parse_from(residual_args);
    let top_level_version_options =
        match parse_cli_version_options(args.min_version.as_deref(), args.force_version.as_deref())
        {
            Ok(options) => options,
            Err(error) => {
                eprintln!("flpdf: {error}");
                std::process::exit(1);
            }
        };
    let normalize_content = normalize_content_enabled(args.normalize_content, args.qdf);

    // --static-id produces a fixed, non-unique trailer /ID. It exists only
    // for deterministic test/parity output. The native `rewrite --static-id`
    // surface warns loudly (stderr only, exit code unchanged) so it is never
    // mistaken for a production option; the top-level qpdf-shaped alias stays
    // silent to mirror qpdf (flpdf-4x6). Done here, after clap parsing
    // succeeds and before any rewrite work, so the warning never precedes a
    // usage error yet is always visible.
    warn_if_static_id(&args);

    // Top-level `--qdf --linearize` is rejected here, before the dispatch
    // chain. The `else if args.linearize` branch (below) wins over the
    // default rewrite branch, so deferring this check into the rewrite branch
    // would let the linearize path run while silently dropping --qdf. QDF is
    // inherently non-linearized; mirror the rewrite/--linearize rejection.
    // (The `Commands::Rewrite` arm performs the
    // equivalent check for the subcommand form.)
    if args.qdf && args.linearize {
        eprintln!("flpdf: --qdf and --linearize cannot be used together");
        std::process::exit(1);
    }

    // Attachment add/remove/copy operations rewrite through their own
    // serializers before the shared rewrite branch. qpdf applies writer
    // normalization to those outputs, but flpdf cannot yet do so without
    // duplicating the consumer. Reject effective `y` until those serializers
    // delegate to the shared rewrite path; list/show are read-only and remain
    // accepted, matching qpdf.
    if normalize_content
        && (args.remove_attachment.is_some()
            || !args.add_attachment.is_empty()
            || !args.copy_attachments_from.is_empty())
    {
        eprintln!(
            "flpdf: --normalize-content is not applied by attachment mutation operations; \
             rerun with --normalize-content=n or without the attachment operation"
        );
        std::process::exit(1);
    }

    // Same rationale as the --normalize-content guard above: the attachment
    // serializers build their own minimal WriterOptions and never call
    // apply_cli_decode_level, so a non-`none` --decode-level would silently
    // be dropped rather than applied.
    if matches!(args.decode_level, Some(level) if level != CliDecodeLevel::None)
        && (args.remove_attachment.is_some()
            || !args.add_attachment.is_empty()
            || !args.copy_attachments_from.is_empty())
    {
        eprintln!(
            "flpdf: --decode-level is not applied by attachment mutation operations; \
             rerun with --decode-level=none or without the attachment operation"
        );
        std::process::exit(1);
    }

    // `--overlay`/`--underlay` groups are stripped from argv before clap by
    // `preprocess_qpdf_args`, so a stripped group leaves no trace for the
    // dispatch chain. Only the rewrite paths (the `Rewrite` subcommand and the
    // top-level default/`--linearize` rewrite branches) consume `overlay_specs`;
    // every other command/mode would silently ignore it. Reject that here so an
    // overlay on, e.g., `check`/`--show-npages`/`--pages` fails loudly instead of
    // being dropped. The top-level predicate mirrors the dispatch chain below
    // (the rewrite branch is the final `else`, reached only when no inspection,
    // attachment, json, or page-op mode is selected) and must stay in sync with
    // it; `--pages`/`--linearize` combinations are rejected later with their own
    // specific diagnostics.
    if !overlay_specs.is_empty() {
        let target_is_rewrite = match &args.command {
            Some(Commands::Rewrite(_)) => true,
            Some(_) => false,
            None => {
                args.json.is_none()
                    && args.show_object.is_none()
                    && !args.show_npages
                    && !args.show_pages
                    && !args.show_xref
                    && !args.check_linearization
                    && !args.show_linearization
                    && !args.show_encryption
                    && !args.check
                    && !args.list_attachments
                    && args.show_attachment.is_none()
                    && args.remove_attachment.is_none()
                    && args.add_attachment.is_empty()
                    && args.copy_attachments_from.is_empty()
            }
        };
        if !target_is_rewrite {
            eprintln!(
                "flpdf: --overlay/--underlay can only be used with rewrite output, \
                 not with inspection or other commands"
            );
            std::process::exit(2);
        }
    }

    let json_input_inspection = (args.json_input || args.update_from_json.is_some())
        && (args.check
            || args.show_npages
            || args.show_pages
            || args.show_xref
            || args.show_encryption);

    // JSON-input/update inspection is routed through the already-created job
    // document before the ordinary file-backed inspection branches. qpdf
    // creates or updates the QPDF object first, then runs read-only consumers
    // such as --check and --show-pages on that same object.
    // For ordinary JSON output, the separate --json branch remains first among
    // the non-inspection modes and retains its existing validation boundary.
    let result = if let Some(path) = args.job_json_file.as_deref() {
        run_job_json_file(
            path,
            args.input.as_deref(),
            args.output.as_deref(),
            &args.password,
        )
    } else if json_input_inspection {
        run_json_input_inspection(&args)
    } else if args.json.is_some() || args.json_output.is_some() {
        run_json(&args)
    } else if let Some(command) = args.command {
        run_command(command, &overlay_specs)
    } else if let Some(object_ref) = args.show_object.as_deref() {
        run_show_object(
            args.input,
            args.repair,
            &args.password,
            object_ref,
            args.raw_stream_data,
            args.filtered_stream_data,
        )
    } else if args.show_npages {
        run_show_npages(args.input, args.repair, &args.password)
    } else if args.show_pages {
        run_show_pages(args.input, args.repair, &args.password)
    } else if args.show_xref {
        run_show_xref(args.input, args.repair, &args.password)
    } else if args.check_linearization {
        run_check_linearization(args.input, args.repair, &args.password, args.no_warn)
    } else if args.show_linearization {
        run_show_linearization(args.input)
    } else if args.show_encryption {
        match args.input.as_ref() {
            Some(input) => run_show_encryption(input, args.repair, &args.password, args.no_warn),
            None => Err("--show-encryption requires an input file".into()),
        }
    } else if args.check {
        run_check(args.input, args.repair, &args.password, args.no_warn)
    } else if args.list_attachments {
        run_list_attachments(args.input, args.repair, &args.password, args.verbose)
    } else if let Some(key) = args.show_attachment {
        run_show_attachment(args.input, args.repair, &args.password, &key)
    } else if let Some(key) = args.remove_attachment {
        run_remove_attachment(
            args.input,
            args.output,
            args.repair,
            &args.password,
            &key,
            args.deterministic_id,
            args.static_id,
            args.preserve_unreferenced,
            &top_level_version_options,
        )
    } else if !args.add_attachment.is_empty() {
        run_add_attachment(
            args.input,
            args.output,
            args.repair,
            &args.password,
            attachment_segments,
            args.deterministic_id,
            args.static_id,
            args.preserve_unreferenced,
            args.verbose,
            &top_level_version_options,
        )
    } else if !args.copy_attachments_from.is_empty() {
        run_copy_attachments_from(
            args.input,
            args.output,
            args.repair,
            &args.password,
            args.copy_attachments_from,
            args.deterministic_id,
            args.static_id,
            args.preserve_unreferenced,
            args.verbose,
            &top_level_version_options,
        )
    } else if args.linearize {
        // --linearize is incompatible with the page-extraction pipeline:
        // extraction produces a normalized, non-linearized document. Without
        // this guard the linearize branch would win the dispatch chain and
        // silently ignore --pages/--rotate/--split-pages (wrong output, no
        // diagnostic). Mirror the same rejection the `rewrite` subcommand
        // performs.
        if page_ops_active(&args.page_ops) {
            eprintln!("flpdf: --linearize cannot be combined with --pages/--rotate/--split-pages");
            std::process::exit(1);
        }
        let mut options = WriterOptions {
            static_id: args.static_id,
            deterministic_id: args.deterministic_id,
            static_aes_iv: args.static_aes_iv,
            no_original_object_ids: args.no_original_object_ids,
            preserve_unreferenced_objects: args.preserve_unreferenced,
            object_streams: args.object_streams.into(),
            stream_data: args.stream_data.map(Into::into),
            content_normalization: normalize_content,
            content_normalization_set: args.normalize_content.is_some(),
            ..WriterOptions::default()
        };
        apply_cli_decode_level(&mut options, args.decode_level);
        apply_cli_version_options(&mut options, &top_level_version_options);
        // Top-level --compress-streams=y|n: parse and wire to WriterOptions.
        // Accepted values are "y" and "n" (qpdf-compatible); other values exit 2.
        if let Some(ref cs) = args.compress_streams {
            match cs.as_str() {
                "y" => options.compress_streams = Some(CompressStreams::Yes),
                "n" => options.compress_streams = Some(CompressStreams::No),
                other => {
                    eprintln!("flpdf: --compress-streams must be y or n, got: {:?}", other);
                    std::process::exit(2);
                }
            }
        }
        // Top-level --encrypt / --copy-encryption on the --linearize
        // alias: wire encryption onto WriterOptions (shared with the
        // non-linearize branch below and the `rewrite` subcommand via
        // apply_encryption_options). Without this call the linearize branch
        // would silently drop --encrypt/--copy-encryption (WriterOptions
        // built here is separate from the non-linearize branch's), emitting
        // plaintext output even though the user asked for encryption.
        apply_encryption_options(
            &mut options,
            &args.encrypt,
            args.copy_encryption.as_deref(),
            args.encryption_file_password.as_deref(),
            &args.password,
        );
        let result = run_rewrite(
            args.input,
            args.output.clone(),
            args.repair,
            &args.password,
            args.json_input,
            args.update_from_json.as_deref(),
            true,
            args.linearize_pass1.as_deref(),
            args.remove_restrictions,
            args.decrypt,
            normalize_content,
            args.coalesce_contents,
            CliRemoveUnreferencedResources::No, // remove_unreferenced (no-op for linearize path)
            false,                              // generate_appearances (not on top-level surface)
            None,                               // flatten_annotations (not on top-level surface)
            false,                              // flatten_rotation (not on top-level surface)
            &overlay_specs,
            args.verbose,
            options,
        );
        result
    } else if page_ops_active(&args.page_ops) {
        // Top-level page-operation path (qpdf-shaped invocation:
        // `flpdf in.pdf --pages . 1-3 -- out.pdf`). Mirrors the `rewrite`
        // subcommand's page-op dispatch below.
        //
        // The page-op pipeline does not thread `WriterOptions.encrypt`
        // through to the page-extraction / page-rewrite paths, so
        // silently honoring `--encrypt` here would emit plaintext output
        // even though the user asked for encryption. Reject upfront with
        // the same shape `rewrite --encrypt --pages …` already uses
        // (mirrors the existing `--decrypt` / `--remove-restrictions`
        // rejection in the subcommand surface). Wiring encryption
        // through the page-op pipeline is a flpdf-9hc.4.9 follow-up.
        if !args.encrypt.is_empty() {
            eprintln!(
                "flpdf: --encrypt is not applied in the \
                 --pages/--rotate/--split-pages/--collate pipeline; \
                 rerun without --encrypt or without the page operation"
            );
            std::process::exit(1);
        }
        if args.copy_encryption.is_some() {
            eprintln!(
                "flpdf: --copy-encryption is not applied in the \
                 --pages/--rotate/--split-pages/--collate pipeline; \
                 rerun without --copy-encryption or without the page operation"
            );
            std::process::exit(1);
        }
        let mut options = WriterOptions {
            static_id: args.static_id,
            deterministic_id: args.deterministic_id,
            static_aes_iv: args.static_aes_iv,
            no_original_object_ids: args.no_original_object_ids,
            preserve_unreferenced_objects: args.preserve_unreferenced,
            object_streams: args.object_streams.into(),
            stream_data: args.stream_data.map(Into::into),
            content_normalization: normalize_content,
            content_normalization_set: args.normalize_content.is_some(),
            qdf: args.qdf,
            ..WriterOptions::default()
        };
        apply_cli_decode_level(&mut options, args.decode_level);
        apply_cli_version_options(&mut options, &top_level_version_options);
        if let Some(ref cs) = args.compress_streams {
            match cs.as_str() {
                "y" => options.compress_streams = Some(CompressStreams::Yes),
                "n" => options.compress_streams = Some(CompressStreams::No),
                other => {
                    eprintln!("flpdf: --compress-streams must be y or n, got: {:?}", other);
                    std::process::exit(2);
                }
            }
        }
        let dispatch = |input: PathBuf, output: PathBuf| -> CliResult<()> {
            if !args.page_ops.pages.is_empty() {
                run_page_extraction(
                    &input,
                    &output,
                    args.repair,
                    &args.password,
                    args.json_input,
                    args.update_from_json.as_deref(),
                    &args.page_ops,
                    &overlay_specs,
                    CliRemoveUnreferencedResources::Auto,
                    options.clone(),
                    args.verbose,
                )
            } else {
                if !overlay_specs.is_empty() {
                    eprintln!(
                        "flpdf: --overlay/--underlay is not applied with \
                         --rotate/--split-pages alone (no --pages); \
                         rerun with --pages or without the overlay"
                    );
                    std::process::exit(1);
                }
                run_rewrite_with_page_ops(
                    &input,
                    &output,
                    args.repair,
                    &args.password,
                    args.json_input,
                    args.update_from_json.as_deref(),
                    &args.page_ops,
                    options.clone(),
                    args.verbose,
                )
            }
        };
        match (args.input.clone(), args.output.clone()) {
            (Some(i), Some(o)) => dispatch(i, o),
            _ => Err("page operations require both an input and an output file".into()),
        }
    } else {
        let mut options = WriterOptions {
            static_id: args.static_id,
            deterministic_id: args.deterministic_id,
            static_aes_iv: args.static_aes_iv,
            no_original_object_ids: args.no_original_object_ids,
            preserve_unreferenced_objects: args.preserve_unreferenced,
            object_streams: args.object_streams.into(),
            stream_data: args.stream_data.map(Into::into),
            content_normalization: normalize_content,
            content_normalization_set: args.normalize_content.is_some(),
            qdf: args.qdf,
            ..WriterOptions::default()
        };
        apply_cli_decode_level(&mut options, args.decode_level);
        apply_cli_version_options(&mut options, &top_level_version_options);
        // Top-level `--qdf` is an alias of `rewrite --qdf`; both configure the
        // same canonical qpdf writer.
        // Top-level --compress-streams=y|n: parse and wire to WriterOptions.
        // Accepted values are "y" and "n" (qpdf-compatible); other values exit 2.
        if let Some(ref cs) = args.compress_streams {
            match cs.as_str() {
                "y" => options.compress_streams = Some(CompressStreams::Yes),
                "n" => options.compress_streams = Some(CompressStreams::No),
                other => {
                    eprintln!("flpdf: --compress-streams must be y or n, got: {:?}", other);
                    std::process::exit(2);
                }
            }
        }
        // Top-level --encrypt / --copy-encryption: wire encryption onto
        // WriterOptions (shared with the `rewrite` surface via
        // apply_encryption_options). Parse / donor-open errors exit 2. The
        // page-op pipeline does not thread either option, so
        // the `else if page_ops_active` arm above already rejects them; this is
        // the non-page-op branch, so no further page-op guard is needed here.
        apply_encryption_options(
            &mut options,
            &args.encrypt,
            args.copy_encryption.as_deref(),
            args.encryption_file_password.as_deref(),
            &args.password,
        );
        run_rewrite(
            args.input,
            args.output,
            args.repair,
            &args.password,
            args.json_input,
            args.update_from_json.as_deref(),
            false,
            None,
            args.remove_restrictions,
            args.decrypt,
            normalize_content,
            args.coalesce_contents,
            CliRemoveUnreferencedResources::No, // remove_unreferenced (top-level alias is no-op)
            false,                              // generate_appearances (not on top-level surface)
            None,                               // flatten_annotations (not on top-level surface)
            false,                              // flatten_rotation (not on top-level surface)
            &overlay_specs,
            args.verbose,
            options,
        )
    };

    if let Err(error) = result {
        // If the error carries an explicit exit code (e.g. from run_check),
        // honour it.  Unknown/generic errors fall back to exit 2 (qpdf
        // convention for "error", unchanged from before this change).
        if let Some(exit_err) = error.downcast_ref::<CliExitError>() {
            // Only print a message when there is one; the caller may have
            // already printed its own summary (e.g. run_check prints the qpdf
            // "checking" block before returning exit 3 for warnings, and its
            // exit-2 path passes an empty message because the error diagnostics
            // were already printed in qpdf shape).
            if !exit_err.message.is_empty() {
                // cov:ignore-start: no production CliExitError currently carries a non-empty message
                emit_logger_error(format!("\n{}: {}\n", progname(), exit_err.message));
                // cov:ignore-end
            }
            std::process::exit(exit_err.code.as_i32());
        }
        if let Some(usage_error) = find_usage_error(error.as_ref()) {
            usage_exit(usage_error);
        }
        emit_logger_error(format!("{}: {error}\n", progname()));
        std::process::exit(2);
    }
}

fn find_usage_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a UsageError> {
    if let Some(usage_error) = error.downcast_ref::<UsageError>() {
        return Some(usage_error);
    }
    if let Some(Error::Usage(usage_error)) = error.downcast_ref::<Error>() {
        return Some(usage_error);
    }
    error.source().and_then(find_usage_error)
}

fn usage_exit(error: &UsageError) -> ! {
    let who = progname();
    emit_logger_error(format!(
        "\n{who}: {error}\n\nFor help:\n  {who} --help=usage       usage information\n  \
{who} --help=topic       help on a topic\n  {who} --help=--option    help on an option\n  \
{who} --help             general help and a topic list\n\n"
    ));
    std::process::exit(2);
}

fn run_job_json_file(
    path: &Path,
    input: Option<&Path>,
    output: Option<&Path>,
    password: &PasswordArgs,
) -> CliResult<()> {
    let json = std::fs::read_to_string(path)
        .map_err(|error| error_with_file(path, Box::new(error) as Box<dyn std::error::Error>))?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());

    job.initialize_from_json_partial(&json).map_err(|error| {
        Box::new(CliExitError {
            code: ExitCode::Errors,
            message: format_job_json_error(path, error),
        }) as Box<dyn std::error::Error>
    })?;
    if let Some(input) = input {
        job.set_input_file(input.to_path_buf()).map_err(|error| {
            Box::new(CliExitError {
                code: ExitCode::Errors,
                message: format_job_json_error(path, error),
            }) as Box<dyn std::error::Error>
        })?;
    }
    if let Some(output) = output {
        job.set_output_file(output.to_path_buf()).map_err(|error| {
            Box::new(CliExitError {
                code: ExitCode::Errors,
                message: format_job_json_error(path, error),
            }) as Box<dyn std::error::Error>
        })?;
    }
    if let Some(password) = password.password.as_deref() {
        job.set_password(password.as_bytes().to_vec());
    }
    // The library JSON entry point uses qpdfjob's C-helper prefix while the
    // CLI's QPDFJob caller uses the ordinary qpdf prefix. Set the CLI
    // boundary after initialization, before any input warning or completion
    // summary is emitted.
    job.set_message_prefix(progname());
    finish_job_exit_status(job.run()?)
}

fn format_job_json_error(path: &Path, error: impl std::fmt::Display) -> String {
    format!(
        "error with job-json file {}: {error}\nRun {} --job-json-help for information on the file format.\n\nFor help:\n  {} --help=usage       usage information\n  {} --help=topic       help on a topic\n  {} --help=--option    help on an option\n  {} --help             general help and a topic list\n",
        path.display(),
        progname(),
        progname(),
        progname(),
        progname(),
        progname(),
    )
}

fn run_json(cli: &Cli) -> CliResult<()> {
    const QPDF_JSON_KEY_NAMES: &[&str] = &[
        "acroform",
        "attachments",
        "encrypt",
        "objectinfo",
        "objects",
        "outlines",
        "pagelabels",
        "pages",
        "qpdf",
    ];

    let json_output_mode = cli.json_output.is_some();
    let json_version = cli
        .json_output
        .as_deref()
        .or(cli.json.as_deref())
        .unwrap_or("2");
    let json_version = match json_version {
        "1" => 1,
        "2" | "latest" => 2,
        other => return Err(format!("unsupported json version {other}").into()),
    };

    // 1. Validate --json-key values before doing any I/O.
    let mut json_keys: Vec<JsonKey> = Vec::new();
    for raw in &cli.json_key {
        if json_version != 1 && matches!(raw.as_str(), "objects" | "objectinfo") {
            eprintln!(
                "flpdf: json keys \"objects\" and \"objectinfo\" are only valid for json version 1"
            );
            std::process::exit(2);
        }
        if json_version == 1 && raw == "qpdf" {
            eprintln!("flpdf: json key \"qpdf\" is only valid for json version > 1");
            std::process::exit(2);
        }
        match JsonKey::from_str(raw.as_str()) {
            Some(k) => json_keys.push(k),
            None => {
                let names = QPDF_JSON_KEY_NAMES.join(",");
                eprintln!("flpdf: --json-key must be given as --json-key={{{names}}}");
                std::process::exit(2);
            }
        }
    }
    if json_output_mode {
        if json_version == 1 {
            eprintln!("flpdf: --json-output requires JSON version 2");
            std::process::exit(2);
        }
        // qpdf's json-output mode always selects the qpdf key in addition to
        // any explicitly requested keys (`QPDFJob_config.cc:312-324`).
        if !json_keys.contains(&JsonKey::Qpdf) {
            json_keys.push(JsonKey::Qpdf);
        }
    }

    // 2. Validate --json-object selectors before doing any I/O.
    let mut json_objects: Vec<JsonObjectSelector> = Vec::new();
    for raw in &cli.json_object {
        match JsonObjectSelector::from_str(raw.as_str()) {
            Some(s) => json_objects.push(s),
            None => {
                eprintln!(
                    "flpdf: --json-object selector \"{raw}\" must be 'trailer', 'N', or 'N,G'"
                );
                std::process::exit(2);
            }
        }
    }

    // 3. Resolve stream-data mode.
    //
    // Ordinary `--json` follows the inspection default of no stream payloads;
    // qpdf's `--json-output` mode selects inline stream data unless the caller
    // overrides it with --json-stream-data.
    let stream_data = match cli
        .json_stream_data
        .as_deref()
        .unwrap_or(if json_output_mode { "inline" } else { "none" })
    {
        "none" => JsonStreamData::None,
        "inline" => JsonStreamData::Inline,
        "file" => JsonStreamData::File,
        other => {
            eprintln!("flpdf: --json-stream-data must be none, inline, or file; got: {other}");
            std::process::exit(2);
        }
    };

    // 4. Reject an output that identifies the input file before opening or
    // truncating it. qpdf performs this check in QPDFJob.cc:627-630. Path
    // spelling alone is insufficient: relative aliases, symlinks, and hard
    // links can all name the same underlying file.
    let input = cli.input.as_ref().ok_or("missing input file")?;
    if let Some(output) = cli
        .output
        .as_ref()
        .filter(|path| path.as_path() != Path::new("-"))
    {
        reject_same_json_output(input, output)?;
    }

    // qpdf reserves standard output for binary/structured save data before
    // opening the document, so warnings and later info cannot claim stdout.
    let mut standard_output = if cli
        .output
        .as_ref()
        .is_none_or(|path| path.as_path() == Path::new("-"))
    {
        Some(standard_save_writer()?)
    } else {
        None
    };

    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());

    // 5. Open the input once and retain an identity handle for the output
    // check. JSON input uses the canonical complete-document importer; a
    // partial update is applied immediately after creation/opening.
    let input_file = File::open(input).map_err(|error| {
        if cli.json_input {
            qpdf_json_input_open_error(input, error)
        } else {
            json_input_open_error(input, error)
        }
    })?;
    let input_identity = input_file
        .try_clone()
        .map_err(|error| error_with_file(input, error.into()))?;

    if cli.json_input {
        let mut pdf = job.create_from_json_document(input_file, input.display().to_string())?;
        apply_json_update_with_job(&mut job, &mut pdf, cli.update_from_json.as_deref())?;
        let mut runtime = JsonJobRuntime {
            input_identity: &input_identity,
            standard_output: &mut standard_output,
            job: &mut job,
        };
        run_json_document(
            cli,
            &mut runtime,
            &mut pdf,
            json_version,
            cli.test_json_schema,
            cli.show_encryption_key,
            json_output_mode,
            stream_data,
            &json_keys,
            &json_objects,
        )
    } else {
        let mut pdf = open_pdf_from_file(input, input_file, cli.repair, &cli.password)?;
        job.record_document_warnings(&pdf);
        apply_json_update_with_job(&mut job, &mut pdf, cli.update_from_json.as_deref())?;
        let mut runtime = JsonJobRuntime {
            input_identity: &input_identity,
            standard_output: &mut standard_output,
            job: &mut job,
        };
        run_json_document(
            cli,
            &mut runtime,
            &mut pdf,
            json_version,
            cli.test_json_schema,
            cli.show_encryption_key,
            json_output_mode,
            stream_data,
            &json_keys,
            &json_objects,
        )
    }
}

fn run_json_input_inspection(cli: &Cli) -> CliResult<()> {
    let input = cli.input.as_ref().ok_or("missing input file")?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(cli.no_warn);

    let file = File::open(input).map_err(|error| {
        if cli.json_input {
            qpdf_json_input_open_error(input, error)
        } else {
            error_with_file(input, error.into())
        }
    })?;

    if cli.json_input {
        let mut pdf = job.create_from_json_document(file, input.display().to_string())?;
        apply_json_update_with_job(&mut job, &mut pdf, cli.update_from_json.as_deref())?;
        return run_job_inspection_on_pdf(cli, &mut job, &mut pdf);
    }

    let mut options = pdf_open_options(cli.repair, &cli.password)?;
    if cli.check {
        // `--check` is a read-only inspection and re-emits collected
        // diagnostics once in its check report rather than delivering them
        // during input creation.
        options.suppress_warnings = true;
    } else if cli.show_encryption {
        // `--show-encryption` has no deferred-replay report body (unlike
        // `--check`): open-time diagnostics are either delivered live
        // (matching qpdf's un-suppressed `--show-encryption` output) or, with
        // `--no-warn`, dropped entirely (matching qpdf, which prints no
        // WARNING lines at all in that case; see `run_show_encryption`).
        options.suppress_warnings = cli.no_warn;
    }
    let mut pdf = match job.open(BufReader::new(file), input.display().to_string(), options) {
        Ok(pdf) => pdf,
        Err(error) => {
            job.report_open_failure(&error)?;
            return Err(error_with_file(input, actionable_password_error(error)));
        }
    };
    apply_json_update_with_job(&mut job, &mut pdf, cli.update_from_json.as_deref())?;
    run_job_inspection_on_pdf(cli, &mut job, &mut pdf)
}

fn run_job_inspection_on_pdf<R: Read + Seek + 'static>(
    cli: &Cli,
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
) -> CliResult<()> {
    if cli.check {
        return finish_check_job(job.check(pdf));
    }
    if cli.show_npages {
        return finish_job_exit_status(job.show_npages(pdf)?);
    }
    if cli.show_pages {
        return finish_job_exit_status(job.show_pages(pdf)?);
    }
    if cli.show_xref {
        return finish_job_exit_status(job.show_xref(pdf)?);
    }
    if cli.show_encryption {
        return finish_show_encryption(job, pdf, cli.password.password_is_hex_key);
    }
    Err("JSON input/update inspection mode is missing a consumer".into())
}

/// Serialize an already-opened job document through the existing qpdf JSON
/// output consumer. Keeping this generic preserves the same output path for
/// file-backed PDF inputs and JSON-created documents.
#[allow(clippy::too_many_arguments)]
fn run_json_document<R: Read + Seek>(
    cli: &Cli,
    runtime: &mut JsonJobRuntime<'_>,
    pdf: &mut Pdf<R>,
    json_version: i32,
    test_json_schema: bool,
    show_encryption_key: bool,
    json_output_mode: bool,
    stream_data: JsonStreamData,
    json_keys: &[JsonKey],
    json_objects: &[JsonObjectSelector],
) -> CliResult<()> {
    // `decode_level` governs both inline `data` payloads and file-mode side
    // files emitted by the job-owned JSON output pipeline.
    let json_decode_level =
        cli.decode_level
            .map(DecodeLevel::from)
            .unwrap_or(if json_output_mode {
                DecodeLevel::None
            } else {
                DecodeLevel::Generalized
            });
    let output_path = cli
        .output
        .as_ref()
        .filter(|path| path.as_path() != Path::new("-"));
    let json_result = if let Some(path) = output_path {
        let mut file = open_verified_json_output(runtime.input_identity, path)?;
        let options = JsonJobOptions {
            decode_level: json_decode_level,
            stream_data,
            stream_prefix: cli.json_stream_prefix.as_deref(),
            keys: json_keys,
            objects: json_objects,
        };
        runtime.job.write_json_with_version(
            pdf,
            json_version,
            test_json_schema,
            json_output_mode,
            show_encryption_key,
            options,
            JsonJobOutput::File {
                filename: path,
                writer: &mut file,
            },
        )
    } else {
        let options = JsonJobOptions {
            decode_level: json_decode_level,
            stream_data,
            stream_prefix: cli.json_stream_prefix.as_deref(),
            keys: json_keys,
            objects: json_objects,
        };
        runtime.job.write_json_with_version(
            pdf,
            json_version,
            test_json_schema,
            json_output_mode,
            show_encryption_key,
            options,
            JsonJobOutput::Stdout(
                runtime
                    .standard_output
                    .as_mut()
                    .expect("stdout writer prepared for JSON stdout"),
            ),
        )
    };
    match json_result {
        Ok(JobExitCode::Success) => {}
        Ok(JobExitCode::Error) => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
        Ok(JobExitCode::Warning) => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Warnings,
                message: String::new(),
            }))
        }
        Err(JsonJobError::Output(error)) => return Err(Box::new(error)),
        Err(JsonJobError::Usage(error)) => return Err(Box::new(error)),
        Err(JsonJobError::Completion(error)) => return Err(Box::new(error)),
    }
    Ok(())
}

fn run_command(command: Commands, overlay_specs: &[OverlaySpec]) -> CliResult<()> {
    match command {
        Commands::Check(cmd) => run_check(Some(cmd.input), cmd.repair, &cmd.password, false),
        Commands::CheckLinearization(cmd) => {
            run_check_linearization(Some(cmd.input), false, &PasswordArgs::default(), false)
        }
        Commands::DumpObject(cmd) => {
            run_dump_object(Some(cmd.input), cmd.repair, &cmd.password, &cmd.object_ref)
        }
        Commands::Pages(cmd) => {
            if cmd.show_npages {
                run_show_npages(Some(cmd.input), cmd.repair, &cmd.password)
            } else {
                run_show_pages(Some(cmd.input), cmd.repair, &cmd.password)
            }
        }
        Commands::Qdf(cmd) => run_qdf(
            Some(cmd.input),
            Some(cmd.output),
            cmd.repair,
            &cmd.password,
            cmd.preserve_unreferenced,
        ),
        Commands::QdfFix(cmd) => run_qdf_fix(&cmd.input, &cmd.output),
        Commands::ShowStream(cmd) => run_show_stream(cmd),
        Commands::ShowEncryption(cmd) => {
            run_show_encryption(&cmd.input, cmd.repair, &cmd.password, false)
        }
        Commands::IsEncrypted(cmd) => run_is_encrypted(&cmd.input, cmd.repair, cmd.recovery),
        Commands::RequiresPassword(cmd) => {
            run_requires_password(&cmd.input, cmd.repair, &cmd.password)
        }
        Commands::ShowEncryptionKey(cmd) => {
            run_show_encryption_key(&cmd.input, cmd.repair, &cmd.password)
        }
        Commands::Rewrite(cmd) => {
            let version_options = match parse_cli_version_options(
                cmd.min_version.as_deref(),
                cmd.force_version.as_deref(),
            ) {
                Ok(options) => options,
                Err(error) => {
                    eprintln!("flpdf: {error}");
                    std::process::exit(1);
                }
            };
            // QDF is inherently non-linearized; reject the combination with a
            // fatal diagnostic, mirroring the rewrite/--linearize rejection
            // above. (The top-level `--qdf --linearize` form is
            // rejected earlier in main(), before the linearize branch wins
            // the dispatch chain.)
            if cmd.qdf && cmd.linearize {
                eprintln!("flpdf: --qdf and --linearize cannot be used together");
                std::process::exit(1);
            }
            let mut options = WriterOptions {
                static_id: cmd.static_id,
                deterministic_id: cmd.deterministic_id,
                static_aes_iv: cmd.static_aes_iv,
                no_original_object_ids: cmd.no_original_object_ids,
                preserve_unreferenced_objects: cmd.preserve_unreferenced,
                // `--qdf` and `--deterministic-id` configure the canonical writer's
                // output preparation directly.
                qdf: cmd.qdf,
                object_streams: cmd.object_streams.into(),
                compress_streams: cmd.compress_streams.map(|mode| match mode {
                    CliYesNo::Yes => CompressStreams::Yes,
                    CliYesNo::No => CompressStreams::No,
                }),
                newline_before_endstream: match cmd.newline_before_endstream {
                    CliNewlineBeforeEndstream::Yes => NewlineBeforeEndstream::Yes,
                    // qpdf treats `--newline-before-endstream=<value>` as the
                    // presence of its boolean option, so `=n` has the same
                    // output as `=y` in the 11.9.0 CLI.
                    CliNewlineBeforeEndstream::No => NewlineBeforeEndstream::Yes,
                    CliNewlineBeforeEndstream::Never => NewlineBeforeEndstream::Never,
                },
                // --stream-data overrides --compress-streams when set.
                stream_data: cmd.stream_data.map(Into::into),
                // Recompressing an existing lone /FlateDecode stream is a writer
                // setting and is applied by the same canonical route.
                recompress_flate: cmd.recompress_flate,
                ..WriterOptions::default()
            };
            apply_cli_decode_level(&mut options, cmd.decode_level);
            apply_cli_version_options(&mut options, &version_options);
            // `rewrite --encrypt` / `--copy-encryption`: wire encryption
            // onto WriterOptions (shared with the top-level surface via
            // apply_encryption_options).
            apply_encryption_options(
                &mut options,
                &cmd.encrypt,
                cmd.copy_encryption.as_deref(),
                cmd.encryption_file_password.as_deref(),
                &cmd.password,
            );
            let normalize_content = matches!(cmd.normalize_content, Some(CliYesNo::Yes));
            options.content_normalization = normalize_content;
            options.content_normalization_set = cmd.normalize_content.is_some();
            let coalesce_contents = cmd.coalesce_contents;
            let remove_unref = cmd.remove_unreferenced_resources;

            // --flatten-annotations / --generate-appearances / --flatten-rotation
            // are applied only on run_rewrite's NON-linearize branch (the
            // content-mutation passes do not exist on the linearize path). Pairing
            // them with --linearize would silently drop the requested
            // transformation, so reject the combination loudly instead — the same
            // shape as the --linearize + page-ops guard below.
            if cmd.linearize
                && (cmd.generate_appearances
                    || cmd.flatten_annotations.is_some()
                    || cmd.flatten_rotation)
            {
                eprintln!(
                    "flpdf: --linearize cannot be combined with \
                     --flatten-annotations/--generate-appearances/--flatten-rotation"
                );
                std::process::exit(1);
            }

            // Page-operation dispatch (flpdf-9hc.8.12). When --pages is set
            // the extraction pipeline owns the write; otherwise --rotate /
            // --split-pages decorate a plain rewrite. --linearize with page
            // ops is rejected (the extraction path produces a normalized,
            // non-linearized document).
            if page_ops_active(&cmd.page_ops) {
                if cmd.linearize {
                    eprintln!(
                        "flpdf: --linearize cannot be combined with --pages/--rotate/--split-pages"
                    );
                    std::process::exit(1);
                }
                // The --rotate/--split-pages-only path does not run overlay
                // stacking; only --pages does (via run_page_extraction below).
                if cmd.page_ops.pages.is_empty() && !overlay_specs.is_empty() {
                    eprintln!(
                        "flpdf: --overlay/--underlay is not applied with \
                         --rotate/--split-pages alone (no --pages); \
                         rerun with --pages or without the overlay"
                    );
                    std::process::exit(1);
                }
                // The page-operation pipeline owns the write and does not run
                // the rewrite-only mutation passes. Silently dropping them
                // would make the command partially succeed; reject the
                // unsupported combinations loudly instead. Writer settings,
                // including content normalization, are applied by the final
                // PdfWriter and are therefore intentionally accepted here.
                //
                // --decrypt is rejected for the same reason: the page-ops
                // pipeline already rejects encrypted inputs (so a useful
                // --decrypt + page-ops combination is impossible), and on
                // plaintext input --decrypt is a silent no-op anyway —
                // rejecting upfront surfaces the unsupported combination
                // instead of leaving the user wondering whether decryption
                // happened.
                if coalesce_contents
                    || cmd.remove_restrictions
                    || cmd.decrypt
                    || !cmd.encrypt.is_empty()
                    || cmd.copy_encryption.is_some()
                    || cmd.generate_appearances
                    || cmd.flatten_annotations.is_some()
                    || cmd.flatten_rotation
                {
                    eprintln!(
                        "flpdf: --coalesce-contents / --remove-restrictions / --decrypt / --encrypt / \
                         --copy-encryption / --flatten-annotations / \
                         --generate-appearances / --flatten-rotation are \
                         not applied in the --pages/--rotate/--split-pages/\
                         --collate pipeline; rerun without them or without \
                         the page operation"
                    );
                    std::process::exit(1);
                }
                // The decorate path (--rotate/--split-pages without --pages)
                // does not thread remove_unreferenced_resources; an explicit
                // Yes/No would be silently dropped, so reject it. Auto (the
                // default) is allowed: there is no extracted subset to prune.
                if cmd.page_ops.pages.is_empty()
                    && remove_unref != CliRemoveUnreferencedResources::Auto
                {
                    eprintln!(
                        "flpdf: --remove-unreferenced-resources is not applied \
                         with --rotate/--split-pages alone; rerun without it \
                         or add --pages"
                    );
                    std::process::exit(1);
                }
                return if !cmd.page_ops.pages.is_empty() {
                    run_page_extraction(
                        &cmd.input,
                        &cmd.output,
                        cmd.repair,
                        &cmd.password,
                        false,
                        None,
                        &cmd.page_ops,
                        overlay_specs,
                        remove_unref,
                        options,
                        cmd.verbose,
                    )
                } else {
                    run_rewrite_with_page_ops(
                        &cmd.input,
                        &cmd.output,
                        cmd.repair,
                        &cmd.password,
                        false,
                        None,
                        &cmd.page_ops,
                        options,
                        cmd.verbose,
                    )
                };
            }

            run_rewrite(
                Some(cmd.input),
                Some(cmd.output),
                cmd.repair,
                &cmd.password,
                false,
                None,
                cmd.linearize,
                None,
                cmd.remove_restrictions,
                cmd.decrypt,
                normalize_content,
                coalesce_contents,
                remove_unref,
                cmd.generate_appearances,
                cmd.flatten_annotations,
                cmd.flatten_rotation,
                overlay_specs,
                cmd.verbose,
                options,
            )
        }
    }
}

fn run_check(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let file = File::open(&input).map_err(|error| error_with_file(&input, error.into()))?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(no_warn);
    let mut options = pdf_open_options(repair, password)?;
    // The job emits the collected diagnostics once, after the qpdf check
    // banner, and owns the shared warning completion boundary.
    options.suppress_warnings = true;
    let mut pdf = match job.open(BufReader::new(file), input.display().to_string(), options) {
        Ok(pdf) => pdf,
        Err(error) => {
            job.report_open_failure(&error)?;
            return Err(error_with_file(&input, actionable_password_error(error)));
        }
    };
    finish_check_job(job.check(&mut pdf))
}

fn run_check_linearization(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let file = File::open(&input).map_err(|error| error_with_file(&input, error.into()))?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(no_warn);
    let options = pdf_open_options(repair, password)?;
    let mut pdf = job
        .open(BufReader::new(file), input.display().to_string(), options)
        .map_err(|error| error_with_file(&input, actionable_password_error(error)))?;
    finish_job_exit_status(job.check_linearization(&mut pdf)?)
}

/// Wire `--encrypt` / `--copy-encryption` onto `options`, shared by the
/// top-level and `rewrite` surfaces so the two stay in lock-step. A `--encrypt`
/// parse error or a `--copy-encryption`
/// donor-open/validation error prints a `flpdf:`-prefixed diagnostic and exits
/// 2, matching the surrounding option parsers. The two options are mutually
/// exclusive at the CLI layer (clap `conflicts_with`), so at most one branch
/// fires.
fn apply_encryption_options(
    options: &mut WriterOptions,
    encrypt: &[String],
    copy_encryption: Option<&std::path::Path>,
    encryption_file_password: Option<&str>,
    password_args: &PasswordArgs,
) {
    if !encrypt.is_empty() {
        match parse_encrypt_segment(encrypt, password_args.allow_weak_crypto) {
            Ok(params) => {
                options.encrypt = Some(params);
            }
            Err(e) => {
                eprintln!("flpdf: {e}");
                std::process::exit(2);
            }
        }
    }
    if let Some(donor_path) = copy_encryption {
        match build_copy_encryption_source(donor_path, encryption_file_password, password_args) {
            Ok(src) => {
                options.copy_encryption = Some(src);
            }
            Err(e) => {
                eprintln!("flpdf: {e}");
                std::process::exit(2);
            }
        }
    }
}

/// Open a donor PDF at `path` (with optional `password`) and extract the
/// information needed to copy its encryption to a new output file
/// (`--copy-encryption`).
///
/// Returns a [`CopyEncryptionSource`] ready to be stored in
/// [`WriterOptions::copy_encryption`] or an error string suitable for printing
/// to stderr before `exit(2)`.
///
/// Only V=4 AES-128 donors are accepted.  Other encryption schemes are
/// rejected with a "not yet supported" message.
fn build_copy_encryption_source(
    path: &std::path::Path,
    password: Option<&str>,
    password_args: &PasswordArgs,
) -> CliResult<CopyEncryptionSource> {
    let file =
        File::open(path).map_err(|e| format!("--copy-encryption: cannot open {:?}: {e}", path))?;
    let reader = BufReader::new(file);

    let mut donor_password = password_args.clone();
    donor_password.password = Some(password.unwrap_or("").to_owned());
    donor_password.password_file = None;
    let mut opts = pdf_open_options(true, &donor_password)
        .map_err(|error| format!("--copy-encryption: failed to configure {:?}: {error}", path))?;
    configure_document_logger(&mut opts, path);
    let mut donor = Pdf::open_with_options(reader, opts)
        .map_err(|e| format!("--copy-encryption: failed to open {:?}: {e}", path))?;
    donor
        .root_handle()
        .map_err(|e| format!("--copy-encryption: failed to open {:?}: {e}", path))?;

    // Validate the donor is encrypted.
    let info = donor
        .encryption_info()
        .map_err(|e| format!("--copy-encryption: failed to read encryption info: {e}"))?
        .ok_or_else(|| format!("--copy-encryption: donor {:?} is not encrypted", path))?;

    // Walking-skeleton scope: only V=4 AES-128 (StmF=AESV2 / StrF=AESV2).
    // Note: encryption_info uses qpdf_name() which returns "AESv2" (lowercase v).
    let is_v4_aes128 = info.v == 4
        && info.length_bits == 128
        && info.stream_method == "AESv2"
        && info.string_method == "AESv2";
    if !is_v4_aes128 {
        return Err(format!(
            "--copy-encryption: donor {:?} uses V={} length={} \
             stream={} string={} — only V=4 AES-128 donors are accepted",
            path, info.v, info.length_bits, info.stream_method, info.string_method,
        )
        .into());
    }

    // Recover the donor's file key.  The error message guides the user to
    // supply the correct password via --encryption-file-password.
    let file_key: Vec<u8> = donor.encryption_file_key().ok_or_else(|| {
        format!(
            "--copy-encryption: failed to recover donor file key for {:?} \
             (wrong --encryption-file-password?)",
            path
        )
    })?;

    // The reader owns the authenticated qpdf copy-encryption boundary. It
    // snapshots the live /Encrypt and /ID[0] handles without exposing the
    // legacy Object route to this external CLI crate.
    let mut source = donor
        .writer_copy_encryption_source()?
        .ok_or_else(|| format!("--copy-encryption: donor {:?} is not encrypted", path))?;
    source.file_key = file_key;
    source.object_key_alg = ObjectKeyAlg::Aes;
    Ok(source)
}

/// Parse the qpdf-shaped `--encrypt USER-PW OWNER-PW KEY-LEN [sub-flags]`
/// segment into an [`EncryptParams`].
///
/// `tokens` is the captured `Vec<String>` from clap's `value_terminator="--"`
/// + `num_args = 3..` segment; it does not include the trailing `--` itself
///   (clap consumes it as the terminator).
///
/// KEY-LEN → method (matching qpdf):
/// - `40` → V=1 R=2 RC4-40 (weak).
/// - `128` + `--use-aes=y` → V=4 R=4 AES-128.
/// - `128` + (`--use-aes=n` or omitted) + `--force-V4` → V=4 R=4 RC4-128 (weak).
/// - `128` + (`--use-aes=n` or omitted) without `--force-V4` → V=2 R=3 RC4-128
///   (qpdf's default, weak).
/// - `256` → V=5 R=6 AES-256 (`--allow-insecure` gates the empty-owner case).
///
/// RC4 outputs (40-bit, or 128-bit without AES) are weak and require
/// `allow_weak_crypto` (the top-level `--allow-weak-crypto` flag), mirroring
/// qpdf's write-side checkConfiguration.
///
/// Permission sub-flags (`--print`, `--modify`, `--extract`, `--annotate`,
/// `--form`, `--assemble`, `--accessibility`) use the R>=3 grammar and are
/// applied left-to-right onto a [`PermissionsConfig`] (matching qpdf's
/// ordering). They are accepted for 128/256-bit only; on 40-bit (R=2) they are
/// rejected (the R=2 `/P` encoding differs).
/// `--cleartext-metadata` is still rejected for V=1/V=2 (40-bit or 128-bit
/// without AES/--force-V4); `--force-R5` is accepted for 256-bit only.
fn parse_perm_yn(flag: &str, val: &str) -> CliResult<bool> {
    match val {
        "y" => Ok(true),
        "n" => Ok(false),
        other => Err(format!("{flag} must be y or n (got {other:?})").into()),
    }
}

fn parse_encrypt_segment(tokens: &[String], allow_weak_crypto: bool) -> CliResult<EncryptParams> {
    if tokens.len() < 3 {
        return Err(format!(
            "--encrypt requires USER-PW OWNER-PW KEY-LEN (got {} arg(s))",
            tokens.len()
        )
        .into());
    }
    for token in &tokens[..3] {
        if token.starts_with("-") && token != "-" {
            return Err(format!(
                "unrecognized argument {token} (encryption options must be terminated with --)"
            )
            .into());
        }
    }
    let user_pw = tokens[0].as_bytes().to_vec();
    let owner_pw = tokens[1].as_bytes().to_vec();
    let key_len: u32 = tokens[2].parse().map_err(|_| {
        format!(
            "--encrypt KEY-LEN must be a positive integer (40 / 128 / 256), got: {:?}",
            tokens[2]
        )
    })?;
    if !matches!(key_len, 40 | 128 | 256) {
        return Err(format!("--encrypt KEY-LEN must be 40, 128, or 256 (got {key_len})").into());
    }

    // Parse sub-flags. Unsupported ones are rejected with a clear message so
    // users do not get a silent shrug when they pass `--print=none`.
    let mut use_aes: Option<bool> = None;
    let mut force_v4 = false;
    let mut force_r5 = false;
    // `--allow-insecure` opts into the V=5 R=6 empty-owner + non-empty-user
    // "insecure" combination; the gate itself lives in the KEY-LEN=256 arm
    // below (flpdf-9hc.4.14, mirroring qpdf's checkConfiguration).
    let mut allow_insecure = false;
    // Permission sub-flags (R>=3 grammar, flpdf-9hc.4.9.5). qpdf applies them
    // LEFT-TO-RIGHT, so mutate `perms` in place as each flag is seen rather
    // than collecting and applying in a fixed order (which would break the
    // observable ordering quirk, e.g. `--modify=none --annotate=y`). Permission
    // flags are R>=3 only (128/256); on 40-bit they are rejected below.
    let mut perms = PermissionsConfig::default();
    let mut perm_flag_seen = false;
    // `--cleartext-metadata` leaves the /Metadata XMP stream unencrypted
    // (flpdf-9hc.4.9.6). Honored for V=4/V=5 only (the V=1/V=2 dict builder has
    // no /EncryptMetadata); rejected for 40-bit / 128-without-AES below.
    let mut cleartext_metadata = false;
    for tok in &tokens[3..] {
        let (flag, val) = tok.split_once('=').unwrap_or((tok.as_str(), ""));
        match flag {
            "--use-aes" => {
                use_aes = Some(match val {
                    "y" => true,
                    "n" => false,
                    other => {
                        return Err(format!("--use-aes must be y or n (got {other:?})").into());
                    }
                });
            }
            // `--force-V4` forces the V=4 handler; combined with RC4 (i.e. no
            // `--use-aes=y`) it selects the V=4 /CFM V2 (RC4-128) variant.
            // Value-less flag.
            "--force-V4" => {
                if tok.contains('=') {
                    return Err(format!("--force-V4 does not take a value (got {tok:?})").into());
                }
                force_v4 = true;
            }
            // Value-less; see the KEY-LEN=256 arm. Reject any `=` form so an
            // opt-out typo (`--allow-insecure=false`) or a generated empty value
            // (`--allow-insecure=`) cannot silently enable the insecure path.
            "--allow-insecure" => {
                if tok.contains('=') {
                    return Err(
                        format!("--allow-insecure does not take a value (got {tok:?})").into(),
                    );
                }
                allow_insecure = true;
            }
            // Permission sub-flags (R>=3 grammar). Mutate `perms` in place so
            // the left-to-right ordering matches qpdf. Bit mapping verified
            // empirically against `qpdf --show-encryption`.
            "--print" => {
                perm_flag_seen = true;
                perms.print = match val {
                    "full" => PrintPermission::High,
                    "low" => PrintPermission::Low,
                    "none" => PrintPermission::None,
                    other => {
                        return Err(
                            format!("--print must be full, low, or none (got {other:?})").into(),
                        );
                    }
                };
            }
            "--modify" => {
                perm_flag_seen = true;
                // Cumulative ladder (qpdf): all => other+annot+forms+assembly,
                // annotate => annot+forms+assembly, form => forms+assembly,
                // assembly => assembly, none => nothing.
                let (other_, annot, forms, asm) = match val {
                    "all" => (true, true, true, true),
                    "annotate" => (false, true, true, true),
                    "form" => (false, false, true, true),
                    "assembly" => (false, false, false, true),
                    "none" => (false, false, false, false),
                    other => {
                        return Err(format!(
                            "--modify must be all, annotate, form, assembly, or none (got {other:?})"
                        )
                        .into());
                    }
                };
                perms.modify_contents = other_;
                perms.annotate = annot;
                perms.fill_forms = forms;
                perms.assemble = asm;
            }
            "--extract" => {
                perm_flag_seen = true;
                perms.extract = parse_perm_yn(flag, val)?;
            }
            "--annotate" => {
                perm_flag_seen = true;
                perms.annotate = parse_perm_yn(flag, val)?;
            }
            "--form" => {
                perm_flag_seen = true;
                perms.fill_forms = parse_perm_yn(flag, val)?;
            }
            "--assemble" => {
                perm_flag_seen = true;
                perms.assemble = parse_perm_yn(flag, val)?;
            }
            "--accessibility" => {
                perm_flag_seen = true;
                perms.accessibility = parse_perm_yn(flag, val)?;
            }
            // Value-less; honored for V=4/V=5 (gated in the dispatch below).
            "--cleartext-metadata" => {
                if tok.contains('=') {
                    return Err(format!(
                        "--cleartext-metadata does not take a value (got {tok:?})"
                    )
                    .into());
                }
                cleartext_metadata = true;
            }
            "--force-R5" => {
                if tok.contains('=') {
                    return Err(format!("--force-R5 does not take a value (got {tok:?})").into());
                }
                force_r5 = true;
            }
            other => {
                return Err(format!(
                    "unknown --encrypt sub-flag {other:?}; supported in this release: \
                     --use-aes=y|n, --force-V4, --force-R5, --allow-insecure, --print, --modify, \
                     --extract, --annotate, --form, --assemble, --accessibility, \
                     --cleartext-metadata"
                )
                .into());
            }
        }
    }

    // Enforce qpdf's per-KEY-LEN option tables: `--use-aes` / `--force-V4` are
    // 128-only and `--allow-insecure` is 256-only. Reject incompatible flags as
    // a usage error rather than silently ignoring them — otherwise
    // `--encrypt … 40 --use-aes=y` would quietly write RC4-40 while the user
    // expected AES (a security-relevant mismatch).
    match key_len {
        40 if use_aes.is_some() || force_v4 || force_r5 || allow_insecure || perm_flag_seen => {
            return Err(
                "--encrypt KEY-LEN=40 (V=1 RC4-40, R=2) does not accept --use-aes, \
                 --force-V4, --force-R5, --allow-insecure, or permission sub-flags; the R>=3 \
                 permission grammar needs a 128- or 256-bit key"
                    .into(),
            );
        }
        128 if allow_insecure || force_r5 => {
            return Err(
                "--encrypt KEY-LEN=128 does not accept --allow-insecure or --force-R5 (256-bit only)".into(),
            );
        }
        256 if use_aes.is_some() || force_v4 => {
            return Err(
                "--encrypt KEY-LEN=256 does not accept --use-aes or --force-V4 (128-bit only)"
                    .into(),
            );
        }
        _ => {}
    }

    // RC4 outputs are weak; qpdf refuses to write them without
    // --allow-weak-crypto, so apply the same gate here. Deprecated R=5
    // (AES-256) output is also gated by flpdf's explicit write policy.
    let guard_weak = |params: EncryptParams| -> CliResult<EncryptParams> {
        if !allow_weak_crypto {
            if params.is_weak_rc4() {
                return Err(
                    "refusing to write a file with RC4, a weak cryptographic algorithm. \
                     Please use 256-bit keys for better security. Pass --allow-weak-crypto \
                     to enable writing insecure files."
                        .into(),
                );
            }
            if params.is_deprecated_r5() {
                return Err(
                    "refusing to write a deprecated revision 5 (R=5) encrypted file. \
                     256-bit revision 6 (the default without --force-R5) is preferred. \
                     Pass --allow-weak-crypto to enable writing R=5 files."
                        .into(),
                );
            }
        }
        Ok(params)
    };

    // --cleartext-metadata needs /EncryptMetadata, a V>=4 concept; the V=1/V=2
    // dict builder cannot emit it. Reject it before dispatch when the chosen
    // method would be V=1 (40-bit) or V=2 (128 without AES / --force-V4).
    if cleartext_metadata {
        let is_v4_or_v5 = key_len == 256 || (key_len == 128 && (use_aes == Some(true) || force_v4));
        if !is_v4_or_v5 {
            return Err(
                "--cleartext-metadata requires V=4 or V=5 (256-bit, or 128-bit with \
                 --use-aes=y or --force-V4); V=1/V=2 have no /EncryptMetadata"
                    .into(),
            );
        }
    }

    match key_len {
        // KEY-LEN=40 is always V=1 RC4-40; --use-aes / --force-V4 do not apply.
        40 => guard_weak(EncryptParams::rc4(
            EncryptMethod::V1Rc440,
            user_pw,
            owner_pw,
        )),
        128 => {
            let mut params = match use_aes {
                Some(true) => EncryptParams::v4_aes128(user_pw, owner_pw),
                // qpdf's 128-bit default is RC4; `--force-V4` selects the V=4
                // /CFM V2 variant, otherwise V=2 R=3.
                Some(false) | None => {
                    let method = if force_v4 {
                        EncryptMethod::V4Rc4128
                    } else {
                        EncryptMethod::V2Rc4128
                    };
                    EncryptParams::rc4(method, user_pw, owner_pw)
                }
            };
            params.permissions = perms;
            // Accessibility (bit 10) is unconditionally permitted for R>3;
            // qpdf ignores `--accessibility=n` there. V=4 is R=4, so force it
            // on; V=2 (R=3) honors the flag.
            if matches!(
                params.method,
                EncryptMethod::V4Aes128 | EncryptMethod::V4Rc4128
            ) {
                params.permissions.accessibility = true;
            }
            // cleartext_metadata was validated to imply V=4 here (the guard
            // above rejects it for the V=2 default).
            if cleartext_metadata {
                params.encrypt_metadata = false;
            }
            guard_weak(params)
        }
        256 => {
            // V=5 R=6 AES-256 — always AES, so `--use-aes` is irrelevant.
            // Insecure-combination gate (flpdf-9hc.4.14, matching qpdf's
            // checkConfiguration): a non-empty user password with an EMPTY
            // owner password under a 256-bit key lets anyone open the file
            // without the owner password, so the owner restrictions are
            // meaningless. Require explicit `--allow-insecure`.
            if owner_pw.is_empty() && !user_pw.is_empty() && !allow_insecure {
                return Err(
                    "A PDF with a non-empty user password and an empty owner password \
                     encrypted with a 256-bit key is insecure as it can be opened without \
                     a password. If you really want to do this, you must also give the \
                     --allow-insecure option before the -- that follows --encrypt."
                        .into(),
                );
            }
            let mut params = if force_r5 {
                EncryptParams::v5_r5(user_pw, owner_pw)
            } else {
                EncryptParams::v5_r6(user_pw, owner_pw)
            };
            params.permissions = perms;
            // V=5 is R=6 (>3): accessibility is unconditionally permitted, so
            // qpdf ignores `--accessibility=n`. Match that.
            params.permissions.accessibility = true;
            if cleartext_metadata {
                params.encrypt_metadata = false;
            }
            // R=6 (the default) passes through; --force-R5 selects deprecated
            // R=5, which guard_weak gates behind --allow-weak-crypto.
            guard_weak(params)
        }
        _ => unreachable!("key_len validated to 40/128/256 above"),
    }
}

#[allow(clippy::too_many_arguments)]
fn run_rewrite(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    json_input: bool,
    update_from_json: Option<&Path>,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    remove_restrictions: bool,
    decrypt: bool,
    normalize_content: bool,
    coalesce_contents: bool,
    _remove_unref: CliRemoveUnreferencedResources,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    options: WriterOptions,
) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let output = output.ok_or("missing output file")?;
    reject_same_job_output(&input, &output)?;
    let opened = open_job_pdf(
        &input,
        repair,
        password,
        json_input,
        update_from_json,
        false,
    )?;
    match opened {
        JobPdf::File(pdf) => run_rewrite_opened(
            pdf,
            &input,
            &output,
            repair,
            password,
            linearize,
            linearize_pass1,
            remove_restrictions,
            decrypt,
            normalize_content,
            coalesce_contents,
            _remove_unref,
            generate_appearances,
            flatten_annotations_mode,
            flatten_rotation,
            overlay_specs,
            verbose,
            options,
        ),
        JobPdf::Json(pdf) => run_rewrite_opened(
            pdf,
            &input,
            &output,
            repair,
            password,
            linearize,
            linearize_pass1,
            remove_restrictions,
            decrypt,
            normalize_content,
            coalesce_contents,
            _remove_unref,
            generate_appearances,
            flatten_annotations_mode,
            flatten_rotation,
            overlay_specs,
            verbose,
            options,
        ),
    }
}

#[allow(clippy::too_many_arguments)]
fn run_rewrite_opened<R: Read + Seek + 'static>(
    mut pdf: Pdf<R>,
    input: &Path,
    output: &Path,
    repair: bool,
    password: &PasswordArgs,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    remove_restrictions: bool,
    decrypt: bool,
    normalize_content: bool,
    coalesce_contents: bool,
    _remove_unref: CliRemoveUnreferencedResources,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    options: WriterOptions,
) -> CliResult<()> {
    let mut standard_output = prepare_pdf_standard_output(output)?;

    // Overlay/underlay stacking mutates page dictionaries and adds objects
    // before the canonical writer plans the output. The linearized path has a
    // separate qpdf ordering contract, so the combination is rejected upfront.
    if linearize && !overlay_specs.is_empty() {
        return Err("--overlay/--underlay cannot be combined with --linearize".into());
    }

    if linearize {
        // --remove-restrictions must strip signatures before the linearization
        // plan is computed: removing signature objects changes the reachable
        // first-page graph. qpdf applies this transformation before planning.
        let had_signatures = if remove_restrictions {
            AcroFormDocumentHelper::new(&mut pdf)?.disable_digital_signatures()?
        } else {
            false
        };
        let mut options = options;
        if decrypt || remove_restrictions {
            options.preserve_encryption = false;
        }
        // Apply content normalization before the writer plans and emits the
        // linearized document.
        let normalization_last_bad = if normalize_content {
            normalize_page_contents(&mut pdf)?
        } else {
            Vec::new()
        };
        let announce_file = standard_output.is_none();
        write_with_pdf_writer(
            &mut pdf,
            output,
            &mut standard_output,
            &options,
            true,
            linearize_pass1,
        )?;
        if verbose && announce_file {
            logger_info(format!("flpdf: wrote file {}\n", output.display()))?;
        }
        if had_signatures {
            logger_warn("flpdf: warning: removed signatures; signatures are now invalidated\n")?;
        }
        // On an encrypted input, `--decrypt`/`--remove-restrictions` has
        // already disabled source-encryption preservation above.
        finish_rewrite_warnings(input, &pdf, &normalization_last_bad, announce_file)?;
    } else {
        // Capture encryption state before the write for the qpdf-compatible
        // restriction diagnostic.
        let was_encrypted = pdf.is_encrypted();
        // qpdf runs disableDigitalSignatures unconditionally under
        // --remove-restrictions: remove catalog /Perms, zero /AcroForm
        // /SigFlags, strip /FT /V /SV /Lock from /Sig form fields, and erase them
        // from the top-level /Fields array (a field still reachable from a page
        // /Annots survives as a plain annotation; orphaned signature dicts are
        // dropped by the canonical rewrite GC). The returned flag reports
        // whether anything changed, driving the warning.
        let had_signatures = if remove_restrictions {
            AcroFormDocumentHelper::new(&mut pdf)?.disable_digital_signatures()?
        } else {
            false
        };
        let mut options = options;
        if decrypt || remove_restrictions {
            options.preserve_encryption = false;
        }
        // ── Content mutation pass ─────────────────────────────────────────────
        //
        // The mutations below operate on the in-memory Pdf model (via set_object).
        // They are all visible in the canonical writer output.
        //
        // Application order follows QPDFJob::handleTransformations:
        //   1. generate appearances;
        //   2. flatten annotations;
        //   3. coalesce page contents;
        //   4. flatten rotation and apply page stacking;
        //   5. normalize content immediately before the writer consumes it.
        // The coalesce operation is the provider-backed PageObjectHelper
        // route; it must not materialize a legacy page byte buffer.
        //
        // NOTE: a plain `rewrite` does NOT prune unreferenced /Resources entries.
        // qpdf only prunes resource-dict entries during page-copy operations
        // (`--pages`/`--split-pages`) — a plain `qpdf IN OUT`, even with
        // `--remove-unreferenced-resources=yes`, keeps every /Resources entry
        // (verified against qpdf 11.9.0). flpdf mirrors this: resource-entry
        // pruning lives in `run_page_extraction` (the --pages path), not here.
        // Pruning on a plain rewrite was a divergence that dropped an
        // unreferenced image XObject (flpdf-79ef); it is the resource-entry half
        // of flpdf-9hc.12.4/12.7, which conflated unreferenced-OBJECT GC (the
        // renumber drops unreachable objects on every canonical rewrite — kept) with
        // /Resources-ENTRY pruning (page-op-only — removed here).
        //
        // qpdf always creates a fresh document and defaults to
        // `--compress-streams=y`; the canonical writer applies those defaults
        // for every rewrite. Version setters therefore always affect the
        // emitted header, including with `--remove-unreferenced-resources=no`.
        // (No resource-entry pruning on the plain rewrite path — see the
        // "Content mutation pass" note above. qpdf prunes /Resources entries only
        // during page operations, which flpdf handles in run_page_extraction.)

        // Step 1: generate missing form-field appearance streams
        // (--generate-appearances). MUST run before --flatten-annotations so
        // value-only fields (e.g. a filled text field with no /AP) are baked
        // into page content instead of being dropped (acceptance ordering:
        // generate first, flatten second).
        if generate_appearances {
            generate_missing_appearances(&mut pdf)?;
        }

        // Step 2: flatten annotations into page content (--flatten-annotations).
        if let Some(mode) = flatten_annotations_mode {
            let (required_flags, forbidden_flags) = mode.flags();
            PageDocumentHelper::new(&mut pdf)
                .flatten_annotations(required_flags, forbidden_flags)?;
        }

        // Step 3: coalesce per-page /Contents arrays into provider-backed
        // streams. This intentionally follows annotation flattening, matching
        // QPDFJob.cc:2183-2187 for the combined flags.
        if coalesce_contents {
            let page_refs = pages::page_refs(&mut pdf)?;
            for page_ref in page_refs {
                PageObjectHelper::new(page_ref, &mut pdf).coalesce_content_streams()?;
            }
        }

        // Step 4: flatten page rotation into content (--flatten-rotation).
        if flatten_rotation {
            let page_refs = pages::page_refs(&mut pdf)?;
            flatten_rotation_on_pages(&mut pdf, &page_refs)?;
        }

        // Step 5: overlay/underlay page stacking (--overlay / --underlay).
        // qpdf applies this as its page-stacking step, after page selection and
        // the other content transforms and before writing; mirror that ordering
        // so the output graph (and thus the bytes) matches qpdf. Each source is
        // opened (with its --password) and imported into the in-memory document
        // here; the new objects are part of the canonical writer graph.
        // qpdf keeps a provider-backed source QPDF alive when
        // `copyForeignObject` copies a Form XObject whose data comes from a
        // `StreamDataProvider` (`libqpdf/QPDF.cc:2248-2257`). The canonical
        // overlay route has the same lifetime contract: retain the opened
        // source documents until after the destination writer has consumed
        // every copied Form stream, not just until page stacking returns.
        let _built_overlay_specs = if !overlay_specs.is_empty() {
            let mut built = build_overlay_specs(overlay_specs, repair, password)?;

            // flpdf-9hc.16.8: propagate max input header version + Adobe
            // extension_level to the writer (mirrors qpdf QPDFJob.cc L1714
            // accumulator + L2913 setMinimumPDFVersion). Executed only when
            // overlay/underlay is in play; a full CLI-wide input-version
            // accumulator across other paths is out of scope here (documented
            // as non-scope in the bd design).
            let initial_version =
                parse_pdf_version(pdf.version()).unwrap_or(PdfVersion::new(1, 0, 0));
            let mut max_version = PdfVersion::new(
                initial_version.major(),
                initial_version.minor(),
                pdf.adobe_extension_level().unwrap_or(0),
            );
            for spec in built.iter_mut() {
                let source_version =
                    parse_pdf_version(spec.source.version()).unwrap_or(PdfVersion::new(1, 0, 0));
                max_version.update_if_greater(PdfVersion::new(
                    source_version.major(),
                    source_version.minor(),
                    spec.source.adobe_extension_level().unwrap_or(0),
                ));
            }
            // Preserve any pre-existing --min-version / --min-extension-level
            // CLI arg by taking pairwise max with the accumulated floor.
            if let Some(ref current) = options.min_version {
                let current_version =
                    parse_pdf_version(current).unwrap_or(PdfVersion::new(1, 0, 0));
                max_version.update_if_greater(PdfVersion::new(
                    current_version.major(),
                    current_version.minor(),
                    options.min_extension_level.unwrap_or(0),
                ));
            }
            let (version, max_ext) = max_version.get_version();
            options.min_version = Some(version);
            options.min_extension_level = (max_ext > 0).then_some(max_ext);

            // --verbose: emit the per-destination-page overlay/underlay plan
            // to stderr before painting, matching qpdf's --verbose output
            // ("processing underlay/overlay" header + `  page N` +
            // `    <file> overlay|underlay <src>`). The report is computed
            // via the flpdf::overlay_verbose_report inspection API so the
            // ordering (underlays first, then overlays, in declaration
            // order across specs) is source-shared with apply_overlay_specs.
            if verbose {
                let report = flpdf::overlay_verbose_report(&mut pdf, &mut built)?;
                let mut message = String::from("flpdf: processing underlay/overlay\n");
                for page in &report {
                    message.push_str(&format!("  page {}\n", page.dest_page));
                    for src in &page.sources {
                        let file = &overlay_specs[src.spec_index].file;
                        let kind_str = match src.kind {
                            flpdf::OverlayKind::Underlay => "underlay",
                            flpdf::OverlayKind::Overlay => "overlay",
                        };
                        message.push_str(&format!("    {} {} {}\n", file, kind_str, src.src_page));
                    }
                }
                logger_info(message)?;
            }

            flpdf::apply_overlay_specs(&mut pdf, &mut built)?;
            Some(built)
        } else {
            None
        };

        // Step 6: normalize after all page transformations. The stream
        // normalizer consumes the provider-backed coalesced route and writes
        // the normalized bytes through ObjectHandle.
        let normalization_last_bad = if normalize_content {
            normalize_page_contents(&mut pdf)?
        } else {
            Vec::new()
        };

        let announce_file = standard_output.is_none();
        write_with_pdf_writer(
            &mut pdf,
            output,
            &mut standard_output,
            &options,
            false,
            None,
        )?;

        if verbose && announce_file {
            logger_info(format!("flpdf: wrote file {}\n", output.display()))?;
        }
        if remove_restrictions && was_encrypted {
            eprintln!("flpdf: removed restrictions (encryption and advisory permissions stripped)");
        }
        if had_signatures {
            logger_warn("flpdf: warning: removed signatures; signatures are now invalidated\n")?;
        }
        // Unencrypted input + --remove-restrictions is a no-op rewrite
        // (exit 0, valid output, no diagnostic) — nothing was restricted,
        // matching qpdf's lenient handling of --remove-restrictions on
        // unencrypted files.
        finish_rewrite_warnings(input, &pdf, &normalization_last_bad, announce_file)?;
    }
    Ok(())
}

/// Route `--generate-appearances` through qpdf's
/// `QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded` boundary.
fn generate_missing_appearances<R: Read + Seek>(pdf: &mut Pdf<R>) -> CliResult<()> {
    AcroFormDocumentHelper::new(pdf)?.generate_appearances_if_needed()?;
    Ok(())
}

// ===========================================================================
// Page operations (flpdf-9hc.8.12): --pages / --rotate / --split-pages /
// --collate plumbing.
//
// qpdf observation basis (/usr/bin/qpdf 11.9.0):
//   - `qpdf --help=page-selection` documents the
//     `--pages [--file=]f [--password=p] [range] [...] -- out` segment, the
//     `.` shorthand for the primary input, and `--collate=n`.
//   - `qpdf in.pdf --pages . 2-3 -- --rotate=+90:1 out.pdf` rotates the FIRST
//     EXTRACTED page (verified: source page 2's object got /Rotate 90, source
//     page 3 stayed /Rotate 0) — so --rotate ranges index OUTPUT page numbers.
//   - `qpdf --split-pages=2 in.pdf out.pdf` writes `out-1-2.pdf`,`out-3-3.pdf`.
//   - `--collate` / `--rotate` / `--split-pages` without `--pages` exit 0 in
//     qpdf; flpdf matches (rotate applies to the source doc, collate no-op,
//     split operates on the rewritten bytes).
// ===========================================================================

/// One parsed entry from the `--pages` segment before file resolution.
struct PageSegmentSpec {
    /// File token as written (`.` = primary input, or a path).
    file_token: String,
    /// Per-input password (`--password=` immediately following the file).
    password: Option<String>,
    /// Page-range string (empty = all pages).
    range: String,
}

/// Parse the raw `--pages` segment tokens into ordered specs.
///
/// Grammar (qpdf 11.9.0 `--help=page-selection`, both the modern
/// `--file=`/`--range=` form and the legacy positional form):
///
/// ```text
/// segment ::= ( file [ '--password=' pw ] [ range ] )+
/// file    ::= '--file=' PATH | PATH | '.'
/// range   ::= '--range=' R | R          (R = qpdf page-range syntax)
/// ```
///
/// Bounded, non-recursive single pass over `tokens`; no panics.
fn parse_pages_segment(tokens: &[String]) -> CliResult<Vec<PageSegmentSpec>> {
    let mut specs: Vec<PageSegmentSpec> = Vec::new();

    for tok in tokens {
        if let Some(path) = tok.strip_prefix("--file=") {
            specs.push(PageSegmentSpec {
                file_token: path.to_string(),
                password: None,
                range: String::new(),
            });
            continue;
        }
        if let Some(pw) = tok.strip_prefix("--password=") {
            let cur = specs
                .last_mut()
                .ok_or("--pages: --password= must follow a file in the --pages segment")?;
            cur.password = Some(pw.to_string());
            continue;
        }
        if let Some(r) = tok.strip_prefix("--range=") {
            let cur = specs
                .last_mut()
                .ok_or("--pages: --range= must follow a file in the --pages segment")?;
            if !cur.range.is_empty() {
                return Err("--pages: duplicate page-range for one input file".into());
            }
            cur.range = r.to_string();
            continue;
        }
        if tok.starts_with("--") {
            return Err(format!(
                "--pages: unsupported token {tok:?} in the page-selection segment"
            )
            .into());
        }
        // Positional token: either a NEW file, or the page-range for the
        // current file. qpdf's heuristic: the token is a page-range iff a
        // file is already open and that file has no range yet AND the token
        // parses as a page-range. Otherwise it starts a new file.
        match specs.last_mut() {
            Some(cur) if cur.range.is_empty() && PageRange::parse(tok).is_ok() => {
                cur.range = tok.clone();
            }
            _ => specs.push(PageSegmentSpec {
                file_token: tok.clone(),
                password: None,
                range: String::new(),
            }),
        }
    }

    if specs.is_empty() {
        return Err("--pages: no input files given in the page-selection segment".into());
    }
    Ok(specs)
}

/// Resolve `--pages` specs into [`InputSpec`]s, mapping the `.` shorthand to
/// the primary input path while preserving the literal filename identity used
/// by qpdf's page-spec source heap.
fn resolve_page_specs(
    specs: &[PageSegmentSpec],
    primary_input: &std::path::Path,
) -> CliResult<Vec<InputSpec>> {
    let mut out = Vec::with_capacity(specs.len());
    for s in specs {
        let path: PathBuf = if s.file_token == "." {
            primary_input.to_path_buf()
        } else {
            PathBuf::from(&s.file_token)
        };
        let range = PageRange::parse(&s.range).map_err(|e| {
            Box::<dyn std::error::Error>::from(format!(
                "--pages: invalid page range {:?}: {e}",
                s.range
            ))
        })?;
        out.push(InputSpec::new(path, s.password.clone(), range));
    }
    Ok(out)
}

// ===========================================================================
// --overlay / --underlay segment parser (flpdf-9hc.16.1)
//
// qpdf 11.9.0 grammar (--help=overlay-underlay):
//   {--overlay|--underlay} [--file=]FILE [--password=PW]
//       [--to=RANGE] [--from=RANGE] [--repeat=RANGE] --
//
// qpdf defaults (observed, NOT encoded here — deferral to .16.4):
//   --from=1-z, --to=1-z, --repeat="" (no repeat; surplus dest pages blank).
//   The task instruction note "default --repeat=z" contradicts qpdf observation
//   and is intentionally NOT adopted. Unspecified options stay None here; the
//   default interpretation is applied in .16.4.
// ===========================================================================

/// Whether a segment introduces overlay content (drawn on top) or underlay (below).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OverlayKind {
    Overlay,
    Underlay,
}

/// Parsed result of a single `--overlay … --` or `--underlay … --` segment.
///
/// Range strings (`from`, `to`, `repeat`) are raw qpdf page-range syntax;
/// `None` means the option was absent. Default range semantics are applied
/// by the caller during page-mapping.
#[derive(Debug, Clone, PartialEq, Eq)]
struct OverlaySpec {
    kind: OverlayKind,
    /// Path to the overlay/underlay source PDF.
    file: String,
    /// Password for the source PDF, if supplied via `--password=`.
    password: Option<String>,
    /// Raw `--from=` page-range string (source pages to cycle through).
    from: Option<String>,
    /// Raw `--to=` page-range string (destination pages to receive content).
    to: Option<String>,
    /// Raw `--repeat=` page-range string (source pages to repeat for surplus dest).
    repeat: Option<String>,
}

struct PreprocessedArgs {
    residual_args: Vec<String>,
    overlay_specs: Vec<OverlaySpec>,
    attachment_segments: Vec<Vec<String>>,
}

/// Parse the raw token slice captured between `--overlay`/`--underlay` and `--`.
///
/// Grammar: `FILE and sub-options in any order`. `FILE` is either bare or `--file=PATH`;
/// `--password=`, `--to=`, `--from=`, `--repeat=` may appear before or after it,
/// mirroring qpdf's UO segment parser (no positional ordering constraint).
///
/// - `FILE` is mandatory (exactly one, either via `--file=PATH` or bare).
/// - `--password=`, `--to=`, `--from=`, `--repeat=` are each optional; duplicates error.
/// - Range values are validated via [`PageRange::parse`] (syntax only; defaults not applied).
/// - Unknown `--xxx` tokens, duplicate files, or an empty token list all produce an error.
///
/// # Errors
///
/// Returns an error if the token slice is empty, a file is missing or duplicated,
/// a range is syntactically invalid, a flag is duplicated, or an unknown `--` flag appears.
fn parse_overlay_segment(kind: OverlayKind, tokens: &[String]) -> CliResult<OverlaySpec> {
    let flag = match kind {
        OverlayKind::Overlay => "--overlay",
        OverlayKind::Underlay => "--underlay",
    };

    if tokens.is_empty() {
        return Err(format!("{flag}: no source file given in the segment").into());
    }

    let mut file: Option<String> = None;
    let mut password: Option<String> = None;
    let mut from: Option<String> = None;
    let mut to: Option<String> = None;
    let mut repeat: Option<String> = None;

    for tok in tokens {
        if let Some(path) = tok.strip_prefix("--file=") {
            if file.is_some() {
                return Err(format!("{flag}: duplicate file in segment").into());
            }
            file = Some(path.to_string());
            continue;
        }
        if let Some(pw) = tok.strip_prefix("--password=") {
            if password.is_some() {
                return Err(format!("{flag}: duplicate --password= in segment").into());
            }
            password = Some(pw.to_string());
            continue;
        }
        if let Some(r) = tok.strip_prefix("--to=") {
            if to.is_some() {
                return Err(format!("{flag}: duplicate --to= in segment").into());
            }
            PageRange::parse(r)
                .map_err(|e| format!("{flag}: invalid --to= page range {r:?}: {e}"))?;
            to = Some(r.to_string());
            continue;
        }
        if let Some(r) = tok.strip_prefix("--from=") {
            if from.is_some() {
                return Err(format!("{flag}: duplicate --from= in segment").into());
            }
            PageRange::parse(r)
                .map_err(|e| format!("{flag}: invalid --from= page range {r:?}: {e}"))?;
            from = Some(r.to_string());
            continue;
        }
        if let Some(r) = tok.strip_prefix("--repeat=") {
            if repeat.is_some() {
                return Err(format!("{flag}: duplicate --repeat= in segment").into());
            }
            PageRange::parse(r)
                .map_err(|e| format!("{flag}: invalid --repeat= page range {r:?}: {e}"))?;
            repeat = Some(r.to_string());
            continue;
        }
        if tok.starts_with("--") {
            return Err(format!("{flag}: unsupported token {tok:?} in segment").into());
        }
        // Bare (non-flag) token: must be the file path (exactly one allowed).
        if file.is_some() {
            return Err(format!("{flag}: duplicate file in segment").into());
        }
        file = Some(tok.clone());
    }

    let file = file.ok_or_else(|| format!("{flag}: no source file given in the segment"))?;

    Ok(OverlaySpec {
        kind,
        file,
        password,
        from,
        to,
        repeat,
    })
}

#[cfg(test)]
fn parse_test_args(args: Vec<String>) -> CliResult<arg_parser::ParsedArgs> {
    let has_program = args.first().is_some_and(|arg| !arg.starts_with('-'));
    let mut parser_args = args;
    if !has_program {
        parser_args.insert(0, "flpdf".to_owned());
    }
    let mut parsed = arg_parser::ArgParser::from_command(Cli::command()).parse(parser_args)?;
    if !has_program {
        parsed.residual_args.remove(0);
    }
    Ok(parsed)
}

#[cfg(test)]
fn rewrite_qpdf_single_dash(args: Vec<String>) -> Vec<String> {
    parse_test_args(args)
        .expect("test argv should parse")
        .residual_args
}

#[cfg(test)]
fn normalize_qpdf_bare_equals(args: Vec<String>) -> Vec<String> {
    rewrite_qpdf_single_dash(args)
}

#[cfg(test)]
fn extract_overlay_groups(args: Vec<String>) -> CliResult<(Vec<String>, Vec<OverlaySpec>)> {
    let parsed = parse_test_args(args)?;
    let mut overlay_specs = Vec::new();
    for segment in parsed.named_segments {
        let kind = match segment.option.as_str() {
            "overlay" => OverlayKind::Overlay,
            "underlay" => OverlayKind::Underlay,
            _ => continue,
        };
        overlay_specs.push(parse_overlay_segment(kind, &segment.tokens)?);
    }
    Ok((parsed.residual_args, overlay_specs))
}

#[cfg(test)]
fn extract_attachment_groups(args: Vec<String>) -> CliResult<(Vec<String>, Vec<Vec<String>>)> {
    let parsed = parse_test_args(args)?;
    let groups = parsed
        .named_segments
        .into_iter()
        .filter(|segment| segment.option == "add-attachment")
        .map(|segment| segment.tokens)
        .collect();
    Ok((parsed.residual_args, groups))
}

/// Build the library [`flpdf::OverlaySpec`]s from the parsed CLI segments,
/// opening each source PDF (with its per-segment `--password`).
///
/// Source files are opened read-only; an authentication failure or unreadable
/// file is surfaced as a CLI error. Weak-crypto sources (RC4, R=5) are accepted
/// unconditionally: `--allow-weak-crypto` only gates weak-crypto *writes*, and
/// an overlay source is a read-only inspection open. This mirrors qpdf's
/// observable behavior and the same treatment the `--check` inspection open
/// applies.
///
/// Page-range defaults match qpdf: an **absent** `--from`/`--to` defaults to all
/// source/destination pages. An **explicit empty** range is distinct from an
/// absent one: empty `--from=` selects an empty source set (so `--repeat` cycles
/// from the first destination page), empty `--to=` selects an empty destination
/// set (the overlay becomes a no-op), and empty `--repeat=` means no repetition
/// (identical to an absent `--repeat`). `--repeat` is `None` by default.
///
/// # Errors
///
/// Returns an error if a source PDF cannot be opened/authenticated or if a
/// stored page-range string fails to parse (already validated by
/// [`parse_overlay_segment`], so a parse failure here would be an internal
/// inconsistency).
fn build_overlay_specs(
    specs: &[OverlaySpec],
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Vec<flpdf::OverlaySpec<BufReader<File>>>> {
    let mut built = Vec::with_capacity(specs.len());
    for spec in specs {
        let path = PathBuf::from(&spec.file);
        let file = File::open(&path).map_err(|error| error_with_file(&path, error.into()))?;
        // Overlay sources are read-only; qpdf accepts weak-crypto opens
        // unconditionally because its flag only gates writes. Retain the
        // command-wide open policy (including recovery and xref handling),
        // replacing only the source-local password.
        let mut source_password = password.clone();
        source_password.password = spec.password.clone();
        source_password.password_file = None;
        let mut options = pdf_open_options(repair, &source_password)?;
        configure_document_logger(&mut options, &path);
        let mut source = Pdf::open_with_options(BufReader::new(file), options)
            .map_err(|error| error_with_file(&path, actionable_password_error(error)))?;
        source
            .root_handle()
            .map_err(|error| error_with_file(&path, actionable_password_error(error)))?;

        let kind = match spec.kind {
            OverlayKind::Overlay => flpdf::OverlayKind::Overlay,
            OverlayKind::Underlay => flpdf::OverlayKind::Underlay,
        };
        // Distinguish an absent `--from` (default: all source pages) from an
        // explicit empty `--from=` (empty source set). qpdf treats the latter as
        // "no from pages", so `--repeat` cycles from the first destination page.
        let from = match spec.from.as_deref() {
            None => PageRange::parse("")?,
            Some("") => PageRange::empty(),
            Some(r) => PageRange::parse(r)?,
        };
        // Distinguish an absent `--to` (default: all destination pages) from an
        // explicit empty `--to=` (empty destination set). qpdf treats the latter
        // as selecting no destination pages, so the overlay is a no-op (observed:
        // byte-identical to a plain rewrite of the destination).
        let to = match spec.to.as_deref() {
            None => PageRange::parse("")?,
            Some("") => PageRange::empty(),
            Some(r) => PageRange::parse(r)?,
        };
        // An explicit empty `--repeat=` means "no repeat", identical to an absent
        // `--repeat` (qpdf-observed: byte-identical to the default overlay). Both
        // map to `None`, the canonical no-repeat representation; mapping to
        // `Some(PageRange::empty())` would resolve to the same empty set in
        // `spec_page_sources`, so `None` is preferred.
        let repeat = match spec.repeat.as_deref() {
            None | Some("") => None,
            Some(r) => Some(PageRange::parse(r)?),
        };
        built.push(flpdf::OverlaySpec {
            source,
            kind,
            from,
            to,
            repeat,
        });
    }
    Ok(built)
}

/// Parse `--collate` value: `n` or `i,j,k,...`. flpdf's [`collate`] supports a
/// single chunk size `n`; the comma form is parsed but only the first value is
/// honoured (a documented divergence — full per-input groups are out of
/// scope).
fn parse_collate_n(raw: &str) -> CliResult<usize> {
    // Only a single positive integer is supported. Silently using the first
    // value of `--collate=1,2` would emit a different page order than the
    // user asked for, so reject comma-separated group lists explicitly.
    let n: usize = raw.parse().map_err(|_| {
        format!(
            "--collate: expected a single positive integer, got {raw:?} \
             (comma-separated group lists are not supported)"
        )
    })?;
    if n == 0 {
        return Err("--collate: group size must be >= 1".into());
    }
    Ok(n)
}

/// Basename of `p` for `--verbose --pages` progress lines (qpdf uses the
/// bare file name — e.g. `fxo-red.pdf`, not the absolute path or `.`).
fn pages_progress_filename(p: &std::path::Path) -> String {
    p.file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| p.display().to_string())
}

/// Run the `--pages` extraction pipeline.
///
/// Processing order is fixed as follows:
///   1. page_combine / page_collate → selected ObjectRef list
///   2. pages::tree_rebuild::rebuild_page_tree → RebuildResult
///   3. apply_rotate_to_pages (on the rebuilt OUTPUT leaves; qpdf-observed)
///      3.5. /PageLabels reconstruction (per selected page, qpdf
///      `handlePageSpecs`-observed)
///   4. job::remap_outline_and_dests
///   5. struct_tree_pg::drop_struct_elem_dangling_pg
///   6. thread_bead_p::drop_thread_bead_dangling_p
///      6.5. objr_obj_annot_p::drop_objr_obj_annot_dangling_p
///   7. QPDFJob::prune_after_subset (Auto/Yes/No)
///   8. QPDFJob::prune_acroform_after_subset
///   9. write (or split_pages when --split-pages is set)
///
/// Multi-source page specifications are handled by the job-level
/// `QPDFJob::handle_page_specs` route, which returns a fresh primary-based
/// document after foreign-page copy, field collision handling, PageLabels
/// reconstruction, and spec-order restoration. The in-place route below is
/// retained for a single source so the existing post-rebuild consumers can
/// continue to operate on the original object graph.
// qpdf-deviation: this single-source in-place pipeline duplicates
// job/page_specs.rs's handle_page_specs (the multi-source job route) rather
// than routing single-source --pages through it. qpdf itself has no such
// split -- QPDFJob::handlePageSpecs (libqpdf/QPDFJob.cc:2360-2632) is always
// used, regardless of input count. Unifying the two routes is tracked
// separately (flpdf-hxmj) since it requires re-verifying all nine steps'
// behavior, not just the acroform-pruning step that surfaced this.
#[allow(clippy::too_many_arguments)]
fn run_page_extraction(
    primary_input: &std::path::Path,
    output: &std::path::Path,
    repair: bool,
    password: &PasswordArgs,
    json_input: bool,
    update_from_json: Option<&Path>,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    options: WriterOptions,
    verbose: bool,
) -> CliResult<()> {
    // `--split-pages` writes one numbered file per output page rather than a
    // single `output` path, so `output` is a naming template here, not a
    // literal file to compare against `primary_input` — matching qpdf's own
    // `(!m->split_pages) && QUtil::same_file(...)` exclusion in
    // `checkConfiguration()` (`QPDFJob.cc:627`).
    if page_ops.split_pages.is_none() {
        reject_same_job_output(primary_input, output)?;
    }
    let standard_output = prepare_page_operation_standard_output(output, page_ops)?;
    let creates_output = standard_output.is_none();
    if page_ops.empty {
        // qpdf accepts `--empty`; ignoring it would silently change which
        // document supplies the catalog/outlines. Fail loudly instead.
        return Err(
            "--empty is accepted by qpdf but not implemented in flpdf at this layer \
             (tracked separately); rerun without --empty"
                .into(),
        );
    }

    let specs = parse_pages_segment(&page_ops.pages)?;
    let mut inputs = resolve_page_specs(&specs, primary_input)?;
    let has_external_source = inputs.iter().any(|spec| spec.path != primary_input);

    // The in-place single-document planner must use the top-level password
    // for the already-authenticated primary when `--pages . ...` carries no
    // segment password. The multi-source QPDFJob route opens the primary
    // separately and must leave secondary credentials segment-local: qpdf does
    // not fall back to the primary password for a distinct source
    // (QPDFJob.cc:2400-2412).
    if !has_external_source {
        if let Some(top_pw) = &password.password {
            for spec in &mut inputs {
                if spec.password.is_none() {
                    spec.password = Some(top_pw.clone());
                }
            }
        }
    }

    // Keep the canonicalized path set for the JSON-input guard and the
    // single-source verbose route. Ordinary page operations below use the
    // literal qpdf filename identity: two spellings of the same file may be
    // distinct QPDF sources, as documented by qpdf's page-spec API.
    let mut distinct: Vec<std::path::PathBuf> = Vec::new();
    for spec in &inputs {
        // Source inputs must exist to be opened; if canonicalization fails
        // fall back to the literal path (the open will surface a clear error).
        let key = std::fs::canonicalize(&spec.path).unwrap_or_else(|_| spec.path.clone());
        if !distinct.contains(&key) {
            distinct.push(key);
        }
    }
    if json_input || update_from_json.is_some() {
        // `run_page_extraction_from_repeated_pdf` below applies every spec's
        // range to the single already-opened job document; it has no way to
        // honor a `spec.path` that names a genuinely different file (unlike
        // the ordinary branch further down, which opens `inputs[0].path`
        // directly). The `distinct.len() > 1` check above only catches this
        // when two *explicit* paths disagree with each other -- a lone
        // explicit source (e.g. `--pages other.pdf 1`, no `.` segment) never
        // puts `primary_input` itself into `distinct`, so it silently
        // resolves to a single-element `distinct` and slips past. Comparing
        // every resolved spec path against `primary_input`'s own canonical
        // path here closes that gap without touching the ordinary branch's
        // (already correct) handling of a genuinely different single source.
        let primary_canonical =
            std::fs::canonicalize(primary_input).unwrap_or_else(|_| primary_input.to_path_buf());
        if distinct.iter().any(|path| *path != primary_canonical) {
            return Err(
                "--pages: cross-document page merge is not supported at this layer \
                 (an explicit --pages source differs from the --json-input/\
                 --update-from-json primary input). Single-document extraction \
                 ('.' or the primary input's own path) is supported; cross-doc \
                 merge with a JSON-created/updated primary is tracked in a \
                 separate issue."
                    .into(),
            );
        }
        let opened = open_job_pdf(
            primary_input,
            repair,
            password,
            json_input,
            update_from_json,
            false,
        )?;
        return match opened {
            JobPdf::File(pdf) => run_page_extraction_from_repeated_pdf(
                pdf,
                primary_input,
                output,
                repair,
                password,
                page_ops,
                overlay_specs,
                remove_unref,
                options,
                verbose,
                standard_output,
                creates_output,
                &inputs,
                &distinct,
            ),
            JobPdf::Json(pdf) => run_page_extraction_from_repeated_pdf(
                pdf,
                primary_input,
                output,
                repair,
                password,
                page_ops,
                overlay_specs,
                remove_unref,
                options,
                verbose,
                standard_output,
                creates_output,
                &inputs,
                &distinct,
            ),
        };
    }

    // qpdf's ordinary page-spec job owns distinct input documents and copies
    // foreign pages into the primary output. Route that case through the
    // library QPDFJob facade; retain the existing in-place route for the
    // single-document path, where its outline/structure post-passes operate
    // on the original object graph.
    if has_external_source {
        return run_page_extraction_from_multiple_sources(
            primary_input,
            output,
            repair,
            password,
            page_ops,
            overlay_specs,
            remove_unref,
            options,
            verbose,
            standard_output,
            creates_output,
            inputs,
        );
    }

    // qpdf's page-operation output inherits encryption from the command's
    // primary input. A plaintext primary importing pages from an encrypted
    // secondary produces plaintext; an encrypted primary remains encrypted.
    // Probe the primary separately because the selected page source may be a
    // different input in qpdf's `--pages` command.
    let primary_encrypted =
        open_pdf(&primary_input.to_path_buf(), repair, password)?.is_encrypted();

    // --verbose: emit qpdf-parity `--pages` progress. Order matches
    // libqpdf/QPDFJob.cc: process_all() emits the shared-resource scan
    // per input file (L2250/L2312), then the top-level pipeline emits
    // "removing unreferenced pages from primary input" (L2539) once, then
    // "adding pages from <file>" per Selection (L2594) inside the copy loop.
    //
    // The qpdf shared-resource heuristic is evaluated again at the consumer
    // boundary immediately before rebuild_page_tree, when the source page
    // tree is still intact. This progress block retains the established
    // ordering; the keep-open-files subsystem remains an unconditional "y"
    // because flpdf has no equivalent file-handle policy.
    if verbose {
        let mut message = String::from("flpdf: selecting --keep-open-files=y\n");
        for path in &distinct {
            let fname = pages_progress_filename(path);
            message.push_str(&format!(
                "flpdf: {fname}: checking for shared resources\nflpdf: no shared resources found\n"
            ));
        }
        logger_info(message)?;
    }

    // CombinedPlan::from_specs opens each file itself; its per-input
    // PagePlans carry source ObjectRefs that are stable across a re-open of
    // identical bytes. We use it only for selection/collation planning, then
    // open the (single) resolved source ourselves for the rebuild passes.
    let plan = CombinedPlan::from_specs(inputs.clone())?;

    if verbose {
        let mut message = String::from("flpdf: removing unreferenced pages from primary input\n");
        for spec in &inputs {
            message.push_str(&format!(
                "flpdf: adding pages from {}\n",
                pages_progress_filename(&spec.path)
            ));
        }
        logger_info(message)?;
    }

    let combined_pages = match page_ops.collate.as_deref() {
        Some(raw) => {
            let n = parse_collate_n(raw)?;
            collate(&plan, n)?
        }
        None => plan.flat_pages().to_vec(),
    };

    let source_path = &inputs[0].path;
    let source_password = inputs[0].password.clone();
    let mut src_pw = password.clone();
    if let Some(pw) = source_password {
        src_pw.password = Some(pw);
        src_pw.password_file = None;
    }
    let mut pdf = open_pdf(&source_path.to_path_buf(), repair, &src_pw)?;
    let primary_copy_encryption = pdf.writer_copy_encryption_source()?;

    run_page_extraction_after_plan(
        pdf,
        output,
        source_path,
        repair,
        password,
        page_ops,
        overlay_specs,
        remove_unref,
        options,
        verbose,
        standard_output,
        creates_output,
        primary_encrypted,
        primary_copy_encryption,
        false,
        true,
        combined_pages,
    )
}

/// Run qpdf's ordinary multi-source page-spec path.
///
/// The primary document is retained at source index zero even when no page
/// spec selects it. Every other literal filename is opened once and reused by
/// the job-level page-spec planner, matching qpdf's page heap keyed by the
/// filename token. The resulting fresh merged document is then passed through
/// the same rotate/structure/overlay/write completion boundary as a
/// single-document extraction.
#[allow(clippy::too_many_arguments)]
fn run_page_extraction_from_multiple_sources(
    primary_input: &Path,
    output: &Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    options: WriterOptions,
    verbose: bool,
    standard_output: Option<PipelineWriter>,
    creates_output: bool,
    inputs: Vec<InputSpec>,
) -> CliResult<()> {
    // qpdf inherits output encryption from the primary input for page
    // operations. Keep this probe separate from the mutable source vector so
    // source opening below can use the same top-level password policy.
    let primary_encrypted =
        open_pdf(&primary_input.to_path_buf(), repair, password)?.is_encrypted();

    // Build literal-path source identity and one qpdf page specification per
    // occurrence. `.` was already normalized to primary_input by
    // resolve_page_specs; path equality therefore preserves qpdf's documented
    // distinction between two different spellings of the same file.
    let mut source_paths = vec![primary_input.to_path_buf()];
    let mut source_passwords: Vec<Option<String>> = vec![None];
    let mut specs = Vec::with_capacity(inputs.len());
    for input in inputs {
        let source_index = if input.path == primary_input {
            0
        } else if let Some(index) = source_paths.iter().position(|path| path == &input.path) {
            index
        } else {
            let index = source_paths.len();
            source_paths.push(input.path.clone());
            source_passwords.push(input.password.clone());
            index
        };
        specs.push(PageSpecInput::new(source_index, input.range));
    }

    if verbose {
        let mut message = String::from("flpdf: selecting --keep-open-files=y\n");
        for path in &source_paths {
            let fname = pages_progress_filename(path);
            message.push_str(&format!(
                "flpdf: {fname}: checking for shared resources\nflpdf: no shared resources found\n"
            ));
        }
        message.push_str("flpdf: removing unreferenced pages from primary input\n");
        for path in &source_paths {
            message.push_str(&format!(
                "flpdf: adding pages from {}\n",
                pages_progress_filename(path)
            ));
        }
        logger_info(message)?;
    }

    let mut sources = Vec::with_capacity(source_paths.len());
    sources.push(open_pdf(&primary_input.to_path_buf(), repair, password)?);
    for (source_index, path) in source_paths.iter().enumerate().skip(1) {
        let mut source_password = password.clone();
        // qpdf opens each secondary with only the password attached to its
        // page specification (QPDFJob.cc:2400-2412). The primary password is
        // not a fallback for a secondary with no segment password; retain the
        // global interpretation/policy flags, but replace both credential
        // fields with the per-source value, including an explicit empty value.
        source_password.password = source_passwords[source_index].clone();
        source_password.password_file = None;
        sources.push(open_pdf(path, repair, &source_password)?);
    }

    // qpdf raises the writer floor from every input processed by the job
    // (`QPDFJob.cc:1714-1715`) and applies that floor before explicit
    // --min-version/--force-version settings
    // (`QPDFJob.cc:2847-2918`). The merged fresh document starts at its
    // baseline version, so carry the source floor explicitly through the
    // multi-source consumer boundary. Keep the existing pairwise version /
    // extension ordering used by the overlay route.
    let mut options = options;
    let mut max_version = PdfVersion::new(1, 0, 0);
    for source in &mut sources {
        let source_version =
            parse_pdf_version(source.version()).unwrap_or(PdfVersion::new(1, 0, 0));
        max_version.update_if_greater(PdfVersion::new(
            source_version.major(),
            source_version.minor(),
            source.adobe_extension_level().unwrap_or(0),
        ));
    }
    if let Some(ref current) = options.min_version {
        let current_version = parse_pdf_version(current).unwrap_or(PdfVersion::new(1, 0, 0));
        max_version.update_if_greater(PdfVersion::new(
            current_version.major(),
            current_version.minor(),
            options.min_extension_level.unwrap_or(0),
        ));
    }
    let (version, max_ext) = max_version.get_version();
    options.min_version = Some(version);
    options.min_extension_level = (max_ext > 0).then_some(max_ext);

    let primary_copy_encryption = sources
        .first_mut()
        .ok_or("--pages: primary input was not opened")?
        .writer_copy_encryption_source()?;

    let collate = page_ops
        .collate
        .as_deref()
        .map(parse_collate_n)
        .transpose()?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let source_warnings = job.has_warnings();
    let mut merged = job.handle_page_specs(
        &mut sources,
        &specs,
        collate,
        remove_unref.into(),
        options.preserve_unreferenced_objects,
    )?;
    let source_warnings = source_warnings || job.has_warnings();

    // The merge job has already rebuilt the target page tree and copied the
    // primary document-level structures. Represent its current output pages
    // as a local selection so the shared post-selection consumer can apply
    // rotate, cleanup, overlays, split naming, and writer options without
    // reintroducing source-document ObjectRefs.
    let selected = pages::page_refs(&mut merged)?;
    let combined_pages: Vec<CombinedPage> = selected
        .iter()
        .enumerate()
        .map(|(index, &page_ref)| {
            Ok(CombinedPage {
                source_index: 0,
                page: flpdf::SelectedPage {
                    index_1based: u32::try_from(index + 1)
                        .map_err(|_| "--pages: too many output pages")?,
                    page_ref,
                },
            })
        })
        .collect::<CliResult<Vec<_>>>()?;

    run_page_extraction_after_plan(
        merged,
        output,
        primary_input,
        repair,
        password,
        page_ops,
        overlay_specs,
        // QPDFJob has already applied the page-copy resource policy to each
        // source page. The post-copy completion boundary must not run the
        // document-wide resource pass a second time; qpdf's --pages job does
        // this pruning before its first page copy and relies on the writer for
        // final reachability cleanup.
        CliRemoveUnreferencedResources::No,
        options,
        verbose,
        standard_output,
        creates_output,
        primary_encrypted,
        primary_copy_encryption,
        source_warnings,
        false,
        combined_pages,
    )
}

#[allow(clippy::too_many_arguments)]
fn run_page_extraction_from_repeated_pdf<R: Read + Seek + 'static>(
    mut pdf: Pdf<R>,
    primary_input: &Path,
    output: &Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    options: WriterOptions,
    verbose: bool,
    standard_output: Option<PipelineWriter>,
    creates_output: bool,
    inputs: &[InputSpec],
    distinct: &[PathBuf],
) -> CliResult<()> {
    let primary_encrypted = pdf.is_encrypted();
    let primary_copy_encryption = pdf.writer_copy_encryption_source()?;
    if verbose {
        let mut message = String::from("flpdf: selecting --keep-open-files=y\n");
        for path in distinct {
            let fname = pages_progress_filename(path);
            message.push_str(&format!(
                "flpdf: {fname}: checking for shared resources\nflpdf: no shared resources found\n"
            ));
        }
        logger_info(message)?;
    }

    let ranges = inputs.iter().map(|spec| spec.range.clone()).collect();
    let plan = CombinedPlan::build_repeated(&mut pdf, ranges)?;

    if verbose {
        let mut message = String::from("flpdf: removing unreferenced pages from primary input\n");
        for spec in inputs {
            message.push_str(&format!(
                "flpdf: adding pages from {}\n",
                pages_progress_filename(&spec.path)
            ));
        }
        logger_info(message)?;
    }

    let combined_pages = match page_ops.collate.as_deref() {
        Some(raw) => {
            let n = parse_collate_n(raw)?;
            collate(&plan, n)?
        }
        None => plan.flat_pages().to_vec(),
    };

    run_page_extraction_after_plan(
        pdf,
        output,
        primary_input,
        repair,
        password,
        page_ops,
        overlay_specs,
        remove_unref,
        options,
        verbose,
        standard_output,
        creates_output,
        primary_encrypted,
        primary_copy_encryption,
        false,
        true,
        combined_pages,
    )
}

#[allow(clippy::too_many_arguments)]
fn run_page_extraction_after_plan<R: Read + Seek + 'static>(
    mut pdf: Pdf<R>,
    output: &Path,
    input_path: &Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    options: WriterOptions,
    verbose: bool,
    mut standard_output: Option<PipelineWriter>,
    creates_output: bool,
    primary_encrypted: bool,
    primary_copy_encryption: Option<CopyEncryptionSource>,
    prior_warnings: bool,
    reconstruct_labels: bool,
    combined_pages: Vec<CombinedPage>,
) -> CliResult<()> {
    let selected: Vec<ObjectRef> = combined_pages.iter().map(|cp| cp.page.page_ref).collect();
    if selected.is_empty() {
        return Err("--pages: page selection is empty".into());
    }

    // qpdf's --pages Auto mode scans the source page tree before it removes
    // the old pages. A page-local indirect /Resources that appears only once
    // does not trigger the expensive page-helper pruning route; inherited or
    // shared resources do (QPDFJob.cc:2251-2337). Preserve that decision
    // before rebuild_page_tree flattens the original inheritance structure.
    let prune_mode = if remove_unref == CliRemoveUnreferencedResources::Auto
        && !should_remove_unreferenced_resources(&mut pdf)?
    {
        CliRemoveUnreferencedResources::No
    } else {
        remove_unref
    };

    let result = rebuild_page_tree(&mut pdf, &selected)?;
    copy_duplicate_page_annotations(&mut pdf, &result)?;
    apply_rotate_specs(&mut pdf, &page_ops.rotate, &result.new_kids)?;

    if reconstruct_labels {
        let mut labels = pdf.page_labels();
        if labels.has_page_labels()? {
            let src_indices: Vec<i64> = combined_pages
                .iter()
                .map(|cp| i64::from(cp.page.index_1based) - 1)
                .collect();
            let entries = labels.labels_for_selection_with_prefix_presence(&src_indices, 0)?;
            // QPDFPageLabelDocumentHelper::getLabelForPage keeps the raw
            // `/P` handle when QPDFJob reconstructs a selected range
            // (libqpdf/QPDFPageLabelDocumentHelper.cc:37-49, 57-92).
            let folded = flpdf::merge_adjacent_ranges_with_prefix_presence(entries);
            labels.write_reconstructed_labels_with_prefix_presence(&folded)?;
        }
    }

    remap_outline_and_dests(&mut pdf, &result)?;
    let objr_obj_targets = drop_struct_elem_dangling_pg(&mut pdf, &result)?;
    drop_thread_bead_dangling_p(&mut pdf, &result)?;
    drop_objr_obj_annot_dangling_p(&mut pdf, &result, &objr_obj_targets)?;
    QPDFJob::prune_after_subset(&mut pdf, prune_mode.into())?;
    QPDFJob::prune_acroform_after_subset(&mut pdf, &result)?;

    let mut options = options;
    options.preserve_encryption = primary_encrypted && page_ops.split_pages.is_none();
    // qpdf keeps the authenticated primary input as the output/base document
    // for `--pages` (libqpdf/QPDFJob.cc:2360-2633). The multi-source job has
    // already copied selected pages into a fresh plaintext Pdf, so its writer
    // cannot rediscover the primary's encryption from the merged document.
    // Carry the authenticated donor explicitly to the final writer; split
    // chunks remain cleartext, matching qpdf's fresh chunk writers. Gate on
    // the same conditions as `PdfWriter::prepared_write_options`'s implicit
    // `can_preserve` (`writer.rs:645-652`) so an explicit source
    // doesn't bypass qpdf's QDF-is-always-cleartext contract
    // (`cell_a_encrypted_input_is_transparently_decrypted_by_qdf`) or its
    // `decode_level == DecodeLevel::None` requirement: `--stream-data`
    // `Uncompress`/`Compress` raise the writer's decode level above `None`
    // (`WriterConfiguration::set_stream_data_mode`, `writer.rs:127-142`),
    // and an explicit non-`none` `--decode-level` does the same directly,
    // both of which `can_preserve` would likewise refuse to auto-preserve
    // through.
    if page_ops.split_pages.is_none()
        && options.copy_encryption.is_none()
        && !options.qdf
        && !options.content_normalization
        && !matches!(
            options.stream_data,
            Some(StreamDataMode::Uncompress) | Some(StreamDataMode::Compress)
        )
        && !(options.decode_level_set && options.decode_level != StreamDecodeLevel::None)
    {
        options.copy_encryption = primary_copy_encryption;
    }
    // qpdf keeps a provider-backed source QPDF alive when
    // `copyForeignObject` copies a Form XObject whose data comes from a
    // `StreamDataProvider` (`libqpdf/QPDF.cc:2248-2257`). Retain the opened
    // source documents through the in-memory writer for the same reason.
    let _built_overlay_specs = if !overlay_specs.is_empty() {
        let mut built = build_overlay_specs(overlay_specs, repair, password)?;
        let initial_version = parse_pdf_version(pdf.version()).unwrap_or(PdfVersion::new(1, 0, 0));
        let mut max_version = PdfVersion::new(
            initial_version.major(),
            initial_version.minor(),
            pdf.adobe_extension_level().unwrap_or(0),
        );
        for spec in built.iter_mut() {
            let source_version =
                parse_pdf_version(spec.source.version()).unwrap_or(PdfVersion::new(1, 0, 0));
            max_version.update_if_greater(PdfVersion::new(
                source_version.major(),
                source_version.minor(),
                spec.source.adobe_extension_level().unwrap_or(0),
            ));
        }
        if let Some(ref current) = options.min_version {
            let current_version = parse_pdf_version(current).unwrap_or(PdfVersion::new(1, 0, 0));
            max_version.update_if_greater(PdfVersion::new(
                current_version.major(),
                current_version.minor(),
                options.min_extension_level.unwrap_or(0),
            ));
        }
        let (version, max_ext) = max_version.get_version();
        options.min_version = Some(version);
        options.min_extension_level = (max_ext > 0).then_some(max_ext);

        if verbose {
            let report = flpdf::overlay_verbose_report(&mut pdf, &mut built)?;
            let mut message = String::from("flpdf: processing underlay/overlay\n");
            for page in &report {
                message.push_str(&format!("  page {}\n", page.dest_page));
                for src in &page.sources {
                    let file = &overlay_specs[src.spec_index].file;
                    let kind_str = match src.kind {
                        flpdf::OverlayKind::Underlay => "underlay",
                        flpdf::OverlayKind::Overlay => "overlay",
                    };
                    message.push_str(&format!("    {} {} {}\n", file, kind_str, src.src_page));
                }
            }
            logger_info(message)?;
        }

        flpdf::apply_overlay_specs(&mut pdf, &mut built)?;
        Some(built)
    } else {
        None
    };

    let bytes = write_qpdf_to_memory(&mut pdf, &options)?;
    if let Some(raw) = page_ops.split_pages.as_deref() {
        let n = parse_split_n(raw)?;
        let (written, mut split_job) = split_rewritten_pdf(
            bytes,
            n,
            output,
            input_path,
            options.deterministic_id,
            writer_configuration(&options, false),
        )?;
        if verbose {
            for path in &written {
                logger_info(format!("flpdf: wrote file {}\n", path.display()))?;
            }
        }
        // The intermediate rewrite may already have repaired the condition
        // that produced a warning in the original source (e.g. --repair's
        // xref reconstruction) or the source document `pdf` itself, so the
        // freshly re-opened split source can look clean even though the
        // original input was not. Fold both signals into the split job
        // before completing it, matching what the non-split branch's
        // `finish_operation_warnings_with_prior` checks below.
        split_job.record_document_warnings(&pdf);
        if prior_warnings {
            split_job.record_warnings();
        }
        return finish_job_exit_status(split_job.complete(true)?);
    } else if let Some(writer) = standard_output.as_mut() {
        writer.write_all(&bytes)?;
    } else {
        std::fs::write(output, &bytes)?;
        if verbose {
            logger_info(format!("flpdf: wrote file {}\n", output.display()))?;
        }
    }
    finish_operation_warnings_with_prior(&pdf, creates_output, prior_warnings)
}

/// Apply qpdf's same-document `fixCopiedAnnotations` boundary to duplicate
/// page slots created by [`rebuild_page_tree`]. The page rebuild intentionally
/// shallow-copies only the page dictionary, so its `/Annots` carrier still
/// points at the first occurrence. qpdf replaces that carrier with a fresh
/// annotation/field-tree copy for every repeated primary page before it
/// resolves field-name collisions.
fn copy_duplicate_page_annotations<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    result: &RebuildResult,
) -> flpdf::Result<()> {
    // `result.ref_map` groups every duplicate by its *source* page ref, so
    // iterating `.values()` visits groups in BTreeMap key order rather than
    // the final output order. `PageObjectHelper::copy_annotations` appends
    // and collision-renames copied AcroForm fields immediately as each
    // duplicate is processed, so that grouping can assign `+N` suffixes out
    // of sequence relative to qpdf's own per-page copy events. Walk
    // `result.new_kids` (already in selection order) instead, and process
    // each duplicate only when its turn in the final page sequence arrives.
    let mut first_occurrence: BTreeMap<ObjectRef, ObjectRef> = BTreeMap::new();
    for page_refs in result.ref_map.values() {
        let Some(&first_page) = page_refs.first() else {
            continue;
        };
        for &duplicate_page in page_refs.iter().skip(1) {
            first_occurrence.insert(duplicate_page, first_page);
        }
    }
    for &new_page in &result.new_kids {
        let Some(&source_page_ref) = first_occurrence.get(&new_page) else {
            continue;
        };
        let source_page = pdf.get_object_handle(source_page_ref);
        let destination_page = pdf.get_object_handle(new_page);
        destination_page.remove_key(b"/Annots");
        pdf.mark_object_handle_dirty(&destination_page)?;
        PageObjectHelper::new(new_page, pdf)
            .copy_annotations(source_page, flpdf::Matrix::default())?;
    }
    Ok(())
}

/// Apply each `--rotate` spec (in order) to `target_pages`, resolving each
/// spec's page-range against the number of target pages.
fn apply_rotate_specs<R: std::io::Read + std::io::Seek>(
    pdf: &mut Pdf<R>,
    rotate_args: &[String],
    target_pages: &[ObjectRef],
) -> CliResult<()> {
    if rotate_args.is_empty() {
        return Ok(());
    }
    let total = u32::try_from(target_pages.len())
        .map_err(|_| "too many pages to apply --rotate".to_string())?;
    for raw in rotate_args {
        let spec =
            RotateSpec::parse(raw).map_err(|e| format!("--rotate: invalid spec {raw:?}: {e}"))?;
        let indices = spec
            .range
            .resolve(total)
            .map_err(|e| format!("--rotate: page range out of bounds in {raw:?}: {e}"))?;
        let pages: Vec<ObjectRef> = indices
            .iter()
            .filter_map(|&i| target_pages.get((i - 1) as usize).copied())
            .collect();
        apply_rotate_to_pages(pdf, &pages, &spec.op)?;
    }
    Ok(())
}

/// Parse `--split-pages[=n]` (default 1; qpdf-compatible).
fn parse_split_n(raw: &str) -> CliResult<usize> {
    let n: usize = raw
        .parse()
        .map_err(|_| format!("--split-pages: expected a positive integer, got {raw:?}"))?;
    if n == 0 {
        return Err("--split-pages: group size must be >= 1".into());
    }
    Ok(n)
}

/// Run qpdf's fresh-document split job on a rewritten in-memory source.
///
/// The page-operation pipeline has already applied its transforms to `bytes`;
/// the job-level split owns the subsequent per-chunk page copy, naming,
/// annotation, label, and output-file lifecycle. `input_path` remains the
/// original command input so the qpdf same-file guard can reject a generated
/// chunk that would truncate it.
fn split_rewritten_pdf(
    bytes: Vec<u8>,
    chunk_size: usize,
    output: &Path,
    input_path: &Path,
    deterministic_id: bool,
    writer_configuration: WriterConfiguration,
) -> CliResult<(Vec<PathBuf>, QPDFJob)> {
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let input_name = input_path.to_string_lossy().into_owned();
    let mut pdf = job.open(Cursor::new(bytes), input_name, PdfOpenOptions::default())?;
    let options = SplitPageOptions::new(chunk_size, output)
        .with_input_path(input_path)
        .with_deterministic_id(deterministic_id)
        .with_writer_configuration(writer_configuration);
    let written = job.split_pages(&mut pdf, options)?;
    Ok((written, job))
}

/// Apply `--rotate` / `--split-pages` to a plain (no `--pages`) rewrite.
///
/// qpdf accepts these without `--pages` (exit 0). `--rotate` mutates the
/// source document's pages directly (no page-tree rebuild); `--split-pages`
/// chunks the rewritten output. `--collate` without `--pages` is a no-op,
/// matching qpdf.
#[allow(clippy::too_many_arguments)]
fn run_rewrite_with_page_ops(
    input: &std::path::Path,
    output: &std::path::Path,
    repair: bool,
    password: &PasswordArgs,
    json_input: bool,
    update_from_json: Option<&Path>,
    page_ops: &PageOpArgs,
    options: WriterOptions,
    verbose: bool,
) -> CliResult<()> {
    let opened = open_job_pdf(input, repair, password, json_input, update_from_json, false)?;
    match opened {
        JobPdf::File(pdf) => {
            run_rewrite_with_page_ops_opened(pdf, input, output, page_ops, options, verbose)
        }
        JobPdf::Json(pdf) => {
            run_rewrite_with_page_ops_opened(pdf, input, output, page_ops, options, verbose)
        }
    }
}

fn run_rewrite_with_page_ops_opened<R: Read + Seek + 'static>(
    mut pdf: Pdf<R>,
    input: &Path,
    output: &std::path::Path,
    page_ops: &PageOpArgs,
    options: WriterOptions,
    verbose: bool,
) -> CliResult<()> {
    let mut standard_output = prepare_page_operation_standard_output(output, page_ops)?;
    let creates_output = standard_output.is_none();
    if page_ops.empty {
        return Err(
            "--empty is accepted by qpdf but not implemented in flpdf at this layer \
             (tracked separately); rerun without --empty"
                .into(),
        );
    }
    if !page_ops.rotate.is_empty() {
        let page_refs = pages::page_refs(&mut pdf)?;
        apply_rotate_specs(&mut pdf, &page_ops.rotate, &page_refs)?;
    }

    // Page operations emit a fresh document and preserve encryption only when
    // the primary input itself was encrypted, matching qpdf's page copier.
    // `--split-pages` is the exception: qpdf's doSplitPages path makes a fresh
    // empty output document per chunk, so its intermediate and final chunks
    // are cleartext unless explicit encryption options are configured. Keep
    // the memory intermediate decryptable before split_pages re-opens it.
    let mut options = options;
    options.preserve_encryption = page_ops.split_pages.is_none() && pdf.is_encrypted();
    let bytes = write_qpdf_to_memory(&mut pdf, &options)?;

    if let Some(raw) = page_ops.split_pages.as_deref() {
        let n = parse_split_n(raw)?;
        let (written, mut split_job) = split_rewritten_pdf(
            bytes,
            n,
            output,
            input,
            options.deterministic_id,
            writer_configuration(&options, false),
        )?;
        if verbose {
            for path in &written {
                // cov:ignore-start: exercised by verbose split-pages subprocess integration tests
                logger_info(format!("flpdf: wrote file {}\n", path.display()))?;
                // cov:ignore-end
            }
        }
        // The intermediate rewrite may already have repaired the condition
        // that produced a warning on the original `pdf` (e.g. --repair's
        // xref reconstruction), so the freshly re-opened split source can
        // look clean even though the original input was not.
        split_job.record_document_warnings(&pdf);
        return finish_job_exit_status(split_job.complete(true)?);
    } else if let Some(writer) = standard_output.as_mut() {
        // cov:ignore-start: exercised by binary_rotate_dash subprocess integration test
        writer.write_all(&bytes)?;
        // cov:ignore-end
    } else {
        std::fs::write(output, &bytes)?;
        if verbose {
            logger_info(format!("flpdf: wrote file {}\n", output.display()))?;
        }
    }
    finish_operation_warnings(&pdf, creates_output)
}

/// True when any page-operation flag that requires the page-op code paths is
/// set. `--collate` alone (no `--pages`) is a documented no-op and does NOT
/// trigger this on its own.
fn page_ops_active(p: &PageOpArgs) -> bool {
    !p.pages.is_empty() || !p.rotate.is_empty() || p.split_pages.is_some() || p.empty
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ContentNormalizationWarning {
    parsed_offset: Option<u64>,
    last_token_was_bad: bool,
}

/// Normalize all page content streams in an in-memory PDF graph.
///
/// Shared by the plain and linearized rewrite paths so both use the same page
/// traversal, indirect `/Contents` handling, alias deduplication, and warning
/// order.
fn normalize_page_contents<R: Read + Seek>(
    pdf: &mut Pdf<R>,
) -> CliResult<Vec<ContentNormalizationWarning>> {
    let mut warnings = Vec::new();
    let mut seen = HashSet::new();
    let page_refs = pages::page_refs(pdf)?;
    for page_ref in page_refs {
        warnings.extend(apply_normalize_content(pdf, page_ref, &mut seen)?);
    }
    Ok(warnings)
}

/// Normalize the content stream(s) for a single page.
///
/// Reads each `/Contents` stream referenced by the page, applies
/// [`normalize_content_stream`] to the decoded bytes, and writes the result
/// back into the in-memory [`Pdf`] model through live `ObjectHandle` mutation.
///
/// The `/Length` entry in each stream's dictionary is updated to the new
/// (normalized) byte count. No filter is applied here — the canonical writer
/// emits the already-normalized bytes through qpdf's normalization branch,
/// which takes precedence over ordinary stream compression.
fn apply_normalize_content<R: std::io::Read + std::io::Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
    seen: &mut HashSet<ObjectRef>,
) -> CliResult<Vec<ContentNormalizationWarning>> {
    let mut warnings = Vec::new();
    let page = pdf.get_object_handle(page_ref);
    pdf.resolve(&page)?;
    let contents = page.get_key(b"/Contents");
    let contents_ref = contents.object_ref();
    pdf.resolve(&contents)?;

    let mut streams = Vec::new();
    if contents.as_stream_dict().is_some() {
        if let Some(stream_ref) = contents_ref {
            streams.push((stream_ref, contents));
        }
    } else if let Some(items) = contents.as_array() {
        for item in items {
            let item_ref = item.object_ref();
            pdf.resolve(&item)?;
            if item.as_stream_dict().is_some() {
                if let Some(item_ref) = item_ref {
                    streams.push((item_ref, item));
                }
            }
        }
    }

    for (stream_ref, stream) in streams {
        if let Some(last_bad) = normalize_and_store_stream_handle(pdf, stream_ref, stream, seen)? {
            warnings.push(last_bad);
        }
    }
    Ok(warnings)
}

/// Normalize the decoded bytes of the indirect stream at `stream_ref` through
/// the live ObjectHandle stream pipeline and mutate that same qpdf-style
/// stream in place. Keeping the stream handle live is important for malformed
/// content holders: the writer must observe one canonical resolution and not
/// parse the legacy raw Object a second time.
fn normalize_and_store_stream_handle<R: std::io::Read + std::io::Seek>(
    pdf: &mut Pdf<R>,
    stream_ref: ObjectRef,
    stream: ObjectHandle,
    seen: &mut HashSet<ObjectRef>,
) -> CliResult<Option<ContentNormalizationWarning>> {
    if !seen.insert(stream_ref) {
        return Ok(None);
    }

    // Decode the stored bytes through qpdf's canonical stream pipeline. This
    // resolves indirect filters/parameters and preserves source recovery
    // diagnostics on the owning document.
    let decoded = stream.get_stream_data(StreamDecodeLevel::All)?;

    // Normalize the decoded content stream bytes.
    let normalized = normalize_content_stream(decoded.as_ref());
    let warning = normalized
        .any_bad_tokens()
        .then(|| ContentNormalizationWarning {
            parsed_offset: u64::try_from(stream.get_parsed_offset()).ok(),
            last_token_was_bad: normalized.last_token_was_bad(),
        });
    let normalized = normalized.into_bytes();

    // Remove filter / encode-form keys and install the fresh direct length;
    // the normalized payload is raw. This is qpdf's in-place stream mutation
    // boundary, so mark the canonical indirect owner dirty for the writer.
    let normalized = std::rc::Rc::new(normalized);
    stream.replace_stream_data(
        std::rc::Rc::clone(&normalized),
        Some(ObjectHandle::null()),
        Some(ObjectHandle::null()),
    );
    if let Some(dict) = stream.as_stream_dict() {
        dict.replace_key(
            b"/Length",
            ObjectHandle::integer(i64::try_from(normalized.len())?),
        )?;
    }
    stream.mark_content_normalization_applied();
    pdf.mark_object_handle_dirty(&stream)?;
    Ok(warning)
}

fn run_qdf(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    preserve_unreferenced: bool,
) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let output = output.ok_or("missing output file")?;
    let mut standard_output = prepare_pdf_standard_output(&output)?;
    let creates_output = standard_output.is_none();
    let mut pdf = open_pdf(&input, repair, password)?;

    // The `qdf` subcommand is the canonical PdfWriter QDF mode.
    let options = WriterOptions {
        qdf: true,
        preserve_unreferenced_objects: preserve_unreferenced,
        ..WriterOptions::default()
    };
    write_with_pdf_writer(
        &mut pdf,
        &output,
        &mut standard_output,
        &options,
        false,
        None,
    )?;
    finish_operation_warnings(&pdf, creates_output)
}

/// `qdf-fix` (qpdf `fix-qdf` equivalent): repair stream `/Length`, xref
/// offsets, `/Size` and `startxref` in a hand-edited QDF file.
///
/// fix_qdf is byte-level: it must operate on the raw file bytes and must
/// NOT reparse/reformat the document, so this reads with `std::fs::read`
/// (not `open_pdf`) and writes the repaired bytes verbatim. No password /
/// no `Pdf` open.
fn run_qdf_fix(input: &std::path::Path, output: &std::path::Path) -> CliResult<()> {
    let bytes = std::fs::read(input)?;
    let fixed = fix_qdf(&bytes)?;
    std::fs::write(output, fixed)?;
    Ok(())
}

fn reject_same_json_output(input: &Path, output: &Path) -> CliResult<()> {
    reject_same_file(
        input,
        output,
        "input file and output file are the same; choose a different --json-output path",
        "--json-output",
    )
}

/// Reject a job whose main input and output resolve to the same file
/// (qpdf's `QUtil::same_file` guard in `checkConfiguration()`,
/// `QPDFJob.cc:627-630`). qpdf's own message references `--replace-input`,
/// a dedicated escape hatch flpdf does not implement; this instead follows
/// the existing `--json-output` guard's wording (a different output path is
/// the only way out today), the same way that guard already departs from
/// qpdf's exact text for the same reason.
///
/// This is a job-wide guard, not one scoped to `--json-input`/
/// `--update-from-json`: qpdf's check is unconditional, and an ordinary
/// `flpdf in.pdf in.pdf` rewrite is just as destructive (the canonical
/// writer reads from `input` while truncating `output`) as the JSON case
/// that surfaced the gap.
fn reject_same_job_output(input: &Path, output: &Path) -> CliResult<()> {
    reject_same_file(
        input,
        output,
        "input file and output file are the same; use a different output path",
        "output",
    )
}

fn reject_same_file(
    input: &Path,
    output: &Path,
    same_file_message: &str,
    inspect_label: &str,
) -> CliResult<()> {
    match std::fs::metadata(output) {
        Ok(_) => {
            // This is only a non-destructive hint: if inspecting the input
            // fails, the real input open below owns its path-specific error.
            // Output metadata failures remain fail-closed in the next arm.
            if qpdf_same_file(input, output) {
                return Err(same_file_message.into());
            }
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(format!(
                "unable to inspect {inspect_label} file {}: {error}",
                output.display()
            )
            .into())
        }
    }
    Ok(())
}

fn json_input_open_error(input: &Path, error: std::io::Error) -> Box<dyn std::error::Error> {
    let rendered = error.to_string();
    let message = error
        .raw_os_error()
        .and_then(|code| rendered.strip_suffix(&format!(" (os error {code})")))
        .unwrap_or(&rendered);
    format!("open {}: {message}", input.display()).into()
}

fn qpdf_json_input_open_error(input: &Path, error: std::io::Error) -> Box<dyn std::error::Error> {
    let rendered = error.to_string();
    let message = if error.kind() == std::io::ErrorKind::NotFound {
        // qpdf uses its portable POSIX wording for a missing JSON input on
        // every host; Rust exposes the native Windows wording instead.
        "No such file or directory"
    } else {
        error
            .raw_os_error()
            .and_then(|code| rendered.strip_suffix(&format!(" (os error {code})")))
            .unwrap_or(&rendered)
    };
    format!("open {}: {message}", input.display()).into()
}

fn open_verified_json_output(input: &File, output: &Path) -> CliResult<File> {
    let mut output_file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(false)
        .open(output)?;
    let input_handle = same_file::Handle::from_file(input.try_clone()?)?;
    let output_handle = same_file::Handle::from_file(output_file.try_clone()?)?;
    if input_handle == output_handle {
        return Err(
            "input file and output file are the same; choose a different --json-output path".into(),
        );
    }
    if output_file.metadata()?.file_type().is_file() {
        output_file.set_len(0)?;
        output_file.seek(SeekFrom::Start(0))?;
    }
    Ok(output_file)
}

fn run_dump_object(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    object_ref: &str,
) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let object_ref = ObjectRef::parse(object_ref)?;

    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    finish_job_exit_status(job.dump_object(&mut pdf, object_ref)?)
}

#[derive(Debug, Clone, Copy)]
enum ShowObjectSelector {
    Trailer,
    Object(ObjectRef),
    Null,
    NoObject,
}

/// Parse qpdf's `--show-object` selector without changing the shared
/// `ObjectRef::parse` syntax used by the legacy `dump-object` command.
fn parse_show_object_selector(value: &str) -> CliResult<ShowObjectSelector> {
    if value == "trailer" {
        return Ok(ShowObjectSelector::Trailer);
    }

    let (number, generation) = value.split_once(',').unwrap_or((value, "0"));
    let number = qpdf_selector_integer(number)?;
    let generation = if generation.is_empty() {
        0
    } else {
        qpdf_selector_integer(generation)?
    };
    if number <= 0 {
        return Ok(ShowObjectSelector::NoObject);
    }
    if !(0..=i32::from(u16::MAX)).contains(&generation) {
        return Ok(ShowObjectSelector::Null);
    }
    Ok(ShowObjectSelector::Object(ObjectRef::new(
        u32::try_from(number).expect("positive i32 fits u32"),
        u16::try_from(generation).expect("validated u16 generation"),
    )))
}

/// qpdf's `QUtil::string_to_int` uses `strtoll`: it accepts a signed decimal
/// prefix and returns zero when no digits are present. `--show-object` treats
/// object number zero as a no-output selector, so retain that observable
/// leniency instead of routing this option through the stricter shared parser.
fn qpdf_selector_integer(value: &str) -> CliResult<i32> {
    let original = value;
    let value = value.trim_start_matches(|character| {
        matches!(
            character,
            ' ' | '\n' | '\r' | '\t' | '\u{000c}' | '\u{000b}'
        )
    });
    let digits_start = usize::from(matches!(value.as_bytes().first(), Some(b'+') | Some(b'-')));
    let digits_end = digits_start
        + value[digits_start..]
            .bytes()
            .take_while(u8::is_ascii_digit)
            .count();
    if digits_end == digits_start {
        return Ok(0);
    }
    let prefix = &value[..digits_end];
    let parsed = prefix.parse::<i128>().map_err(|_| {
        UsageError::new(format!(
            "overflow/underflow converting {original} to 64-bit integer"
        ))
    })?;
    if !(i128::from(i64::MIN)..=i128::from(i64::MAX)).contains(&parsed) {
        return Err(UsageError::new(format!(
            "overflow/underflow converting {original} to 64-bit integer"
        ))
        .into());
    }
    let parsed = parsed as i64;
    Ok(i32::try_from(parsed).map_err(|_| {
        UsageError::new(format!(
            "integer out of range converting {parsed} from a 8-byte signed type to a 4-byte signed type"
        ))
    })?)
}

/// Show one object through qpdf's canonical object/stream inspection split.
fn run_show_object(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    selector: &str,
    raw_stream_data: bool,
    filtered_stream_data: bool,
) -> CliResult<()> {
    // qpdf's Config::showObject callback parses the selector during argv
    // parsing, before QPDFJob::run() ever opens the input file, so a usage
    // error in the selector must surface even when no input file is given.
    let selector = parse_show_object_selector(selector)?;
    let input = input.ok_or("missing input file")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let object = match selector {
        ShowObjectSelector::Trailer => pdf.trailer(),
        ShowObjectSelector::Object(object_ref) => pdf.get_object_handle(object_ref),
        ShowObjectSelector::NoObject => {
            return finish_job_exit_status(
                job.inspect(&mut pdf, |_pdf| Ok::<(), flpdf::Error>(()))?,
            );
        }
        ShowObjectSelector::Null => {
            logger_info(b"null\n")?;
            return finish_job_exit_status(
                job.inspect(&mut pdf, |_pdf| Ok::<(), flpdf::Error>(()))?,
            );
        }
    };
    finish_job_exit_status(job.show_object(
        &mut pdf,
        object,
        raw_stream_data,
        filtered_stream_data,
    )?)
}

fn run_show_stream(cmd: ShowStreamCommand) -> CliResult<()> {
    let object_ref = ObjectRef::parse(&cmd.object_ref)?;
    let mut pdf = open_pdf(&cmd.input, cmd.repair, &cmd.password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    finish_job_exit_status(job.show_stream(&mut pdf, object_ref, cmd.raw_stream_data)?)
}

fn run_show_npages(input: Option<PathBuf>, repair: bool, password: &PasswordArgs) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    finish_job_exit_status(job.show_npages(&mut pdf)?)
}

fn run_show_pages(input: Option<PathBuf>, repair: bool, password: &PasswordArgs) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    finish_job_exit_status(job.show_pages(&mut pdf)?)
}

fn run_show_xref(input: Option<PathBuf>, repair: bool, password: &PasswordArgs) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    finish_job_exit_status(job.show_xref(&mut pdf)?)
}

fn run_show_linearization(input: Option<PathBuf>) -> CliResult<()> {
    let input = input.ok_or("missing input file")?;
    match show_linearization_path_with_warnings(&input) {
        Ok(result) => {
            for warning in &result.warnings {
                logger_warn(format!("WARNING: {}: {warning}\n", input.display()))?;
            }
            // `result.dump` already ends with a trailing newline (the hint-table
            // dump, or qpdf's "<name> is not linearized" line). qpdf prints
            // both to stdout and exits 0; use print! to avoid a second LF.
            logger_info(result.dump)?;
            if result.warnings.is_empty() {
                Ok(())
            } else {
                finish_warning_state(true, false)
            }
        }
        Err(ShowLinearizationError::Malformed { message }) => {
            // cov:ignore-start: none of show.rs's public entry points return
            // this variant any more (see ShowLinearizationError's doc) --
            // every linearization-data decode failure qpdf's
            // showLinearizationData would catch is now surfaced as an `Ok`
            // with an empty dump and one warning, matching qpdf's own single
            // try/catch around readLinearizationData. Retained as a
            // defensive arm since the type still has this variant.
            logger_error(format!("flpdf: malformed linearization data: {message}\n"))?;
            std::process::exit(ExitCode::Errors.as_i32());
            // cov:ignore-end
        }
        Err(ShowLinearizationError::Io(e)) => Err(e.to_string().into()),
    }
}

// ---------------------------------------------------------------------------
// Encryption inspection subcommands (flpdf-9hc.3.17)
//
// qpdf exit-code semantics for these subcommands, from
// qpdf/include/qpdf/Constants.h `enum qpdf_exit_code_e`:
//   qpdf_exit_success           = 0
//   qpdf_exit_error             = 2
//   qpdf_exit_is_not_encrypted  = 2   (--is-encrypted / --requires-password)
//   qpdf_exit_correct_password  = 3   (--requires-password)
// and the qpdf manual "Exit Status" / option tables:
//   https://qpdf.readthedocs.io/en/stable/cli.html
//
// The layer-1 `ExitCode` enum is generic (Ok=0, Errors=2, Warnings=3); these
// subcommands reuse the numeric values 2 and 3 with subcommand-specific
// MEANINGS (not "errors"/"warnings"), documented at each construction site.
// ---------------------------------------------------------------------------

/// Outcome of attempting to open a possibly-encrypted document for an
/// inspection subcommand, where (unlike normal processing) a failed
/// password attempt is informative rather than fatal.
enum EncryptionProbe {
    /// Opened successfully. The bool is `Pdf::is_encrypted()`.
    Opened { encrypted: bool },
    /// The file is encrypted but the supplied/empty password did not
    /// authenticate (`BadPassword`). qpdf can still report "encrypted" /
    /// "password required" without authenticating, so this is a normal
    /// classification here, not an error.
    EncryptedAuthFailed,
}

/// Open `input` for a read-only encryption inspection (`is-encrypted` /
/// `requires-password`), treating a wrong/empty password (`BadPassword`) as
/// "the file is encrypted but we could not authenticate" rather than a hard
/// error. This mirrors qpdf's ability to answer these queries for
/// password-protected files without the password.
///
/// qpdf applies its weak-crypto refusal to write/transform operations, not to
/// these read-only inspections. Authentication still runs first, so a wrong
/// password yields `BadPassword` exactly as before.
fn probe_encryption(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<EncryptionProbe> {
    let file = File::open(input)?;
    let mut options = pdf_open_options(repair, password)?;
    configure_document_logger(&mut options, input);
    match Pdf::open_with_options(BufReader::new(file), options) {
        Ok(mut pdf) => {
            pdf.root_handle()
                .map_err(|error| error_with_file(input, actionable_password_error(error)))?;
            Ok(EncryptionProbe::Opened {
                encrypted: pdf.is_encrypted(),
            })
        }
        // A wrong/empty password: the document is definitely encrypted, we
        // just have not authenticated it. qpdf treats this as "encrypted,
        // password required".
        Err(error) if is_bad_password_error(&error) => Ok(EncryptionProbe::EncryptedAuthFailed),
        Err(other) => Err(other.into()),
    }
}

fn is_bad_password_error(error: &flpdf::Error) -> bool {
    let source = error.open_failure().map_or(error, |(source, _)| source);
    matches!(
        source,
        flpdf::Error::Encrypted(flpdf::EncryptedError::BadPassword)
    )
}

/// `is-encrypted FILE`: exit 0 if encrypted, exit 2 if not.
///
/// qpdf `--is-encrypted` (qpdf manual): exit 0 = encrypted, exit 2 = not
/// encrypted (`qpdf_exit_is_not_encrypted = 2`). No required stdout.
fn run_is_encrypted(input: &PathBuf, repair: bool, recovery: RecoveryArgs) -> CliResult<()> {
    // No password is taken/used: qpdf detects encryption structurally
    // (presence of /Encrypt) without authenticating, so we deliberately
    // probe with an empty password and accept the auth-failed outcome.
    let password = PasswordArgs {
        recovery,
        ..PasswordArgs::default()
    };
    let encrypted = match probe_encryption(input, repair, &password)? {
        EncryptionProbe::Opened { encrypted } => encrypted,
        EncryptionProbe::EncryptedAuthFailed => true,
    };
    if encrypted {
        Ok(()) // exit 0 — file is encrypted.
    } else {
        // Exit 2 — NOT an error here: qpdf_exit_is_not_encrypted = 2 means
        // "file is not encrypted" for --is-encrypted specifically.
        Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        }))
    }
}

/// `requires-password FILE [--password ...]`: qpdf `--requires-password`.
///
/// Exit codes (qpdf manual + Constants.h):
///   2 = not encrypted              (qpdf_exit_is_not_encrypted)
///   3 = encrypted, supplied/empty password opens it
///       (qpdf_exit_correct_password — no further password required)
///   0 = encrypted, a password other than the one supplied is required
///
/// Weak-crypto (RC4 / R=5) files are answered purely on the password, matching
/// qpdf: a correct password yields 3 and a wrong/absent one yields 0, with no
/// `--allow-weak-crypto` opt-in required (see `probe_encryption`).
fn run_requires_password(input: &PathBuf, repair: bool, password: &PasswordArgs) -> CliResult<()> {
    match probe_encryption(input, repair, password)? {
        EncryptionProbe::Opened { encrypted: false } => {
            // Exit 2 — qpdf_exit_is_not_encrypted: file is not encrypted.
            Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
        EncryptionProbe::Opened { encrypted: true } => {
            // Exit 3 — qpdf_exit_correct_password: encrypted, but the
            // supplied/empty password opened it, so no other password is
            // required. Reuses ExitCode::Warnings's numeric 3 with this
            // subcommand-specific meaning.
            Err(Box::new(CliExitError {
                code: ExitCode::Warnings,
                message: String::new(),
            }))
        }
        EncryptionProbe::EncryptedAuthFailed => {
            // Exit 0 — encrypted and a password OTHER than the one supplied
            // is required (qpdf manual: "a password, other than as
            // supplied, is required").
            Ok(())
        }
    }
}

/// `show-encryption-key FILE [--password ...]`: qpdf `--show-encryption-key`.
///
/// Authenticate, then print the derived file encryption key as lowercase
/// hex. Not encrypted or wrong password → error (exit 2), matching qpdf
/// (which errors when it cannot derive the key). Weak-crypto (RC4 / R=5) files
/// are inspectable with the correct password and no `--allow-weak-crypto`,
/// matching qpdf's read-only treatment (see [`open_pdf_for_inspection`]).
fn run_show_encryption_key(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<()> {
    let pdf = open_pdf_for_inspection(input, repair, password)?;
    match pdf.encryption_file_key() {
        Some(key) => {
            logger_info(format!("{}\n", hex_lower(&key)))?;
            finish_operation_warnings(&pdf, false)
        }
        None if pdf.is_encrypted() => Err("encrypted PDF: incorrect password".into()),
        None => Err("file is not encrypted; no encryption key to show".into()),
    }
}

/// `show-encryption FILE [--password ...]`: qpdf `--show-encryption`.
///
/// The report is the qpdf `QPDFJob::showEncryption` format. Weak-crypto
/// (RC4 / R=5) files are inspectable with the correct password and no
/// `--allow-weak-crypto`, matching qpdf's read-only treatment.
///
/// Opens through its own job (rather than the shared
/// [`open_pdf_for_inspection`] helper) so `--no-warn` reaches
/// `QPDFJob::set_suppress_warnings`, matching `run_check`/
/// `run_check_linearization`'s pattern.
fn run_show_encryption(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
) -> CliResult<()> {
    let file = File::open(input).map_err(|error| error_with_file(input, error.into()))?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(no_warn);
    let mut options = pdf_open_options(repair, password)?;
    // qpdf's `--no-warn` drops open-time repair diagnostics entirely for
    // `--show-encryption` (no deferred replay, unlike `--check`'s report
    // body); verified against `qpdf --no-warn --show-encryption` on a
    // damaged fixture, which prints no WARNING lines at all. Without this,
    // `job.set_suppress_warnings(no_warn)` above only gates the trailing
    // "operation succeeded with warnings" summary while the live
    // `WARNING: ...` lines from `Pdf::open_for_encryption_inspection` still
    // print unconditionally.
    options.suppress_warnings = no_warn;
    let mut pdf = job
        .open_for_encryption_inspection(BufReader::new(file), input.display().to_string(), options)
        .map_err(|error| error_with_file(input, actionable_password_error(error)))?;
    finish_show_encryption(&mut job, &mut pdf, password.password_is_hex_key)
}

/// Emit the qpdf-verbatim encryption report through the job-owned renderer,
/// then complete the same warning/exit-status boundary as other inspections.
/// The document may have come from either a file-backed input or a JSON update,
/// so the already-open document must be passed through unchanged.
fn finish_show_encryption<R: Read + Seek>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
    password_is_hex_key: bool,
) -> CliResult<()> {
    job.show_encryption(pdf, password_is_hex_key)?;
    job.record_document_warnings(pdf);
    finish_job_exit_status(job.complete(false)?)
}

/// Lowercase hex encoding (qpdf `--show-encryption-key` format).
fn hex_lower(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push_str(&format!("{b:02x}"));
    }
    out
}

/// Main-input variants accepted by the qpdf-shaped job boundary.
///
/// The JSON importer owns a `Pdf<Cursor<Vec<u8>>>` because its rootless seed
/// is an in-memory PDF. Ordinary files keep the existing buffered-file reader.
/// The enum is intentionally confined to this CLI boundary; every downstream
/// consumer still receives its normal generic `Pdf<R>` and therefore uses the
/// canonical resolver/object-handle route.
enum JobPdf {
    File(Pdf<BufReader<File>>),
    Json(Pdf<Cursor<Vec<u8>>>),
}

struct JsonJobRuntime<'a> {
    input_identity: &'a File,
    standard_output: &'a mut Option<PipelineWriter>,
    job: &'a mut QPDFJob,
}

fn apply_json_update<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    update_from_json: Option<&Path>,
) -> CliResult<()> {
    if let Some(path) = update_from_json {
        let source = File::open(path).map_err(|error| qpdf_json_input_open_error(path, error))?;
        pdf.update_from_json(source, path.display().to_string())
            .map_err(|error| Box::new(error) as Box<dyn std::error::Error>)?;
    }
    Ok(())
}

fn apply_json_update_with_job<R: Read + Seek + 'static>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
    update_from_json: Option<&Path>,
) -> CliResult<()> {
    if let Some(path) = update_from_json {
        let source = File::open(path).map_err(|error| qpdf_json_input_open_error(path, error))?;
        job.update_from_json(pdf, source, path.display().to_string())?;
    }
    Ok(())
}

/// Open the main qpdf job input and apply `--update-from-json` at the same
/// point qpdf's `QPDFJob::createQPDF` does: immediately after input creation,
/// before page specifications, rotations, overlays, or serialization.
/// `check_inspection` applies `run_check`'s warning-aggregation policy (see
/// [`open_pdf_for_check_inspection`]) to the
/// non-`--json-input` (`--update-from-json` only) branch. It has no effect
/// on the `--json-input` branch: [`Pdf::create_from_json`] always seeds from
/// the fixed, never-encrypted rootless bootstrap document, so this policy
/// only matters for a real encrypted PDF opened through
/// `--update-from-json`.
fn open_job_pdf(
    input: &Path,
    repair: bool,
    password: &PasswordArgs,
    json_input: bool,
    update_from_json: Option<&Path>,
    check_inspection: bool,
) -> CliResult<JobPdf> {
    if json_input {
        Ok(JobPdf::Json(open_json_pdf(input, update_from_json)?))
    } else {
        let mut pdf = if check_inspection {
            open_pdf_for_check_inspection(&input.to_path_buf(), repair, password)?
        } else {
            open_pdf(&input.to_path_buf(), repair, password)?
        };
        apply_json_update(&mut pdf, update_from_json)?;
        Ok(JobPdf::File(pdf))
    }
}

fn open_json_pdf(input: &Path, update_from_json: Option<&Path>) -> CliResult<Pdf<Cursor<Vec<u8>>>> {
    let source = File::open(input).map_err(|error| qpdf_json_input_open_error(input, error))?;
    let mut pdf = Pdf::create_from_json(source, input.display().to_string())
        .map_err(|error| Box::new(error) as Box<dyn std::error::Error>)?;
    apply_json_update(&mut pdf, update_from_json)?;
    Ok(pdf)
}

fn open_pdf(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Pdf<BufReader<File>>> {
    open_pdf_impl(input, repair, password, false)
}

fn open_pdf_from_file(
    input: &Path,
    file: File,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Pdf<BufReader<File>>> {
    open_pdf_file_impl(input, file, repair, password, false, false)
}

/// Open for the read-only encryption inspections (`show-encryption`,
/// `show-encryption-key`).
///
/// qpdf treats these as read-only inspections rather than a write policy: it
/// derives and prints the key / encryption block for a weak file with the
/// correct password and emits no weak-crypto warning (verified qpdf 11.9.0).
/// A wrong password retains qpdf's parsed encryption state so show-encryption
/// can report it rather than failing before the report.
fn open_pdf_for_inspection(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Pdf<BufReader<File>>> {
    let file = File::open(input).map_err(|error| error_with_file(input, error.into()))?;
    open_pdf_file_impl(input, file, repair, password, false, true)
}

/// Open for `--update-from-json --check`'s generic job-inspection route.
///
/// Mirrors `run_check`'s own inspection policy, plus `suppress_warnings` so
/// open/update-time repair diagnostics are collected
/// rather than delivered live, since the qpdf-shaped job check re-emits the
/// same diagnostics from the document after its check banner -- without
/// this, a `--repair`-triggered warning prints twice). `--show-npages`/
/// `--show-pages` do not need either policy: like their non-JSON siblings
/// `run_show_npages`/`run_show_pages`, they use the plain [`open_pdf`]
/// path via [`open_job_pdf`]'s `check_inspection` parameter.
fn open_pdf_for_check_inspection(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Pdf<BufReader<File>>> {
    open_pdf_impl(input, repair, password, true)
}

fn open_pdf_impl(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
    suppress_warnings: bool,
) -> CliResult<Pdf<BufReader<File>>> {
    let file = File::open(input).map_err(|error| error_with_file(input, error.into()))?;
    open_pdf_file_impl(input, file, repair, password, suppress_warnings, false)
}

fn open_pdf_file_impl(
    input: &Path,
    file: File,
    repair: bool,
    password: &PasswordArgs,
    suppress_warnings: bool,
    encryption_inspection: bool,
) -> CliResult<Pdf<BufReader<File>>> {
    let mut options = pdf_open_options(repair, password)?;
    if suppress_warnings {
        options.suppress_warnings = true;
    }
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let pdf = if encryption_inspection {
        job.open_for_encryption_inspection(
            BufReader::new(file),
            input.display().to_string(),
            options,
        )
    } else {
        job.open(BufReader::new(file), input.display().to_string(), options)
    }
    .map_err(|error| error_with_file(input, actionable_password_error(error)))?;
    Ok(pdf)
}

fn pdf_open_options(repair: bool, password: &PasswordArgs) -> CliResult<PdfOpenOptions> {
    let password_bytes = if let Some(password) = &password.password {
        password.as_bytes().to_vec()
    } else if let Some(path) = &password.password_file {
        let mut bytes = std::fs::read(path)?;
        if bytes.ends_with(b"\r\n") {
            bytes.truncate(bytes.len() - 2);
        } else if bytes.ends_with(b"\n") {
            bytes.truncate(bytes.len() - 1);
        }
        bytes
    } else {
        Vec::new()
    };

    Ok(pdf_open_options_with_password_bytes(
        repair,
        password,
        password_bytes,
    ))
}

fn pdf_open_options_with_password_bytes(
    repair: bool,
    password: &PasswordArgs,
    password_bytes: Vec<u8>,
) -> PdfOpenOptions {
    let recovery = password.recovery;
    PdfOpenOptions {
        // qpdf's recovery permission is enabled on the document by default;
        // --suppress-recovery is the explicit opt-out.
        repair: !recovery.suppress_recovery && (repair || PdfOpenOptions::default().repair),
        ignore_xref_streams: recovery.ignore_xref_streams,
        password: password_bytes,
        password_mode: password.password_mode.into(),
        suppress_password_recovery: password.suppress_password_recovery,
        password_is_hex_key: password.password_is_hex_key,
        ..PdfOpenOptions::default()
    }
}

fn cli_logger() -> QPDFLogger {
    static LOGGER: OnceLock<QPDFLogger> = OnceLock::new();
    LOGGER.get_or_init(QPDFLogger::create).clone()
}

fn standard_save_writer() -> CliResult<PipelineWriter> {
    standard_save_writer_for(&cli_logger())
}

fn standard_save_writer_for(logger: &QPDFLogger) -> CliResult<PipelineWriter> {
    logger.save_to_standard_output(true)?;
    Ok(PipelineWriter {
        pipeline: logger.get_save()?,
    })
}

fn prepare_pdf_standard_output(output: &Path) -> CliResult<Option<PipelineWriter>> {
    if output.as_os_str() == "-" {
        Ok(Some(standard_save_writer()?))
    } else {
        Ok(None)
    }
}

// cov:ignore-start: exercised by page-operation stdout subprocess integration tests
fn prepare_page_operation_standard_output(
    output: &Path,
    page_ops: &PageOpArgs,
) -> CliResult<Option<PipelineWriter>> {
    if output.as_os_str() == "-" && page_ops.split_pages.is_some() {
        return Err("--split-pages may not be used when writing to standard output".into());
    }
    prepare_pdf_standard_output(output)
}
// cov:ignore-end

fn logger_info(data: impl AsRef<[u8]>) -> CliResult<()> {
    cli_logger().info(data)?;
    Ok(())
}

fn logger_warn(data: impl AsRef<[u8]>) -> CliResult<()> {
    cli_logger().warn(data)?;
    Ok(())
}

fn logger_error(data: impl AsRef<[u8]>) -> CliResult<()> {
    cli_logger().error(data)?;
    Ok(())
}

fn emit_logger_error(data: impl AsRef<[u8]>) {
    if let Err(error) = cli_logger().error(data) {
        eprintln!("flpdf: unable to write diagnostic: {error}"); // cov:ignore: last-resort path after the standard error sink itself fails
    }
}

fn configure_document_logger(options: &mut PdfOpenOptions, input: &Path) {
    options.logger = Some(cli_logger());
    options.description = input.display().to_string();
}

/// Program name used in qpdf-parity diagnostic prefixes.
///
/// `FLPDF_PROGNAME` overrides the default so the qpdf qtest harness shim can
/// present flpdf as `qpdf`; unset or empty, the prefix is always `flpdf`.
fn progname() -> String {
    std::env::var("FLPDF_PROGNAME")
        .ok()
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| "flpdf".to_string())
}

/// Render the `<file>` / `<file> (offset N)` location part shared by the
/// qpdf-shaped diagnostic lines (qpdf 11.9.0 observed format; qpdf
/// suppresses the offset display when it is unknown).
fn diagnostic_location(input: &Path, offset: Option<u64>) -> String {
    match offset {
        Some(offset) => format!("{} (offset {offset})", input.display()),
        None => input.display().to_string(),
    }
}

/// Finish a successful operation after all requested output has been emitted.
/// qpdf aggregates warnings from both open-time and lazy object resolution;
/// the summary shape depends on whether this route created a PDF output.
fn finish_operation_warnings<R: Read + Seek>(pdf: &Pdf<R>, creates_output: bool) -> CliResult<()> {
    finish_operation_warnings_with_prior(pdf, creates_output, false)
}

/// Complete the warning boundary while retaining warnings observed in source
/// documents that were merged into a fresh output PDF.
fn finish_operation_warnings_with_prior<R: Read + Seek>(
    pdf: &Pdf<R>,
    creates_output: bool,
    prior_warnings: bool,
) -> CliResult<()> {
    finish_warning_state(
        prior_warnings || !pdf.repair_diagnostics().entries().is_empty(),
        creates_output,
    )
}

fn finish_job_exit_status(status: JobExitCode) -> CliResult<()> {
    match status {
        JobExitCode::Success => Ok(()),
        JobExitCode::Error => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
        JobExitCode::Warning => Err(Box::new(CliExitError {
            code: ExitCode::Warnings,
            message: String::new(),
        })),
    }
}

/// Map the qpdf-shaped check consumer's result to the CLI exit contract.
/// Diagnostics have already been emitted by [`QPDFJob::check`]; this adapter
/// only selects qpdf's error (2), warning (3), or success (0) process status.
fn finish_check_job(result: std::result::Result<JobExitCode, CheckError>) -> CliResult<()> {
    match result {
        Ok(status) => finish_job_exit_status(status),
        Err(CheckError::ErrorsDetected) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
        Err(CheckError::Operation(error)) => Err(Box::new(error)),
    }
}

fn finish_warning_state(has_warnings: bool, creates_output: bool) -> CliResult<()> {
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    if has_warnings {
        job.record_warnings();
    }

    match job.complete(creates_output)? {
        JobExitCode::Success => Ok(()),
        JobExitCode::Error => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
        JobExitCode::Warning => Err(Box::new(CliExitError {
            code: ExitCode::Warnings,
            message: String::new(),
        })),
    }
}

fn emit_content_normalization_warnings(
    input: &Path,
    warning: ContentNormalizationWarning,
) -> CliResult<()> {
    let location = diagnostic_location(input, warning.parsed_offset);
    let mut message =
        format!("WARNING: {location}: content normalization encountered bad tokens\n");
    if warning.last_token_was_bad {
        message.push_str(&format!(
            "WARNING: {location}: normalized content ended with a bad token; \
             you may be able to resolve this by coalescing content streams in \
             combination with normalizing content. From the command line, \
             specify --coalesce-contents\n"
        ));
    }
    message.push_str(&format!(
        "WARNING: {location}: Resulting stream data may be corrupted but is may \
         still useful for manual inspection. For more information on this \
         warning, search for content normalization in the manual.\n"
    ));
    logger_warn(message)
}

fn finish_rewrite_warnings<R: Read + Seek>(
    input: &Path,
    pdf: &Pdf<R>,
    normalization_warnings: &[ContentNormalizationWarning],
    creates_output: bool,
) -> CliResult<()> {
    // qpdf retains open-time warnings in the document warning collection and
    // emits the final summary after the output writer completes. Include the
    // full collection here, not only warnings added after this route opened
    // the document.
    let has_repair_warnings = !pdf.repair_diagnostics().entries().is_empty();
    for &warning in normalization_warnings {
        emit_content_normalization_warnings(input, warning)?;
    }
    if normalization_warnings.is_empty() && !has_repair_warnings {
        return Ok(());
    }
    finish_warning_state(true, creates_output)
}

/// Prefix a fatal error with the input path so main() renders the observed
/// qpdf shape `<progname>: <file>: <msg>` for open failures.
///
/// This type-erases the error; do not downcast the result.
fn error_with_file(input: &Path, error: Box<dyn std::error::Error>) -> Box<dyn std::error::Error> {
    format!("{}: {error}", input.display()).into()
}

fn actionable_password_error(error: flpdf::Error) -> Box<dyn std::error::Error> {
    if is_bad_password_error(&error) {
        return "encrypted PDF: incorrect password; retry with --password or --password-file"
            .into();
    }
    error.into()
}

// ── Attachment helpers (flpdf-9hc.10.9) ──────────────────────────────────────

/// Parse and retain the PDF timestamp syntax accepted by qpdf's
/// `QUtil::pdf_time_to_qpdf_time`: `D:YYYYMMDDHHmmSS`, optionally followed by
/// `Z` or a signed `HH'MM'` offset. The raw value is retained so qpdf's exact
/// timezone spelling is written to `/Params`.
fn parse_pdf_date_arg(s: &str) -> CliResult<Vec<u8>> {
    let s = s
        .strip_prefix("D:")
        .ok_or_else(|| format!("invalid PDF date {s:?}: must start with D:"))?;
    // Validate the required 14-character body is ASCII digits BEFORE slicing
    // by byte offsets: a multibyte value (e.g. fullwidth digits
    // `D:2024…`) would otherwise panic on a non-char-boundary slice.
    if s.len() < 14 || !s.as_bytes()[..14].iter().all(u8::is_ascii_digit) {
        return Err(format!(
            "invalid PDF date D:{s:?}: need at least 14 ASCII digits (YYYYMMDDHHmmSS)"
        )
        .into());
    }
    let suffix = &s[14..];
    let valid_suffix = match suffix.as_bytes() {
        b"" | b"Z" => true,
        [sign, hour_tens, hour_ones, b'\'', minute_tens, minute_ones, b'\''] => {
            matches!(sign, b'+' | b'-')
                && hour_tens.is_ascii_digit()
                && hour_ones.is_ascii_digit()
                && minute_tens.is_ascii_digit()
                && minute_ones.is_ascii_digit()
        }
        _ => false,
    };
    if !valid_suffix {
        return Err(format!("invalid PDF date D:{s:?}: timezone must be Z or [+|-]HH'MM'").into());
    }
    Ok(format!("D:{s}").into_bytes())
}

/// Parsed sub-flags for the `--add-attachment FILE [sub-flags] --` segment.
struct AddAttachmentArgs {
    /// Path to the file whose bytes will be embedded.
    file: PathBuf,
    /// Name-tree key (default: basename of `file`).
    key: Option<Vec<u8>>,
    /// Filename stored in both `/F` and `/UF` by qpdf's `createFileSpec` path.
    filename: Option<Vec<u8>>,
    /// MIME type for `/EmbeddedFile /Subtype`.
    mimetype: Option<Vec<u8>>,
    /// Human-readable description for `/Filespec /Desc`.
    description: Option<Vec<u8>>,
    /// `/Params /CreationDate` as the raw PDF date string.
    creation_date: Option<Vec<u8>>,
    /// `/Params /ModDate` as the raw PDF date string.
    mod_date: Option<Vec<u8>>,
    /// When true, replace an existing attachment with the same key.
    replace: bool,
}

/// Parse the raw token Vec captured by `--add-attachment … --` into
/// [`AddAttachmentArgs`].
///
/// Expected token order: FILE [--key=K] [--filename=F] [--mimetype=M]
/// [--description=D] [--creationdate=D] [--moddate=D] [--replace]
fn parse_add_attachment_segment(tokens: Vec<String>) -> CliResult<AddAttachmentArgs> {
    let mut iter = tokens.into_iter();
    let file: PathBuf = iter
        .next()
        .ok_or("--add-attachment: missing FILE argument")?
        .into();

    let mut key: Option<Vec<u8>> = None;
    let mut filename: Option<Vec<u8>> = None;
    let mut mimetype: Option<Vec<u8>> = None;
    let mut description: Option<Vec<u8>> = None;
    let mut creation_date: Option<Vec<u8>> = None;
    let mut mod_date: Option<Vec<u8>> = None;
    let mut replace = false;

    for token in iter {
        if let Some(v) = token.strip_prefix("--key=") {
            key = Some(v.as_bytes().to_vec());
        } else if let Some(v) = token.strip_prefix("--filename=") {
            filename = Some(v.as_bytes().to_vec());
        } else if let Some(v) = token.strip_prefix("--mimetype=") {
            if !v.contains('/') {
                return Err("mime type should be specified as type/subtype".into());
            }
            mimetype = Some(v.as_bytes().to_vec());
        } else if let Some(v) = token.strip_prefix("--description=") {
            description = Some(v.as_bytes().to_vec());
        } else if let Some(v) = token.strip_prefix("--creationdate=") {
            creation_date = Some(parse_pdf_date_arg(v)?);
        } else if let Some(v) = token.strip_prefix("--moddate=") {
            mod_date = Some(parse_pdf_date_arg(v)?);
        } else if token == "--replace" {
            replace = true;
        } else {
            return Err(format!(
                "--add-attachment: unknown sub-flag or unexpected token {token:?}"
            )
            .into());
        }
    }

    Ok(AddAttachmentArgs {
        file,
        key,
        filename,
        mimetype,
        description,
        creation_date,
        mod_date,
        replace,
    })
}

/// Parsed sub-flags for the `--copy-attachments-from FILE [sub-flags] --` segment.
struct CopyAttachmentsArgs {
    /// Source PDF path.
    file: PathBuf,
    /// Password for the source PDF (empty = no password).
    password: Vec<u8>,
    /// Prefix prepended to each copied key.
    prefix: Option<Vec<u8>>,
}

/// Parse the raw token Vec captured by `--copy-attachments-from … --` into
/// [`CopyAttachmentsArgs`].
///
/// Expected token order: FILE [--password=P] [--prefix=X]
fn parse_copy_attachments_segment(tokens: Vec<String>) -> CliResult<CopyAttachmentsArgs> {
    let mut iter = tokens.into_iter();
    let file: PathBuf = iter
        .next()
        .ok_or("--copy-attachments-from: missing FILE argument")?
        .into();

    let mut password: Vec<u8> = Vec::new();
    let mut prefix: Option<Vec<u8>> = None;

    for token in iter {
        if let Some(v) = token.strip_prefix("--password=") {
            password = v.as_bytes().to_vec();
        } else if let Some(v) = token.strip_prefix("--prefix=") {
            prefix = Some(v.as_bytes().to_vec());
        } else {
            return Err(format!(
                "--copy-attachments-from: unknown sub-flag or unexpected token {token:?}"
            )
            .into());
        }
    }

    Ok(CopyAttachmentsArgs {
        file,
        password,
        prefix,
    })
}

/// Return the basename of `path` as raw bytes, or error if the path has no
/// valid file name component.
fn path_basename(path: &std::path::Path) -> CliResult<Vec<u8>> {
    path.file_name()
        .ok_or_else(|| format!("cannot determine filename from path {:?}", path).into())
        .map(|n| n.to_string_lossy().into_owned().into_bytes())
}

/// `--add-attachment FILE [sub-flags] -- output.pdf`
#[allow(clippy::too_many_arguments)]
fn run_add_attachment(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    segments: Vec<Vec<String>>,
    deterministic_id: bool,
    static_id: bool,
    preserve_unreferenced: bool,
    verbose: bool,
    version_options: &CliVersionOptions,
) -> CliResult<()> {
    let input = input.ok_or("--add-attachment: missing input PDF")?;
    let output = output.ok_or("--add-attachment: missing output PDF")?;
    let attachment_options = segments
        .into_iter()
        .map(|tokens| {
            let args = parse_add_attachment_segment(tokens)?;
            let basename = path_basename(&args.file)?;
            let key = args.key.unwrap_or_else(|| basename.clone());
            let filename = args.filename.unwrap_or_else(|| basename.clone());
            Ok(AttachmentAddOptions {
                path: args.file,
                key,
                filename,
                mimetype: args.mimetype,
                description: args.description,
                creation_date: args.creation_date,
                modification_date: args.mod_date,
                replace: args.replace,
                verbose,
            })
        })
        .collect::<CliResult<Vec<_>>>()?;

    let file = File::open(&input).map_err(|error| error_with_file(&input, error.into()))?;
    let options = pdf_open_options(repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let mut pdf = job
        .open(BufReader::new(file), input.display().to_string(), options)
        .map_err(|error| error_with_file(&input, actionable_password_error(error)))?;

    let mut standard_output = prepare_pdf_standard_output(&output)?;

    job.add_attachments(&mut pdf, &attachment_options)?;

    let mut options = WriterOptions {
        deterministic_id,
        static_id,
        preserve_unreferenced_objects: preserve_unreferenced,
        ..WriterOptions::default()
    };
    apply_cli_version_options(&mut options, version_options);
    write_with_pdf_writer(
        &mut pdf,
        &output,
        &mut standard_output,
        &options,
        false,
        None,
    )?;
    if verbose && output.as_os_str() != "-" {
        job.logger()
            .info(format!("{}: wrote file {}\n", progname(), output.display()))?;
    }
    job.record_document_warnings(&pdf);
    finish_job_exit_status(job.complete(true)?)
}

/// `--remove-attachment KEY [input] [output]`
#[allow(clippy::too_many_arguments)]
fn run_remove_attachment(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    key: &str,
    deterministic_id: bool,
    static_id: bool,
    preserve_unreferenced: bool,
    version_options: &CliVersionOptions,
) -> CliResult<()> {
    let input = input.ok_or("--remove-attachment: missing input PDF")?;
    let output = output.ok_or("--remove-attachment: missing output PDF")?;

    let mut pdf = open_pdf(&input, repair, password)?;

    let found = pdf.embedded_files().remove_embedded_file(key.as_bytes())?;
    if !found {
        return Err(format!("--remove-attachment: key {:?} not found in document", key).into());
    }

    let mut options = WriterOptions {
        deterministic_id,
        static_id,
        preserve_unreferenced_objects: preserve_unreferenced,
        ..WriterOptions::default()
    };
    apply_cli_version_options(&mut options, version_options);
    let mut standard_output = None;
    write_with_pdf_writer(
        &mut pdf,
        &output,
        &mut standard_output,
        &options,
        false,
        None,
    )?;
    finish_operation_warnings(&pdf, true)
}

/// `--list-attachments [--verbose] input`
fn run_list_attachments(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    verbose: bool,
) -> CliResult<()> {
    let input = input.ok_or("--list-attachments: missing input PDF")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_input_name(input.display().to_string());
    let status = job.list_attachments(&mut pdf, verbose)?;
    finish_job_exit_status(status)
}

/// `--show-attachment KEY [-o PATH] input`
fn run_show_attachment(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    key: &str,
) -> CliResult<()> {
    let input = input.ok_or("--show-attachment: missing input PDF")?;
    let mut pdf = open_pdf(&input, repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_input_name(input.display().to_string());
    let status = job
        .show_attachment(&mut pdf, key.as_bytes())
        .map_err(|error| {
            format!(
                "--show-attachment: key {:?} not found or unreadable: {error}",
                key
            )
        })?;
    finish_job_exit_status(status)
}

/// `--copy-attachments-from FILE [--password=P] [--prefix=X] -- input output`
#[allow(clippy::too_many_arguments)]
fn run_copy_attachments_from(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    tokens: Vec<String>,
    deterministic_id: bool,
    static_id: bool,
    preserve_unreferenced: bool,
    verbose: bool,
    version_options: &CliVersionOptions,
) -> CliResult<()> {
    let input = input.ok_or("--copy-attachments-from: missing input PDF")?;
    let output = output.ok_or("--copy-attachments-from: missing output PDF")?;
    let args = parse_copy_attachments_segment(tokens)?;

    let file = File::open(&input).map_err(|error| error_with_file(&input, error.into()))?;
    let options = pdf_open_options(repair, password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    let mut pdf = job
        .open(BufReader::new(file), input.display().to_string(), options)
        .map_err(|error| error_with_file(&input, actionable_password_error(error)))?;

    let mut standard_output = prepare_pdf_standard_output(&output)?;

    // Open the source with its own password (independent of the target's).
    // Retain the command-wide open policy so qpdf's recovery/xref controls
    // apply to this secondary input exactly as they do to the target.
    let mut source_password = password.clone();
    source_password.password = None;
    source_password.password_file = None;
    let mut src_options =
        pdf_open_options_with_password_bytes(repair, &source_password, args.password.clone());
    configure_document_logger(&mut src_options, &args.file);
    let src_file =
        File::open(&args.file).map_err(|error| error_with_file(&args.file, error.into()))?;
    let mut src = Pdf::open_with_options(BufReader::new(src_file), src_options)
        .map_err(|error| error_with_file(&args.file, actionable_password_error(error)))?;
    src.root_handle()
        .map_err(|error| error_with_file(&args.file, actionable_password_error(error)))?;

    job.copy_attachments(
        &mut pdf,
        &mut src,
        &AttachmentCopyOptions {
            path: args.file,
            prefix: args.prefix.unwrap_or_default(),
            verbose,
        },
    )?;

    let mut writer_options = WriterOptions {
        deterministic_id,
        static_id,
        preserve_unreferenced_objects: preserve_unreferenced,
        ..WriterOptions::default()
    };
    apply_cli_version_options(&mut writer_options, version_options);
    write_with_pdf_writer(
        &mut pdf,
        &output,
        &mut standard_output,
        &writer_options,
        false,
        None,
    )?;
    if verbose && output.as_os_str() != "-" {
        job.logger()
            .info(format!("{}: wrote file {}\n", progname(), output.display()))?;
    }
    job.record_document_warnings(&pdf);
    finish_job_exit_status(job.complete(true)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use flpdf::pipeline::{Pipeline, PipelineResult};
    use std::sync::{Arc, Mutex};

    struct ChunkRecordingSink {
        chunks: Arc<Mutex<Vec<Vec<u8>>>>,
    }

    impl Pipeline for ChunkRecordingSink {
        fn identifier(&self) -> &str {
            "chunk recording sink"
        }

        fn write(&mut self, data: &[u8]) -> PipelineResult<()> {
            self.chunks.lock().unwrap().push(data.to_vec());
            Ok(())
        }

        fn finish(&mut self) -> PipelineResult<()> {
            Ok(())
        }
    }

    fn strs(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn preprocess_qpdf_args_routes_raw_segments_through_arg_parser() {
        let PreprocessedArgs {
            residual_args: residual,
            overlay_specs,
            attachment_segments,
        } = preprocess_qpdf_args(strs(&["flpdf", "--overlay", "source.pdf", "--to=1", "--"]))
            .expect("qpdf preprocessing should succeed");

        assert_eq!(residual, strs(&["flpdf"]));
        assert_eq!(overlay_specs.len(), 1);
        assert_eq!(overlay_specs[0].file, "source.pdf");
        assert_eq!(overlay_specs[0].to.as_deref(), Some("1"));
        assert!(attachment_segments.is_empty());
    }

    #[test]
    fn standard_save_writer_rejects_stdout_after_info_use() {
        let logger = QPDFLogger::create();
        logger.info([]).unwrap();

        let error = standard_save_writer_for(&logger).err().unwrap();

        assert_eq!(
            error.to_string(),
            "QPDFLogger: called setSave on standard output after standard output has already been used"
        );
    }

    #[test]
    fn json_input_open_error_uses_qpdf_not_found_wording() {
        let error = qpdf_json_input_open_error(
            Path::new("missing.json"),
            std::io::Error::from(std::io::ErrorKind::NotFound),
        );

        assert_eq!(
            error.to_string(),
            "open missing.json: No such file or directory"
        );
    }

    #[test]
    fn parse_add_attachment_rejects_mimetype_without_type_subtype_separator() {
        let Err(error) =
            parse_add_attachment_segment(strs(&["payload.txt", "--mimetype=textplain"]))
        else {
            panic!("the CLI parser must reject a mimetype without a slash"); // cov:ignore: parser regression guard
        };

        assert_eq!(
            error.to_string(),
            "mime type should be specified as type/subtype"
        );
    }

    #[test]
    fn show_pages_writes_each_logical_line_incrementally() {
        let chunks = Arc::new(Mutex::new(Vec::<Vec<u8>>::new()));
        let logger = QPDFLogger::create();
        let mut sink = ChunkRecordingSink {
            chunks: Arc::clone(&chunks),
        };
        assert_eq!(sink.identifier(), "chunk recording sink");
        sink.finish().unwrap();
        logger.set_info(Some(PipelineHandle::new(sink)));
        let mut pdf = Pdf::open_mem_owned(
            include_bytes!("../../../tests/fixtures/compat/one-page.pdf").to_vec(),
        )
        .unwrap();

        let mut job = QPDFJob::new();
        job.set_logger(logger);
        assert_eq!(job.show_pages(&mut pdf).unwrap(), JobExitCode::Success);

        let chunks = chunks.lock().unwrap();
        assert_eq!(chunks.len(), 5);
        assert_eq!(
            chunks.concat(),
            b"page 1: 3 0 R\n  media-box: [ 0 0 612 792 ]\n  resources: << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >>\n  contents: 7 0 R\n  rotate: 0\n"
        );
    }

    #[test]
    fn probe_encryption_classifies_bad_password_after_repair_warnings() {
        let mut input =
            include_bytes!("../../../tests/fixtures/compat/encrypted-r4-three-page.pdf").to_vec();
        let xref = input
            .windows(4)
            .position(|window| window == b"xref")
            .expect("encrypted fixture should contain an xref keyword");
        input[xref + 2] = b'X';

        let directory = tempfile::tempdir().expect("temporary directory");
        let path = directory.path().join("damaged-encrypted.pdf");
        std::fs::write(&path, input).expect("write damaged encrypted fixture");
        let outcome = probe_encryption(
            &path,
            true,
            &PasswordArgs {
                password: Some("wrong".to_owned()),
                ..PasswordArgs::default()
            },
        );

        assert!(matches!(outcome, Ok(EncryptionProbe::EncryptedAuthFailed)));
    }

    #[test]
    fn probe_encryption_prefixes_a_dangling_root_error_with_the_input_path() {
        let input = b"%PDF-1.4\nxref\n0 1\n0000000000 65535 f \ntrailer\n<< /Size 1 >>\nstartxref\n9\n%%EOF\n";
        let directory = tempfile::tempdir().expect("temporary directory");
        let path = directory.path().join("missing-root.pdf");
        std::fs::write(&path, input).expect("write missing-root fixture");

        let Err(error) = probe_encryption(&path, false, &PasswordArgs::default()) else {
            panic!("a missing /Root must be a hard error");
        };

        assert!(
            error.to_string().contains(&path.display().to_string()),
            "error should carry the input path like other open boundaries: {error}"
        );
        assert!(error
            .to_string()
            .contains("unable to find /Root dictionary"));
    }

    #[cfg(unix)]
    #[test]
    fn verified_json_output_rejects_hardlink_swapped_after_path_check() {
        let temp = tempfile::tempdir().unwrap();
        let input_path = temp.path().join("input.pdf");
        let output_path = temp.path().join("output.json");
        let original = b"input bytes must survive".to_vec();
        std::fs::write(&input_path, &original).unwrap();
        std::fs::write(&output_path, b"distinct output").unwrap();
        reject_same_json_output(&input_path, &output_path).unwrap();

        std::fs::remove_file(&output_path).unwrap();
        std::fs::hard_link(&input_path, &output_path).unwrap();
        let input_file = File::open(&input_path).unwrap();

        let error = open_verified_json_output(&input_file, &output_path).unwrap_err();

        assert!(error
            .to_string()
            .contains("input file and output file are the same"));
        assert_eq!(std::fs::read(&input_path).unwrap(), original);
    }

    // --- parse_overlay_segment ------------------------------------------

    #[test]
    fn overlay_bare_file() {
        let spec = parse_overlay_segment(OverlayKind::Overlay, &strs(&["over.pdf"])).unwrap();
        assert_eq!(
            spec,
            OverlaySpec {
                kind: OverlayKind::Overlay,
                file: "over.pdf".into(),
                password: None,
                from: None,
                to: None,
                repeat: None,
            }
        );
    }

    #[test]
    fn underlay_bare_file() {
        let spec = parse_overlay_segment(OverlayKind::Underlay, &strs(&["under.pdf"])).unwrap();
        assert_eq!(spec.kind, OverlayKind::Underlay);
        assert_eq!(spec.file, "under.pdf");
    }

    #[test]
    fn overlay_file_flag_form() {
        let spec =
            parse_overlay_segment(OverlayKind::Overlay, &strs(&["--file=over.pdf"])).unwrap();
        assert_eq!(spec.file, "over.pdf");
        assert_eq!(spec.password, None);
    }

    #[test]
    fn overlay_password() {
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["over.pdf", "--password=secret"]),
        )
        .unwrap();
        assert_eq!(spec.file, "over.pdf");
        assert_eq!(spec.password, Some("secret".into()));
    }

    #[test]
    fn overlay_from_to_repeat() {
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--from=1-3", "--to=2-4", "--repeat=1"]),
        )
        .unwrap();
        assert_eq!(spec.from, Some("1-3".into()));
        assert_eq!(spec.to, Some("2-4".into()));
        assert_eq!(spec.repeat, Some("1".into()));
    }

    #[test]
    fn overlay_all_flags_via_file_flag() {
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&[
                "--file=src.pdf",
                "--password=pw",
                "--to=1",
                "--from=1-z",
                "--repeat=z",
            ]),
        )
        .unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.password, Some("pw".into()));
        assert_eq!(spec.to, Some("1".into()));
        assert_eq!(spec.from, Some("1-z".into()));
        assert_eq!(spec.repeat, Some("z".into()));
    }

    #[test]
    fn overlay_empty_tokens_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &[])
            .unwrap_err()
            .to_string();
        assert!(err.contains("--overlay"), "got: {err}");
        assert!(err.contains("no source file"), "got: {err}");
    }

    #[test]
    fn overlay_missing_file_with_only_sub_options_error() {
        // Sub-options present but no file token at all: fails with a missing-file
        // error (order-independent parsing means --password= alone no longer
        // triggers a "must follow" positional check).
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["--password=pw"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("--overlay"), "got: {err}");
        assert!(err.contains("no source file"), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_file_bare_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["a.pdf", "b.pdf"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("duplicate file"), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_file_flag_error() {
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["--file=a.pdf", "--file=b.pdf"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate file"), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_file_mixed_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["a.pdf", "--file=b.pdf"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("duplicate file"), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_to_error() {
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--to=1", "--to=2"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate --to="), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_from_error() {
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--from=1", "--from=2"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate --from="), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_repeat_error() {
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--repeat=1", "--repeat=z"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate --repeat="), "got: {err}");
    }

    #[test]
    fn overlay_unknown_flag_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["src.pdf", "--bogus=x"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("--overlay"), "got: {err}");
        assert!(err.contains("unsupported token"), "got: {err}");
    }

    #[test]
    fn underlay_unknown_flag_error_prefix() {
        let err = parse_overlay_segment(OverlayKind::Underlay, &strs(&["src.pdf", "--unknown"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("--underlay"), "got: {err}");
    }

    #[test]
    fn overlay_invalid_range_to_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["src.pdf", "--to=abc!"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("invalid --to="), "got: {err}");
    }

    #[test]
    fn overlay_invalid_range_from_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["src.pdf", "--from=abc!"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("invalid --from="), "got: {err}");
    }

    #[test]
    fn overlay_invalid_range_repeat_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["src.pdf", "--repeat=abc!"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("invalid --repeat="), "got: {err}");
    }

    #[test]
    fn overlay_option_before_file_to_ok() {
        // qpdf accepts sub-options before the file token within a UO segment.
        let spec =
            parse_overlay_segment(OverlayKind::Overlay, &strs(&["--to=1", "src.pdf"])).unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.to, Some("1".into()));
        assert_eq!(spec.from, None);
        assert_eq!(spec.repeat, None);
        assert_eq!(spec.password, None);
    }

    #[test]
    fn overlay_option_before_file_from_ok() {
        let spec =
            parse_overlay_segment(OverlayKind::Overlay, &strs(&["--from=1", "src.pdf"])).unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.from, Some("1".into()));
    }

    #[test]
    fn overlay_option_before_file_repeat_ok() {
        let spec =
            parse_overlay_segment(OverlayKind::Overlay, &strs(&["--repeat=1", "src.pdf"])).unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.repeat, Some("1".into()));
    }

    #[test]
    fn overlay_option_before_file_password_ok() {
        let spec =
            parse_overlay_segment(OverlayKind::Overlay, &strs(&["--password=pw", "src.pdf"]))
                .unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.password, Some("pw".into()));
    }

    #[test]
    fn overlay_options_mixed_around_file_ok() {
        // Sub-options both before and after the file token, mirroring qpdf's
        // free-order UO segment parsing.
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&[
                "--password=pw",
                "--from=1",
                "src.pdf",
                "--to=2",
                "--repeat=z",
            ]),
        )
        .unwrap();
        assert_eq!(spec.file, "src.pdf");
        assert_eq!(spec.password, Some("pw".into()));
        assert_eq!(spec.from, Some("1".into()));
        assert_eq!(spec.to, Some("2".into()));
        assert_eq!(spec.repeat, Some("z".into()));
    }

    #[test]
    fn underlay_option_before_file_ok() {
        let spec = parse_overlay_segment(
            OverlayKind::Underlay,
            &strs(&["--to=1", "--from=2", "under.pdf"]),
        )
        .unwrap();
        assert_eq!(spec.kind, OverlayKind::Underlay);
        assert_eq!(spec.file, "under.pdf");
        assert_eq!(spec.to, Some("1".into()));
        assert_eq!(spec.from, Some("2".into()));
    }

    #[test]
    fn overlay_duplicate_to_before_file_error() {
        // Duplicate detection stays effective even when duplicates straddle
        // the file token.
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["--to=1", "src.pdf", "--to=2"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate --to="), "got: {err}");
    }

    #[test]
    fn overlay_invalid_range_before_file_error() {
        // Range validation runs regardless of where the sub-option appears.
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["--to=abc!", "src.pdf"]))
            .unwrap_err()
            .to_string();
        assert!(err.contains("invalid --to="), "got: {err}");
    }

    #[test]
    fn overlay_duplicate_password_error() {
        let err = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--password=a", "--password=b"]),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("duplicate --password="), "got: {err}");
    }

    // --- rewrite_qpdf_single_dash ---------------------------------------

    #[test]
    fn single_dash_long_becomes_double_dash() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-qdf", "-static-id", "in.pdf"]));
        assert_eq!(out, strs(&["flpdf", "--qdf", "--static-id", "in.pdf"]));
    }

    #[test]
    fn single_dash_long_with_equals_becomes_double_dash() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-object-streams=generate"]));
        assert_eq!(out, strs(&["flpdf", "--object-streams=generate"]));
    }

    #[test]
    fn single_dash_bare_equals_value_is_discarded_after_rewriting() {
        let out =
            normalize_qpdf_bare_equals(rewrite_qpdf_single_dash(strs(&["flpdf", "-qdf=ignored"])));
        assert_eq!(out, strs(&["flpdf", "--qdf"]));
    }

    #[test]
    fn qpdf_bare_boolean_equals_values_are_discarded() {
        let out = normalize_qpdf_bare_equals(strs(&[
            "flpdf",
            "--check=ignored",
            "--qdf=ignored",
            "--static-id=ignored",
            "--verbose=ignored",
            "--preserve-unreferenced=ignored",
        ]));
        assert_eq!(
            out,
            strs(&[
                "flpdf",
                "--check",
                "--qdf",
                "--static-id",
                "--verbose",
                "--preserve-unreferenced",
            ])
        );
    }

    #[test]
    fn qpdf_bare_normalization_preserves_value_options() {
        let args = strs(&[
            "flpdf",
            "--json=2",
            "--object-streams=generate",
            "--normalize-content=y",
            "--newline-before-endstream=never",
        ]);
        assert_eq!(normalize_qpdf_bare_equals(args.clone()), args);
    }

    #[test]
    fn newline_before_endstream_discards_an_unrecognized_equals_value() {
        let args = strs(&["flpdf", "--newline-before-endstream=garbage"]);

        assert_eq!(
            normalize_qpdf_bare_equals(args),
            strs(&["flpdf", "--newline-before-endstream"])
        );
    }

    #[test]
    fn qpdf_bare_normalization_preserves_value_terminated_segments() {
        let args = strs(&[
            "flpdf",
            "--encrypt",
            "user",
            "owner",
            "256",
            "--qdf=an-encrypt-suboption-value",
            "--",
            "--check=after-segment",
        ]);
        assert_eq!(
            normalize_qpdf_bare_equals(args),
            strs(&[
                "flpdf",
                "--encrypt",
                "user",
                "owner",
                "256",
                "--qdf=an-encrypt-suboption-value",
                "--",
                "--check",
            ])
        );
    }

    #[test]
    fn double_dash_long_is_untouched() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "--qdf", "--static-id"]));
        assert_eq!(out, strs(&["flpdf", "--qdf", "--static-id"]));
    }

    #[test]
    fn known_short_flags_untouched() {
        // -o and -h are the only shorts flpdf declares; they must not be
        // rewritten to `--o`/`--h`.
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-o", "path", "-h"]));
        assert_eq!(out, strs(&["flpdf", "-o", "path", "-h"]));
    }

    #[test]
    fn stdin_sentinel_and_options_terminator_untouched() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-", "--"]));
        assert_eq!(out, strs(&["flpdf", "-", "--"]));
    }

    #[test]
    fn single_dash_long_after_section_terminator_is_rewritten() {
        let out = rewrite_qpdf_single_dash(strs(&[
            "flpdf",
            "-pages",
            ".",
            "--",
            "-qdf",
            "-not-an-option",
        ]));
        assert_eq!(
            out,
            strs(&["flpdf", "--pages", ".", "--", "--qdf", "-not-an-option",])
        );
    }

    #[test]
    fn top_level_terminator_preserves_remaining_tokens() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "--", "-in.pdf", "-qdf"]));
        assert_eq!(out, strs(&["flpdf", "--", "-in.pdf", "-qdf"]));
    }

    #[test]
    fn attached_short_output_is_untouched() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-o/tmp/out"]));
        assert_eq!(out, strs(&["flpdf", "-o/tmp/out"]));
    }

    #[test]
    fn hyphenated_segment_operand_is_untouched() {
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-add-attachment", "-note.txt", "--"]));
        assert_eq!(out, strs(&["flpdf", "--add-attachment", "-note.txt", "--"]));
    }

    #[test]
    fn single_dash_segment_sub_option_is_rewritten() {
        let parsed = arg_parser::ArgParser::from_command(Cli::command())
            .parse(strs(&["flpdf", "-overlay", "stamp.pdf", "-to=1", "--"]))
            .unwrap();
        assert_eq!(parsed.residual_args, strs(&["flpdf"]));
        assert_eq!(parsed.named_segments[0].option, "overlay");
        assert_eq!(
            parsed.named_segments[0].tokens,
            strs(&["stamp.pdf", "--to=1"])
        );
    }

    #[test]
    fn each_segment_kind_recognizes_its_sub_options() {
        let parsed = arg_parser::ArgParser::from_command(Cli::command())
            .parse(strs(&[
                "flpdf",
                "--encrypt",
                "-use-aes",
                "--",
                "--pages",
                "-range=1",
                "--",
                "--add-attachment",
                "-replace",
                "--",
                "--copy-attachments-from",
                "-prefix=copy-",
                "--",
            ]))
            .unwrap();

        assert_eq!(parsed.named_segments[0].tokens, ["--use-aes"]);
        assert_eq!(parsed.named_segments[1].tokens, ["--range=1"]);
        assert_eq!(parsed.named_segments[2].tokens, ["--replace"]);
        assert_eq!(parsed.named_segments[3].tokens, ["--prefix=copy-"]);
    }

    #[test]
    fn collect_clap_long_options_includes_aliases() {
        let command = clap::Command::new("test")
            .arg(clap::Arg::new("mode").long("mode").alias("legacy-mode"));
        let parsed = arg_parser::ArgParser::from_command(command)
            .parse(strs(&["test", "-legacy-mode"]))
            .unwrap();

        assert_eq!(parsed.residual_args, strs(&["test", "--legacy-mode"]));
    }

    #[test]
    fn legacy_encrypt_password_is_not_rewritten() {
        let out =
            rewrite_qpdf_single_dash(strs(&["flpdf", "-encrypt", "-user", "owner", "128", "--"]));
        assert_eq!(
            out,
            strs(&["flpdf", "--encrypt", "-user", "owner", "128", "--",])
        );
    }

    #[test]
    fn non_bare_hyphen_encrypt_password_is_rejected() {
        let err = parse_encrypt_segment(&strs(&["-user", "owner", "128"]), true)
            .unwrap_err()
            .to_string();
        assert!(err.contains("unrecognized argument -user"), "got: {err}");
    }

    #[test]
    fn bare_hyphen_encrypt_password_is_accepted() {
        let params = parse_encrypt_segment(&strs(&["-", "-", "128"]), true).unwrap();
        assert_eq!(params.user_password, b"-");
        assert_eq!(params.owner_password, b"-");
    }

    #[test]
    fn negative_number_positional_untouched() {
        // -1 / -0.5 are numeric positionals, never options.
        let out = rewrite_qpdf_single_dash(strs(&["flpdf", "-1", "-0.5"]));
        assert_eq!(out, strs(&["flpdf", "-1", "-0.5"]));
    }

    // --- extract_overlay_groups -----------------------------------------

    #[test]
    fn extract_no_overlay_leaves_args_untouched() {
        let argv = strs(&["flpdf", "rewrite", "--static-id", "in.pdf", "out.pdf"]);
        let (residual, specs) = extract_overlay_groups(argv.clone()).unwrap();
        assert_eq!(residual, argv);
        assert!(specs.is_empty());
    }

    #[test]
    fn extract_single_attachment_group_leaves_a_clap_dispatch_marker() {
        let argv = strs(&[
            "flpdf",
            "in.pdf",
            "--add-attachment",
            "one.txt",
            "--key=one",
            "--",
            "out.pdf",
        ]);
        let (residual, groups) = extract_attachment_groups(argv).unwrap();

        assert_eq!(
            residual,
            strs(&[
                "flpdf",
                "in.pdf",
                "--add-attachment",
                "one.txt",
                "--key=one",
                "--",
                "out.pdf",
            ])
        );
        assert_eq!(groups, vec![strs(&["one.txt", "--key=one"])]);
    }

    #[test]
    fn extract_repeated_attachment_groups_preserves_order_and_boundaries() {
        let argv = strs(&[
            "flpdf",
            "in.pdf",
            "--add-attachment",
            "one.txt",
            "--key=one",
            "--",
            "--add-attachment",
            "two.txt",
            "--key=two",
            "--",
            "out.pdf",
        ]);
        let (residual, groups) = extract_attachment_groups(argv).unwrap();

        assert_eq!(
            residual,
            strs(&[
                "flpdf",
                "in.pdf",
                "--add-attachment",
                "one.txt",
                "--key=one",
                "--",
                "out.pdf",
            ])
        );
        assert_eq!(
            groups,
            vec![
                strs(&["one.txt", "--key=one"]),
                strs(&["two.txt", "--key=two"]),
            ]
        );
    }

    #[test]
    fn extract_attachment_groups_leaves_opaque_sibling_values_untouched() {
        let argv = strs(&[
            "flpdf",
            "--pages",
            "--add-attachment",
            "one.txt",
            "--",
            "out.pdf",
        ]);
        let (residual, groups) = extract_attachment_groups(argv.clone()).unwrap();

        assert_eq!(residual, argv);
        assert!(groups.is_empty());
    }

    #[test]
    fn extract_attachment_groups_rejects_an_unterminated_group() {
        let error = extract_attachment_groups(strs(&["flpdf", "--add-attachment", "one.txt"]))
            .expect_err("an attachment group must have a terminator");

        assert_eq!(error.to_string(), "--add-attachment: missing -- terminator");
    }

    #[test]
    fn extract_attachment_groups_discards_the_equals_value_like_qpdfs_bare_option() {
        // qpdf's `--add-attachment` is a bare option (QPDFJob_argv.cc:38's
        // addBare): `QPDFArgParser` silently discards any `=value` attached
        // to the flag itself, so a later plain positional token becomes the
        // file. Confirmed against /usr/bin/qpdf 11.9.0: `--add-attachment=
        // bogus.txt payload.txt --` embeds `payload.txt` and drops `bogus.txt`.
        let argv = strs(&[
            "flpdf",
            "in.pdf",
            "--add-attachment=bogus.txt",
            "payload.txt",
            "--",
            "out.pdf",
        ]);
        let (_, groups) = extract_attachment_groups(argv).unwrap();

        assert_eq!(groups, vec![strs(&["payload.txt"])]);
    }

    #[test]
    fn extract_attachment_groups_equals_form_with_no_positional_yields_an_empty_segment() {
        // Confirmed against /usr/bin/qpdf 11.9.0: `--add-attachment=x --`
        // errors "add attachment: no file specified" because nothing
        // follows the discarded `=value` to serve as the file.
        let argv = strs(&[
            "flpdf",
            "in.pdf",
            "--add-attachment=payload.txt",
            "--",
            "out.pdf",
        ]);
        let (_, groups) = extract_attachment_groups(argv).unwrap();

        assert_eq!(groups, vec![Vec::<String>::new()]);
    }

    #[test]
    fn extract_single_overlay_group() {
        let argv = strs(&[
            "flpdf",
            "rewrite",
            "in.pdf",
            "--overlay",
            "over.pdf",
            "--",
            "out.pdf",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        // The flag, its tokens, and the terminating `--` are removed.
        assert_eq!(residual, strs(&["flpdf", "rewrite", "in.pdf", "out.pdf"]));
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].kind, OverlayKind::Overlay);
        assert_eq!(specs[0].file, "over.pdf");
    }

    #[test]
    fn extract_two_overlay_groups_preserves_boundaries_and_order() {
        // The design-mandated case: two groups must split, not flatten.
        let argv = strs(&["--overlay", "a.pdf", "--", "--overlay", "b.pdf", "--"]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert!(
            residual.is_empty(),
            "all overlay tokens stripped: {residual:?}"
        );
        assert_eq!(
            specs.len(),
            2,
            "two distinct groups, not one flattened list"
        );
        assert_eq!(specs[0].file, "a.pdf");
        assert_eq!(specs[1].file, "b.pdf");
    }

    #[test]
    fn extract_mixed_overlay_underlay_preserves_declaration_order() {
        // Mixed kinds must keep CLI declaration order (overlay then underlay);
        // the library re-groups under-then-over internally.
        let argv = strs(&[
            "in.pdf",
            "--overlay",
            "one.pdf",
            "--",
            "--underlay",
            "two.pdf",
            "--",
            "out.pdf",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(residual, strs(&["in.pdf", "out.pdf"]));
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].kind, OverlayKind::Overlay);
        assert_eq!(specs[0].file, "one.pdf");
        assert_eq!(specs[1].kind, OverlayKind::Underlay);
        assert_eq!(specs[1].file, "two.pdf");
    }

    #[test]
    fn extract_captures_sub_flags_per_group() {
        let argv = strs(&[
            "--overlay",
            "--file=src.pdf",
            "--password=pw",
            "--from=1",
            "--to=2-3",
            "--repeat=1",
            "--",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert!(residual.is_empty());
        assert_eq!(specs.len(), 1);
        let s = &specs[0];
        assert_eq!(s.file, "src.pdf");
        assert_eq!(s.password.as_deref(), Some("pw"));
        assert_eq!(s.from.as_deref(), Some("1"));
        assert_eq!(s.to.as_deref(), Some("2-3"));
        assert_eq!(s.repeat.as_deref(), Some("1"));
    }

    #[test]
    fn extract_leaves_trailing_top_level_flag_after_group_terminator() {
        // qtest form-xobject uo-3 style: a top-level flag appears AFTER the
        // overlay/underlay group's `--` terminator. The extractor must place
        // that trailing flag verbatim into the residual argv so clap sees it.
        // A regression here would reintroduce the flpdf-9hc.16.18 diagnosis
        // trap ("blame the extractor when the top-level flag is missing from
        // clap's schema").
        let argv = strs(&[
            "flpdf",
            "in.pdf",
            "out.pdf",
            "--overlay",
            "src.pdf",
            "--",
            "--coalesce-contents",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(
            residual,
            strs(&["flpdf", "in.pdf", "out.pdf", "--coalesce-contents"])
        );
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].file, "src.pdf");
    }

    #[test]
    fn extract_unterminated_group_errors() {
        // No bare `--` after the file => qpdf requires the terminator.
        let argv = strs(&["--overlay", "over.pdf", "out.pdf"]);
        let err = extract_overlay_groups(argv).unwrap_err().to_string();
        assert!(err.contains("terminated by a `--`"), "got: {err}");
    }

    #[test]
    fn extract_propagates_segment_parse_errors() {
        // An invalid page range inside a group surfaces the segment error.
        let argv = strs(&["--overlay", "over.pdf", "--to=abc!", "--"]);
        let err = extract_overlay_groups(argv).unwrap_err().to_string();
        assert!(err.contains("invalid --to="), "got: {err}");
    }

    #[test]
    fn extract_sub_options_before_file_within_group() {
        // qpdf accepts sub-options in any order within a UO segment, so the raw
        // argv `--overlay --to=1 src.pdf --` must parse to a single overlay
        // group with `to=1` and `file=src.pdf`. Mirrors the repro in the issue:
        // `flpdf rewrite in.pdf --overlay --to=1 src.pdf -- out.pdf`.
        let argv = strs(&[
            "flpdf",
            "rewrite",
            "in.pdf",
            "--overlay",
            "--to=1",
            "src.pdf",
            "--",
            "out.pdf",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(residual, strs(&["flpdf", "rewrite", "in.pdf", "out.pdf"]));
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].kind, OverlayKind::Overlay);
        assert_eq!(specs[0].file, "src.pdf");
        assert_eq!(specs[0].to.as_deref(), Some("1"));
    }

    #[test]
    fn extract_overlay_equals_form_without_positional_file_is_rejected() {
        // qpdf discards the attached value on this bare option, so the segment
        // still has no source file and is rejected.
        let argv = strs(&["flpdf", "--overlay=discarded", "--"]);
        let err = extract_overlay_groups(argv).unwrap_err().to_string();
        assert!(err.contains("--overlay"), "got: {err}");
        assert!(err.contains("no source file"), "got: {err}");
    }

    #[test]
    fn extract_underlay_equals_form_without_positional_file_is_rejected() {
        let argv = strs(&["flpdf", "--underlay=discarded", "--"]);
        let err = extract_overlay_groups(argv).unwrap_err().to_string();
        assert!(err.contains("--underlay"), "got: {err}");
        assert!(err.contains("no source file"), "got: {err}");
    }

    #[test]
    fn extract_overlay_equals_form_discards_value_when_positional_source_follows() {
        let argv = strs(&["flpdf", "--overlay=discarded", "src.pdf", "--"]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(residual, strs(&["flpdf"]));
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].file, "src.pdf");
    }

    #[test]
    fn extract_underlay_equals_form_discards_value_when_positional_source_follows() {
        let argv = strs(&["flpdf", "--underlay=discarded", "src.pdf", "--"]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(residual, strs(&["flpdf"]));
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].file, "src.pdf");
    }

    #[test]
    fn extract_password_sub_flag_not_mistaken_for_terminator() {
        // `--password=…` starts with `--` but only a bare `--` terminates.
        let argv = strs(&["--overlay", "src.pdf", "--password=--weird", "--"]);
        let (_residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].password.as_deref(), Some("--weird"));
    }

    #[test]
    fn extract_overlay_token_inside_encrypt_segment_is_not_a_group() {
        // `--overlay` here is a *value* of the value-terminated --encrypt segment
        // (a literal user password), not a new overlay group. It must survive in
        // the residual for clap, and no spurious group is produced.
        let argv = strs(&[
            "flpdf",
            "rewrite",
            "--encrypt",
            "--overlay",
            "owner",
            "128",
            "--use-aes=y",
            "--",
            "in.pdf",
            "out.pdf",
        ]);
        let (residual, specs) = extract_overlay_groups(argv.clone()).unwrap();
        assert!(specs.is_empty(), "no overlay group, got: {specs:?}");
        assert_eq!(residual, argv, "encrypt segment copied verbatim");
    }

    #[test]
    fn extract_underlay_token_inside_pages_segment_is_not_a_group() {
        // Same protection for the --pages segment (and --underlay).
        let argv = strs(&["--pages", "a.pdf", "--underlay", "b.pdf", "--", "out.pdf"]);
        let (residual, specs) = extract_overlay_groups(argv.clone()).unwrap();
        assert!(specs.is_empty(), "got: {specs:?}");
        assert_eq!(residual, argv);
    }

    #[test]
    fn extract_real_overlay_after_encrypt_segment_still_extracted() {
        // A genuine --overlay group AFTER the encrypt segment's own `--` is still
        // recognised and stripped; the encrypt segment is preserved verbatim.
        let argv = strs(&[
            "--encrypt",
            "u",
            "o",
            "128",
            "--",
            "--overlay",
            "src.pdf",
            "--",
            "in.pdf",
            "out.pdf",
        ]);
        let (residual, specs) = extract_overlay_groups(argv).unwrap();
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].file, "src.pdf");
        assert_eq!(
            residual,
            strs(&["--encrypt", "u", "o", "128", "--", "in.pdf", "out.pdf"])
        );
    }

    #[test]
    fn extract_unterminated_sibling_segment_errors_at_parser_boundary() {
        // qpdf's named option table must be terminated before the parser
        // resumes the main table; the inner --overlay is not a new group.
        let argv = strs(&["--encrypt", "u", "o", "128", "--overlay", "x"]);
        let error = extract_overlay_groups(argv).unwrap_err().to_string();
        assert!(error.contains("--encrypt"), "got: {error}");
        assert!(error.contains("terminated"), "got: {error}");
    }

    #[test]
    fn extract_overlay_token_inside_equals_form_attachment_segment_is_not_a_group() {
        // `--add-attachment=discarded` (qpdf's bare-option equals-form) starts the
        // same opaque segment as `--add-attachment`. A file literally named
        // `--overlay` as the segment's positional token must not be hijacked into
        // a new overlay group by this earlier pass.
        let argv = strs(&["--add-attachment=discarded", "--overlay", "--", "out.pdf"]);
        let (residual, specs) = extract_overlay_groups(argv.clone()).unwrap();
        assert!(specs.is_empty(), "no overlay group, got: {specs:?}");
        assert_eq!(
            residual,
            strs(&["--add-attachment", "--overlay", "--", "out.pdf"]),
            "qpdf discards the equals value on a bare segment option"
        );
    }

    #[test]
    fn extract_overlay_groups_normalizes_equals_form_sibling_segments() {
        for (equals_form, bare_form) in [
            ("--encrypt=discarded", "--encrypt"),
            ("--pages=discarded", "--pages"),
            (
                "--copy-attachments-from=discarded",
                "--copy-attachments-from",
            ),
        ] {
            let argv = strs(&["in.pdf", equals_form, "--overlay", "--", "out.pdf"]);
            let (residual, specs) = extract_overlay_groups(argv).unwrap();
            assert!(specs.is_empty(), "no overlay group, got: {specs:?}");
            assert_eq!(
                residual,
                strs(&["in.pdf", bare_form, "--overlay", "--", "out.pdf"]),
                "equals value must be discarded like qpdf for {equals_form}"
            );
        }
    }

    #[test]
    fn extract_attachment_groups_normalizes_equals_form_sibling_segments() {
        for (equals_form, bare_form) in [
            ("--encrypt=discarded", "--encrypt"),
            ("--pages=discarded", "--pages"),
            (
                "--copy-attachments-from=discarded",
                "--copy-attachments-from",
            ),
        ] {
            let argv = strs(&[
                "flpdf",
                "in.pdf",
                equals_form,
                "source.pdf",
                "--",
                "out.pdf",
            ]);
            let (residual, groups) = extract_attachment_groups(argv).unwrap();
            assert!(
                groups.is_empty(),
                "sibling segment must not become attachment groups"
            );
            assert_eq!(
                residual,
                strs(&["flpdf", "in.pdf", bare_form, "source.pdf", "--", "out.pdf"]),
                "equals value must be discarded like qpdf for {equals_form}"
            );
        }
    }

    // --- build_overlay_specs --------------------------------------------

    fn compat_fixture(name: &str) -> String {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(name)
            .to_str()
            .expect("utf-8 path")
            .to_string()
    }

    #[test]
    fn build_overlay_specs_opens_source_and_maps_fields() {
        // A bare unencrypted source with all ranges set: opens the Pdf, maps the
        // kind, and parses from/to/repeat (repeat present here).
        let cli_specs = vec![OverlaySpec {
            kind: OverlayKind::Underlay,
            file: compat_fixture("one-page.pdf"),
            password: None,
            from: Some("1".into()),
            to: Some("1-2".into()),
            repeat: Some("1".into()),
        }];
        let built = build_overlay_specs(&cli_specs, false, &PasswordArgs::default()).unwrap();
        assert_eq!(built.len(), 1);
        assert_eq!(built[0].kind, flpdf::OverlayKind::Underlay);
        // repeat is Some when the segment supplied --repeat.
        assert!(built[0].repeat.is_some());
    }

    #[test]
    fn build_overlay_specs_defaults_ranges_when_absent() {
        // No from/to/repeat: from/to default to the empty (all-pages) range and
        // repeat stays None.
        let cli_specs = vec![OverlaySpec {
            kind: OverlayKind::Overlay,
            file: compat_fixture("one-page.pdf"),
            password: None,
            from: None,
            to: None,
            repeat: None,
        }];
        let built = build_overlay_specs(&cli_specs, false, &PasswordArgs::default()).unwrap();
        assert_eq!(built[0].kind, flpdf::OverlayKind::Overlay);
        assert!(
            built[0].repeat.is_none(),
            "repeat None when --repeat absent"
        );
    }

    #[test]
    fn build_overlay_specs_missing_file_errors() {
        let cli_specs = vec![OverlaySpec {
            kind: OverlayKind::Overlay,
            file: "/nonexistent/overlay/source.pdf".into(),
            password: None,
            from: None,
            to: None,
            repeat: None,
        }];
        // `flpdf::OverlaySpec` is not Debug (it holds a `Pdf`), so match the Ok
        // arm explicitly instead of `unwrap_err()`.
        let err = match build_overlay_specs(&cli_specs, false, &PasswordArgs::default()) {
            Ok(_) => panic!("expected error for a missing source file"),
            Err(e) => e.to_string(),
        };
        assert!(
            err.contains("source.pdf"),
            "error should name the unreadable file: {err}"
        );
    }

    fn encrypted_fixture(name: &str) -> String {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/encrypted")
            .join(name)
            .to_str()
            .expect("utf-8 path")
            .to_string()
    }

    #[test]
    fn build_overlay_specs_distinguishes_absent_and_empty_from() {
        // qpdf parity: an absent `--from` defaults to all source pages, while an
        // explicit empty `--from=` selects no source pages (so `--repeat` cycles
        // from the first destination page).
        let file = compat_fixture("three-page.pdf");
        let spec = |from: Option<&str>| {
            vec![OverlaySpec {
                kind: OverlayKind::Overlay,
                file: file.clone(),
                password: None,
                from: from.map(str::to_string),
                to: None,
                repeat: None,
            }]
        };

        let absent = build_overlay_specs(&spec(None), false, &PasswordArgs::default()).unwrap();
        assert_eq!(absent[0].from.resolve(3).unwrap(), vec![1, 2, 3]);

        let empty = build_overlay_specs(&spec(Some("")), false, &PasswordArgs::default()).unwrap();
        assert_eq!(empty[0].from.resolve(3).unwrap(), Vec::<u32>::new());

        let explicit =
            build_overlay_specs(&spec(Some("2")), false, &PasswordArgs::default()).unwrap();
        assert_eq!(explicit[0].from.resolve(3).unwrap(), vec![2]);
    }

    #[test]
    fn build_overlay_specs_distinguishes_absent_and_empty_to() {
        // qpdf parity: an absent `--to` defaults to all destination pages, while
        // an explicit empty `--to=` selects no destination pages (the overlay
        // becomes a no-op). A non-empty `--to=` is honored verbatim.
        let file = compat_fixture("three-page.pdf");
        let spec = |to: Option<&str>| {
            vec![OverlaySpec {
                kind: OverlayKind::Overlay,
                file: file.clone(),
                password: None,
                from: None,
                to: to.map(str::to_string),
                repeat: None,
            }]
        };

        let absent = build_overlay_specs(&spec(None), false, &PasswordArgs::default()).unwrap();
        assert_eq!(absent[0].to.resolve(3).unwrap(), vec![1, 2, 3]);

        let empty = build_overlay_specs(&spec(Some("")), false, &PasswordArgs::default()).unwrap();
        assert_eq!(empty[0].to.resolve(3).unwrap(), Vec::<u32>::new());

        let explicit =
            build_overlay_specs(&spec(Some("2-3")), false, &PasswordArgs::default()).unwrap();
        assert_eq!(explicit[0].to.resolve(3).unwrap(), vec![2, 3]);
    }

    #[test]
    fn build_overlay_specs_distinguishes_absent_and_empty_repeat() {
        // qpdf parity: an explicit empty `--repeat=` is "no repeat", identical to
        // an absent `--repeat` (both map to `None`). A non-empty `--repeat=` is
        // parsed into a source-page range.
        let file = compat_fixture("three-page.pdf");
        let spec = |repeat: Option<&str>| {
            vec![OverlaySpec {
                kind: OverlayKind::Overlay,
                file: file.clone(),
                password: None,
                from: None,
                to: None,
                repeat: repeat.map(str::to_string),
            }]
        };

        let absent = build_overlay_specs(&spec(None), false, &PasswordArgs::default()).unwrap();
        assert!(absent[0].repeat.is_none(), "absent --repeat -> None");

        let empty = build_overlay_specs(&spec(Some("")), false, &PasswordArgs::default()).unwrap();
        assert!(
            empty[0].repeat.is_none(),
            "explicit empty --repeat= -> None (no repeat), same as absent"
        );

        let explicit =
            build_overlay_specs(&spec(Some("2")), false, &PasswordArgs::default()).unwrap();
        assert_eq!(
            explicit[0].repeat.as_ref().unwrap().resolve(3).unwrap(),
            vec![2]
        );
    }

    #[test]
    fn build_overlay_specs_opens_rc4_source_without_allow_weak_crypto() {
        // qpdf-parity: RC4 (weak-crypto) overlay sources open unconditionally,
        // because the `--allow-weak-crypto` flag gates weak-crypto *writes*,
        // not reads. `build_overlay_specs` is a read-only inspection open — the
        // same category `run_check` handles — and matches qpdf's silent-accept
        // behavior on RC4 sources (verified against qtest `form-xobject` test 31
        // / uo-7).
        let cli_specs = vec![OverlaySpec {
            kind: OverlayKind::Overlay,
            file: encrypted_fixture("v2-rc4-128-r3.pdf"),
            password: Some("user-v2".into()),
            from: None,
            to: None,
            repeat: None,
        }];

        let built = build_overlay_specs(&cli_specs, false, &PasswordArgs::default()).unwrap();
        assert_eq!(built.len(), 1);
        assert_eq!(built[0].kind, flpdf::OverlayKind::Overlay);
    }

    #[test]
    fn show_object_selector_defaults_generation_like_qpdf() {
        assert!(matches!(
            parse_show_object_selector("1"),
            Ok(ShowObjectSelector::Object(ObjectRef {
                number: 1,
                generation: 0,
            }))
        ));
        assert!(matches!(
            parse_show_object_selector("1,"),
            Ok(ShowObjectSelector::Object(ObjectRef {
                number: 1,
                generation: 0,
            }))
        ));
    }

    #[test]
    fn show_object_selector_integer_errors_match_qpdf() {
        let overflow = qpdf_selector_integer("9223372036854775808").expect_err("i64 overflow");
        assert_eq!(
            overflow.to_string(),
            "overflow/underflow converting 9223372036854775808 to 64-bit integer"
        );
        assert!(
            overflow.downcast_ref::<UsageError>().is_some(),
            "qpdf reports this as a QPDFUsage-class error (thrown from argv parsing, \
             before the input file is opened), so it must route through \
             flpdf-cli's usage_exit path rather than the generic error path"
        );

        // A digit run too long to even fit in the i128 staging type used to
        // detect i64 overflow (rather than merely exceeding i64's range).
        let huge = qpdf_selector_integer("99999999999999999999999999999999999999999999999999")
            .expect_err("digit run exceeding i128");
        assert_eq!(
            huge.to_string(),
            "overflow/underflow converting 99999999999999999999999999999999999999999999999999 to 64-bit integer"
        );
        assert!(huge.downcast_ref::<UsageError>().is_some());

        let narrowing = qpdf_selector_integer("2147483648").expect_err("i32 narrowing overflow");
        assert_eq!(
            narrowing.to_string(),
            "integer out of range converting 2147483648 from a 8-byte signed type to a 4-byte signed type"
        );
        assert!(narrowing.downcast_ref::<UsageError>().is_some());
    }

    #[test]
    fn show_object_selector_parses_before_checking_for_an_input_file() {
        // qpdf's Config::showObject parses the selector during argv parsing,
        // before QPDFJob::run() ever opens an input file, so a usage error in
        // the selector must surface even when no input file was given.
        let error = run_show_object(
            None,
            false,
            &PasswordArgs::default(),
            "2147483648",
            false,
            false,
        )
        .expect_err("overflow selector with no input file");
        assert!(
            error.downcast_ref::<UsageError>().is_some(),
            "got {error} instead of a UsageError -- the missing-input-file check must not \
             run before selector parsing"
        );
    }
}