flpdf-cli 0.9.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
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
#![forbid(unsafe_code)]

mod arg_parser;
mod qpdf_help;

use clap::{Args as ClapArgs, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use flpdf::fix_qdf;
use flpdf::job::{
    AttachmentAddOptions, CheckError, FlattenAnnotationsMode, ImageOptimizationOptions,
    JobExitCode, JsonStreamData, QPDFJob, RemoveUnreferencedResources,
};
use flpdf::pipeline::{FlateAction, Pipeline, PipelineHandle, PlFlate, PlStdioFile};
use flpdf::qutil::same_file as qpdf_same_file;
use flpdf::writer::DecodeLevel as StreamDecodeLevel;
#[cfg(test)]
use flpdf::PasswordWriteNotice;
use flpdf::{
    json_inspect::{DecodeLevel, JsonKey},
    normalize_content_stream, pages, parse_pdf_version, CompressStreams, CopyEncryptionSource,
    EncryptMethod, EncryptParams, Error, Matrix, NewlineBeforeEndstream, ObjectHandle,
    ObjectKeyAlg, ObjectRef, ObjectStreamMode, PageObjectHelper, PasswordMode, Pdf, PdfOpenOptions,
    PdfVersion, PermissionsConfig, PrintPermission, QPDFLogger, R2PermissionsConfig,
    StreamDataMode, UsageError, WriterConfiguration,
};
use flpdf::{
    pages::tree_rebuild::{rebuild_page_tree_with_duplicate_hook, RebuildResult},
    qutil::parse_numrange,
    PageRange,
};
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{BufReader, Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

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

/// CLI-local page-spec input. qpdf keeps this state inside `QPDFJob::Config`;
/// it is not a library-facing page-plan type.
struct CliInputSpec {
    path: PathBuf,
}

impl CliInputSpec {
    fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }
}

struct PipelineWriter {
    pipeline: PipelineHandle,
}

impl PipelineWriter {
    fn new(pipeline: PipelineHandle) -> Self {
        Self { pipeline }
    }
}

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())
    }

    /// `Write::flush` is intentionally a no-op: the PDF writer's pipeline
    /// lifetime is owned by its own output boundary, and the job's JSON
    /// destinations are batched and finished inside the job itself.
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// CLI-owned writer configuration. The library's lower-level option bridge is
/// intentionally private; final CLI output is configured through QPDFJob.
#[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,
    compression_level: Option<i32>,
    progress: bool,
    report_memory_usage: bool,
    static_id: bool,
    deterministic_id: bool,
    static_aes_iv: bool,
    no_original_object_ids: bool,
    input_version_floor: Option<PdfVersion>,
    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,
    password_mode: PasswordMode,
    allow_weak_crypto: bool,
    allow_insecure: bool,
    accessibility_disabled: bool,
}

#[derive(Debug, Clone, Default)]
struct PageLabelOptions {
    set: Option<Vec<Vec<u8>>>,
    remove: bool,
}

/// The qpdf job keeps explicit inline-image externalization separate from the
/// `optimizeImages` option. Preserve that distinction at the CLI boundary so
/// an explicit request can externalize without invoking JPEG optimization, and
/// can override `keepInlineImages` when both transformations are selected
/// (`libqpdf/QPDFJob.cc:2151-2174`).
#[derive(Debug, Clone, Copy, Default)]
struct ImageTransformOptions {
    externalize_inline_images: bool,
    optimize_images: bool,
    image_options: ImageOptimizationOptions,
}

impl ImageTransformOptions {
    fn new(
        externalize_inline_images: bool,
        optimize_images: bool,
        image_options: ImageOptimizationOptions,
    ) -> Self {
        Self {
            externalize_inline_images,
            optimize_images,
            image_options,
        }
    }
}

/// Transformations that qpdf applies before a top-level inspection or
/// attachment operation. Keeping this carrier at the job boundary prevents
/// the CLI from accepting a transform and then silently dropping it before
/// `doInspection` or attachment mutation (`libqpdf/QPDFJob.cc:473,484-491,
/// 2046-2247`).
#[derive(Debug, Clone, Copy)]
struct InspectionTransformOptions<'a> {
    image: ImageTransformOptions,
    generate_appearances: bool,
    flatten_annotations: Option<CliFlattenMode>,
    flatten_rotation: bool,
    rotations: &'a [OsString],
}

impl<'a> InspectionTransformOptions<'a> {
    fn new(
        image: ImageTransformOptions,
        generate_appearances: bool,
        flatten_annotations: Option<CliFlattenMode>,
    ) -> Self {
        Self {
            image,
            generate_appearances,
            flatten_annotations,
            flatten_rotation: false,
            rotations: &[],
        }
    }

    fn with_rotations(mut self, rotations: &'a [OsString]) -> Self {
        self.rotations = rotations;
        self
    }

    fn is_empty(self) -> bool {
        !self.generate_appearances
            && self.flatten_annotations.is_none()
            && !self.flatten_rotation
            && self.rotations.is_empty()
            && !self.image.externalize_inline_images
            && !self.image.optimize_images
    }
}

fn page_label_options(set: Option<&[OsString]>, remove: bool) -> PageLabelOptions {
    PageLabelOptions {
        set: set.map(|specs| {
            specs
                .iter()
                .map(|spec| arg_parser::os_bytes(spec.as_os_str()))
                .collect()
        }),
        remove,
    }
}

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,
            compression_level: None,
            progress: false,
            report_memory_usage: false,
            static_id: false,
            deterministic_id: false,
            static_aes_iv: false,
            no_original_object_ids: false,
            input_version_floor: None,
            min_version: None,
            min_extension_level: None,
            force_version: None,
            force_extension_level: None,
            encrypt: None,
            copy_encryption: None,
            preserve_encryption: true,
            password_mode: PasswordMode::default(),
            allow_weak_crypto: false,
            allow_insecure: false,
            accessibility_disabled: false,
        }
    }
}

#[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);
    }
}

/// Accumulate qpdf's `max_input_version` floor without touching the explicit
/// raw `--min-version` option. qpdf gathers input versions in `QPDFJob` and
/// applies that floor to the writer before applying the explicit minimum
/// (`libqpdf/QPDFJob.cc:1695-1716,2907-2924`).
fn update_input_version_floor<R: Read + Seek>(
    floor: &mut Option<PdfVersion>,
    pdf: &mut Pdf<R>,
) -> CliResult<()> {
    if let Some(source_version) = parse_pdf_version(pdf.version()) {
        // `get_extension_level` clamps to `i32` range and warns on overflow,
        // matching qpdf's `getExtensionLevel` (`libqpdf/QPDF.cc:2328-2346`)
        // that `getVersionAsPDFVersion` calls here; the raw
        // `adobe_extension_level` accessor this replaced kept the full
        // 64-bit value and never warned.
        let candidate = PdfVersion::new(
            source_version.major(),
            source_version.minor(),
            i64::from(pdf.get_extension_level()?),
        );
        if floor.is_none_or(|current| current < candidate) {
            *floor = Some(candidate);
        }
    }
    Ok(())
}

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;
    }
}

/// Build the writer settings shared by top-level rewrite-shaped routes.
///
/// qpdf applies these settings after each top-level transformation, including
/// `--add-attachment`, `--remove-attachment`, and `--copy-attachments-from`
/// (`QPDFJob.cc:484-507,2046-2248,2847-2945`). Keeping the assembly here
/// prevents an operation-specific writer from silently dropping a setting
/// that the canonical rewrite path already honors.
fn top_level_writer_options(
    args: &Cli,
    normalize_content: bool,
    compression_level: Option<i32>,
    version_options: &CliVersionOptions,
) -> WriterOptions {
    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,
        progress: args.progress,
        report_memory_usage: args.report_memory_usage,
        recompress_flate: args.recompress_flate,
        compression_level,
        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,
        newline_before_endstream: newline_before_endstream_setting(args.newline_before_endstream),
        password_mode: args.password.password_mode.into(),
        allow_weak_crypto: args.password.allow_weak_crypto,
        ..WriterOptions::default()
    };
    apply_cli_decode_level(&mut options, args.decode_level);
    apply_cli_version_options(&mut options, 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 => {
                emit_logger_error(format!(
                    "flpdf: --compress-streams must be y or n, got: {:?}\n",
                    other
                ));
                std::process::exit(2);
            }
        }
    }

    apply_encryption_options(
        &mut options,
        EncryptionCliOptions {
            encrypt: args.raw_encrypt.as_deref(),
            encrypt_segments: args.raw_encrypt_segments.as_deref(),
            parsed_encrypt_segments: args.parsed_encrypt_segments.as_deref(),
            copy_encryption: args.copy_encryption.as_deref(),
            encryption_file_password: args.raw_encryption_file_password.as_deref(),
            password_args: &args.password,
            suppress_warnings: args.no_warn,
            last_mode: args.last_encryption_mode,
        },
    );
    if args.decrypt {
        options.preserve_encryption = false;
    }
    options
}

fn parse_compression_level(value: Option<&str>) -> CliResult<Option<i32>> {
    value.map(qpdf_selector_integer).transpose()
}

/// Parse the unsigned image thresholds through the same qpdf `strtoull` /
/// `QIntC::to_uint` boundary used by `QPDFJob::Config::oiMin*` and
/// `iiMinBytes` (`libqpdf/QPDFJob_config.cc:232-234,422-445`).
fn parse_image_uint(value: Option<&str>) -> CliResult<Option<u32>> {
    let Some(value) = value else {
        return Ok(None);
    };
    if value.is_empty() {
        return Ok(Some(0));
    }
    let parsed = parse_qpdf_unsigned_option(value.as_bytes())?;
    // The shared qpdf unsigned conversion rejects values above u32::MAX before
    // returning the usize used by the CLI image options.
    Ok(Some(parsed as u32))
}

fn image_optimization_options(
    keep_inline_images: bool,
    oi_min_width: Option<&str>,
    oi_min_height: Option<&str>,
    oi_min_area: Option<&str>,
    ii_min_bytes: Option<&str>,
) -> CliResult<ImageOptimizationOptions> {
    let mut options = ImageOptimizationOptions::default();
    if let Some(value) = parse_image_uint(oi_min_width)? {
        options.min_width = value;
    }
    if let Some(value) = parse_image_uint(oi_min_height)? {
        options.min_height = value;
    }
    if let Some(value) = parse_image_uint(oi_min_area)? {
        options.min_area = value;
    }
    if let Some(value) = parse_image_uint(ii_min_bytes)? {
        options.inline_min_bytes = value as usize;
    }
    options.keep_inline_images = keep_inline_images;
    Ok(options)
}

/// Apply qpdf's canonical create-stage transformations before a top-level
/// inspection or attachment consumer. The job owns the ordering: image
/// transforms run before `generateAppearancesIfNeeded`, matching
/// `QPDFJob::handleTransformations` (`QPDFJob.cc:2138-2194`).
fn apply_inspection_transformations<R: Read + Seek + 'static>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
    options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    apply_top_level_inspection_transformations(job, pdf, options, verbose, false, false)
}

/// Report donor authentication failures at the CLI boundary while preserving
/// the typed error returned by the library's public job API. qpdf's copy
/// attachment loop lets the donor `processFile` exception escape
/// (`libqpdf/QPDFJob.cc:2089-2100`); `open_job_source` has already retained the
/// failed donor path on the job, so `report_job_error` can render qpdf's
/// path-qualified message without changing `Error::Encrypted` into a byte
/// string for library callers.
fn apply_transformations_for_cli<R: Read + Seek + 'static>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
) -> CliResult<()> {
    match job.apply_transformations(pdf) {
        Ok(()) => Ok(()),
        Err(error) if is_bad_password_error(&error) => {
            job.report_job_error(&error)?;
            Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
        Err(error) => Err(Box::new(error)),
    }
}

/// Apply every create-stage transformation that can accompany a top-level
/// inspection. qpdf performs these mutations before `doInspection`, even
/// though the inspection branch creates no output (`QPDFJob.cc:459-489,
/// 2138-2248`).
fn apply_top_level_inspection_transformations<R: Read + Seek + 'static>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
    options: InspectionTransformOptions<'_>,
    verbose: bool,
    remove_restrictions: bool,
    coalesce_contents: bool,
) -> CliResult<()> {
    configure_top_level_inspection_transformations(
        job,
        options,
        verbose,
        remove_restrictions,
        coalesce_contents,
    )?;
    apply_transformations_for_cli(job, pdf)?;
    Ok(())
}

/// Configure the create-stage transformations that qpdf applies before a
/// top-level inspection. Keeping this separate from the application step lets
/// the full `QPDFJob::create_qpdf` lifecycle own page-selection inspections as
/// well as already-open standalone documents.
fn configure_top_level_inspection_transformations(
    job: &mut QPDFJob,
    options: InspectionTransformOptions<'_>,
    verbose: bool,
    remove_restrictions: bool,
    coalesce_contents: bool,
) -> CliResult<()> {
    if options.is_empty() && !remove_restrictions && !coalesce_contents {
        return Ok(());
    }

    job.set_verbose(verbose);
    {
        let mut configuration = job.config();
        for parameter in options.rotations {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        if remove_restrictions {
            configuration.remove_restrictions();
        }
        if coalesce_contents {
            configuration.coalesce_contents();
        }
        if options.generate_appearances {
            configuration.generate_appearances();
        }
        if let Some(mode) = options.flatten_annotations {
            configuration.flatten_annotations(mode.into());
        }
        if options.flatten_rotation {
            configuration.flatten_rotation();
        }
        if options.image.externalize_inline_images {
            configuration.externalize_inline_images(options.image.image_options.inline_min_bytes);
        }
        if options.image.optimize_images {
            configuration.optimize_images(options.image.image_options);
        }
    }
    Ok(())
}

/// Builds a [`WriterConfiguration`] without normalizing encryption passwords
/// or checking for weak crypto (qpdf's `maybeFixWritePassword` and the
/// weak-crypto refusal that follows it in `QPDFJob::setEncryptionOptions`,
/// `QPDFJob.cc:2655-2723,2748-2761`).
///
/// Callers that pass the result to [`QPDFJob::write_qpdf`] must use this
/// instead of [`writer_configuration`]: `write_qpdf`'s own write stage
/// already performs qpdf's write-time password normalization, notice
/// emission, and weak-crypto refusal in that order (mirroring
/// `setEncryptionOptions`), so calling both would normalize the same
/// password bytes twice — the second pass would reject the already-
/// transcoded bytes from the first as invalid UTF-8 — and would also check
/// weak crypto before normalization instead of after.
fn writer_configuration_unnormalized(
    options: &WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
) -> CliResult<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));
    }
    // qpdf keeps the job's generalized decode default for inspection consumers,
    // but only forwards it to QPDFWriter when decode_level_set is true
    // (`QPDFJob.cc:2847-2875`). Do not infer a writer decode request from the
    // create-stage --generate-appearances transformation.
    if options.decode_level_set {
        configuration.set_decode_level(options.decode_level);
    }
    configuration.set_recompress_flate(options.recompress_flate);
    if let Some(level) = options.compression_level {
        configuration.set_compression_level(level);
    }
    configuration.set_qdf_mode(options.qdf && !linearize);
    configuration.set_linearization(linearize);
    if let Some(path) = linearize_pass1 {
        configuration.set_linearization_pass1_filename(path.to_path_buf());
    }
    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.input_version_floor {
        let (version, extension_level) = version.get_version();
        configuration.set_minimum_pdf_version(version, extension_level);
    }
    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);
    }
    Ok(configuration)
}

/// Emit qpdf's per-password write diagnostics in the order returned by
/// `QPDFJob::maybeFixWritePassword` (`QPDFJob.cc:2696-2710`). The logger is
/// injected so the direct CLI boundary remains fallible under custom sinks.
#[cfg(test)]
fn emit_password_write_notices(
    logger: &QPDFLogger,
    prefix: &str,
    notices: impl IntoIterator<Item = PasswordWriteNotice>,
    verbose: bool,
) -> CliResult<()> {
    for notice in notices {
        match notice {
            PasswordWriteNotice::Info if verbose => {
                logger.info(format!(
                    "{prefix}: automatically converting Unicode password to single-byte encoding as required for 40-bit or 128-bit encryption\n"
                ))?;
            }
            PasswordWriteNotice::Warning => {
                logger.error(format!(
                    "{prefix}: WARNING: supplied password looks like a Unicode password with characters not allowed in passwords for 40-bit and 128-bit encryption; most readers will not be able to open this file with the supplied password. (Use --password-mode=bytes to suppress this warning and use the password anyway.)\n"
                ))?;
            }
            PasswordWriteNotice::None | PasswordWriteNotice::Info => {}
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// qpdf-compatible exit-code infrastructure
//
// 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.
//
// Each subcommand expresses its 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.
// ---------------------------------------------------------------------------

/// The CLI's process exit status.
///
/// The variant names describe what a normal job reports; the numeric values
/// are what actually reaches the shell, and a few subcommands reuse them for
/// their own classification results rather than for errors or warnings --
/// `--is-encrypted` exits 2 for an unencrypted file, and
/// `--requires-password` exits 3 when the supplied password is correct.
/// Each such construction site documents its own meaning.
///
/// - `Ok` = 0: success, no errors or warnings
/// - `Errors` = 2: errors detected (file invalid / unprocessable)
/// - `Warnings` = 3: warnings found but no errors (recoverable issues)
///
/// qpdf correspondence: `qpdf_exit_code_e` from `qpdf/include/qpdf/Constants.h`.
#[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)]
struct CliRawExitError {
    code: ExitCode,
    message: Vec<u8>,
}

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

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

#[derive(Debug)]
struct CliPathError {
    path: Vec<u8>,
    operation: Option<&'static str>,
    message: String,
    source: Box<dyn std::error::Error>,
}

impl std::fmt::Display for CliPathError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(operation) = self.operation {
            write!(formatter, "{operation} ")?;
        }
        write!(
            formatter,
            "{}: {}",
            String::from_utf8_lossy(&self.path),
            self.message
        )
    }
}

impl std::error::Error for CliPathError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.source.as_ref())
    }
}

#[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)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    // Legacy options kept for compatibility.
    #[arg(long, conflicts_with = "output", overrides_with = "check")]
    check: bool,
    /// Suppress warning delivery while retaining qpdf's warning exit status.
    #[arg(long)]
    no_warn: bool,
    /// Exit 0 when the job has warnings (`QPDFJob::Config::warningExitZero`).
    #[arg(long = "warning-exit-0")]
    warning_exit_zero: bool,
    /// Check whether the input's linearization hint tables are correct
    /// (qpdf --check-linearization).
    #[arg(
        long = "check-linearization",
        overrides_with = "check_linearization",
        conflicts_with_all = [
            "json",
            "json_output",
        ]
    )]
    check_linearization: bool,
    #[arg(long)]
    repair: bool,
    #[command(flatten)]
    password: PasswordArgs,
    #[arg(
        long,
        require_equals = true,
        conflicts_with = "output",
        overrides_with = "show_object"
    )]
    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", overrides_with = "show_npages")]
    show_npages: bool,
    #[arg(long, conflicts_with = "output", overrides_with = "show_pages")]
    show_pages: bool,
    /// Include image XObject details in `--show-pages` output (qpdf
    /// `--with-images`). This is a modifier and does not itself select an
    /// inspection mode.
    #[arg(long = "with-images")]
    with_images: bool,
    #[arg(long, conflicts_with = "output", overrides_with = "show_xref")]
    show_xref: bool,
    #[arg(long, conflicts_with = "output", overrides_with = "show_linearization")]
    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",
        overrides_with = "show_encryption"
    )]
    show_encryption: bool,

    /// Exit 0 when INPUT is encrypted and 2 otherwise (qpdf
    /// `--is-encrypted`). This is an inspection-only top-level argv option;
    /// it does not authenticate the input or produce output.
    #[arg(
        long = "is-encrypted",
        conflicts_with_all = ["requires_password", "output"]
    )]
    is_encrypted: bool,

    /// Exit 3 when INPUT is encrypted and the supplied password opens it, 0
    /// when another password is required, and 2 when it is not encrypted
    /// (qpdf `--requires-password`).
    #[arg(
        long = "requires-password",
        conflicts_with_all = ["is_encrypted", "output"]
    )]
    requires_password: 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",
        action = clap::ArgAction::Append,
        value_name = "PATH",
        require_equals = true
    )]
    job_json_file: Vec<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 remains exclusive with inspection modes that claim the
    // no-output branch and with the OUTPUT positional contract. qpdf still
    // accepts the writer/attachment combinations covered below: writer-only
    // settings are ignored by JSON, while create-stage transformations and
    // attachment mutations are applied by the same Job before serialization.
    #[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",
              "show_object",
              "show_npages", "show_pages", "show_xref", "show_linearization",
              "show_encryption",
              "is_encrypted", "requires_password",
              "list_attachments", "show_attachment",
          ],
          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",
        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,
        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"],
        conflicts_with_all = [
            "check",
            "show_object",
            "show_npages", "show_pages", "show_xref", "show_linearization",
            "show_encryption",
            "is_encrypted", "requires_password",
            "list_attachments", "show_attachment",
        ],
        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",
        require_equals = true,
        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",
        require_equals = true,
        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",
        require_equals = true,
        overrides_with = "json_stream_data",
        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",
        require_equals = true,
        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<OsString>,

    // 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,

    /// Replace the input file with the rewritten output (qpdf
    /// `--replace-input`). The canonical QPDFJob owns the temporary output,
    /// source close, backup, rename, and warning lifecycle.
    #[arg(long = "replace-input")]
    replace_input: 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", require_equals = true)]
    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", require_equals = true)]
    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.
    /// If both this flag and `--static-id` are supplied, qpdf gives
    /// `--static-id` precedence for the emitted ID. The deterministic setting
    /// still makes the combination incompatible with encrypted output.
    #[arg(long = "deterministic-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,
    /// Remove digital-signature restrictions while preserving authenticated
    /// source encryption (top-level alias of `flpdf rewrite
    /// --remove-restrictions`; qpdf `--remove-restrictions` equivalent).
    /// Combine with `--decrypt` to strip encryption too. Does NOT bypass
    /// authentication.
    // qpdf applies this create-stage mutation before `doInspection`, so the
    // supported inspection combinations are routed through the combined Job
    // inspection boundary.
    #[arg(long = "remove-restrictions")]
    remove_restrictions: bool,
    /// Remove explicit page labels from the output (qpdf-compatible).
    #[arg(long = "remove-page-labels")]
    remove_page_labels: bool,
    /// Set page labels using qpdf's option-table grammar. Terminate the
    /// specification list with `--`.
    #[arg(
        long = "set-page-labels",
        num_args = 0..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "SPEC..."
    )]
    set_page_labels: Option<Vec<OsString>>,
    /// 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). Both flags are silent when the operation succeeds.
    ///
    /// Relationship with `--remove-restrictions`: this flag removes source
    /// encryption, while `--remove-restrictions` preserves it and only removes
    /// digital-signature restrictions. Neither flag invents a success diagnostic.
    // qpdf accepts --decrypt with the output-free --check and --show-npages
    // consumers; those writer settings are ignored when no output is created.
    // The same create/write boundary accepts it with every output-free
    // inspection consumer.
    #[arg(long = "decrypt")]
    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",
        require_equals = true,
        overrides_with = "compress_streams"
    )]
    compress_streams: Option<String>,
    /// Re-encode streams that are already a lone `/FlateDecode` (qpdf
    /// `--recompress-flate`).
    #[arg(long = "recompress-flate")]
    recompress_flate: bool,
    /// Set the zlib compression level used when emitting Flate streams
    /// (qpdf `--compression-level=level`).
    #[arg(
        long = "compression-level",
        value_name = "LEVEL",
        require_equals = true
    )]
    compression_level: 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,
        require_equals = true,
        overrides_with = "decode_level"
    )]
    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,
        require_equals = true,
        default_value_t = CliObjectStreamMode::Preserve,
        overrides_with = "object_streams"
    )]
    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,
        require_equals = true,
        overrides_with = "stream_data"
    )]
    stream_data: Option<CliStreamDataMode>,
    /// Insert an extra newline before each `endstream` keyword (qpdf
    /// `--newline-before-endstream`).
    ///
    /// qpdf registers this as a bare flag, so an attached `=value` of any
    /// spelling is discarded and the flag's presence alone enables it.
    /// Omitting the flag keeps qpdf's default framing, where exactly
    /// `/Length` bytes sit between `stream` and `endstream`.
    // `overrides_with` self is clap's idiom for accepting repeated
    // occurrences. qpdf re-fires the bare handler on every occurrence
    // (`QPDFArgParser.cc:535-537`), so `--newline-before-endstream` twice is
    // accepted and means the same as once; without this clap rejects the
    // second occurrence as "cannot be used multiple times".
    #[arg(
        long = "newline-before-endstream",
        overrides_with = "newline_before_endstream"
    )]
    newline_before_endstream: bool,
    /// `qpdf --linearize-pass1=PATH` compatibility flag. Writes the
    /// linearization writer's distinct pass-1 intermediate file.
    #[arg(long = "linearize-pass1", require_equals = true)]
    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,

    /// Remove unreferenced page-resource entries using qpdf's job policy.
    ///
    /// `auto` (the default) runs qpdf's shared-resource heuristic, `yes`
    /// always runs the page-level pruning pass, and `no` leaves `/Resources`
    /// entries untouched. The policy is consumed by page-copy and split jobs;
    /// plain rewrites accept the option but do not prune resource entries,
    /// matching qpdf 11.9.0.
    #[arg(
        long = "remove-unreferenced-resources",
        value_enum,
        require_equals = true,
        default_value_t = CliRemoveUnreferencedResources::Auto,
        help = "Remove unreferenced page resources (qpdf default: auto)",
        overrides_with = "remove_unreferenced_resources"
    )]
    remove_unreferenced_resources: CliRemoveUnreferencedResources,

    /// 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,
        require_equals = true,
        help = "Normalize page content streams (qpdf default: n; --qdf default: y)",
        overrides_with = "normalize_content"
    )]
    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. It may be combined with `--linearize`; qpdf applies this
    /// create-stage transformation before constructing its linearized writer.
    /// The top-level JSON route also applies this create-stage transformation
    /// before serializing, matching qpdf's `createQPDF`/`writeQPDF` boundary.
    /// Output-free inspection conflicts themselves remain explicit because
    /// qpdf's inspection consumers do not accept an output file.
    #[arg(long = "coalesce-contents")]
    coalesce_contents: bool,

    /// Flatten annotations into page content (top-level alias of
    /// `rewrite --flatten-annotations`; qpdf `--flatten-annotations`
    /// equivalent). Values are `all`, `screen`, or `print`. qpdf applies this
    /// after page selection when `--pages` is present.
    // JSON output is a create-stage consumer too. The transformation is
    // applied by `run_json` before the JSON serializer, so qpdf-compatible
    // combinations such as `--flatten-annotations=all --json-output=2` must
    // remain reachable.
    #[arg(
        long = "flatten-annotations",
        value_enum,
        value_name = "MODE",
        require_equals = true,
        overrides_with = "flatten_annotations",
        help = "Flatten annotations into page content; MODE is all, screen, or print",
        overrides_with = "flatten_annotations"
    )]
    flatten_annotations: Option<CliFlattenMode>,

    /// Flatten page rotation by baking `/Rotate` into page content (qpdf
    /// `--flatten-rotation`). This is a create-stage transformation and is
    /// intentionally compatible with top-level `--rotate`, linearization,
    /// and split-page output; qpdf applies it in `handleTransformations`
    /// after rotation and before `writeQPDF` (`QPDFJob.cc:469-473,2190-2194`).
    #[arg(
        long = "flatten-rotation",
        help = "Flatten page rotation by baking /Rotate into content"
    )]
    flatten_rotation: bool,

    /// Generate appearance streams for form fields that need them (qpdf
    /// `--generate-appearances`). qpdf runs this inside
    /// `handleTransformations`, which `createQPDF` calls before `writeQPDF`
    /// dispatches to `doInspection` (`QPDFJob.cc:473,484-491,2178-2180`), and
    /// `checkConfiguration` (`QPDFJob.cc:566-641`) rejects no combination, so
    /// the read-only inspection modes accept this flag and observe the
    /// transformed document. It remains available after page-operation modes,
    /// whose selected document is transformed before writing. Attachment
    /// inspection and rewrite routes use the same canonical job phase. Combining
    /// with `--linearize` is supported (threaded through the linearize branch
    /// of `run_rewrite`), so it is intentionally absent from this list.
    #[arg(long = "generate-appearances")]
    generate_appearances: bool,

    /// Recompress eligible non-JPEG images as DCT/JPEG (qpdf
    /// `--optimize-images`). Inspection and attachment modes may be combined
    /// with this flag like qpdf, which rejects neither combination: the image
    /// flags only set their own members (`QPDFJob_config.cc:443-447`) and
    /// `checkConfiguration` (`QPDFJob.cc:566-641`) has no branch that reads
    /// them. qpdf runs the transformation for those modes too -- `createQPDF`
    /// calls `handleTransformations` before `writeQPDF` picks the inspection
    /// branch (`QPDFJob.cc:473,484-491`), and the attachment phases run inside
    /// the same `handleTransformations` after the image phase (`:2151-2177`,
    /// `:2230-2247`). The top-level inspection and attachment routes both
    /// thread the image options through their own open/transform boundary.
    /// `--pages`/`--rotate`/`--split-pages`/`--empty`/`--json`/
    /// `--json-output` are intentionally absent: all of those routes are
    /// already threaded through (see `top_level_image_options` at each call
    /// site).
    #[arg(long = "optimize-images")]
    optimize_images: bool,
    /// Convert inline images into ordinary Image XObjects
    /// (qpdf `--externalize-inline-images`). This is a distinct transform
    /// from `--optimize-images`; when both are selected the shared image phase
    /// externalizes first and then optimizes reachable Image XObjects.
    /// Inspection and attachment modes may be combined with this flag like
    /// qpdf. As with `--optimize-images`, the top-level inspection routes run
    /// the transformation before their report (`QPDFJob.cc:473,2151-2155`), and
    /// the attachment routes run it in the same `handleTransformations` before
    /// the attachment phases (`:2230-2247`).
    #[arg(long = "externalize-inline-images")]
    externalize_inline_images: bool,
    /// Exclude inline images from the optimization pass.
    #[arg(long = "keep-inline-images")]
    keep_inline_images: bool,
    /// Minimum image width for `--optimize-images` (qpdf default: 128).
    #[arg(long = "oi-min-width", value_name = "WIDTH", require_equals = true)]
    oi_min_width: Option<String>,
    /// Minimum image height for `--optimize-images` (qpdf default: 128).
    #[arg(long = "oi-min-height", value_name = "HEIGHT", require_equals = true)]
    oi_min_height: Option<String>,
    /// Minimum image area for `--optimize-images` (qpdf default: 16384).
    #[arg(long = "oi-min-area", value_name = "AREA", require_equals = true)]
    oi_min_area: Option<String>,
    /// Minimum inline-image payload to externalize (qpdf default: 1024).
    #[arg(long = "ii-min-bytes", value_name = "BYTES", require_equals = true)]
    ii_min_bytes: Option<String>,

    // ── Page-operation flags ──────────────────────────────────────────────
    // 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, 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<OsString>,

    /// 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<OsString>,

    // ── Attachment flags ──────────────────────────────────────────────────
    // 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 = 0..,
        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<OsString>,

    /// Remove an attachment by key (qpdf --remove-attachment compatible).
    ///
    /// KEY is the name-tree key used when the attachment was added. The flag
    /// may be repeated; keys are removed in argv order.
    #[arg(
        long = "remove-attachment",
        value_name = "KEY",
        require_equals = true,
        help = "Remove the embedded file with the given key (qpdf --remove-attachment)"
    )]
    remove_attachment: Vec<OsString>,

    /// List all embedded-file attachments (qpdf --list-attachments compatible).
    #[arg(
        long = "list-attachments",
        conflicts_with = "output",
        overrides_with = "list_attachments",
        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,

    /// Report approximate write progress (qpdf --progress).
    #[arg(long = "progress")]
    progress: bool,

    /// Report the maximum amount of memory used (qpdf --report-memory-usage).
    #[arg(long = "report-memory-usage")]
    report_memory_usage: 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",
        require_equals = true,
        overrides_with = "show_attachment",
        help = "Extract the embedded file with the given key to stdout \
                (qpdf --show-attachment)"
    )]
    show_attachment: Option<OsString>,

    /// 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<OsString>,

    /// 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 = 0..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "USER-PW OWNER-PW KEY-LEN [sub-flags]",
        help = "Encrypt output (qpdf --encrypt compatible): \
                USER-PW OWNER-PW KEY-LEN [sub-flags] --"
    )]
    encrypt: Option<Vec<OsString>>,
    #[arg(skip)]
    raw_encrypt: Option<Vec<Vec<u8>>>,
    #[arg(skip)]
    raw_encrypt_segments: Option<Vec<Vec<Vec<u8>>>>,
    #[arg(skip)]
    parsed_encrypt_segments: Option<Vec<ParsedEncryptSegment>>,
    #[arg(skip)]
    last_encryption_mode: Option<EncryptionMode>,

    /// 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).  The writer accepts the
    /// Standard handler schemes that qpdf's `copyEncryptionParameters` emits:
    /// V=1/V=2 RC4, V=4 canonicalized to AESV2, and V=5 AESV3.
    ///
    /// `--linearize` may be combined with this option; qpdf supports copying
    /// encryption into a linearized output. When this option is combined with
    /// `--decrypt` or `--encrypt`, the last option in argv order wins, like
    /// qpdf's Config setters.
    #[arg(
        long = "copy-encryption",
        value_name = "FILE",
        require_equals = true,
        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",
        require_equals = true,
        requires = "copy_encryption",
        help = "User password to open the donor PDF for --copy-encryption"
    )]
    encryption_file_password: Option<OsString>,
    #[arg(skip)]
    raw_encryption_file_password: Option<Vec<u8>>,

    #[arg(skip)]
    raw_copy_attachments_from: Option<Vec<Vec<Vec<u8>>>>,

    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 {
    /// Manage whether qpdf keeps secondary `--pages` input files open
    /// (`--keep-files-open=y|n`). When omitted, qpdf selects the value from
    /// the distinct page-spec source count and [`Self::keep_files_open_threshold`].
    #[arg(
        long = "keep-files-open",
        value_enum,
        require_equals = true,
        overrides_with = "keep_files_open"
    )]
    keep_files_open: Option<CliYesNo>,

    /// Distinct page-spec source count at which qpdf automatically switches
    /// `--keep-files-open` off (default 200).
    #[arg(
        long = "keep-files-open-threshold",
        value_name = "COUNT",
        require_equals = true
    )]
    keep_files_open_threshold: Option<String>,

    /// 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<OsString>,
    #[arg(skip)]
    raw_pages: Option<Vec<Vec<u8>>>,
    #[arg(skip)]
    parsed_page_specs: Option<Vec<PageSegmentSpec>>,

    /// Rotate pages by a multiple of 90 degrees (qpdf `--rotate`).
    ///
    /// Form: `[+|-]angle[:page-range]` where angle ∈ {0,90,180,270}.
    /// Repeatable; duplicate raw ranges use qpdf's last-write-wins map and
    /// distinct ranges are applied in lexical 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]",
        require_equals = true,
        help = "Rotate pages by 0/90/180/270 degrees (qpdf --rotate); repeatable"
    )]
    rotate: Vec<OsString>,

    /// 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,
        action = clap::ArgAction::Append,
        default_missing_value = "1",
        require_equals = true,
        value_name = "N[,M,...]",
        help = "Collate --pages selections in groups of N[,M,...] (qpdf --collate[=n[,m,...]], default 1)"
    )]
    collate: Vec<String>,

    /// `qpdf --empty` — use a new empty document as the primary input for
    /// rewrite, inspection, or `--pages` processing.
    #[arg(
        long = "empty",
        help = "(qpdf --empty) use an empty document as the primary input"
    )]
    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(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(
        name = "zlib-flate",
        about = "Compress or uncompress a raw zlib stream on stdin/stdout"
    )]
    ZlibFlate(ZlibFlateCommand),
    #[command(about = "Rewrite the input PDF to a normalized output")]
    Rewrite(RewriteCommand),
    #[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 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,
}

/// Args for the qpdf `zlib-flate` utility surface.
#[derive(Debug, ClapArgs)]
struct ZlibFlateCommand {
    /// `-uncompress`, `-compress`, or `-compress=n`.
    #[arg(value_name = "MODE", allow_hyphen_values = true, num_args = 0..)]
    modes: Vec<OsString>,
}

#[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. When
    /// combined with `--static-id`, qpdf gives `--static-id` precedence for
    /// the emitted ID. Any use of this flag remains 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")]
    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,
    /// Remove digital-signature restrictions while preserving authenticated
    /// source encryption (qpdf `--remove-restrictions` equivalent). Combine
    /// with `--decrypt` to strip encryption too.
    ///
    /// A normal rewrite preserves authenticated source encryption. This flag
    /// removes qpdf's digital-signature restrictions without inventing a
    /// success diagnostic. It does NOT bypass authentication.
    ///
    /// See `--decrypt` for the silent qpdf-compatible encryption-removal flag.
    #[arg(long = "remove-restrictions")]
    remove_restrictions: bool,
    /// Remove explicit page labels from the output (qpdf-compatible).
    #[arg(long = "remove-page-labels")]
    remove_page_labels: bool,
    /// Set page labels using qpdf's option-table grammar. Terminate the
    /// specification list with `--`.
    #[arg(
        long = "set-page-labels",
        num_args = 0..,
        value_terminator = "--",
        allow_hyphen_values = true,
        value_name = "SPEC..."
    )]
    set_page_labels: Option<Vec<OsString>>,
    /// 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`: this flag removes source
    /// encryption, while `--remove-restrictions` preserves it and only removes
    /// digital-signature restrictions. Neither flag invents a success 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 = 0..,
        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: Option<Vec<OsString>>,
    #[arg(skip)]
    raw_encrypt: Option<Vec<Vec<u8>>>,
    #[arg(skip)]
    parsed_encrypt_segments: Option<Vec<ParsedEncryptSegment>>,
    /// 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).  The writer accepts the
    /// Standard handler schemes that qpdf's `copyEncryptionParameters` emits:
    /// V=1/V=2 RC4, V=4 canonicalized to AESV2, and V=5 AESV3.
    ///
    /// 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",
        require_equals = true,
        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",
        require_equals = true,
        requires = "copy_encryption",
        help = "User password to open the donor PDF for --copy-encryption"
    )]
    encryption_file_password: Option<OsString>,
    #[arg(skip)]
    raw_encryption_file_password: Option<Vec<u8>>,

    #[arg(skip)]
    raw_copy_attachments_from: Option<Vec<Vec<Vec<u8>>>>,
    /// 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", require_equals = true)]
    min_version: Option<String>,
    /// Force the output PDF version header to exactly this value.
    ///
    /// Overrides the source version and every computed minimum, even when the
    /// file uses features that version does not cover.
    /// Mirrors `qpdf --force-version`.
    #[arg(long = "force-version", require_equals = true)]
    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, require_equals = true, default_value_t = CliObjectStreamMode::Preserve, overrides_with = "object_streams")]
    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,
        require_equals = true,
        help = "Compress output streams with FlateDecode (qpdf default: y)",
        overrides_with = "compress_streams"
    )]
    compress_streams: Option<CliYesNo>,

    /// Control which qpdf stream filters are decoded during rewrite.
    #[arg(
        long = "decode-level",
        value_enum,
        require_equals = true,
        overrides_with = "decode_level"
    )]
    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,
        require_equals = true,
        help = "Normalize page content streams (qpdf default: n)",
        overrides_with = "normalize_content"
    )]
    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, require_equals = true,
          default_value_t = CliRemoveUnreferencedResources::Auto,
          help = "Remove unreferenced /Resources entries (qpdf default: auto)",
          overrides_with = "remove_unreferenced_resources")]
    remove_unreferenced_resources: CliRemoveUnreferencedResources,

    /// Insert an extra newline before each `endstream` keyword
    /// (qpdf `--newline-before-endstream`).
    ///
    /// qpdf registers this as a bare flag, so every attached `=value`
    /// spelling — `=y`, `=n`, or anything else — is discarded and the flag's
    /// presence alone enables it. When enabled, exactly one `\n` is written
    /// before `endstream`.
    ///
    /// Omitting the flag keeps qpdf's default framing, where exactly
    /// `/Length` bytes sit between `stream` and `endstream`. That default is
    /// required for byte-identical qpdf-equivalent rewrites.
    ///
    /// Only affects the full-rewrite path.
    // `overrides_with` self is clap's idiom for accepting repeated
    // occurrences. qpdf re-fires the bare handler on every occurrence
    // (`QPDFArgParser.cc:535-537`), so `--newline-before-endstream` twice is
    // accepted and means the same as once; without this clap rejects the
    // second occurrence as "cannot be used multiple times".
    #[arg(
        long = "newline-before-endstream",
        help = "For an extra newline before endstream",
        overrides_with = "newline_before_endstream"
    )]
    newline_before_endstream: bool,

    /// 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,
        require_equals = true,
        overrides_with = "stream_data"
    )]
    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,

    /// Set the zlib compression level used when emitting Flate streams
    /// (qpdf `--compression-level=level`).
    #[arg(
        long = "compression-level",
        value_name = "LEVEL",
        require_equals = true
    )]
    compression_level: Option<String>,

    /// 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",
        require_equals = true,
        help = "Flatten annotations into page content; MODE is all, screen, or print",
        overrides_with = "flatten_annotations"
    )]
    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,

    /// Recompress eligible non-JPEG images as DCT/JPEG (qpdf
    /// `--optimize-images`).
    #[arg(long = "optimize-images")]
    optimize_images: bool,
    /// Convert inline images into ordinary Image XObjects before later image
    /// transformations (qpdf `--externalize-inline-images`).
    #[arg(long = "externalize-inline-images")]
    externalize_inline_images: bool,
    /// Exclude inline images from the optimization pass.
    #[arg(long = "keep-inline-images")]
    keep_inline_images: bool,
    /// Minimum image width for `--optimize-images` (qpdf default: 128).
    #[arg(long = "oi-min-width", value_name = "WIDTH", require_equals = true)]
    oi_min_width: Option<String>,
    /// Minimum image height for `--optimize-images` (qpdf default: 128).
    #[arg(long = "oi-min-height", value_name = "HEIGHT", require_equals = true)]
    oi_min_height: Option<String>,
    /// Minimum image area for `--optimize-images` (qpdf default: 16384).
    #[arg(long = "oi-min-area", value_name = "AREA", require_equals = true)]
    oi_min_area: Option<String>,
    /// Minimum inline-image payload to externalize (qpdf default: 1024).
    #[arg(long = "ii-min-bytes", value_name = "BYTES", require_equals = true)]
    ii_min_bytes: Option<String>,

    /// 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 ──────────────────────────────────────────
    // 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<OsString>,

    /// 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<OsString>,

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

    /// Report approximate write progress (qpdf --progress).
    #[arg(long = "progress")]
    progress: bool,

    /// Report the maximum amount of memory used (qpdf --report-memory-usage).
    #[arg(long = "report-memory-usage")]
    report_memory_usage: 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 {
    /// Delegate qpdf's mode-to-mask mapping to the canonical job boundary.
    #[cfg(test)]
    fn flags(self) -> (i64, i64) {
        FlattenAnnotationsMode::from(self).qpdf_flags()
    }
}

impl From<CliFlattenMode> for FlattenAnnotationsMode {
    fn from(value: CliFlattenMode) -> Self {
        match value {
            CliFlattenMode::All => Self::All,
            CliFlattenMode::Screen => Self::Screen,
            CliFlattenMode::Print => Self::Print,
        }
    }
}

/// 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,
    }
}

/// Map `--newline-before-endstream` flag presence onto the writer setting.
///
/// qpdf registers the option through `QPDFArgParser::addBare`
/// (`libqpdf/qpdf/auto_job_init.hh:58`), which leaves `parameter_needed`
/// false and `choices` empty (`libqpdf/QPDFArgParser.cc:99-103`). The
/// dispatch loop only rejects a supplied parameter when `choices` is
/// non-empty (`libqpdf/QPDFArgParser.cc:505-534`), so any `=value` suffix is
/// parsed off and discarded before the bare handler fires. Flag presence is
/// therefore the only input, and flag absence leaves qpdf's default framing.
fn newline_before_endstream_setting(flag: bool) -> NewlineBeforeEndstream {
    if flag {
        NewlineBeforeEndstream::Yes
    } else {
        NewlineBeforeEndstream::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,
    #[arg(skip)]
    verbose: bool,
    #[arg(skip)]
    raw_password: Option<Vec<u8>>,
    /// Password bytes for encrypted PDFs.
    #[arg(long, require_equals = true)]
    password: Option<OsString>,
    /// File containing password bytes. Only the first LF-delimited line is
    /// used; a trailing CR before that LF is stripped. `-` reads from stdin.
    #[arg(long = "password-file", value_name = "PATH", require_equals = true)]
    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, require_equals = true, default_value_t = CliPasswordMode::Auto, overrides_with = "password_mode")]
    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,
}

impl PasswordArgs {
    fn password_bytes(&self) -> Option<Vec<u8>> {
        self.raw_password.clone().or_else(|| {
            self.password
                .as_ref()
                .map(|password| arg_parser::os_bytes(password))
        })
    }

    fn set_password_bytes(&mut self, password: Option<Vec<u8>>) {
        self.raw_password = password.clone();
        self.password = password.map(|password| arg_parser::os_string_from_bytes(&password));
    }
}

#[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;
    }
    emit_logger_error(
        "flpdf: warning: --static-id is for testing only and must not be used for production output\n",
    );
}

fn preprocess_qpdf_args<T: Into<OsString>>(args: Vec<T>) -> CliResult<PreprocessedArgs> {
    let args = args.into_iter().map(Into::into).collect();
    let mut segment_handler = QpdfSegmentHandler::default();
    let parsed = arg_parser::ArgParser::from_command(cli_command())
        .parse_os_with_handler(args, &mut segment_handler)?;
    let QpdfSegmentHandler {
        overlay_specs,
        page_specs,
        encrypt_segments,
        ..
    } = segment_handler;
    let arg_parser::ParsedArgs {
        residual_args,
        original_residual_args,
        raw_residual_args,
        raw_named_segments,
        native_subcommand_mode,
        expanded_arg_count,
        first_unknown_option,
        ..
    } = parsed;
    let mut attachment_segments = Vec::new();
    let mut raw_encrypt = None;
    let mut raw_encrypt_segments = Vec::new();
    let mut raw_pages = None;
    let mut raw_copy_attachments_from = Vec::new();
    let password_file_is_last = password_file_is_last(&raw_residual_args);

    for segment in raw_named_segments {
        let option = segment.option;
        let tokens = segment
            .tokens
            .into_iter()
            .map(|token| token.as_bytes().to_vec())
            .collect::<Vec<_>>();
        match option.as_str() {
            "overlay" | "underlay" => {}
            "add-attachment" => attachment_segments.push(tokens),
            "encrypt" => {
                raw_encrypt_segments.push(tokens.clone());
                raw_encrypt = Some(tokens);
            }
            "pages" => raw_pages = Some(tokens),
            "copy-attachments-from" => {
                // qpdf accumulates every --copy-attachments-from group and
                // copies from all of them (`QPDFJob.hh:683`,
                // `QPDFJob_config.cc:825-833`, `QPDFJob.cc:2089-2100`).
                raw_copy_attachments_from.push(tokens)
            }
            _ => {}
        }
    }

    Ok(PreprocessedArgs {
        residual_args,
        raw_residual_args: raw_residual_args.clone(),
        original_residual_args,
        native_subcommand_mode,
        expanded_arg_count,
        first_unknown_option,
        overlay_specs,
        attachment_segments,
        raw_overrides: RawCliOverrides {
            password: (!password_file_is_last)
                .then(|| raw_option_value(&raw_residual_args, "password"))
                .flatten(),
            password_file_is_last,
            encryption_file_password: raw_option_value(
                &raw_residual_args,
                "encryption-file-password",
            ),
            raw_encrypt,
            raw_pages,
            parsed_page_specs: page_specs,
            raw_encrypt_segments: (!raw_encrypt_segments.is_empty())
                .then_some(raw_encrypt_segments),
            parsed_encrypt_segments: (!encrypt_segments.is_empty()).then_some(encrypt_segments),
            last_encryption_mode: last_encryption_mode(&raw_residual_args),
            raw_copy_attachments_from: (!raw_copy_attachments_from.is_empty())
                .then_some(raw_copy_attachments_from),
        },
    })
}

fn password_file_is_last(args: &[arg_parser::RawArg]) -> bool {
    let mut last_is_file = false;
    let mut seen = false;
    let mut index = 1;
    while index < args.len() {
        let bytes = args[index].as_bytes();
        if bytes == b"--" {
            break;
        }
        if is_named_segment_option(bytes) {
            index += 1;
            while index < args.len() && args[index].as_bytes() != b"--" {
                index += 1;
            }
            index += usize::from(index < args.len());
            continue;
        }
        if bytes == b"--password" || bytes.starts_with(b"--password=") {
            seen = true;
            last_is_file = false;
        } else if bytes == b"--password-file" || bytes.starts_with(b"--password-file=") {
            seen = true;
            last_is_file = true;
        }
        index += 1;
    }
    seen && last_is_file
}

fn raw_option_value(args: &[arg_parser::RawArg], name: &str) -> Option<Vec<u8>> {
    let mut attached_prefix = b"--".to_vec();
    attached_prefix.extend_from_slice(name.as_bytes());
    let mut separate_option = b"--".to_vec();
    separate_option.extend_from_slice(name.as_bytes());
    let mut found = None;
    let mut index = 1;
    while index < args.len() {
        let bytes = args[index].as_bytes();
        if bytes == b"--" {
            break;
        }
        if is_named_segment_option(bytes) {
            index += 1;
            while index < args.len() && args[index].as_bytes() != b"--" {
                index += 1;
            }
            index += usize::from(index < args.len());
            continue;
        }
        if let Some(value) = bytes
            .strip_prefix(attached_prefix.as_slice())
            .and_then(|value| {
                value
                    .first()
                    .is_some_and(|byte| *byte == b'=')
                    .then(|| value[1..].to_vec())
            })
        {
            found = Some(value);
        } else if bytes == separate_option.as_slice() {
            if let Some(value) = args.get(index + 1) {
                found = Some(value.as_bytes().to_vec());
                index += 1;
            }
        }
        index += 1;
    }
    found
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EncryptionMode {
    Decrypt,
    Encrypt,
    CopyEncryption,
}

fn last_encryption_mode(args: &[arg_parser::RawArg]) -> Option<EncryptionMode> {
    let mut mode = None;
    for arg in args.iter().skip(1) {
        let bytes = arg.as_bytes();
        match bytes {
            b"--decrypt" => mode = Some(EncryptionMode::Decrypt),
            b"--encrypt" => mode = Some(EncryptionMode::Encrypt),
            bytes
                if bytes
                    .strip_prefix(b"--copy-encryption")
                    .is_some_and(|suffix| suffix.is_empty() || suffix[0] == b'=') =>
            {
                mode = Some(EncryptionMode::CopyEncryption);
            }
            _ => {}
        }
    }
    mode
}

fn is_named_segment_option(bytes: &[u8]) -> bool {
    arg_parser::is_named_segment_option(bytes)
}

fn raw_os_args(args: &[OsString]) -> Vec<Vec<u8>> {
    args.iter().map(|arg| arg_parser::os_bytes(arg)).collect()
}

fn apply_raw_overrides(args: &mut Cli, overrides: RawCliOverrides) {
    let RawCliOverrides {
        password,
        password_file_is_last,
        encryption_file_password,
        raw_encrypt,
        raw_encrypt_segments,
        raw_pages,
        parsed_page_specs,
        parsed_encrypt_segments,
        last_encryption_mode,
        raw_copy_attachments_from,
    } = overrides;
    args.password.raw_password = password.clone();
    if password_file_is_last {
        args.password.password = None;
    }
    args.raw_encryption_file_password = encryption_file_password.clone().or_else(|| {
        args.encryption_file_password
            .as_ref()
            .map(|value| arg_parser::os_bytes(value))
    });
    args.last_encryption_mode = last_encryption_mode;
    args.raw_encrypt =
        raw_encrypt.or_else(|| args.encrypt.as_ref().map(|tokens| raw_os_args(tokens)));
    args.raw_encrypt_segments = raw_encrypt_segments;
    args.parsed_encrypt_segments = parsed_encrypt_segments.clone();
    args.page_ops.raw_pages = raw_pages
        .or_else(|| (!args.page_ops.pages.is_empty()).then(|| raw_os_args(&args.page_ops.pages)));
    args.page_ops.parsed_page_specs = parsed_page_specs.clone();
    args.raw_copy_attachments_from = raw_copy_attachments_from.or_else(|| {
        (!args.copy_attachments_from.is_empty())
            .then(|| vec![raw_os_args(&args.copy_attachments_from)])
    });

    if let Some(command) = args.command.as_mut() {
        match command {
            Commands::Check(command) => {
                command.password.raw_password = password.clone();
                if password_file_is_last {
                    command.password.password = None;
                }
            }
            Commands::Pages(command) => {
                command.password.raw_password = password.clone();
                if password_file_is_last {
                    command.password.password = None;
                }
            }
            Commands::Qdf(command) => {
                command.password.raw_password = password.clone();
                if password_file_is_last {
                    command.password.password = None;
                }
            }
            Commands::ShowEncryption(command)
            | Commands::RequiresPassword(command)
            | Commands::ShowEncryptionKey(command) => {
                command.password.raw_password = password.clone();
                if password_file_is_last {
                    command.password.password = None;
                }
            }
            Commands::Rewrite(command) => {
                command.password.raw_password = password.clone();
                if password_file_is_last {
                    command.password.password = None;
                }
                command.raw_encryption_file_password = args.raw_encryption_file_password.clone();
                command.raw_encrypt = args.raw_encrypt.clone();
                command.parsed_encrypt_segments = args.parsed_encrypt_segments.clone();
                command.page_ops.raw_pages = args.page_ops.raw_pages.clone();
                command.page_ops.parsed_page_specs = args.page_ops.parsed_page_specs.clone();
                command.raw_copy_attachments_from = args.raw_copy_attachments_from.clone();
            }
            Commands::CheckLinearization(_)
            | Commands::IsEncrypted(_)
            | Commands::QdfFix(_)
            | Commands::ZlibFlate(_) => {}
        }
    }
}

// The flattened clap model is deep enough that constructing it can exhaust
// Windows' default process stack after a small option addition. Keep every
// production command-construction boundary on a grown stack; the returned
// command itself and all parsing behavior remain unchanged.
const CLI_COMMAND_STACK_RED_ZONE: usize = 4 * 1024 * 1024;
const CLI_COMMAND_STACK_GROWTH_SIZE: usize = 4 * 1024 * 1024;

fn cli_command() -> clap::Command {
    stacker::maybe_grow(
        CLI_COMMAND_STACK_RED_ZONE,
        CLI_COMMAND_STACK_GROWTH_SIZE,
        || arg_parser::configure_qpdf_repeatable_bare_options(Cli::command()),
    )
}

#[cfg(test)]
fn cli_parse_from(args: Vec<OsString>) -> Cli {
    cli_parse_from_mode(args, true)
}

fn cli_parse_from_mode(args: Vec<OsString>, native_subcommand_mode: bool) -> Cli {
    stacker::maybe_grow(
        CLI_COMMAND_STACK_RED_ZONE,
        CLI_COMMAND_STACK_GROWTH_SIZE,
        || {
            let command = if native_subcommand_mode {
                cli_command()
            } else {
                // clap has no public operation that removes generated
                // subcommands from a Command. Rename and hide them for the
                // qpdf-compat parse only, retaining the same generated argument
                // schema while making every positional obey qpdf's flat grammar.
                let mut disabled_index = 0;
                cli_command().mut_subcommands(|subcommand| {
                    let disabled_name: &'static str = Box::leak(
                        format!("__flpdf_qpdf_compat_native_subcommand_{disabled_index}")
                            .into_boxed_str(),
                    );
                    disabled_index += 1;
                    subcommand
                        .name(disabled_name)
                        .hide(true)
                        .alias(None)
                        .visible_alias(None)
                        .short_flag(None)
                        .short_flag_alias(None)
                        .visible_short_flag_alias(None)
                })
            };
            let matches = command.get_matches_from(args);
            Cli::from_arg_matches(&matches).unwrap_or_else(|error| error.exit())
        },
    )
}

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

/// Print qpdf's sole-option copyright response (`QPDFJob_argv.cc:108-135`).
fn print_qpdf_copyright() {
    emit_logger_info(format!(
        "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.\n",
        flpdf::qpdf_version()
    ));
}

/// Return the value of a sole top-level qpdf help option, preserving raw
/// bytes so an unknown topic can be sent through the qpdf usage boundary.
/// `None` means plain `--help`/`-help`; `Some(bytes)` means `--help=...`.
fn qpdf_sole_help_topic(preprocessed: &PreprocessedArgs) -> Option<Option<Vec<u8>>> {
    if preprocessed.expanded_arg_count != 2 || preprocessed.original_residual_args.len() != 2 {
        return None;
    }
    let bytes = preprocessed.original_residual_args[1].as_bytes();
    if bytes == b"--help" || bytes == b"-help" {
        return Some(None);
    }
    bytes
        .strip_prefix(b"--help=")
        .or_else(|| bytes.strip_prefix(b"-help="))
        .map(|topic| Some(topic.to_vec()))
}

fn unknown_help_option_error(topic: &[u8]) -> UsageError {
    let mut message = b"unknown help option".to_vec();
    if !topic.is_empty() {
        message.push(b' ');
        message.extend_from_slice(topic);
    }
    UsageError::new(message)
}

fn unrecognized_argument_error(argument: &[u8]) -> UsageError {
    let mut message = b"unrecognized argument ".to_vec();
    message.extend_from_slice(argument);
    UsageError::new(message)
}

fn qpdf_compat_help_usage_error(preprocessed: &PreprocessedArgs) -> Option<UsageError> {
    if preprocessed.native_subcommand_mode {
        return None;
    }

    let sole_option = preprocessed.expanded_arg_count == 2 && preprocessed.residual_args.len() == 2;
    let args = &preprocessed.residual_args;
    let original_args = &preprocessed.original_residual_args;
    debug_assert_eq!(args.len(), original_args.len());
    let mut index = 1;
    while index < args.len() {
        let bytes = arg_parser::os_bytes(&args[index]);
        if is_named_segment_option(&bytes) {
            index += 1;
            while index < args.len() && arg_parser::os_bytes(&args[index]) != b"--" {
                index += 1;
            }
            index += usize::from(index < args.len());
            continue;
        }

        let original_bytes = original_args[index].as_bytes();
        if preprocessed
            .first_unknown_option
            .as_ref()
            .is_some_and(|(unknown_index, _)| *unknown_index == index)
        {
            return Some(unrecognized_argument_error(original_bytes));
        }

        let is_help_table_option = original_bytes == b"-h"
            || original_bytes == b"--help"
            || original_bytes == b"-help"
            || original_bytes.starts_with(b"--help=")
            || original_bytes.starts_with(b"-help=")
            || original_bytes == b"--version"
            || original_bytes == b"-version"
            || original_bytes == b"--copyright"
            || original_bytes == b"-copyright";
        if is_help_table_option && (!sole_option || original_bytes == b"-h") {
            return Some(unrecognized_argument_error(original_bytes));
        }
        index += 1;
    }
    None
}

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<OsString> = std::env::args_os().collect();
    if raw_args
        .first()
        .is_some_and(|program| is_zlib_flate_program(program))
    {
        if let Err(error) = run_zlib_flate(&raw_args[1..], "zlib-flate", "zlib-flate") {
            let code = error
                .downcast_ref::<CliExitError>()
                .map_or(ExitCode::Errors, |error| error.code);
            std::process::exit(code.as_i32());
        }
        return;
    }
    let preprocessed = match preprocess_qpdf_args(raw_args) {
        Ok(parsed) => parsed,
        Err(error) => {
            // qpdf's arg parser raises its errors through
            // `QPDFArgParser::usage` (`QPDFArgParser.cc:506-533`), rendered by
            // the CLI's `usageExit` blank-line + `For help:` block. Route a
            // pre-scan UsageError (e.g. `--password value`) through the same
            // formatter so it matches qpdf byte-for-byte.
            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);
        }
    };
    if let Some(topic) = qpdf_sole_help_topic(&preprocessed) {
        match topic {
            None => {
                emit_logger_info(qpdf_help::render_top(&progname()));
                return;
            }
            Some(topic) => {
                if let Some(body) = qpdf_help::render(&topic, &progname()) {
                    emit_logger_info(body);
                    return;
                }
                usage_exit(&unknown_help_option_error(&topic));
            }
        }
    }
    if let Some(error) = qpdf_compat_help_usage_error(&preprocessed) {
        usage_exit(&error);
    }
    // qpdf treats --version/--copyright/--help as a valid sole option only
    // when the whole expanded argv is exactly `<prog> <option>` (argc == 2),
    // checked after @argfile expansion but before named-group parsing
    // (`QPDFArgParser.cc:437,478-483`). Use the expanded count, not the
    // post-strip residual, so e.g. `--overlay f -- --version` is not mistaken
    // for a sole --version.
    if preprocessed.expanded_arg_count == 2 && preprocessed.original_residual_args.len() == 2 {
        match preprocessed.original_residual_args[1].as_bytes() {
            b"--version" | b"-version" => {
                print_qpdf_version();
                return;
            }
            b"--copyright" | b"-copyright" => {
                print_qpdf_copyright();
                return;
            }
            _ => {}
        }
    }
    let PreprocessedArgs {
        residual_args,
        raw_residual_args,
        native_subcommand_mode,
        overlay_specs,
        attachment_segments,
        raw_overrides,
        ..
    } = preprocessed;
    let qpdf_preflight = if native_subcommand_mode {
        None
    } else {
        Some(match preflight_qpdf_cli_events(&raw_residual_args) {
            Ok(preflight) => preflight,
            Err(error) => exit_qpdf_parse_error(error),
        })
    };
    let mut args = cli_parse_from_mode(residual_args, native_subcommand_mode);
    apply_raw_overrides(&mut args, raw_overrides);
    let _ = CLI_WARNING_EXIT_ZERO.set(args.warning_exit_zero);
    let _ = CLI_REPORT_MEMORY_USAGE.set(args.report_memory_usage);
    // qpdf keeps --verbose on QPDFJob rather than on the password parser, but
    // the reader owns the authentication retry boundary in flpdf. Carry the
    // job policy through the existing PasswordArgs copy used by every open
    // helper so the qpdf retry diagnostic is emitted before the alternate
    // candidate is attempted.
    args.password.verbose = args.verbose;
    if let Err(error) = validate_keep_files_open_threshold(&args.page_ops) {
        qpdf_usage_exit(error);
    }
    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) => {
                emit_logger_error(format!("flpdf: {error}\n"));
                std::process::exit(1);
            }
        };
    let top_level_compression_level =
        match parse_compression_level(args.compression_level.as_deref()) {
            Ok(level) => level,
            Err(error) => qpdf_usage_exit(error),
        };
    let top_level_image_options = match image_optimization_options(
        args.keep_inline_images,
        args.oi_min_width.as_deref(),
        args.oi_min_height.as_deref(),
        args.oi_min_area.as_deref(),
        args.ii_min_bytes.as_deref(),
    ) {
        Ok(options) => options,
        Err(error) => qpdf_usage_exit(error),
    };
    let top_level_image_transform_options = ImageTransformOptions::new(
        args.externalize_inline_images,
        args.optimize_images,
        top_level_image_options,
    );
    let top_level_rotation_parameters = args.page_ops.rotate.clone();
    let mut top_level_inspection_transform_options = InspectionTransformOptions::new(
        top_level_image_transform_options,
        args.generate_appearances,
        args.flatten_annotations,
    )
    .with_rotations(&top_level_rotation_parameters);
    top_level_inspection_transform_options.flatten_rotation = args.flatten_rotation;
    // QPDFWriter::doWriteSetup clears QDF before deriving QDF's implicit
    // normalization defaults for linearized output (`QPDFWriter.cc:2068-2080`).
    // Keep an explicit --normalize-content value, but do not synthesize the
    // QDF default when --linearize will clear QDF in the writer.
    let normalize_content =
        normalize_content_enabled(args.normalize_content, args.qdf && !args.linearize);

    // --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. 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);

    // `--overlay`/`--underlay` groups are stripped from argv before clap by
    // `preprocess_qpdf_args`, so a stripped group leaves no trace for native
    // subcommand dispatch. Native commands other than `rewrite` do not own a
    // create/write consumer and must reject the group instead of silently
    // ignoring it. The qpdf-flat top-level inspection and attachment routes
    // are handled below by the combined QPDFJob path; keep them accepted.
    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()
            }
        };
        let target_is_inspection = args.check
            || args.show_object.is_some()
            || args.show_npages
            || args.show_pages
            || args.show_xref
            || args.check_linearization
            || args.show_linearization
            || args.list_attachments
            || args.show_attachment.is_some();
        if !target_is_rewrite && !target_is_inspection {
            emit_logger_error(
                "flpdf: --overlay/--underlay can only be used with rewrite output, \
                 not with inspection or other commands\n",
            );
            std::process::exit(2);
        }
    }

    // qpdf rejects a non-zero split size with --replace-input before opening
    // the input (`QPDFJob.cc:572-579`). The page-operation dispatch below
    // requires an explicit output path, so enforce the canonical job
    // boundary here instead of falling through to its unrelated arity error.
    if args.replace_input && split_pages_active(args.page_ops.split_pages.as_deref()) {
        usage_exit(&UsageError::new(
            "--split-pages may not be used with --replace-input",
        ));
    }
    if args.replace_input
        && (args.check
            || args.check_linearization
            || args.show_object.is_some()
            || args.show_npages
            || args.show_pages
            || args.show_xref
            || args.show_linearization
            || args.show_encryption
            || args.is_encrypted
            || args.requires_password
            || args.list_attachments
            || args.show_attachment.is_some())
    {
        usage_exit(&UsageError::new(
            "no output file may be given for this option",
        ));
    }

    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_object.is_some()
            || args.check_linearization
            || args.show_linearization
            || args.show_encryption
            || args.list_attachments
            || args.show_attachment.is_some());

    // 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.
    if args.check_linearization && args.output.is_some() {
        usage_exit(&no_output_file_for_inspection_error());
    }

    let attachment_mutation_requested = !attachment_segments.is_empty()
        || !args.remove_attachment.is_empty()
        || !args.copy_attachments_from.is_empty();

    let result = if args.replace_input && (args.json.is_some() || args.json_output.is_some()) {
        Err(UsageError::new("--json may not be used with --replace-input").into())
    } else if !args.job_json_file.is_empty() {
        run_job_json_files(
            qpdf_preflight.expect("flat qpdf job-json route requires its preflight"),
            args.no_warn,
        )
    } else if json_input_inspection {
        run_json_input_inspection(
            &args,
            top_level_inspection_transform_options,
            &overlay_specs,
            &attachment_segments,
        )
    // `QPDFJob::writeQPDF` chooses one of three arms -- `doInspection`,
    // `doSplitPages`, `writeOutfile` (`libqpdf/QPDFJob.cc:486-491`) -- and the
    // JSON document is written from inside `writeOutfile`. A truthy
    // `--split-pages` therefore claims the run before JSON output is
    // reachable, so this route steps aside and the page-operation dispatch
    // below owns the split, the way it already does for the `--empty` rewrite
    // and `--linearize` routes above. The JSON selectors leave no trace on
    // that output: `Config::jsonOutput` lowers `decode_level` without setting
    // `decode_level_set` (`libqpdf/QPDFJob_config.cc:312-326`), which is the
    // only flag `setWriterOptions` would replay (`libqpdf/QPDFJob.cc:2873`),
    // and every other JSON option is consumed by `writeJSON` alone.
    } else if (args.json.is_some() || args.json_output.is_some())
        && !split_pages_active(args.page_ops.split_pages.as_deref())
    {
        run_json(
            &args,
            top_level_inspection_transform_options,
            &attachment_segments,
            args.page_ops.empty,
        )
    } else if let Some(command) = args.command {
        run_command(command, &overlay_specs)
    } else if args.is_encrypted {
        if args.page_ops.empty {
            run_empty_document_encryption_status()
        } else {
            match args.input.as_ref() {
                Some(input) => run_is_encrypted(input, args.repair, &args.password, args.no_warn),
                None => Err(missing_input_usage_error().into()),
            }
        }
    } else if args.requires_password {
        if args.page_ops.empty {
            run_empty_document_encryption_status()
        } else {
            match args.input.as_ref() {
                Some(input) => {
                    run_requires_password(input, args.repair, &args.password, args.no_warn)
                }
                None => Err(missing_input_usage_error().into()),
            }
        }
    } else if top_level_inspection_combination_requested(
        &args,
        !overlay_specs.is_empty(),
        attachment_mutation_requested,
    ) {
        run_combined_top_level_inspection(
            &args,
            top_level_inspection_transform_options,
            &overlay_specs,
            &attachment_segments,
        )
    } else if attachment_mutation_requested {
        let options = top_level_writer_options(
            &args,
            normalize_content,
            top_level_compression_level,
            &top_level_version_options,
        );
        run_all_attachment_mutations(
            &args,
            &overlay_specs,
            &attachment_segments,
            options,
            top_level_inspection_transform_options,
        )
    } else if args.page_ops.empty
        && args.page_ops.pages.is_empty()
        && args.page_ops.rotate.is_empty()
        && !split_pages_active(args.page_ops.split_pages.as_deref())
    {
        // With --empty, qpdf has already consumed the primary-input slot, so
        // the first positional is the output for an ordinary rewrite. Keep
        // this route separate from --empty --pages, whose existing page-copy
        // pipeline owns a fresh output document and source selection.
        let options = top_level_writer_options(
            &args,
            normalize_content,
            top_level_compression_level,
            &top_level_version_options,
        );
        run_rewrite(
            args.input,
            args.output,
            args.replace_input,
            args.repair,
            &args.password,
            args.json_input,
            args.update_from_json.as_deref(),
            args.linearize,
            args.linearize_pass1.as_deref(),
            args.remove_restrictions,
            args.decrypt,
            normalize_content,
            args.coalesce_contents,
            args.remove_unreferenced_resources,
            args.generate_appearances,
            top_level_image_transform_options,
            args.flatten_annotations,
            args.flatten_rotation,
            page_label_options(args.set_page_labels.as_deref(), args.remove_page_labels),
            &overlay_specs,
            args.verbose,
            args.no_warn,
            options,
            true,
        )
    } else if args.linearize && !page_ops_active(&args.page_ops) {
        let options = top_level_writer_options(
            &args,
            normalize_content,
            top_level_compression_level,
            &top_level_version_options,
        );
        let result = run_rewrite(
            args.input,
            args.output.clone(),
            args.replace_input,
            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,
            args.remove_unreferenced_resources,
            args.generate_appearances,
            top_level_image_transform_options,
            args.flatten_annotations,
            args.flatten_rotation,
            page_label_options(args.set_page_labels.as_deref(), args.remove_page_labels),
            &overlay_specs,
            args.verbose,
            args.no_warn,
            options,
            args.page_ops.empty,
        );
        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.
        //
        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,
            progress: args.progress,
            report_memory_usage: args.report_memory_usage,
            recompress_flate: args.recompress_flate,
            compression_level: top_level_compression_level,
            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,
            // qpdf applies `--newline-before-endstream` to every output
            // writer (`QPDFWriter.cc:1560`), including page-operation output.
            newline_before_endstream: newline_before_endstream_setting(
                args.newline_before_endstream,
            ),
            password_mode: args.password.password_mode.into(),
            // Now that this route accepts an explicit --encrypt, it also has to
            // honour the opt-in that lets RC4 through, exactly as
            // `top_level_writer_options` and the `rewrite` initializer do.
            allow_weak_crypto: args.password.allow_weak_crypto,
            ..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 => {
                    emit_logger_error(format!(
                        "flpdf: --compress-streams must be y or n, got: {:?}\n",
                        other
                    ));
                    std::process::exit(2);
                }
            }
        }
        // `--copy-encryption` is a QPDFJob writer setting, not a page-source
        // parser setting. Leave donor opening to `write_qpdf`, which also
        // gives the create-stage page resolver access to qpdf's
        // encryption-file-password fallback.
        apply_encryption_options(
            &mut options,
            EncryptionCliOptions {
                encrypt: args.raw_encrypt.as_deref(),
                encrypt_segments: args.raw_encrypt_segments.as_deref(),
                parsed_encrypt_segments: args.parsed_encrypt_segments.as_deref(),
                copy_encryption: None,
                encryption_file_password: args.raw_encryption_file_password.as_deref(),
                password_args: &args.password,
                suppress_warnings: args.no_warn,
                last_mode: args.last_encryption_mode,
            },
        );
        if args.decrypt {
            // qpdf applies --decrypt at the writer boundary after page
            // selection, so page-operation output must not preserve the
            // authenticated primary's encryption.
            options.preserve_encryption = false;
        }
        run_page_operations_with_qpdf_job(
            &args,
            options,
            top_level_image_transform_options,
            &overlay_specs,
        )
    } else {
        let options = top_level_writer_options(
            &args,
            normalize_content,
            top_level_compression_level,
            &top_level_version_options,
        );
        run_rewrite(
            args.input,
            args.output,
            args.replace_input,
            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,
            args.remove_unreferenced_resources,
            args.generate_appearances,
            top_level_image_transform_options,
            args.flatten_annotations,
            args.flatten_rotation,
            page_label_options(args.set_page_labels.as_deref(), args.remove_page_labels),
            &overlay_specs,
            args.verbose,
            args.no_warn,
            options,
            args.page_ops.empty,
        )
    };

    if let Err(error) = result {
        exit_with_cli_error(error);
    }
}

/// Render a fatal CLI error in qpdf's `realmain` shape and exit.
///
/// qpdf catches every fatal job failure in one place (`qpdf/qpdf.cc:36-40`),
/// which prints `whoami: e.what()` and returns `EXIT_ERROR`. Routing every
/// fatal CLI error through a single renderer keeps a failure raised while
/// configuring the writer -- the `--copy-encryption` donor open reached from
/// `QPDFJob::setWriterOptions` (`libqpdf/QPDFJob.cc:2891-2899`) -- framed
/// exactly like a primary-input failure, as it is in qpdf.
fn exit_with_cli_error(error: Box<dyn std::error::Error>) -> ! {
    let _ = cli_logger().flush();
    if let Some(exit_err) = error.downcast_ref::<CliRawExitError>() {
        if !exit_err.message.is_empty() {
            let mut line = format!("\n{}: ", progname()).into_bytes();
            line.extend_from_slice(&exit_err.message);
            line.push(b'\n');
            emit_logger_error(line);
        }
        std::process::exit(exit_err.code.as_i32());
    }
    // 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() {
            emit_logger_error(format!("\n{}: {}\n", progname(), exit_err.message));
        }
        std::process::exit(exit_err.code.as_i32());
    }
    if let Some(usage_error) = find_usage_error(error.as_ref()) {
        usage_exit(usage_error);
    }
    if let Some(message) = find_raw_error_message(error.as_ref()) {
        let mut line = progname().into_bytes();
        line.extend_from_slice(b": ");
        line.extend_from_slice(message);
        line.push(b'\n');
        emit_logger_error(line);
        std::process::exit(2);
    }
    if let Some(flpdf::Error::FileIo {
        operation: "open",
        path,
        source,
    }) = error.downcast_ref::<flpdf::Error>()
    {
        let mut line = progname().into_bytes();
        line.extend_from_slice(b": open ");
        line.extend_from_slice(&path_description(path));
        line.extend_from_slice(b": ");
        line.extend_from_slice(qpdf_open_io_error_message(source).as_bytes());
        line.push(b'\n');
        emit_logger_error(line);
        std::process::exit(2);
    }
    if let Some(path_error) = error.downcast_ref::<CliPathError>() {
        let mut line = progname().into_bytes();
        line.extend_from_slice(b": ");
        if let Some(operation) = path_error.operation {
            line.extend_from_slice(operation.as_bytes());
            line.push(b' ');
        }
        line.extend_from_slice(&path_error.path);
        line.extend_from_slice(b": ");
        line.extend_from_slice(path_error.message.as_bytes());
        line.push(b'\n');
        emit_logger_error(line);
        std::process::exit(2);
    }
    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 find_raw_error_message<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a [u8]> {
    if let Some(error) = error.downcast_ref::<Error>() {
        if let Some(message) = error.raw_message() {
            return Some(message);
        }
    }
    error.source().and_then(find_raw_error_message)
}

fn usage_exit(error: &UsageError) -> ! {
    let who = progname();
    let mut message = format!("\n{who}: ").into_bytes();
    message.extend_from_slice(error.what_bytes());
    message.extend_from_slice(
        format!(
            "\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"
        )
        .as_bytes(),
    );
    emit_logger_error(message);
    std::process::exit(2);
}

fn exit_qpdf_parse_error(error: Box<dyn std::error::Error>) -> ! {
    // The job-JSON preflight reads the file here, so its diagnostics reach this
    // exit path rather than the one in `main`. Keep the raw-byte branch first so
    // a non-UTF-8 path survives instead of going through `Display`.
    if let Some(exit_error) = error.downcast_ref::<CliRawExitError>() {
        if !exit_error.message.is_empty() {
            let mut line = format!("\n{}: ", progname()).into_bytes();
            line.extend_from_slice(&exit_error.message);
            line.push(b'\n');
            emit_logger_error(line);
        }
        std::process::exit(exit_error.code.as_i32());
    }
    if let Some(exit_error) = error.downcast_ref::<CliExitError>() {
        if !exit_error.message.is_empty() {
            emit_logger_error(format!("\n{}: {}\n", progname(), exit_error.message));
        }
        std::process::exit(exit_error.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);
}

/// Route a qpdf-compatible CLI parameter failure through the usage renderer.
/// The ordinary post-parse path reaches here only for values whose qpdf
/// callback conversion was deferred until after raw argv preflight.
fn qpdf_usage_exit(error: Box<dyn std::error::Error>) -> ! {
    if let Some(usage_error) = find_usage_error(error.as_ref()) {
        usage_exit(usage_error);
    }
    let usage_error = UsageError::new(error.to_string());
    usage_exit(&usage_error);
}

fn missing_input_usage_error() -> UsageError {
    UsageError::new("an input file name is required")
}

/// `QPDFJob::checkConfiguration` raises this usage error whenever a route that
/// writes output has no output file name (`libqpdf/QPDFJob.cc:591-593`).
fn missing_output_usage_error() -> UsageError {
    UsageError::new("an output file name is required; use - for standard output")
}

fn no_output_file_for_inspection_error() -> UsageError {
    UsageError::new("no output file may be given for this option")
}

fn reject_empty_inspection_output(input: Option<&Path>) -> CliResult<()> {
    if input.is_some() {
        return Err(no_output_file_for_inspection_error().into());
    }
    Ok(())
}

fn new_cli_job(suppress_warnings: bool) -> QPDFJob {
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(suppress_warnings);
    job.set_warnings_exit_zero(cli_warning_exit_zero());
    job.set_report_memory_usage(cli_report_memory_usage());
    job
}

fn top_level_inspection_combination_requested(
    args: &Cli,
    overlay_requested: bool,
    attachment_mutation_requested: bool,
) -> bool {
    let inspection_count = [
        args.check,
        args.show_object.is_some(),
        args.show_npages,
        args.show_pages,
        args.show_xref,
        args.check_linearization,
        args.show_linearization,
        args.show_encryption,
        args.list_attachments,
        args.show_attachment.is_some(),
    ]
    .into_iter()
    .filter(|selected| *selected)
    .count();

    // qpdf's `doInspection` (`libqpdf/QPDFJob.cc:1645-1693`) always runs
    // every selected inspection branch through the same
    // `initializeFromArgv`/`run()`/`getExitCode` dispatch, independent of how
    // many branches are selected -- there is no separate qpdf code path for
    // "exactly one inspection flag". Route every one of these ten flags
    // through the combined job lifecycle unconditionally, matching that
    // structure. `--show-object` no longer needs a special case: neither the
    // generation-clamp gap nor the raw-identity-vs-xref-backed-lookup gap
    // this comment used to describe still exists.
    // `crate::job::lifecycle::parse_job_object_selector` accepts any
    // non-negative generation, matching qpdf's `parse_object_id`
    // (`libqpdf/QPDFJob.cc:929-941`, no clamp), and
    // `JobObjectSelector::Object` resolves through
    // `Pdf::get_object_handle_by_raw_identity` (`QPDF::getObjectByID`,
    // `libqpdf/QPDF.cc:1973-1977`), the same primitive the CLI's own
    // (now-removed) standalone selector used.
    let migrated_flag_selected = args.check
        || args.show_object.is_some()
        || args.show_npages
        || args.show_pages
        || args.show_xref
        || args.check_linearization
        || args.show_linearization
        || args.show_encryption
        || args.list_attachments
        || args.show_attachment.is_some();
    if migrated_flag_selected {
        return true;
    }

    if overlay_requested && inspection_count > 0 {
        return true;
    }
    inspection_count > 1
        || (inspection_count == 1 && !args.page_ops.pages.is_empty())
        || (inspection_count == 1 && (args.remove_restrictions || args.coalesce_contents))
        || (inspection_count == 1 && attachment_mutation_requested)
}

fn configure_top_level_inspection_job(job: &mut QPDFJob, args: &Cli) -> CliResult<()> {
    job.set_password_is_hex_key(args.password.password_is_hex_key);
    job.set_show_encryption_key(args.show_encryption_key);
    job.set_with_images(args.with_images);
    job.set_verbose(args.verbose);
    if args.normalize_content.is_some() {
        job.set_content_normalization(matches!(args.normalize_content, Some(CliYesNo::Yes)));
    }

    let mut configuration = job.config();
    if args.check {
        configuration.check();
    }
    if args.show_npages {
        configuration.show_npages();
    }
    if args.show_encryption {
        configuration.show_encryption();
    }
    if args.check_linearization {
        configuration.check_linearization();
    }
    if args.show_linearization {
        configuration.show_linearization();
    }
    if args.show_xref {
        configuration.show_xref();
    }
    if let Some(selector) = args.show_object.as_deref() {
        configuration.show_object(selector)?;
        if args.raw_stream_data {
            configuration.raw_stream_data();
        }
        if args.filtered_stream_data {
            configuration.filtered_stream_data();
        }
    }
    if args.show_pages {
        configuration.show_pages();
    }
    if args.list_attachments {
        configuration.list_attachments();
    }
    if let Some(key) = args.show_attachment.as_ref() {
        configuration.show_attachment(arg_parser::os_bytes(key.as_os_str()).to_vec());
    }
    Ok(())
}

/// Queue top-level attachment mutations on the same job that owns
/// `--check-linearization` inspection. qpdf applies these mutations inside
/// `handleTransformations` before `doInspection`, even when no output file is
/// requested (`libqpdf/QPDFJob.cc:473,2230-2247`).
fn configure_top_level_attachment_mutations(
    job: &mut QPDFJob,
    args: &Cli,
    attachment_segments: &[Vec<Vec<u8>>],
) -> CliResult<()> {
    let mut configuration = job.config();
    for tokens in attachment_segments.iter().cloned() {
        let attachment = parse_add_attachment_segment(tokens)?;
        let basename = path_basename(&attachment.file)?;
        configuration.add_attachment(AttachmentAddOptions {
            path: attachment.file,
            key: attachment.key.unwrap_or_else(|| basename.clone()),
            filename: attachment.filename.unwrap_or(basename),
            mimetype: attachment.mimetype,
            description: attachment.description,
            creation_date: attachment.creation_date,
            modification_date: attachment.mod_date,
            replace: attachment.replace,
            verbose: args.verbose,
        });
    }
    for key in &args.remove_attachment {
        configuration.remove_attachment(arg_parser::os_bytes(key));
    }

    for tokens in args.raw_copy_attachments_from.clone().unwrap_or_default() {
        let donor = parse_copy_attachments_segment(tokens)?;
        configuration.copy_attachments_from(
            donor.file,
            donor.password,
            donor.prefix.unwrap_or_default(),
        );
    }
    Ok(())
}

/// Queue parsed CLI underlay/overlay groups on the canonical job
/// configuration. qpdf opens these sources and runs `handleUnderOverlay` in
/// `createQPDF` before `handleTransformations` and before the `doInspection`
/// branch (`QPDFJob.cc:459-489`). Keeping the raw path, password, and range
/// values on `QPDFJobConfig` lets that same lifecycle own source lifetime,
/// warning delivery, and page-tree repair for inspection consumers.
fn configure_cli_overlay_specs(job: &mut QPDFJob, specs: &[OverlaySpec]) -> CliResult<()> {
    if specs.is_empty() {
        return Ok(());
    }

    let mut configuration = job.config();
    for spec in specs {
        let from = match spec.from.as_deref() {
            None => PageRange::all(),
            Some("") => PageRange::empty(),
            Some(range) => PageRange::parse_numrange(range)?,
        };
        let to = match spec.to.as_deref() {
            None => PageRange::all(),
            Some("") => PageRange::empty(),
            Some(range) => PageRange::parse_numrange(range)?,
        };
        let repeat = match spec.repeat.as_deref() {
            None | Some("") => None,
            Some(range) => Some(PageRange::parse_numrange(range)?),
        };
        let password = spec
            .raw_password
            .clone()
            .or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password).to_vec())
            })
            .unwrap_or_default();
        let path = PathBuf::from(spec.file.clone());
        match spec.kind {
            OverlayKind::Overlay => {
                configuration.overlay(path, password, from, to, repeat);
            }
            OverlayKind::Underlay => {
                configuration.underlay(path, password, from, to, repeat);
            }
        }
    }
    Ok(())
}

/// Run a top-level `--pages` invocation whose output is a qpdf inspection.
///
/// qpdf still creates and transforms the page-selected document before its
/// inspection branch; the absence of an output file only changes the
/// `writeQPDF` consumer. Keep this route on the public QPDFJob lifecycle so
/// page selection cannot be silently bypassed by a standalone inspection
/// helper.
fn run_top_level_page_selection_inspection(
    args: &Cli,
    transform_options: InspectionTransformOptions<'_>,
    overlay_specs: &[OverlaySpec],
    attachment_segments: &[Vec<Vec<u8>>],
) -> CliResult<()> {
    let mut job = new_cli_job(args.no_warn);
    let input_options = pdf_open_options(args.repair, &args.password)?;
    job.set_password(input_options.password);
    job.set_password_mode(args.password.password_mode.into());
    job.set_password_is_hex_key(args.password.password_is_hex_key);
    job.set_suppress_password_recovery(args.password.suppress_password_recovery);
    job.set_suppress_recovery(args.password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(args.password.recovery.ignore_xref_streams);
    job.set_verbose(args.verbose);
    configure_top_level_inspection_job(&mut job, args)?;
    configure_cli_overlay_specs(&mut job, overlay_specs)?;
    if args.show_attachment.is_some() {
        // qpdf reserves the save pipeline inside checkConfiguration
        // (`QPDFJob.cc:621-626`), before any page-selection or mutation info
        // output can claim standard output. The attachment report repeats the
        // idempotent reservation, but it must not be the first call after an
        // earlier info report.
        job.logger().save_to_standard_output(true)?;
    }
    configure_top_level_attachment_mutations(&mut job, args, attachment_segments)?;
    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        args.verbose,
        args.remove_restrictions,
        args.coalesce_contents,
    )?;
    configure_keep_files_open(&mut job, &args.page_ops)?;

    if args.page_ops.empty {
        reject_empty_inspection_output(args.input.as_deref())?;
        job.config().empty_input()?;
    } else {
        let input = args.input.as_ref().ok_or_else(missing_input_usage_error)?;
        job.config().input_file(input.clone())?;
    }

    let raw_specs = configured_page_specs(&args.page_ops)?;
    {
        let mut configuration = job.config();
        for spec in raw_specs {
            let password = spec.raw_password.or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password.as_os_str()))
            });
            configuration.add_page_spec(PathBuf::from(spec.file_token), &spec.range, password)?;
        }
        for parameter in &args.page_ops.rotate {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        for parameter in &args.page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        configuration.remove_unreferenced_resources(args.remove_unreferenced_resources.into());
    }

    finish_job_exit_status(job.run()?)
}

fn run_combined_top_level_inspection(
    args: &Cli,
    transform_options: InspectionTransformOptions<'_>,
    overlay_specs: &[OverlaySpec],
    attachment_segments: &[Vec<Vec<u8>>],
) -> CliResult<()> {
    if !args.page_ops.pages.is_empty() {
        return run_top_level_page_selection_inspection(
            args,
            transform_options,
            overlay_specs,
            attachment_segments,
        );
    }

    let mut job = new_cli_job(args.no_warn);
    configure_top_level_inspection_job(&mut job, args)?;
    configure_cli_overlay_specs(&mut job, overlay_specs)?;
    if args.show_attachment.is_some() {
        // qpdf reserves the save pipeline during checkConfiguration, before
        // doInspection emits any info output (`QPDFJob.cc:614-626`). The
        // attachment report itself repeats the idempotent reservation, but
        // it must not be the first call after an earlier info report.
        job.logger().save_to_standard_output(true)?;
    }

    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        args.verbose,
        args.remove_restrictions,
        args.coalesce_contents,
    )?;
    configure_top_level_attachment_mutations(&mut job, args, attachment_segments)?;

    if args.page_ops.empty {
        reject_empty_inspection_output(args.input.as_deref())?;
        job.config().empty_input()?;
    } else {
        let input = args.input.as_ref().ok_or_else(missing_input_usage_error)?;
        let input_options = pdf_open_options(args.repair, &args.password)?;
        job.set_password(input_options.password);
        job.set_password_mode(args.password.password_mode.into());
        job.set_password_is_hex_key(args.password.password_is_hex_key);
        job.set_suppress_password_recovery(args.password.suppress_password_recovery);
        job.set_suppress_recovery(args.password.recovery.suppress_recovery);
        job.set_ignore_xref_streams(args.password.recovery.ignore_xref_streams);
        job.config().input_file(input.clone())?;
    }

    // qpdf applies rotations before underlay/overlay and both before the
    // create-stage transformations (`QPDFJob.cc:466-473`). Queue the raw
    // parameters on the same job so the inspection consumer observes the
    // fully prepared document rather than a manually opened primary.
    {
        let mut configuration = job.config();
        for parameter in &args.page_ops.rotate {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
    }

    // `QPDFJob::run` owns primary/donor opening, create-stage ordering, and
    // the final configured inspection completion. This is the same lifecycle
    // used by rewrite and page-selection routes, including donor-specific
    // open options and path-scoped errors.
    finish_job_exit_status(job.run()?)
}

fn create_empty_primary_document(
    job: &mut QPDFJob,
    update_from_json: Option<&Path>,
) -> CliResult<flpdf::job::JobDocument> {
    let mut pdf = job.create_empty_document()?;
    apply_json_update_with_job(job, &mut pdf, update_from_json)?;
    Ok(pdf)
}

struct QpdfCliPreflight {
    job: QPDFJob,
}

/// Convert an error from a qpdf argv callback into the usage-error class used
/// by `QPDFArgParser::usage` (`libqpdf/QPDFArgParser.cc:337-344`). The core
/// library keeps numeric conversion failures as `Error::System`; at this CLI
/// boundary qpdf catches the corresponding C++ runtime error and rethrows it
/// as `QPDFUsage` (`libqpdf/QPDFJob_argv.cc:408-415`).
fn qpdf_argv_usage_error(error: Box<dyn std::error::Error>) -> Box<dyn std::error::Error> {
    if let Some(usage_error) = find_usage_error(error.as_ref()) {
        return Box::new(UsageError::new(usage_error.what_bytes()));
    }
    Box::new(UsageError::new(error.to_string()))
}

/// Parse one qpdf unsigned option value through the shared direct conversion
/// used by `QPDFJob::Config::keepFilesOpenThreshold` and image thresholds.
/// This intentionally does not use the comma-separated collate parser: qpdf's
/// `QUtil::string_to_uint` stops at the first non-digit byte.
fn parse_qpdf_unsigned_option(value: &[u8]) -> CliResult<usize> {
    let value = String::from_utf8_lossy(value);
    QPDFJob::parse_keep_files_open_threshold(&value)
        .map_err(|error| qpdf_argv_usage_error(Box::new(error)))
}

/// Build one canonical job from the argv/job-json boundary that qpdf's own
/// CLI wraps directly around `QPDFJob::initializeFromArgv`
/// (`qpdf/qpdf.cc:27-43`). Runs for every non-subcommand invocation, before
/// clap's post-parse route selection, so qpdf's own occurrence-order
/// immediate parameter validation (`--rotate`, `--collate`,
/// `--compression-level`, image thresholds, `--split-pages`,
/// `--show-object`, `--json`/`--json-output`, and every other option the
/// canonical initializer's argv grammar covers) happens before any file is
/// opened, matching qpdf. The prepared job becomes the real job for the
/// `--job-json-file` route; every other route discards it after this
/// validation pass.
///
/// Two flpdf-cli-only adjustments to the raw argv fed to the canonical
/// initializer:
/// - `--repair` (`Cli::repair`) has no qpdf counterpart (confirmed absent
///   from `libqpdf/qpdf/auto_job_init.hh`'s 124-option registry; every other
///   top-level `Cli` flag, including the flattened `PasswordArgs`/
///   `PageOpArgs` fields, does have one) and is filtered out so the
///   canonical initializer does not reject it as unrecognized.
/// - `--password-file` is filtered out unless `--job-json-file` is also
///   present. Its Config callback is one of only two in
///   `libqpdf/QPDFJob_config.cc` with a discard-time file-read side effect
///   (`passwordFile:661`, alongside `jobJsonFile:774`, confirmed by
///   grepping that file for `read_lines_from_file`/`read_file_into_string`);
///   running it during a validation pass whose job is later discarded would
///   read the file (and emit its multi-line warning) a second time when the
///   real, clap-driven non-job-json-file route processes `--password-file`
///   again.
///
/// The message prefix is set from [`progname`] rather than the raw
/// `argv[0]` element so `FLPDF_PROGNAME` keeps overriding it for the qtest
/// harness shim: qpdf's own `getProgname()` is `argv[0]`-derived
/// (`QPDFArgParser.cc:418-428`), but this env-var override has no qpdf
/// counterpart and every other flpdf-cli diagnostic already goes through
/// [`progname`] instead of the raw executable name.
fn preflight_qpdf_cli_events(args: &[arg_parser::RawArg]) -> CliResult<QpdfCliPreflight> {
    let has_job_json = args.iter().any(arg_parser::is_job_json_file_argument);
    // These two are CLI-only spellings with no qpdf main-table entry, so they
    // must not reach `initialize_from_raw_argv`. Drop them only while scanning
    // the main table: inside a named segment qpdf's sub-parser owns the token
    // and rejects it as `unrecognized argument <token> (<table> options must
    // be terminated with --)`, which a byte-only filter would silence.
    let mut in_segment = false;
    let mut filtered: Vec<Vec<u8>> = args
        .iter()
        .filter(|argument| {
            let bytes = argument.as_bytes();
            if in_segment {
                if bytes == b"--" {
                    in_segment = false;
                }
                return true;
            }
            if is_named_segment_option(bytes) {
                in_segment = true;
                return true;
            }
            bytes != b"--repair" && (has_job_json || !bytes.starts_with(b"--password-file="))
        })
        .map(|argument| argument.as_bytes().to_vec())
        .collect();
    if let Some(program) = filtered.first_mut() {
        *program = progname().into_bytes();
    }
    let mut job = QPDFJob::new();
    // `args` has already been through `expand_arg_files` once (this
    // function's caller builds it from `PreprocessedArgs::raw_residual_args`,
    // which `arg_parser::ArgParser::parse_os_with_handler` produces after its
    // own single-level `@file` expansion). Using
    // `initialize_from_expanded_raw_argv` here, instead of
    // `initialize_from_raw_argv`, keeps that expansion at exactly the one
    // level qpdf's own `QPDFArgParser` performs: a literal `@file` token that
    // survived expansion (because it came from inside an already-expanded
    // file, per qpdf's no-recursion rule) must stay literal, not be expanded
    // again here.
    job.initialize_from_expanded_raw_argv(&filtered)
        .map_err(|error| qpdf_argv_usage_error(Box::new(error)))?;
    Ok(QpdfCliPreflight { job })
}

fn run_job_json_files(preflight: QpdfCliPreflight, suppress_warnings: bool) -> CliResult<()> {
    let QpdfCliPreflight { mut job } = preflight;
    // The retained job has already parsed the JSON, and qpdf's JSON handlers
    // for these two are bare setters -- `addBare([this]() { c_main->noWarn(); })`
    // (`auto_job_json_init.hh:287-289`) and the `warningExit0` entry at `:469`
    // -- so neither source can ever clear the flag. Setting the CLI value
    // unconditionally would let its `false` default erase what the JSON asked
    // for. Only turn the flag on, never off.
    if cli_warning_exit_zero() {
        job.set_warnings_exit_zero(true);
    }
    job.set_logger(cli_logger());
    if suppress_warnings {
        job.set_suppress_warnings(true);
    }
    // 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 run_json(
    cli: &Cli,
    transform_options: InspectionTransformOptions<'_>,
    attachment_segments: &[Vec<Vec<u8>>],
    empty: bool,
) -> 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 {
        // Both checks are `QPDFJob::checkConfiguration` usage errors
        // (`QPDFJob.cc:633-641`), so they take qpdf's usage exit — the leading
        // blank line, the program name, and the trailing `For help:` block.
        if json_version != 1 && matches!(raw.as_str(), "objects" | "objectinfo") {
            usage_exit(&UsageError::new(
                "json keys \"objects\" and \"objectinfo\" are only valid for json version 1",
            ));
        }
        if json_version == 1 && raw == "qpdf" {
            usage_exit(&UsageError::new(
                "json key \"qpdf\" is only valid for json version > 1",
            ));
        }
        match JsonKey::from_str(raw.as_str()) {
            Some(k) => json_keys.push(k),
            None => {
                let names = QPDF_JSON_KEY_NAMES.join(",");
                emit_logger_error(format!(
                    "flpdf: --json-key must be given as --json-key={{{names}}}\n"
                ));
                std::process::exit(2);
            }
        }
    }
    // qpdf's json-output mode also always selects the qpdf key in addition to
    // any explicitly requested keys (`QPDFJob_config.cc:312-326`); the job
    // configuration's own `json_output` selector owns that addition.
    if json_output_mode && json_version == 1 {
        emit_logger_error("flpdf: --json-output requires JSON version 2\n");
        std::process::exit(2);
    }

    // 2. Retain --json-object selectors in their raw qpdf spelling. qpdf
    // parses them from `getWantedJSONObjects` only when the object section is
    // emitted (`QPDFJob.cc:929-997`), after earlier JSON sections have reached
    // stdout. The JSON job boundary owns that deferred conversion.
    let json_objects = cli.json_object.clone();

    // 3. Parse an explicit stream-data mode.
    //
    // Ordinary `--json` follows the job configuration's default of no stream
    // payloads; qpdf's `--json-output` mode selects inline stream data unless
    // `--json-stream-data` was given (`QPDFJob_config.cc:312-326`), so the job
    // configuration owns both defaults.
    let stream_data = cli.json_stream_data.as_deref().map(|value| match value {
        "none" => JsonStreamData::None,
        "inline" => JsonStreamData::Inline,
        "file" => JsonStreamData::File,
        other => {
            emit_logger_error(format!(
                "flpdf: --json-stream-data must be none, inline, or file; got: {other}\n"
            ));
            std::process::exit(2);
        }
    });

    // 4. Resolve the input and output positions. With --empty, the first
    // positional is the output rather than an input because qpdf already has
    // its primary input from `Config::emptyInput`. An output that identifies
    // the input is rejected by `check_configuration` below, where qpdf rejects
    // it (`QUtil::same_file`, `libqpdf/QPDFJob.cc:626-630`).
    let input = if empty {
        None
    } else {
        Some(cli.input.as_ref().ok_or_else(missing_input_usage_error)?)
    };
    let output_path = if empty {
        if let Some(extra) = cli.output.as_ref() {
            return Err(UsageError::new(format!("unknown argument {}", extra.display())).into());
        }
        cli.input.as_deref()
    } else {
        cli.output.as_deref()
    };
    let mut job = QPDFJob::new();
    job.set_warnings_exit_zero(cli_warning_exit_zero());
    // This route builds its job directly rather than through `new_cli_job`,
    // so it needs the same carry (`QPDFJob.cc:505-509` prints from whichever
    // job finished the run, and `--json` finishes one like any other route).
    job.set_report_memory_usage(cli_report_memory_usage());
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(cli.no_warn);
    // qpdf applies these global input policies to every QPDF created by the
    // job, including attachment donors opened by copyAttachments
    // (`QPDFJob.cc:651-665,1695-1711`). The JSON route opens its primary
    // document directly, but its donors still cross `open_job_source`, which
    // reads these values from the job configuration.
    job.set_password_mode(cli.password.password_mode.into());
    job.set_password_is_hex_key(cli.password.password_is_hex_key);
    job.set_suppress_password_recovery(cli.password.suppress_password_recovery);
    job.set_suppress_recovery(cli.password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(cli.password.recovery.ignore_xref_streams);
    // `create_qpdf`'s primary-input open reads the password from the job's
    // own configuration rather than an argument, unlike the CLI-local
    // `open_pdf_from_file`/`pdf_open_options` helper this route used before.
    // Reuse that helper only for its `--password`/`--password-file` decoding
    // (hex-key parsing, `-` for stdin, and so on) and set the resulting bytes
    // on the job.
    let input_options = pdf_open_options(cli.repair, &cli.password)?;
    job.set_password(input_options.password);
    // qpdf builds this diagnostic from `pdf.getFilename()`
    // (`libqpdf/QPDFJob.cc:2129-2130`), so the create-stage job needs the
    // same input name the write routes already set.
    if let Some(input) = input {
        job.set_input_name_bytes(path_description(input));
    }
    // qpdf gates its attachment reports on the job's own verbosity
    // (`QPDFJob::doIfVerbose`, `libqpdf/QPDFJob.cc:340-345`, used by the
    // attach report at `:2067-2070`). The inspection-transformation
    // configurator sets it only when it has a transformation to install.
    job.set_verbose(cli.verbose);
    configure_top_level_attachment_mutations(&mut job, cli, attachment_segments)?;
    // The page-source file lifetime is a property of the job that runs the
    // merge, not of the write route: `QPDFJob::handlePageSpecs` consults
    // `m->keep_files_open` when it decides whether to hold every donor open
    // (`QPDFJob.cc:2404-2434`), and that runs inside `createQPDF` for JSON
    // output as much as for a PDF write. Without this the explicit
    // `--keep-files-open=n` is dropped and the job re-derives the policy from
    // the source count, announcing a selection qpdf never makes.
    configure_keep_files_open(&mut job, &cli.page_ops)?;

    // qpdf applies page selection, rotations, and underlay/overlay before the
    // remaining create-stage transformations inside `createQPDF`
    // (`libqpdf/QPDFJob.cc:428-481`), and only then does `writeQPDF` serialize
    // JSON (`libqpdf/QPDFJob.cc:428-480,484-489`). Queue every create-stage
    // configuration on this job so all three JSON input branches
    // (empty/json-input/plain) share the same canonical `create_qpdf`
    // boundary that `QPDFJob::prepare_document` already implements for the
    // rewrite/page-operation routes, instead of hand-rolling a narrower,
    // primary-input-only page-spec path here.
    //
    // The JSON output selectors belong to the same configuration: `writeQPDF`
    // dispatches on `createsOutput()` and `writeOutfile` chooses `writeJSON`'s
    // destination from the job's own output name
    // (`libqpdf/QPDFJob.cc:484-489,3031-3042,3093-3115`), so the destination
    // never travels as a separate argument.
    {
        let mut configuration = job.config();
        if !cli.page_ops.pages.is_empty() {
            let raw_specs = configured_page_specs(&cli.page_ops)?;
            for spec in &raw_specs {
                let password = spec.raw_password.clone().or_else(|| {
                    spec.password
                        .as_ref()
                        .map(|password| arg_parser::os_bytes(password))
                });
                configuration.add_page_spec(
                    PathBuf::from(&spec.file_token),
                    &spec.range,
                    password,
                )?;
            }
        }
        for parameter in &cli.page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        for parameter in &cli.page_ops.rotate {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        // An explicit `--remove-unreferenced-resources` must reach the job, or
        // it stays at `Auto` and the shared-resource heuristic decides instead
        // -- which qpdf only does when the option was not given
        // (`QPDFJob.cc:2484-2510`). The other `create_qpdf` page-selection
        // routes set this the same way.
        configuration.remove_unreferenced_resources(cli.remove_unreferenced_resources.into());
        // qpdf reuses `--encryption-file-password` for a page source whose
        // filename matches the `--copy-encryption` donor
        // (`QPDFJob.cc:1240-1252`). That fallback needs the donor configured
        // on this job; otherwise the donor opens with an empty password.
        if let Some(path) = cli.copy_encryption.as_ref() {
            let password = cli
                .raw_encryption_file_password
                .clone()
                .or_else(|| {
                    cli.encryption_file_password
                        .as_ref()
                        .map(|password| arg_parser::os_bytes(password))
                })
                .unwrap_or_default();
            configuration.copy_encryption(path.clone(), password);
        }
        if empty {
            configuration.empty_input()?;
        } else {
            configuration.input_file(
                input
                    .expect("a non-empty JSON job has an input")
                    .to_path_buf(),
            )?;
        }
        if cli.json_input {
            configuration.json_input();
        }
        if let Some(update_from_json) = cli.update_from_json.as_deref() {
            configuration.update_from_json(update_from_json.to_path_buf());
        }
        if let Some(path) = output_path {
            configuration.output_file(path.to_path_buf())?;
        }
        if json_output_mode {
            configuration.json_output(json_version);
        } else {
            configuration.json(json_version);
        }
        for key in &json_keys {
            configuration.json_key(*key);
        }
        for object in &json_objects {
            configuration.json_object(object.clone());
        }
        if let Some(stream_data) = stream_data {
            configuration.json_stream_data(stream_data);
        }
        if let Some(prefix) = cli.json_stream_prefix.as_deref() {
            configuration.json_stream_prefix(arg_parser::os_bytes(prefix));
        }
        if cli.test_json_schema {
            configuration.test_json_schema();
        }
        if let Some(decode_level) = cli.decode_level {
            configuration.decode_level(StreamDecodeLevel::from(decode_level));
        }
    }
    // `create_qpdf`'s `prepare_document` already applies every create-stage
    // transformation queued on the configuration (rotations, copy-attachments,
    // page selection, ...) exactly once (`libqpdf/QPDFJob.cc:428-481`).
    // Queue the inspection-only transformations (image externalization,
    // appearance generation, annotation/rotation flattening,
    // remove-restrictions, coalesce-contents) here too, on the *same*
    // configuration, instead of applying them a second time afterward through
    // `QPDFJob::apply_transformations` -- that second pass would re-run
    // `prepare_document_transformations` against the unchanged configuration
    // and re-execute already-applied, non-idempotent steps such as
    // `copy_attachments_from`.
    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        cli.verbose,
        cli.remove_restrictions,
        cli.coalesce_contents,
    )?;
    job.set_show_encryption_key(cli.show_encryption_key);
    // `QPDFJob::createQPDF` runs `checkConfiguration` before it opens the
    // primary input (`libqpdf/QPDFJob.cc:428-431`). It assigns the implicit
    // JSON destination `-` when no output file was given and reserves standard
    // output for the JSON document, so warnings and later info cannot claim
    // the stream the document itself needs (`:582-586,613-625`).
    job.check_configuration()?;

    let mut pdf = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    run_json_document(&mut job, &mut pdf)
}

fn run_json_input_inspection(
    cli: &Cli,
    transform_options: InspectionTransformOptions<'_>,
    overlay_specs: &[OverlaySpec],
    attachment_segments: &[Vec<Vec<u8>>],
) -> CliResult<()> {
    if cli.page_ops.empty {
        reject_empty_inspection_output(cli.input.as_deref())?;
        let mut job = new_cli_job(cli.no_warn);
        configure_top_level_inspection_job(&mut job, cli)?;
        configure_cli_overlay_specs(&mut job, overlay_specs)?;
        configure_top_level_inspection_transformations(
            &mut job,
            transform_options,
            cli.verbose,
            cli.remove_restrictions,
            cli.coalesce_contents,
        )?;
        if cli.show_attachment.is_some() {
            job.logger().save_to_standard_output(true)?;
        }
        configure_top_level_attachment_mutations(&mut job, cli, attachment_segments)?;
        let mut pdf = create_empty_primary_document(&mut job, cli.update_from_json.as_deref())?;
        job.apply_transformations(&mut pdf)?;
        return run_job_inspection_on_pdf(cli, &mut job, &mut pdf);
    }
    let input = cli.input.as_ref().ok_or_else(missing_input_usage_error)?;
    let mut job = QPDFJob::new();
    job.set_warnings_exit_zero(cli_warning_exit_zero());
    // This route builds its job directly rather than through `new_cli_job`,
    // so it needs the same carry (`QPDFJob.cc:505-509` prints from whichever
    // job finished the run, and `--json` finishes one like any other route).
    job.set_report_memory_usage(cli_report_memory_usage());
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(cli.no_warn);
    configure_top_level_inspection_job(&mut job, cli)?;
    configure_cli_overlay_specs(&mut job, overlay_specs)?;
    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        cli.verbose,
        cli.remove_restrictions,
        cli.coalesce_contents,
    )?;
    if cli.show_attachment.is_some() {
        job.logger().save_to_standard_output(true)?;
    }
    configure_top_level_attachment_mutations(&mut job, cli, attachment_segments)?;

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

    if cli.json_input {
        let mut pdf = job
            .create_from_json_document(file, path_description(input))
            .map_err(|error| json_error_with_file(input, Box::new(error)))?;
        apply_json_update_with_job(&mut job, &mut pdf, cli.update_from_json.as_deref())?;
        job.apply_transformations(&mut pdf)?;
        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_with_description(BufReader::new(file), path_description(input), 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())?;
    job.apply_transformations(&mut pdf)?;
    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<()> {
    configure_top_level_inspection_job(job, cli)?;
    match job.inspect_configured(pdf) {
        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)),
    }
}

/// Write one already-created job document through the job's own write stage.
///
/// `QPDFJob::writeQPDF` dispatches on `createsOutput()` and, for a JSON job,
/// reaches `writeJSON` through `writeOutfile`, which picks the destination
/// from the job's own output name (`libqpdf/QPDFJob.cc:484-489,3031-3042,
/// 3093-3115`). The CLI therefore configures the destination and hands the
/// document over rather than selecting an output itself.
fn run_json_document<R: Read + Seek + 'static>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
) -> CliResult<()> {
    match job.write_qpdf(pdf) {
        Ok(()) => finish_job_exit_status(job.get_exit_code()),
        // qpdf's `QPDFUsage` escapes `writeQPDF` uncaught and is rendered by
        // `usageExit` (`qpdf/qpdf.cc:37-38`); `writeJSON` raises one for a
        // stdout destination that cannot name its stream side files.
        Err(Error::Usage(error)) => Err(Box::new(error)),
        // Every other write failure has already been reported by the job.
        Err(_) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
    }
}

fn run_command(command: Commands, overlay_specs: &[OverlaySpec]) -> CliResult<()> {
    match command {
        Commands::Check(cmd) => run_check(
            Some(cmd.input),
            cmd.repair,
            &cmd.password,
            false,
            false,
            false,
            InspectionTransformOptions::new(ImageTransformOptions::default(), false, None),
            false,
        ),
        Commands::CheckLinearization(cmd) => run_check_linearization(
            Some(cmd.input),
            false,
            &PasswordArgs::default(),
            false,
            false,
            InspectionTransformOptions::new(ImageTransformOptions::default(), false, None),
            false,
        ),
        Commands::Pages(cmd) => {
            if cmd.show_npages {
                run_show_npages(
                    Some(cmd.input),
                    cmd.repair,
                    &cmd.password,
                    false,
                    false,
                    InspectionTransformOptions::new(ImageTransformOptions::default(), false, None),
                    false,
                )
            } else {
                run_show_pages(
                    Some(cmd.input),
                    cmd.repair,
                    &cmd.password,
                    false,
                    false,
                    false,
                    InspectionTransformOptions::new(ImageTransformOptions::default(), false, None),
                    false,
                )
            }
        }
        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::ZlibFlate(cmd) => {
            let whoami = progname();
            let usage_name = format!("{whoami} zlib-flate");
            run_zlib_flate(&cmd.modes, &whoami, &usage_name)
        }
        Commands::ShowEncryption(cmd) => {
            // The native subcommand has no `--show-encryption-key` flag of its
            // own (the dedicated `show-encryption-key` subcommand covers that
            // need); only the qpdf-argv-compatible top-level `--show-encryption`
            // flag combines with `--show-encryption-key`.
            run_show_encryption(
                Some(cmd.input),
                cmd.repair,
                &cmd.password,
                false,
                false,
                false,
                InspectionTransformOptions::new(ImageTransformOptions::default(), false, None),
                false,
            )
        }
        Commands::IsEncrypted(cmd) => {
            let password = PasswordArgs {
                recovery: cmd.recovery,
                ..PasswordArgs::default()
            };
            run_is_encrypted(&cmd.input, cmd.repair, &password, false)
        }
        Commands::RequiresPassword(cmd) => {
            run_requires_password(&cmd.input, cmd.repair, &cmd.password, false)
        }
        Commands::ShowEncryptionKey(cmd) => {
            run_show_encryption_key(&cmd.input, cmd.repair, &cmd.password)
        }
        Commands::Rewrite(mut cmd) => {
            // qpdf keeps --verbose on QPDFJob, so the subcommand's copy of the
            // password arguments must carry the job policy to the reader's
            // retry boundary exactly like the top-level path does.
            cmd.password.verbose = cmd.verbose;
            validate_collate_values(&cmd.page_ops.collate);
            validate_keep_files_open_threshold(&cmd.page_ops)?;
            let version_options = match parse_cli_version_options(
                cmd.min_version.as_deref(),
                cmd.force_version.as_deref(),
            ) {
                Ok(options) => options,
                Err(error) => {
                    emit_logger_error(format!("flpdf: {error}\n"));
                    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,
                progress: cmd.progress,
                report_memory_usage: cmd.report_memory_usage,
                // `--qdf` and `--deterministic-id` configure the canonical writer's
                // output preparation directly.
                qdf: cmd.qdf,
                password_mode: cmd.password.password_mode.into(),
                allow_weak_crypto: cmd.password.allow_weak_crypto,
                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: newline_before_endstream_setting(
                    cmd.newline_before_endstream,
                ),
                // --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,
                compression_level: parse_compression_level(cmd.compression_level.as_deref())?,
                ..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,
                EncryptionCliOptions {
                    encrypt: cmd.raw_encrypt.as_deref(),
                    encrypt_segments: None,
                    parsed_encrypt_segments: cmd.parsed_encrypt_segments.as_deref(),
                    copy_encryption: cmd.copy_encryption.as_deref(),
                    encryption_file_password: cmd.raw_encryption_file_password.as_deref(),
                    password_args: &cmd.password,
                    suppress_warnings: false,
                    last_mode: None,
                },
            );
            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;
            let image_options = image_optimization_options(
                cmd.keep_inline_images,
                cmd.oi_min_width.as_deref(),
                cmd.oi_min_height.as_deref(),
                cmd.oi_min_area.as_deref(),
                cmd.ii_min_bytes.as_deref(),
            )?;
            let image_transform_options = ImageTransformOptions::new(
                cmd.externalize_inline_images,
                cmd.optimize_images,
                image_options,
            );

            // Page-operation dispatch. When --pages is set
            // the extraction pipeline owns the write; otherwise --rotate /
            // --split-pages decorate a plain rewrite. Linearization is a
            // writer setting applied after the page-operation mutations, just
            // as qpdf applies `setWriterOptions` after `createQPDF`.
            if page_ops_active(&cmd.page_ops) {
                // 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() {
                    emit_logger_error(
                        "flpdf: --overlay/--underlay is not applied with \
                         --rotate/--split-pages alone (no --pages); \
                         rerun with --pages or without the overlay\n",
                    );
                    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 explicit --encrypt and content normalization, are
                // applied by the final QPDFJob writer and are therefore accepted
                // here.
                // --coalesce-contents is handled separately below: it is a
                // page transformation with the same post-selection owner as
                // generate-appearances and flatten-annotations.
                // --optimize-images and --externalize-inline-images are NOT in
                // this list: unlike the other
                // rewrite-only mutation passes above, the page-operation
                // functions below (run_page_extraction /
                // run_rewrite_with_page_ops) already accept and apply it via
                // `image_transform_options`, mirroring
                // the top-level --pages/--rotate/--split-pages routes.
                // --copy-encryption is carried in WriterOptions and applied
                // by the final writer for each page-operation output.
                // 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
                {
                    emit_logger_error(
                        "flpdf: --remove-unreferenced-resources is not applied \
                         with --rotate/--split-pages alone; rerun without it \
                         or add --pages\n",
                    );
                    std::process::exit(1);
                }
                return if cmd.page_ops.empty && !cmd.page_ops.pages.is_empty() {
                    // `PageOpArgs` is shared with the top-level surface, whose
                    // `--empty --pages` route dispatches here too (main
                    // dispatch, `args.page_ops.empty && ...`); without this
                    // arm `cmd.input` (unused for an empty primary) is
                    // rejected instead of routed, and the two surfaces
                    // silently diverge on the identical flag combination.
                    run_empty_page_extraction(
                        &cmd.output,
                        &cmd.password,
                        None,
                        &cmd.page_ops,
                        overlay_specs,
                        remove_unref,
                        cmd.remove_restrictions,
                        cmd.decrypt,
                        options,
                        cmd.linearize,
                        None,
                        image_transform_options,
                        cmd.coalesce_contents,
                        cmd.generate_appearances,
                        cmd.flatten_annotations,
                        cmd.flatten_rotation,
                        cmd.verbose,
                        false,
                    )
                } else if !cmd.page_ops.pages.is_empty() {
                    run_page_extraction(
                        &cmd.input,
                        &cmd.output,
                        cmd.repair,
                        &cmd.password,
                        &cmd.page_ops,
                        overlay_specs,
                        remove_unref,
                        cmd.remove_restrictions,
                        cmd.decrypt,
                        options,
                        cmd.linearize,
                        None,
                        image_transform_options,
                        cmd.coalesce_contents,
                        cmd.generate_appearances,
                        cmd.flatten_annotations,
                        cmd.flatten_rotation,
                        cmd.verbose,
                        false,
                    )
                } else {
                    run_rewrite_with_page_ops(
                        &cmd.input,
                        &cmd.output,
                        cmd.repair,
                        &cmd.password,
                        false,
                        None,
                        &cmd.page_ops,
                        remove_unref,
                        cmd.remove_restrictions,
                        cmd.decrypt,
                        options,
                        cmd.linearize,
                        None,
                        image_transform_options,
                        cmd.coalesce_contents,
                        cmd.generate_appearances,
                        cmd.flatten_annotations,
                        cmd.flatten_rotation,
                        cmd.verbose,
                        false,
                    )
                };
            }

            run_rewrite(
                Some(cmd.input),
                Some(cmd.output),
                false,
                cmd.repair,
                &cmd.password,
                false,
                None,
                cmd.linearize,
                None,
                cmd.remove_restrictions,
                cmd.decrypt,
                normalize_content,
                coalesce_contents,
                remove_unref,
                cmd.generate_appearances,
                image_transform_options,
                cmd.flatten_annotations,
                cmd.flatten_rotation,
                page_label_options(cmd.set_page_labels.as_deref(), cmd.remove_page_labels),
                overlay_specs,
                cmd.verbose,
                false, // no_warn: the `rewrite` subcommand has no --no-warn flag
                options,
                cmd.page_ops.empty,
            )
        }
    }
}

/// `flpdf check FILE`: the flpdf-native subcommand. This has no qpdf argv
/// counterpart -- qpdf has no subcommand grammar -- so it is not part of the
/// top-level `--check` inspection dispatch and keeps its own standalone
/// document-open/run sequence rather than routing through
/// [`run_combined_top_level_inspection`].
#[allow(clippy::too_many_arguments)]
fn run_check(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
    show_encryption_key: bool,
    empty: bool,
    transform_options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    let mut job = new_cli_job(no_warn);
    job.set_show_encryption_key(show_encryption_key);
    job.set_verbose(verbose);
    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        verbose,
        false,
        false,
    )?;
    {
        let mut configuration = job.config();
        configuration.check();
    }
    if empty {
        reject_empty_inspection_output(input.as_deref())?;
        job.config().empty_input()?;
    } else {
        let input = input.ok_or_else(missing_input_usage_error)?;
        let input_options = pdf_open_options(repair, password)?;
        job.set_input_file(input)?;
        job.set_password(input_options.password);
        job.set_password_mode(password.password_mode.into());
        job.set_password_is_hex_key(password.password_is_hex_key);
        job.set_suppress_password_recovery(password.suppress_password_recovery);
        job.set_suppress_recovery(password.recovery.suppress_recovery);
        job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    }
    finish_job_exit_status(job.run()?)
}

/// `flpdf check-linearization FILE`: the flpdf-native subcommand
/// counterpart of `run_check` above -- same qpdf-grammar-free scope.
fn run_check_linearization(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
    empty: bool,
    transform_options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    if empty {
        reject_empty_inspection_output(input.as_deref())?;
        let mut job = new_cli_job(no_warn);
        let mut pdf = create_empty_primary_document(&mut job, None)?;
        apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
        return finish_job_exit_status(job.show_linearization(&mut pdf)?);
    }
    let input = input.ok_or_else(missing_input_usage_error)?;
    let file = File::open(&input).map_err(|error| open_error_with_file(&input, error.into()))?;
    let mut job = new_cli_job(no_warn);
    let options = pdf_open_options(repair, password)?;
    let mut pdf = job
        .open_with_description(BufReader::new(file), path_description(&input), options)
        .map_err(|error| error_with_file(&input, actionable_password_error(error)))?;
    apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
    finish_job_exit_status(job.check_linearization(&mut pdf)?)
}

struct EncryptionCliOptions<'a> {
    encrypt: Option<&'a [Vec<u8>]>,
    encrypt_segments: Option<&'a [Vec<Vec<u8>>]>,
    parsed_encrypt_segments: Option<&'a [ParsedEncryptSegment]>,
    copy_encryption: Option<&'a std::path::Path>,
    encryption_file_password: Option<&'a [u8]>,
    password_args: &'a PasswordArgs,
    suppress_warnings: bool,
    last_mode: Option<EncryptionMode>,
}

/// Wire the final qpdf encryption mode onto `options`, shared by the
/// top-level and `rewrite` surfaces. A `--encrypt` parse error prints a
/// `progname:`-prefixed diagnostic and exits 2, matching the surrounding
/// option parsers; a `--copy-encryption` donor-open/validation failure goes
/// through [`exit_with_cli_error`] so it is framed exactly like the
/// primary-input failure it is in qpdf. qpdf's Config setters clear the other
/// modes, so only the last mode in argv order is applied.
fn apply_encryption_options(options: &mut WriterOptions, inputs: EncryptionCliOptions<'_>) {
    let EncryptionCliOptions {
        encrypt,
        encrypt_segments,
        parsed_encrypt_segments,
        copy_encryption,
        encryption_file_password,
        password_args,
        suppress_warnings,
        last_mode,
    } = inputs;
    let parsed_encrypt = parsed_encrypt_segments
        .and_then(|segments| segments.last().cloned())
        .or_else(|| {
            encrypt_segments.map(|segments| {
                let mut parsed = None;
                for segment in segments {
                    match parse_encrypt_segment(segment) {
                        Ok(value) => parsed = Some(value),
                        Err(error) => {
                            emit_logger_error(format!("{}: {error}\n", progname()));
                            std::process::exit(2);
                        }
                    }
                }
                parsed.expect("non-empty encrypt segment list")
            })
        });
    match last_mode.or_else(|| {
        if encrypt.is_some() {
            Some(EncryptionMode::Encrypt)
        } else if copy_encryption.is_some() {
            Some(EncryptionMode::CopyEncryption)
        } else {
            None
        }
    }) {
        Some(EncryptionMode::Encrypt) => {
            let parsed = parsed_encrypt.or_else(|| {
                encrypt.map(|encrypt| match parse_encrypt_segment(encrypt) {
                    Ok(value) => value,
                    Err(error) => {
                        emit_logger_error(format!("{}: {error}\n", progname()));
                        std::process::exit(2);
                    }
                })
            });
            if let Some(parsed) = parsed {
                // qpdf's own -accessibility=n notice comes from
                // QPDFJob::setEncryptionOptions, called once per split-pages
                // chunk from inside the per-chunk write loop
                // (QPDFJob.cc:2746-2747, QPDFJob.cc:2976-3022). Route this
                // through the job's accessibility_disabled field (applied
                // below via job.set_accessibility_disabled) so the library's
                // own prepare_writer_configuration -- already called once
                // per chunk -- emits the notice with the correct
                // repeat count, instead of a single, argument-parse-time
                // print here.
                options.accessibility_disabled = parsed.accessibility_warning;
                options.allow_insecure = parsed.allow_insecure;
                options.encrypt = Some(parsed.params);
            }
        }
        Some(EncryptionMode::CopyEncryption) => {
            if let Some(donor_path) = copy_encryption {
                match build_copy_encryption_source(
                    donor_path,
                    encryption_file_password,
                    password_args,
                    suppress_warnings,
                ) {
                    Ok(src) => {
                        if let Some(src) = src {
                            options.copy_encryption = Some(src);
                        } else {
                            // qpdf's QPDFWriter::copyEncryptionParameters
                            // clears implicit source-encryption preservation
                            // before inspecting the donor (`QPDFWriter.cc:651-658`).
                            options.preserve_encryption = false;
                        }
                    }
                    Err(error) => exit_with_cli_error(error),
                }
            }
        }
        Some(EncryptionMode::Decrypt) | None => {}
    }
}

/// 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 the donor's [`CopyEncryptionSource`], or `None` for qpdf's explicit
/// plaintext-donor no-op, or the open failure in the same shape the
/// primary-input open boundary produces, for [`exit_with_cli_error`] to render
/// before `exit(2)`.
///
/// The accepted Standard-handler matrix is V=1/V=2 RC4, V=4 canonicalized to
/// AESV2, and V=5 AESV3, matching qpdf's `copyEncryptionParameters` path.
fn build_copy_encryption_source(
    path: &std::path::Path,
    password: Option<&[u8]>,
    password_args: &PasswordArgs,
    suppress_warnings: bool,
) -> CliResult<Option<CopyEncryptionSource>> {
    // qpdf opens the donor through the same `QPDFJob::processFile` boundary as
    // the primary input (`libqpdf/QPDFJob.cc:2891-2899` vs `:434`), so a donor
    // failure carries no option-specific framing: it reaches `realmain`'s one
    // `catch` as `whoami: e.what()` exactly like a primary-input failure.
    let file = File::open(path).map_err(|error| open_error_with_file(path, error.into()))?;
    let reader = BufReader::new(file);

    let mut donor_password = password_args.clone();
    donor_password.set_password_bytes(password.map(ToOwned::to_owned));
    donor_password.password_file = None;
    let opts = pdf_open_options(true, &donor_password)?;
    let mut job = QPDFJob::new();
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(suppress_warnings);
    let mut donor = job
        .open_with_description(reader, path_description(path), opts)
        .map_err(|error| error_with_file(path, actionable_password_error(error)))?;
    donor
        .root_handle()
        .map_err(|error| error_with_file(path, actionable_password_error(error)))?;

    // Validate the donor is encrypted using qpdf's individual encryption
    // projections rather than a crate-specific aggregate information object.
    let Some(version) = donor.encryption_version() else {
        // qpdf's copyEncryptionParameters leaves the writer unencrypted when
        // the donor trailer has no `/Encrypt`; absence is an explicit no-op,
        // not a malformed donor (`QPDFWriter.cc:651-658`).
        return Ok(None);
    };
    // qpdf's QPDFWriter::copyEncryptionParameters reads V, R, and /Length and
    // feeds them straight to setEncryptionParametersInternal, which chooses
    // RC4 for V<4 and AES for V>=4 without validating the combination
    // (`QPDFWriter.cc:651-702`). The donor boundary therefore checks only
    // that the trailer has an /Encrypt dictionary at all.

    // 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 Some(mut source) = donor.writer_copy_encryption_source()? else {
        return Ok(None);
    };
    source.file_key = file_key;
    source.object_key_alg = if version >= 4 {
        ObjectKeyAlg::Aes
    } else {
        ObjectKeyAlg::Rc4
    };
    Ok(Some(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`, and `--modify-other`) use the
/// key-length-specific qpdf option table and are applied left-to-right. R=2
/// uses its separate four-bit permission configuration; R>=3 uses
/// [`PermissionsConfig`]. `--cleartext-metadata` promotes 128-bit output to
/// V=4, while `--force-R5` selects the 256-bit R=5 path.
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()),
    }
}
#[derive(Debug, Clone)]
struct ParsedEncryptSegment {
    params: EncryptParams,
    accessibility_warning: bool,
    /// qpdf keeps `--allow-insecure` on the job
    /// (`QPDFJob::EncConfig::allowInsecure`,
    /// `libqpdf/QPDFJob_config.cc:1171-1174`) so `QPDFJob.cc:601`'s refusal
    /// can see it. The CLI parses the flag here, so it must travel to the job
    /// rather than being consumed by this segment alone.
    allow_insecure: bool,
}

trait RawCliArg {
    fn raw_bytes(&self) -> Vec<u8>;
    fn os_string(&self) -> OsString;
}

impl RawCliArg for String {
    fn raw_bytes(&self) -> Vec<u8> {
        self.as_bytes().to_vec()
    }

    fn os_string(&self) -> OsString {
        OsString::from(self)
    }
}

impl RawCliArg for OsString {
    fn raw_bytes(&self) -> Vec<u8> {
        arg_parser::os_bytes(self)
    }

    fn os_string(&self) -> OsString {
        self.clone()
    }
}

impl RawCliArg for Vec<u8> {
    fn raw_bytes(&self) -> Vec<u8> {
        self.clone()
    }

    fn os_string(&self) -> OsString {
        arg_parser::os_string_from_bytes(self)
    }
}

impl RawCliArg for arg_parser::RawArg {
    fn raw_bytes(&self) -> Vec<u8> {
        self.as_bytes().to_vec()
    }

    fn os_string(&self) -> OsString {
        self.as_os_str().to_os_string()
    }
}

/// Return qpdf's active option-table name for an encryption segment.
///
/// qpdf selects the key-length-specific table as soon as it consumes the
/// third positional argument or `--bits`; `QPDFArgParser` includes that table
/// name in unknown-argument diagnostics (`QPDFArgParser.cc:496-502`).
fn encrypt_option_table_name(key_len: Option<u32>) -> &'static str {
    match key_len {
        Some(40) => "40-bit encryption",
        Some(128) => "128-bit encryption",
        Some(256) => "256-bit encryption",
        None | Some(_) => "encryption",
    }
}

/// Return whether the active qpdf encryption option table registers `name`.
/// qpdf switches tables immediately after consuming the key length, so an
/// option from another key-length table must fail at that token rather than
/// being deferred until the segment terminator (`auto_job_init.hh:133-166`).
fn encryption_option_table_accepts(key_len: Option<u32>, name: &str) -> bool {
    match key_len {
        None => matches!(name, "user-password" | "owner-password" | "bits"),
        Some(40) => matches!(name, "extract" | "annotate" | "print" | "modify"),
        Some(128) => matches!(
            name,
            "cleartext-metadata"
                | "force-V4"
                | "accessibility"
                | "extract"
                | "print"
                | "assemble"
                | "annotate"
                | "form"
                | "modify-other"
                | "modify"
                | "use-aes"
        ),
        Some(256) => matches!(
            name,
            "cleartext-metadata"
                | "force-R5"
                | "allow-insecure"
                | "accessibility"
                | "extract"
                | "print"
                | "assemble"
                | "annotate"
                | "form"
                | "modify-other"
                | "modify"
        ),
        Some(_) => false,
    }
}

fn unrecognized_encrypt_argument(token: &str, key_len: Option<u32>) -> UsageError {
    UsageError::new(format!(
        "unrecognized argument {token} ({} options must be terminated with --)",
        encrypt_option_table_name(key_len)
    ))
}

#[derive(Debug, Clone)]
struct EncryptSubFlag {
    original: Vec<u8>,
    canonical: Vec<u8>,
}

struct EncryptSegmentCallbackState {
    positional: Vec<Vec<u8>>,
    dashed_mode: bool,
    positional_mode: bool,
    user_password: Option<Vec<u8>>,
    owner_password: Option<Vec<u8>>,
    key_len: Option<u32>,
    key_len_seen: bool,
    subflags: Vec<EncryptSubFlag>,
}

impl EncryptSegmentCallbackState {
    fn new() -> Self {
        Self {
            positional: Vec::new(),
            dashed_mode: false,
            positional_mode: false,
            user_password: None,
            owner_password: None,
            key_len: None,
            key_len_seen: false,
            subflags: Vec::new(),
        }
    }

    fn push(&mut self, original: &[u8], canonical: &[u8]) -> CliResult<()> {
        let token_text = String::from_utf8_lossy(original);
        let equal = canonical.iter().position(|byte| *byte == b'=');
        let (raw_name, attached) = match equal {
            Some(position) => (&canonical[..position], Some(&canonical[position + 1..])),
            None => (canonical, None),
        };
        let option_name = segment_option_name(raw_name);

        if let Some(name) = option_name {
            if !encryption_option_table_accepts(self.key_len, name) {
                return Err(unrecognized_encrypt_argument(&token_text, self.key_len).into());
            }
            if matches!(name, "user-password" | "owner-password" | "bits") {
                if self.positional_mode {
                    return Err(Box::new(UsageError::new(
                        "positional and dashed encryption arguments may not be mixed",
                    )));
                }
                let value = attached.ok_or_else(|| {
                    let parameter = match name {
                        "user-password" => "user_password",
                        "owner-password" => "owner_password",
                        // qpdf's dashed `--bits` shares `auto_job_init.hh`'s
                        // `choices` set with the top-level `--bits` flag, so a
                        // missing value renders the same
                        // `QPDFArgParser::checkCompletion` message
                        // (`libqpdf/QPDFArgParser.cc:505-522`) as an invalid
                        // one: dictionary-sorted `{128,256,40}` (the
                        // `std::set<std::string>` choices are string-ordered,
                        // not numeric), not the numeric order used below.
                        "bits" => "{128,256,40}",
                        _ => unreachable!("name was matched above"),
                    };
                    Box::new(UsageError::new(format!(
                        "--{name} must be given as --{name}={parameter}"
                    ))) as Box<dyn std::error::Error>
                })?;
                self.dashed_mode = true;
                match name {
                    "user-password" => self.user_password = Some(value.to_vec()),
                    "owner-password" => self.owner_password = Some(value.to_vec()),
                    "bits" => {
                        self.key_len =
                            Some(parse_dashed_encrypt_bits(&String::from_utf8_lossy(value))?);
                        self.key_len_seen = true;
                    }
                    _ => unreachable!("name was matched above"),
                }
                return Ok(());
            }
        }

        if canonical.starts_with(b"-") && canonical != b"-" {
            if self.dashed_mode && !self.key_len_seen {
                return Err(unrecognized_encrypt_argument(&token_text, self.key_len).into());
            }
            if !self.dashed_mode && self.positional.len() < 3 {
                return Err(unrecognized_encrypt_argument(&token_text, self.key_len).into());
            }
            self.subflags.push(EncryptSubFlag {
                original: original.to_vec(),
                canonical: canonical.to_vec(),
            });
            return Ok(());
        }

        if self.dashed_mode {
            return Err(Box::new(UsageError::new(
                "positional and dashed encryption arguments may not be mixed",
            )));
        }
        if self.positional.len() < 3 {
            self.positional_mode = true;
            self.positional.push(canonical.to_vec());
            if self.positional.len() == 3 {
                self.key_len = Some(parse_encrypt_key_len(&String::from_utf8_lossy(canonical))?);
            }
            return Ok(());
        }

        Err(unrecognized_encrypt_argument(&token_text, self.key_len).into())
    }

    fn finish(self) -> CliResult<ParsedEncryptSegment> {
        let EncryptSegmentCallbackState {
            positional,
            dashed_mode,
            user_password,
            owner_password,
            key_len,
            subflags,
            ..
        } = self;
        finish_encrypt_segment(
            positional,
            dashed_mode,
            user_password,
            owner_password,
            key_len,
            subflags,
        )
    }
}

fn parse_encrypt_segment<T: RawCliArg>(tokens: &[T]) -> CliResult<ParsedEncryptSegment> {
    let mut parser = EncryptSegmentCallbackState::new();
    for token in tokens {
        let token_bytes = token.raw_bytes();
        parser.push(&token_bytes, &token_bytes)?;
    }
    parser.finish()
}

fn finish_encrypt_segment(
    positional: Vec<Vec<u8>>,
    dashed_mode: bool,
    user_password: Option<Vec<u8>>,
    owner_password: Option<Vec<u8>>,
    key_len: Option<u32>,
    subflags: Vec<EncryptSubFlag>,
) -> CliResult<ParsedEncryptSegment> {
    let (user_password, owner_password, key_len) = if dashed_mode {
        if key_len.is_none() && !subflags.is_empty() {
            return Err(Box::new(UsageError::new(
                "--encrypt key length is required before encryption options",
            )));
        }
        (
            user_password.unwrap_or_default(),
            owner_password.unwrap_or_default(),
            key_len.ok_or_else(|| {
                Box::new(UsageError::new("encryption key length is required"))
                    as Box<dyn std::error::Error>
            })?,
        )
    } else {
        if positional.len() < 3 {
            return Err(Box::new(UsageError::new(
                "encryption key length is required",
            )));
        }
        let key_len = key_len.ok_or_else(|| {
            Box::new(UsageError::new("encryption key length is required"))
                as Box<dyn std::error::Error>
        })?;
        (positional[0].clone(), positional[1].clone(), key_len)
    };

    let mut use_aes = None;
    let mut force_v4 = false;
    let mut force_r5 = false;
    let mut allow_insecure = false;
    let mut perms = PermissionsConfig::default();
    let mut r2_permissions = R2PermissionsConfig::default();
    let mut cleartext_metadata = false;
    let mut accessibility_explicitly_disabled = false;

    for token in &subflags {
        let token_text = String::from_utf8_lossy(&token.original);
        let token_bytes = &token.canonical;
        let equal = token_bytes.iter().position(|byte| *byte == b'=');
        let (raw_flag, value_bytes) = match equal {
            Some(position) => (&token_bytes[..position], &token_bytes[position + 1..]),
            None => (token_bytes.as_slice(), b"".as_slice()),
        };
        let flag = raw_flag
            .strip_prefix(b"--")
            .or_else(|| raw_flag.strip_prefix(b"-"))
            .and_then(|flag| std::str::from_utf8(flag).ok())
            .unwrap_or("");
        let value = match std::str::from_utf8(value_bytes) {
            Ok(value) => value,
            Err(_) => return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into()),
        };
        match flag {
            "use-aes" => {
                if key_len != 128 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                use_aes = Some(parse_perm_yn(flag, value)?);
            }
            "force-V4" => {
                if key_len != 128 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                force_v4 = true;
            }
            "force-R5" => {
                if key_len != 256 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                force_r5 = true;
            }
            "allow-insecure" => {
                if key_len != 256 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                allow_insecure = true;
            }
            "cleartext-metadata" => {
                if !matches!(key_len, 128 | 256) {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                cleartext_metadata = true;
            }
            "print" => {
                if key_len == 40 {
                    r2_permissions.print = parse_perm_yn(flag, value)?;
                } else {
                    perms.print = match value {
                        "full" => PrintPermission::High,
                        "low" => PrintPermission::Low,
                        "none" => PrintPermission::None,
                        other => {
                            return Err(format!(
                                "--print must be full, low, or none (got {other:?})"
                            )
                            .into());
                        }
                    };
                }
            }
            "modify" => {
                if key_len == 40 {
                    r2_permissions.modify = parse_perm_yn(flag, value)?;
                } else {
                    let (other, annotate, forms, assemble) = match value {
                        "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 = annotate;
                    perms.fill_forms = forms;
                    perms.assemble = assemble;
                }
            }
            "extract" => {
                let value = parse_perm_yn(flag, value)?;
                if key_len == 40 {
                    r2_permissions.extract = value;
                } else {
                    perms.extract = value;
                }
            }
            "annotate" => {
                let value = parse_perm_yn(flag, value)?;
                if key_len == 40 {
                    r2_permissions.annotate = value;
                } else {
                    perms.annotate = value;
                }
            }
            "form" => {
                if key_len == 40 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                perms.fill_forms = parse_perm_yn(flag, value)?;
            }
            "assemble" => {
                if key_len == 40 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                perms.assemble = parse_perm_yn(flag, value)?;
            }
            "accessibility" => {
                if key_len == 40 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                perms.accessibility = parse_perm_yn(flag, value)?;
                accessibility_explicitly_disabled = value == "n";
            }
            "modify-other" => {
                if key_len == 40 {
                    return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
                }
                perms.modify_contents = parse_perm_yn(flag, value)?;
            }
            _other => {
                return Err(unrecognized_encrypt_argument(&token_text, Some(key_len)).into());
            }
        }
    }

    if key_len == 40 && (force_r5 || allow_insecure || cleartext_metadata) {
        return Err("--encrypt KEY-LEN=40 does not accept this encryption option".into());
    }
    if key_len == 128 && (force_r5 || allow_insecure) {
        return Err("--encrypt KEY-LEN=128 does not accept this encryption option".into());
    }
    if key_len == 256 && (force_v4 || use_aes.is_some()) {
        return Err("--encrypt KEY-LEN=256 does not accept --force-V4 or --use-aes".into());
    }

    let method = match key_len {
        40 => EncryptMethod::V1Rc440,
        128 if force_v4 || cleartext_metadata => {
            if use_aes.unwrap_or(false) {
                EncryptMethod::V4Aes128
            } else {
                EncryptMethod::V4Rc4128
            }
        }
        128 if use_aes == Some(true) => EncryptMethod::V4Aes128,
        128 => EncryptMethod::V2Rc4128,
        256 if force_r5 => EncryptMethod::V5R5Aes256,
        256 => EncryptMethod::V5R6Aes256,
        _ => unreachable!("key length was validated"),
    };

    if cleartext_metadata
        && !matches!(
            method,
            EncryptMethod::V4Aes128
                | EncryptMethod::V4Rc4128
                | EncryptMethod::V5R5Aes256
                | EncryptMethod::V5R6Aes256
        )
    {
        return Err("--cleartext-metadata requires V=4 or V=5".into());
    }

    let params = match method {
        EncryptMethod::V1Rc440 => {
            let mut params = EncryptParams::rc4(method, user_password, owner_password);
            params.r2_permissions = r2_permissions;
            params
        }
        EncryptMethod::V2Rc4128 => {
            let mut params = EncryptParams::rc4(method, user_password, owner_password);
            params.permissions = perms;
            params
        }
        EncryptMethod::V4Rc4128 | EncryptMethod::V4Aes128 => {
            let mut params = if method == EncryptMethod::V4Aes128 {
                EncryptParams::v4_aes128(user_password, owner_password)
            } else {
                EncryptParams::rc4(method, user_password, owner_password)
            };
            params.permissions = perms;
            params.permissions.accessibility = true;
            params.encrypt_metadata = !cleartext_metadata;
            params
        }
        EncryptMethod::V5R5Aes256 | EncryptMethod::V5R6Aes256 => {
            if owner_password.is_empty() && !user_password.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 method == EncryptMethod::V5R5Aes256 {
                EncryptParams::v5_r5(user_password, owner_password)
            } else {
                EncryptParams::v5_r6(user_password, owner_password)
            };
            params.permissions = perms;
            params.permissions.accessibility = true;
            params.encrypt_metadata = !cleartext_metadata;
            params
        }
    };

    Ok(ParsedEncryptSegment {
        params,
        allow_insecure,
        accessibility_warning: accessibility_explicitly_disabled
            && matches!(
                method,
                EncryptMethod::V4Rc4128
                    | EncryptMethod::V4Aes128
                    | EncryptMethod::V5R5Aes256
                    | EncryptMethod::V5R6Aes256
            ),
    })
}

fn parse_encrypt_key_len(value: &str) -> CliResult<u32> {
    // qpdf's ArgParser::argEncBits compares the raw argument against the three
    // accepted spellings and reports one fixed message for everything else
    // (`libqpdf/QPDFJob_argv.cc:211-229`). It never parses the value as a
    // number, so a non-numeric argument and an out-of-range one produce the
    // same diagnostic, and a numerically equal spelling like "040" is rejected.
    match value {
        "40" => Ok(40),
        "128" => Ok(128),
        "256" => Ok(256),
        // A UsageError, not a plain string: qpdf reports this through
        // `ArgParser::usage`, whose output carries the leading blank line and
        // the trailing "For help:" block that `usage_exit` models.
        _ => Err(UsageError::new("encryption key length must be 40, 128, or 256").into()),
    }
}

/// The dashed `--bits=value` form of `--encrypt` never reaches
/// `ArgParser::argEncBits`'s own validation: qpdf's generated
/// `this->ap.addChoices("bits", p(&ArgParser::argEncBits), true,
/// enc_bits_choices)` (`libqpdf/qpdf/auto_job_init.hh:137`, generated from
/// `job.yml`'s `table: encryption` / `required_choices: {bits: enc_bits}`)
/// registers `bits`'s choices (`{"40", "128", "256"}`,
/// `auto_job_init.hh:26`) on the named option itself, so an invalid or
/// missing dashed value is caught first by
/// `QPDFArgParser::checkCompletion`'s generic choices check
/// (`libqpdf/QPDFArgParser.cc:505-522`), which never calls into
/// `argEncBits` at all. That check's `choices` set is a
/// `std::set<std::string>` (`QPDFArgParser::addChoices`,
/// `QPDFArgParser.cc:125-134`), so the message lists the three values in
/// dictionary order (`128,256,40`), not the numeric order
/// `parse_encrypt_key_len`'s positional-path message uses.
fn parse_dashed_encrypt_bits(value: &str) -> CliResult<u32> {
    match value {
        "40" => Ok(40),
        "128" => Ok(128),
        "256" => Ok(256),
        _ => Err(UsageError::new("--bits must be given as --bits={128,256,40}").into()),
    }
}

#[allow(clippy::too_many_arguments)]
fn run_rewrite(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    replace_input: bool,
    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,
    image_options: ImageTransformOptions,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    page_labels: PageLabelOptions,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    no_warn: bool,
    options: WriterOptions,
    empty: bool,
) -> CliResult<()> {
    if empty {
        if replace_input && (input.is_some() || output.is_some()) {
            return Err(UsageError::new(
                "replace-input can't be used since output file has already been given",
            )
            .into());
        }
        if replace_input {
            return Err(UsageError::new("--replace-input may not be used with --empty").into());
        }
        let output = match (input, output) {
            (Some(output), None) | (None, Some(output)) => output,
            (Some(_), Some(extra)) => {
                return Err(UsageError::new(format!("unknown argument {}", extra.display())).into())
            }
            (None, None) => return Err(missing_output_usage_error().into()),
        };
        let mut job = new_cli_job(no_warn);
        let pdf = create_empty_primary_document(&mut job, update_from_json)?;
        return run_rewrite_opened(
            pdf,
            Path::new("empty PDF"),
            &output,
            false,
            repair,
            password,
            linearize,
            linearize_pass1,
            remove_restrictions,
            decrypt,
            normalize_content,
            coalesce_contents,
            _remove_unref,
            generate_appearances,
            image_options,
            flatten_annotations_mode,
            flatten_rotation,
            page_labels,
            overlay_specs,
            verbose,
            no_warn,
            options,
        );
    }
    let input = input.ok_or_else(missing_input_usage_error)?;
    if replace_input && output.is_some() {
        return Err(UsageError::new(
            "replace-input can't be used since output file has already been given",
        )
        .into());
    }
    let output = if replace_input {
        input.clone()
    } else {
        output.ok_or_else(missing_output_usage_error)?
    };
    if !replace_input {
        reject_same_job_output(&input, &output)?;
    }
    run_rewrite_with_qpdf_job(
        &input,
        &output,
        replace_input,
        repair,
        password,
        json_input,
        update_from_json,
        linearize,
        linearize_pass1,
        remove_restrictions,
        decrypt,
        normalize_content,
        coalesce_contents,
        generate_appearances,
        image_options,
        flatten_annotations_mode,
        flatten_rotation,
        page_labels,
        overlay_specs,
        verbose,
        no_warn,
        options,
        &[],
        None,
        _remove_unref.into(),
    )
}

/// Execute top-level page operations through qpdf's one-job create/write
/// lifecycle.
///
/// qpdf parses page specifications during `createQPDF`, applies rotations and
/// all document transformations to that same primary, and only then lets
/// `writeQPDF` select ordinary or split output and configure encryption
/// (`QPDFJob.cc:428-520`). Keeping this route on [`QPDFJob`] is observable for
/// `--copy-encryption`: `handlePageSpecs` reuses the encryption-file password
/// for an unqualified page source whose raw filename is the donor filename
/// (`QPDFJob.cc:2405-2410`), while `writeQPDF` opens that donor at its own
/// writer boundary (`QPDFJob.cc:2891-2899`).
#[allow(clippy::too_many_arguments)]
fn run_page_operations_with_qpdf_job(
    args: &Cli,
    options: WriterOptions,
    image_options: ImageTransformOptions,
    overlay_specs: &[OverlaySpec],
) -> CliResult<()> {
    let (input, output) = if args.page_ops.empty {
        if args.replace_input && (args.input.is_some() || args.output.is_some()) {
            return Err(UsageError::new(
                "replace-input can't be used since output file has already been given",
            )
            .into());
        }
        if args.replace_input {
            return Err(UsageError::new("--replace-input may not be used with --empty").into());
        }
        match (args.input.clone(), args.output.clone()) {
            (Some(output), None) | (None, Some(output)) => (None, output),
            (Some(_), Some(_)) => {
                return Err(UsageError::new(
                    "empty input can't be used since input file has already been given",
                )
                .into())
            }
            (None, None) => return Err(missing_output_usage_error().into()),
        }
    } else {
        let input = args.input.clone().ok_or_else(missing_input_usage_error)?;
        let output = if args.replace_input {
            // QPDFJob owns the temporary output and in-place swap when
            // replace_input is set; the writer-facing path is ignored by that
            // configuration. Keep the input as a placeholder so page ops can
            // share the same job setup without inventing a user-visible file.
            input.clone()
        } else {
            args.output.clone().ok_or_else(missing_output_usage_error)?
        };
        // qpdf exempts a split run from the same-file check
        // (`QPDFJob.cc:627`: `if ((!m->split_pages) && QUtil::same_file(...))`).
        // A split never opens the output path itself -- it is a template that
        // derives `input-1.pdf` and so on -- so naming the input there is not
        // the overwrite this check exists to prevent.
        if !args.replace_input && args.page_ops.split_pages.is_none() {
            reject_same_job_output(&input, &output)?;
        }
        (Some(input), output)
    };

    let input_name = input.clone().unwrap_or_else(|| PathBuf::from("empty PDF"));
    let page_labels = page_label_options(args.set_page_labels.as_deref(), args.remove_page_labels);
    let linearize_normalization =
        args.linearize && options.content_normalization_set && options.content_normalization;
    // Keep the writer-side normalization state enabled after the explicit
    // create-stage pass. The live stream marker makes the canonical writer
    // skip a second tokenizer pass while still selecting qpdf's
    // normalization-before-compression policy for linearization.
    let job_options = options;

    let mut job = configure_rewrite_job(
        &input_name,
        &output,
        args.replace_input,
        &args.password,
        args.linearize,
        args.linearize_pass1.as_deref(),
        args.remove_restrictions,
        image_options,
        args.generate_appearances,
        args.flatten_annotations,
        args.coalesce_contents,
        args.flatten_rotation,
        &page_labels,
        overlay_specs,
        args.verbose,
        args.no_warn,
        &job_options,
    )?;

    if let Some(input) = input {
        if !args.replace_input {
            job.set_input_file(input)?;
        }
    } else {
        job.config().empty_input()?;
    }

    {
        let mut configuration = job.config();
        if args.json_input {
            configuration.json_input();
        }
        if let Some(update_from_json) = args.update_from_json.as_ref() {
            configuration.update_from_json(update_from_json.clone());
        }
    }

    let input_options = pdf_open_options(args.repair, &args.password)?;
    job.set_password(input_options.password);
    configure_keep_files_open(&mut job, &args.page_ops)?;

    let raw_specs = if args.page_ops.pages.is_empty() {
        Vec::new()
    } else {
        configured_page_specs(&args.page_ops)?
    };
    if (args.json_input || args.update_from_json.is_some()) && !args.page_ops.empty {
        // The JSON-input/update page consumer historically accepts only page
        // specs that resolve to the already-created primary. Preserve that
        // command-boundary contract while the actual create-stage work is
        // owned by QPDFJob; a distinct source would require a JSON-aware
        // source factory rather than silently substituting the primary.
        let primary = args.input.as_ref().ok_or_else(missing_input_usage_error)?;
        let primary_canonical = std::fs::canonicalize(primary).unwrap_or_else(|_| primary.clone());
        let has_external_source = raw_specs.iter().any(|spec| {
            if spec.file_token == OsStr::new(".") {
                return false;
            }
            let path = PathBuf::from(&spec.file_token);
            let canonical = std::fs::canonicalize(&path).unwrap_or(path);
            canonical != primary_canonical
        });
        if has_external_source {
            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(),
            );
        }
    }
    if args.page_ops.empty
        && raw_specs
            .iter()
            .any(|spec| spec.file_token == OsStr::new("."))
    {
        return Err("--pages: '.' cannot refer to a primary input with --empty".into());
    }

    {
        let mut configuration = job.config();
        if let Some(path) = args.copy_encryption.as_ref() {
            let password = args
                .raw_encryption_file_password
                .clone()
                .or_else(|| {
                    args.encryption_file_password
                        .as_ref()
                        .map(|password| arg_parser::os_bytes(password))
                })
                .unwrap_or_default();
            configuration.copy_encryption(path.clone(), password);
        }
        for spec in raw_specs {
            let password = spec.raw_password.or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password))
            });
            configuration.add_page_spec(PathBuf::from(spec.file_token), &spec.range, password)?;
        }
        for parameter in &args.page_ops.rotate {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        for parameter in &args.page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        if let Some(parameter) = args.page_ops.split_pages.as_deref() {
            configuration.split_pages(parameter.as_bytes())?;
        }
        if args.coalesce_contents {
            configuration.coalesce_contents();
        }
        configuration.remove_unreferenced_resources(args.remove_unreferenced_resources.into());
    }

    let writer_configuration = writer_configuration_unnormalized(
        &job_options,
        args.linearize,
        args.linearize_pass1.as_deref(),
    )?;
    job.set_writer_configuration(writer_configuration);

    let mut pdf = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    if linearize_normalization {
        let warnings = normalize_page_contents(&mut pdf)?;
        if !warnings.is_empty() {
            job.record_warnings();
            if !args.no_warn {
                for warning in warnings {
                    emit_content_normalization_warnings(&input_name, warning)?;
                }
            }
        }
    }

    match job.write_qpdf(&mut pdf) {
        Ok(()) => finish_job_exit_status(job.get_exit_code()),
        Err(_) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
    }
}

#[allow(clippy::too_many_arguments)]
fn run_rewrite_with_qpdf_job(
    input: &Path,
    output: &Path,
    replace_input: bool,
    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,
    generate_appearances: bool,
    image_options: ImageTransformOptions,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    page_labels: PageLabelOptions,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    no_warn: bool,
    options: WriterOptions,
    rotate_args: &[OsString],
    split_pages: Option<&str>,
    remove_unreferenced_resources: RemoveUnreferencedResources,
) -> CliResult<()> {
    // qpdf's createQPDF owns input creation and all document transformations;
    // only writer configuration is deferred until writeQPDF. The explicit
    // normalization pass remains after createQPDF and before writeQPDF, while
    // its writer-side option stays enabled so linearization can consume the
    // normalized-stream membership.
    let linearize_normalization =
        linearize && normalize_content && options.content_normalization_set;
    let job_options = options.clone();

    let mut job = configure_rewrite_job(
        input,
        output,
        replace_input,
        password,
        linearize,
        linearize_pass1,
        remove_restrictions,
        image_options,
        generate_appearances,
        flatten_annotations_mode,
        coalesce_contents,
        flatten_rotation,
        &page_labels,
        overlay_specs,
        verbose,
        no_warn,
        &job_options,
    )?;
    if !replace_input {
        job.set_input_file(input.to_path_buf())?;
    }
    let input_options = pdf_open_options(repair, password)?;
    job.set_password(input_options.password);
    {
        let mut configuration = job.config();
        if json_input {
            configuration.json_input();
        }
        if let Some(path) = update_from_json {
            configuration.update_from_json(path.to_path_buf());
        }
        for parameter in rotate_args {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        if let Some(parameter) = split_pages {
            configuration.split_pages(parameter.as_bytes())?;
            configuration.remove_unreferenced_resources(remove_unreferenced_resources);
        }
    }

    let mut pdf = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    if linearize_normalization {
        let warnings = normalize_page_contents(&mut pdf)?;
        if !warnings.is_empty() {
            job.record_warnings();
            if !no_warn {
                for warning in warnings {
                    emit_content_normalization_warnings(input, warning)?;
                }
            }
        }
    }

    // qpdf constructs writer options inside writeOutfile, after createQPDF;
    // keep password normalization and weak-crypto validation at that same
    // boundary rather than exposing them during input creation.
    let mut writer_options = job_options;
    if decrypt {
        writer_options.preserve_encryption = false;
    }
    job.set_writer_configuration(writer_configuration_unnormalized(
        &writer_options,
        linearize,
        linearize_pass1,
    )?);
    match job.write_qpdf(&mut pdf) {
        Ok(()) => finish_job_exit_status(job.get_exit_code()),
        Err(_) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
    }
}

#[allow(clippy::too_many_arguments)]
fn configure_rewrite_job(
    input: &Path,
    output: &Path,
    replace_input: bool,
    password: &PasswordArgs,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    remove_restrictions: bool,
    image_options: ImageTransformOptions,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    coalesce_contents: bool,
    flatten_rotation: bool,
    page_labels: &PageLabelOptions,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    no_warn: bool,
    options: &WriterOptions,
) -> CliResult<QPDFJob> {
    let mut job = new_cli_job(no_warn);
    job.set_input_name_bytes(path_description(input));
    if replace_input {
        job.set_input_file(input.to_path_buf())?;
        job.config().replace_input()?;
    } else {
        job.set_output_file(output.to_path_buf())?;
    }
    job.set_suppress_recovery(password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    // `open_job_source` reads these three from the job configuration, so an
    // overlay/underlay source opened by the job has to see the same
    // interpretation the primary open used.
    job.set_password_mode(password.password_mode.into());
    job.set_password_is_hex_key(password.password_is_hex_key);
    job.set_suppress_password_recovery(password.suppress_password_recovery);
    job.set_allow_weak_crypto(options.allow_weak_crypto);
    job.set_allow_insecure(options.allow_insecure);
    job.set_accessibility_disabled(options.accessibility_disabled);
    job.set_verbose(verbose);
    job.set_progress(options.progress);
    job.set_report_memory_usage(options.report_memory_usage);
    job.set_linearization(linearize, linearize_pass1.map(Path::to_path_buf));

    {
        let mut configuration = job.config();
        if remove_restrictions {
            configuration.remove_restrictions();
        }
        if image_options.optimize_images {
            let mut optimization = image_options.image_options;
            if image_options.externalize_inline_images {
                optimization.keep_inline_images = false;
            }
            configuration.optimize_images(optimization);
        } else if image_options.externalize_inline_images {
            configuration.externalize_inline_images(image_options.image_options.inline_min_bytes);
        }
        if generate_appearances {
            configuration.generate_appearances();
        }
        if let Some(mode) = flatten_annotations_mode {
            configuration.flatten_annotations(FlattenAnnotationsMode::from(mode));
        }
        if coalesce_contents {
            configuration.coalesce_contents();
        }
        if flatten_rotation {
            configuration.flatten_rotation();
        }
        if let Some(specs) = page_labels.set.as_ref().filter(|specs| !specs.is_empty()) {
            configuration.set_page_labels(specs.iter().map(Vec::as_slice))?;
        }
        if page_labels.remove {
            configuration.remove_page_labels();
        }
        for spec in overlay_specs {
            let password = spec
                .raw_password
                .clone()
                .or_else(|| {
                    spec.password
                        .as_ref()
                        .map(|password| arg_parser::os_bytes(password.as_os_str()))
                })
                .unwrap_or_default();
            let from = match spec.from.as_deref() {
                None => PageRange::all(),
                Some("") => PageRange::empty(),
                Some(range) => PageRange::parse_numrange(range)?,
            };
            let to = match spec.to.as_deref() {
                None => PageRange::all(),
                Some("") => PageRange::empty(),
                Some(range) => PageRange::parse_numrange(range)?,
            };
            let repeat = match spec.repeat.as_deref() {
                None | Some("") => None,
                Some(range) => Some(PageRange::parse_numrange(range)?),
            };
            match spec.kind {
                OverlayKind::Overlay => {
                    configuration.overlay(PathBuf::from(&spec.file), password, from, to, repeat)
                }
                OverlayKind::Underlay => {
                    configuration.underlay(PathBuf::from(&spec.file), password, from, to, repeat)
                }
            };
        }
    }
    Ok(job)
}

#[allow(clippy::too_many_arguments)]
fn run_rewrite_opened<R: Read + Seek + 'static>(
    mut pdf: Pdf<R>,
    input: &Path,
    output: &Path,
    replace_input: bool,
    _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,
    image_options: ImageTransformOptions,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    page_labels: PageLabelOptions,
    overlay_specs: &[OverlaySpec],
    verbose: bool,
    no_warn: bool,
    options: WriterOptions,
) -> CliResult<()> {
    // The linearized writer has pass-one and final emission phases. Perform
    // the explicit canonical content pass once before those phases, but keep
    // the writer-side normalization state enabled: the stream marker avoids a
    // second tokenizer pass and preserves qpdf's compression precedence.
    let linearize_normalization =
        linearize && normalize_content && options.content_normalization_set;
    let job_options = options.clone();
    let mut job = configure_rewrite_job(
        input,
        output,
        replace_input,
        _password,
        linearize,
        linearize_pass1,
        remove_restrictions,
        image_options,
        generate_appearances,
        flatten_annotations_mode,
        coalesce_contents,
        flatten_rotation,
        &page_labels,
        overlay_specs,
        verbose,
        no_warn,
        &job_options,
    )?;
    apply_transformations_for_cli(&mut job, &mut pdf)?;
    if linearize_normalization {
        let warnings = normalize_page_contents(&mut pdf)?;
        if !warnings.is_empty() {
            job.record_warnings();
            if !no_warn {
                for warning in warnings {
                    emit_content_normalization_warnings(input, warning)?;
                }
            }
        }
    }
    // qpdf builds the writer only inside writeQPDF -> writeOutfile ->
    // setWriterOptions (`QPDFJob.cc:484-495,2752-2761`), so its write-time
    // validation - the auto-password notices and the RC4 refusal - runs after
    // the create stage, never before it. write_qpdf's own write stage
    // performs that validation, so this configuration must stay unnormalized
    // here or the password bytes get normalized twice.
    let mut writer_options = job_options;
    if _decrypt {
        writer_options.preserve_encryption = false;
    }
    job.set_writer_configuration(writer_configuration_unnormalized(
        &writer_options,
        linearize,
        linearize_pass1,
    )?);
    match job.write_qpdf(&mut pdf) {
        Ok(()) => finish_job_exit_status(job.get_exit_code()),
        Err(_) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
    }
}

// ===========================================================================
// Page operations: --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.
#[derive(Debug, Clone)]
struct PageSegmentSpec {
    /// File token as written (`.` = primary input, or a path).
    file_token: OsString,
    /// Per-input password (`--password=` immediately following the file).
    password: Option<OsString>,
    /// Raw per-input password bytes, retained when the OS projection is lossy.
    raw_password: Option<Vec<u8>>,
    /// Page-range string (empty = all pages).
    range: String,
}

#[derive(Default)]
struct PagesSegmentParser {
    specs: Vec<PageSegmentSpec>,
    called_pages_file: bool,
    called_pages_range: bool,
}

impl PagesSegmentParser {
    fn push(&mut self, original: &[u8], canonical: &[u8], file_token: OsString) -> CliResult<()> {
        if let Some(path) = canonical.strip_prefix(b"--file=") {
            self.specs.push(PageSegmentSpec {
                file_token: arg_parser::os_string_from_bytes(path),
                password: None,
                raw_password: None,
                range: String::new(),
            });
            self.called_pages_range = false;
            return Ok(());
        }
        if let Some(pw) = canonical.strip_prefix(b"--password=") {
            let cur = self.specs.last_mut().ok_or_else(|| {
                Box::new(UsageError::new(
                    "in --pages, --password must follow a file name",
                )) as Box<dyn std::error::Error>
            })?;
            if cur.password.is_some() {
                return Err(Box::new(UsageError::new(
                    "--password already specified for this file",
                )));
            }
            cur.password = Some(arg_parser::os_string_from_bytes(pw));
            cur.raw_password = Some(pw.to_vec());
            return Ok(());
        }
        if let Some(range) = canonical.strip_prefix(b"--range=") {
            let cur = self.specs.last_mut().ok_or_else(|| {
                Box::new(UsageError::new("in --range must follow a file name"))
                    as Box<dyn std::error::Error>
            })?;
            if !cur.range.is_empty() {
                return Err(Box::new(UsageError::new(
                    "--range already specified for this file",
                )));
            }
            cur.range = String::from_utf8(range.to_vec())
                .map_err(|_| UsageError::new("--range must be valid UTF-8"))?;
            return Ok(());
        }

        if canonical.starts_with(b"-") && canonical != b"-" {
            let name = segment_option_name(canonical);
            if let Some(name) = name {
                let parameter = match name {
                    "file" => Some("file"),
                    "range" => Some("page-range"),
                    "password" => Some("password"),
                    _ => None,
                };
                if !canonical.contains(&b'=') {
                    if let Some(parameter) = parameter {
                        return Err(Box::new(UsageError::new(format!(
                            "--{name} must be given as --{name}={parameter}"
                        ))));
                    }
                }
            }
            return Err(Box::new(UsageError::new(format!(
                "unrecognized argument {} (pages options must be terminated with --)",
                String::from_utf8_lossy(original)
            ))));
        }

        if !self.called_pages_file {
            self.specs.push(PageSegmentSpec {
                file_token,
                password: None,
                raw_password: None,
                range: String::new(),
            });
            self.called_pages_file = true;
            return Ok(());
        }
        if self.called_pages_range {
            self.specs.push(PageSegmentSpec {
                file_token,
                password: None,
                raw_password: None,
                range: String::new(),
            });
            self.called_pages_range = false;
            return Ok(());
        }

        match parse_numrange(canonical, 0) {
            Ok(_) => {
                let range_bytes = canonical
                    .split(|byte| *byte == 0)
                    .next()
                    .unwrap_or(canonical);
                let range = String::from_utf8_lossy(range_bytes).into_owned();
                let cur = self
                    .specs
                    .last_mut()
                    .expect("qpdf page range requires a preceding file");
                if !cur.range.is_empty() {
                    return Err(Box::new(UsageError::new(
                        "--range already specified for this file",
                    )));
                }
                cur.range = range;
                self.called_pages_range = true;
            }
            Err(error) => {
                if !matches!(&error, Error::SystemBytes(_)) {
                    return Err(Box::new(error));
                }
                let is_file = canonical == b"."
                    || File::open(arg_parser::os_string_from_bytes(canonical)).is_ok();
                if is_file {
                    self.specs.push(PageSegmentSpec {
                        file_token,
                        password: None,
                        raw_password: None,
                        range: String::new(),
                    });
                    self.called_pages_range = false;
                } else {
                    let message = error
                        .raw_message()
                        .map_or_else(|| error.to_string().into_bytes(), ToOwned::to_owned);
                    return Err(Box::new(UsageError::new(message)));
                }
            }
        }
        Ok(())
    }

    fn finish(self) -> CliResult<Vec<PageSegmentSpec>> {
        if self.specs.is_empty() {
            return Err(Box::new(UsageError::new(
                "--pages: no page specifications given",
            )));
        }
        Ok(self.specs)
    }
}

fn segment_option_name(bytes: &[u8]) -> Option<&str> {
    let name = bytes
        .strip_prefix(b"--")
        .or_else(|| bytes.strip_prefix(b"-"))?;
    if name.is_empty() || name[0] == b'-' || name[0].is_ascii_digit() {
        return None;
    }
    let end = name
        .iter()
        .position(|byte| *byte == b'=')
        .unwrap_or(name.len());
    std::str::from_utf8(&name[..end]).ok()
}

/// 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<T: RawCliArg>(tokens: &[T]) -> CliResult<Vec<PageSegmentSpec>> {
    let mut parser = PagesSegmentParser::default();
    for tok in tokens {
        let token_bytes = tok.raw_bytes();
        parser.push(&token_bytes, &token_bytes, tok.os_string())?;
    }
    parser.finish()
}

fn raw_page_tokens(page_ops: &PageOpArgs) -> Vec<Vec<u8>> {
    page_ops
        .raw_pages
        .clone()
        .unwrap_or_else(|| raw_os_args(&page_ops.pages))
}

fn configured_page_specs(page_ops: &PageOpArgs) -> CliResult<Vec<PageSegmentSpec>> {
    page_ops
        .parsed_page_specs
        .clone()
        .map_or_else(|| parse_pages_segment(&raw_page_tokens(page_ops)), Ok)
}

/// Resolve `--pages` specs into CLI-local inputs, 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<CliInputSpec>> {
    let mut out = Vec::with_capacity(specs.len());
    for s in specs {
        let path: PathBuf = if s.file_token == OsStr::new(".") {
            primary_input.to_path_buf()
        } else {
            PathBuf::from(&s.file_token)
        };
        // The range itself is validated here (for the same CLI-boundary usage
        // errors the former route reported) but not retained: page-spec
        // ranges now travel to `QPDFJob::add_page_spec` as the original
        // string, matching qpdf's `handlePageSpecs`. The per-segment
        // password likewise no longer needs to be carried here.
        if !s.range.is_empty() {
            PageRange::parse_numrange(&s.range).map_err(|e| {
                let message = e
                    .raw_message()
                    .expect("PageRange::parse_numrange delegates to qutil raw range errors");
                let mut what = b"parsing numeric range for ".to_vec();
                what.extend_from_slice(&path_description(&path));
                what.extend_from_slice(b": ");
                what.extend_from_slice(message);
                Box::new(Error::SystemBytes(what)) as Box<dyn std::error::Error>
            })?;
        }
        out.push(CliInputSpec::new(path));
    }
    Ok(out)
}

// ===========================================================================
// --overlay / --underlay segment parser
//
// 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: OsString,
    /// Password for the source PDF, if supplied via `--password=`.
    password: Option<OsString>,
    /// Raw password bytes, retained when the OS projection is lossy.
    raw_password: Option<Vec<u8>>,
    /// 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 OverlaySegmentParser {
    kind: OverlayKind,
    file: Option<OsString>,
    password: Option<OsString>,
    raw_password: Option<Vec<u8>>,
    from: Option<String>,
    to: Option<String>,
    repeat: Option<String>,
}

impl OverlaySegmentParser {
    fn new(kind: OverlayKind) -> Self {
        Self {
            kind,
            file: None,
            password: None,
            raw_password: None,
            from: None,
            to: None,
            repeat: None,
        }
    }

    fn flag(&self) -> &'static str {
        match self.kind {
            OverlayKind::Overlay => "overlay",
            OverlayKind::Underlay => "underlay",
        }
    }

    fn push(&mut self, original: &[u8], canonical: &[u8], file_token: OsString) -> CliResult<()> {
        if let Some(path) = canonical.strip_prefix(b"--file=") {
            if self.file.is_some() {
                return Err(Box::new(UsageError::new(format!(
                    "{} file already specified",
                    self.flag()
                ))));
            }
            self.file = Some(arg_parser::os_string_from_bytes(path));
            return Ok(());
        }
        if let Some(password) = canonical.strip_prefix(b"--password=") {
            // QPDFJob::UOConfig::password is a regular setter and therefore
            // follows qpdf's last-setting behavior when repeated.
            self.password = Some(arg_parser::os_string_from_bytes(password));
            self.raw_password = Some(password.to_vec());
            return Ok(());
        }
        if let Some(range) = canonical.strip_prefix(b"--to=") {
            let range = String::from_utf8(range.to_vec())
                .map_err(|_| format!("{} --to must be valid UTF-8", self.flag()))?;
            PageRange::parse_numrange(&range).map_err(|error| {
                format!(
                    "{}: invalid --to= page range {range:?}: {error}",
                    self.flag()
                )
            })?;
            self.to = Some(range);
            return Ok(());
        }
        if let Some(range) = canonical.strip_prefix(b"--from=") {
            let range = String::from_utf8(range.to_vec())
                .map_err(|_| format!("{} --from must be valid UTF-8", self.flag()))?;
            if !range.is_empty() {
                PageRange::parse_numrange(&range).map_err(|error| {
                    format!(
                        "{}: invalid --from= page range {range:?}: {error}",
                        self.flag()
                    )
                })?;
            }
            self.from = Some(range);
            return Ok(());
        }
        if let Some(range) = canonical.strip_prefix(b"--repeat=") {
            let range = String::from_utf8(range.to_vec())
                .map_err(|_| format!("{} --repeat must be valid UTF-8", self.flag()))?;
            if !range.is_empty() {
                PageRange::parse_numrange(&range).map_err(|error| {
                    format!(
                        "{}: invalid --repeat= page range {range:?}: {error}",
                        self.flag()
                    )
                })?;
            }
            self.repeat = Some(range);
            return Ok(());
        }

        if canonical.starts_with(b"-") && canonical != b"-" {
            let name = segment_option_name(canonical);
            if let Some(name) = name {
                let parameter = match name {
                    "file" => Some("file"),
                    "password" => Some("password"),
                    "to" | "from" | "repeat" => Some("page-range"),
                    _ => None,
                };
                if !canonical.contains(&b'=') {
                    if let Some(parameter) = parameter {
                        return Err(Box::new(UsageError::new(format!(
                            "--{name} must be given as --{name}={parameter}"
                        ))));
                    }
                }
            }
            return Err(Box::new(UsageError::new(format!(
                "unrecognized argument {} (underlay/overlay options must be terminated with --)",
                String::from_utf8_lossy(original)
            ))));
        }

        if self.file.is_some() {
            return Err(Box::new(UsageError::new(format!(
                "{} file already specified",
                self.flag()
            ))));
        }
        self.file = Some(file_token);
        Ok(())
    }

    fn finish(self) -> CliResult<OverlaySpec> {
        let flag = self.flag();
        let file = self.file.ok_or_else(|| {
            Box::new(UsageError::new(format!("{} file not specified", flag)))
                as Box<dyn std::error::Error>
        })?;
        if file.is_empty() {
            return Err(Box::new(UsageError::new(format!(
                "{} file not specified",
                flag
            ))));
        }
        Ok(OverlaySpec {
            kind: self.kind,
            file,
            password: self.password,
            raw_password: self.raw_password,
            from: self.from,
            to: self.to,
            repeat: self.repeat,
        })
    }
}

struct PreprocessedArgs {
    residual_args: Vec<OsString>,
    /// Raw residual argv after qpdf named-segment removal, preserving the
    /// occurrence order needed by the partial job-JSON route.
    raw_residual_args: Vec<arg_parser::RawArg>,
    /// Raw residual argv before qpdf-to-clap canonicalization. qpdf's usage
    /// diagnostics echo this spelling, including a single leading dash.
    original_residual_args: Vec<arg_parser::RawArg>,
    native_subcommand_mode: bool,
    overlay_specs: Vec<OverlaySpec>,
    attachment_segments: Vec<Vec<Vec<u8>>>,
    raw_overrides: RawCliOverrides,
    /// argv token count after `@argfile` expansion, before named-segment
    /// stripping (qpdf's `m->argc` at the sole-option check).
    expanded_arg_count: usize,
    first_unknown_option: Option<(usize, arg_parser::RawArg)>,
}

#[derive(Debug, Default)]
struct RawCliOverrides {
    password: Option<Vec<u8>>,
    password_file_is_last: bool,
    encryption_file_password: Option<Vec<u8>>,
    raw_encrypt: Option<Vec<Vec<u8>>>,
    raw_encrypt_segments: Option<Vec<Vec<Vec<u8>>>>,
    raw_pages: Option<Vec<Vec<u8>>>,
    parsed_page_specs: Option<Vec<PageSegmentSpec>>,
    parsed_encrypt_segments: Option<Vec<ParsedEncryptSegment>>,
    last_encryption_mode: Option<EncryptionMode>,
    raw_copy_attachments_from: Option<Vec<Vec<Vec<u8>>>>,
}

enum ActiveQpdfSegment {
    Pages(PagesSegmentParser),
    Overlay(OverlaySegmentParser),
    Encrypt(EncryptSegmentCallbackState),
    Other,
}

#[derive(Default)]
struct QpdfSegmentHandler {
    active: Option<ActiveQpdfSegment>,
    pages_seen: bool,
    page_specs: Option<Vec<PageSegmentSpec>>,
    overlay_specs: Vec<OverlaySpec>,
    encrypt_segments: Vec<ParsedEncryptSegment>,
}

impl arg_parser::SegmentHandler for QpdfSegmentHandler {
    fn begin(&mut self, kind: arg_parser::SegmentKind, option: &str) -> CliResult<()> {
        if self.active.is_some() {
            return Err(Error::Internal("nested qpdf named segment".into()).into());
        }
        self.active = Some(match kind {
            arg_parser::SegmentKind::Pages => {
                if self.pages_seen {
                    return Err(Box::new(UsageError::new(
                        "--pages may only be specified one time",
                    )));
                }
                self.pages_seen = true;
                ActiveQpdfSegment::Pages(PagesSegmentParser::default())
            }
            arg_parser::SegmentKind::Overlay => {
                let kind = if option == "underlay" {
                    OverlayKind::Underlay
                } else {
                    OverlayKind::Overlay
                };
                ActiveQpdfSegment::Overlay(OverlaySegmentParser::new(kind))
            }
            arg_parser::SegmentKind::Encrypt => {
                ActiveQpdfSegment::Encrypt(EncryptSegmentCallbackState::new())
            }
            arg_parser::SegmentKind::AddAttachment
            | arg_parser::SegmentKind::CopyAttachments
            | arg_parser::SegmentKind::PageLabels => ActiveQpdfSegment::Other,
        });
        Ok(())
    }

    fn token(
        &mut self,
        _kind: arg_parser::SegmentKind,
        original: &arg_parser::RawArg,
        canonical: &arg_parser::RawArg,
    ) -> CliResult<()> {
        match self.active.as_mut() {
            Some(ActiveQpdfSegment::Pages(parser)) => parser.push(
                original.as_bytes(),
                canonical.as_bytes(),
                original.as_os_str().to_os_string(),
            ),
            Some(ActiveQpdfSegment::Overlay(parser)) => parser.push(
                original.as_bytes(),
                canonical.as_bytes(),
                original.as_os_str().to_os_string(),
            ),
            Some(ActiveQpdfSegment::Encrypt(parser)) => {
                parser.push(original.as_bytes(), canonical.as_bytes())
            }
            Some(ActiveQpdfSegment::Other) | None => Ok(()),
        }
    }

    fn end(&mut self, _kind: arg_parser::SegmentKind) -> CliResult<()> {
        let active = self
            .active
            .take()
            .ok_or_else(|| Error::Internal("qpdf named segment ended without a begin".into()))?;
        match active {
            ActiveQpdfSegment::Pages(parser) => self.page_specs = Some(parser.finish()?),
            ActiveQpdfSegment::Overlay(parser) => self.overlay_specs.push(parser.finish()?),
            ActiveQpdfSegment::Encrypt(parser) => self.encrypt_segments.push(parser.finish()?),
            ActiveQpdfSegment::Other => {}
        }
        Ok(())
    }

    fn missing_terminator(
        &mut self,
        kind: arg_parser::SegmentKind,
        _option: &str,
    ) -> Box<dyn std::error::Error> {
        let table = match self.active.as_ref() {
            Some(ActiveQpdfSegment::Encrypt(parser)) => encrypt_option_table_name(parser.key_len),
            Some(ActiveQpdfSegment::Pages(_)) => "pages",
            Some(ActiveQpdfSegment::Overlay(_)) => "underlay/overlay",
            Some(ActiveQpdfSegment::Other) | None => match kind {
                arg_parser::SegmentKind::Encrypt => "encryption",
                arg_parser::SegmentKind::Pages => "pages",
                arg_parser::SegmentKind::AddAttachment => "attachment",
                arg_parser::SegmentKind::CopyAttachments => "copy attachment",
                arg_parser::SegmentKind::Overlay => "underlay/overlay",
                arg_parser::SegmentKind::PageLabels => "set page labels",
            },
        };
        UsageError::new(format!("missing -- at end of {table} options")).into()
    }
}

/// 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 and
///   repeated values use qpdf's last-setting behavior.
/// - Range values are validated via [`PageRange::parse_numrange`] (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.
#[cfg(test)]
fn parse_overlay_segment<T: RawCliArg>(kind: OverlayKind, tokens: &[T]) -> CliResult<OverlaySpec> {
    let mut parser = OverlaySegmentParser::new(kind);
    for tok in tokens {
        let token_bytes = tok.raw_bytes();
        parser.push(&token_bytes, &token_bytes, tok.os_string())?;
    }
    parser.finish()
}

#[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
        .into_iter()
        .map(|arg| arg.into_string().expect("test argv must be UTF-8"))
        .collect()
}

#[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)?);
    }
    let residual_args = parsed
        .residual_args
        .into_iter()
        .map(|arg| arg.into_string().expect("test argv must be UTF-8"))
        .collect();
    Ok((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
                .into_iter()
                .map(|token| token.into_string().expect("test argv must be UTF-8"))
                .collect()
        })
        .collect();
    let residual_args = parsed
        .residual_args
        .into_iter()
        .map(|arg| arg.into_string().expect("test argv must be UTF-8"))
        .collect();
    Ok((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).
#[cfg(test)]
fn build_overlay_specs(
    specs: &[OverlaySpec],
    repair: bool,
    password: &PasswordArgs,
) -> CliResult<Vec<flpdf::OverlaySpec<BufReader<File>>>> {
    build_overlay_specs_with_suppression(specs, repair, password, false)
}

#[cfg(test)]
fn build_overlay_specs_with_suppression(
    specs: &[OverlaySpec],
    repair: bool,
    password: &PasswordArgs,
    suppress_warnings: bool,
) -> CliResult<Vec<flpdf::OverlaySpec<BufReader<File>>>> {
    let mut built = Vec::with_capacity(specs.len());
    for spec in specs {
        let path = PathBuf::from(spec.file.as_os_str());
        let file = File::open(&path).map_err(|error| open_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.set_password_bytes(spec.raw_password.clone().or_else(|| {
            spec.password
                .as_ref()
                .map(|password| arg_parser::os_bytes(password))
        }));
        source_password.password_file = None;
        let options = pdf_open_options(repair, &source_password)?;
        let mut source_job = QPDFJob::new();
        source_job.set_logger(cli_logger());
        source_job.set_message_prefix(progname());
        source_job.set_suppress_warnings(suppress_warnings);
        let mut source = source_job
            .open_with_description(BufReader::new(file), path_description(&path), 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::all(),
            Some("") => PageRange::empty(),
            Some(r) => PageRange::parse_numrange(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::all(),
            Some("") => PageRange::empty(),
            Some(r) => PageRange::parse_numrange(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_numrange(r)?),
        };
        built.push(flpdf::OverlaySpec {
            source,
            kind,
            from,
            to,
            repeat,
        });
    }
    Ok(built)
}

/// Parse each raw CLI `--collate` occurrence through the shared qpdf job
/// configuration parser. qpdf appends values when the option is repeated, so
/// preserve occurrence order in the returned vector.
fn parse_collate_values(raw_values: &[String]) -> CliResult<Option<Vec<usize>>> {
    if raw_values.is_empty() {
        return Ok(None);
    }
    let mut values = Vec::new();
    for raw in raw_values {
        values.extend(QPDFJob::parse_collate(raw)?);
    }
    Ok(Some(values))
}

fn validate_collate_values(raw_values: &[String]) {
    if let Err(error) = parse_collate_values(raw_values) {
        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);
    }
}

/// Apply the page-job-owned keep-open configuration from the CLI surface.
fn configure_keep_files_open(job: &mut QPDFJob, page_ops: &PageOpArgs) -> CliResult<()> {
    if let Some(value) = page_ops.keep_files_open {
        job.set_keep_files_open(matches!(value, CliYesNo::Yes));
    }
    if let Some(threshold) = page_ops.keep_files_open_threshold.as_deref() {
        job.set_keep_files_open_threshold(QPDFJob::parse_keep_files_open_threshold(threshold)?);
    }
    Ok(())
}

/// Validate the qpdf unsigned threshold even when no page operation is
/// selected. qpdf parses all options before dispatch, so a malformed value
/// must not be silently ignored by an ordinary rewrite route.
fn validate_keep_files_open_threshold(page_ops: &PageOpArgs) -> CliResult<()> {
    if let Some(value) = page_ops.keep_files_open_threshold.as_deref() {
        QPDFJob::parse_keep_files_open_threshold(value)?;
    }
    Ok(())
}

/// Run the `--pages` extraction pipeline.
///
/// Processing order is fixed as follows:
///   1. every `--pages` specification is resolved and copied, including
///      repeated occurrences of one source
///   2. apply the shared post-copy page-operation consumers
///   3. write (or split_pages when --split-pages is set)
///
/// qpdf 11.9.0 always enters `QPDFJob::handlePageSpecs` when page
/// specifications exist (`libqpdf/QPDFJob.cc:466-470`). The single-source
/// branch below configures those specifications on `QPDFJob::create_qpdf`'s
/// canonical page-spec lifecycle (the same boundary
/// [`run_empty_page_extraction`] and the top-level `--pages` route already
/// use), matching qpdf's `createQPDF` → `handlePageSpecs` call order. The
/// multi-source branch reaches the same boundary as of
/// `flpdf-3yn9.48.192`; it no longer opens sources or calls
/// `QPDFJob::handle_page_specs` itself.
///
/// The `--json-input`/`--update-from-json` combination with `--pages` has no
/// grammar on the `rewrite` subcommand (this function's only caller): those
/// flags are `--json-input`-route-only and never reach this pipeline.
#[allow(clippy::too_many_arguments)]
fn run_page_extraction(
    primary_input: &std::path::Path,
    output: &std::path::Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    verbose: bool,
    no_warn: 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 !split_pages_active(page_ops.split_pages.as_deref()) {
        reject_same_job_output(primary_input, output)?;
    }
    let standard_output = prepare_page_operation_standard_output(output, page_ops)?;
    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 raw_specs = configured_page_specs(page_ops)?;
    let inputs = resolve_page_specs(&raw_specs, primary_input)?;
    // The library keys its page-spec source map on the raw filename bytes,
    // matching qpdf (`QPDFJob.cc:2393-2401`). Classify here the same way: a
    // raw-distinct spelling of the primary is a separate source there, and
    // routing it through the single-source path instead would rebuild the
    // output from the merged document and drop the primary's encryption.
    let has_external_source = inputs
        .iter()
        .any(|spec| spec.path.as_os_str() != primary_input.as_os_str());

    // qpdf's ordinary page-spec job owns every page-spec selection, whether
    // the segment names one source or several. Distinct input documents are
    // copied into the primary output by the same library QPDFJob facade as
    // the single-source route below.
    if has_external_source {
        return run_page_extraction_from_multiple_sources(
            primary_input,
            output,
            repair,
            password,
            page_ops,
            raw_specs,
            overlay_specs,
            remove_unref,
            remove_restrictions,
            decrypt,
            options,
            linearize,
            linearize_pass1,
            image_options,
            coalesce_contents,
            generate_appearances,
            flatten_annotations_mode,
            flatten_rotation,
            verbose,
            no_warn,
            standard_output,
        );
    }

    run_page_extraction_from_single_source(
        primary_input,
        output,
        repair,
        password,
        page_ops,
        raw_specs,
        overlay_specs,
        remove_unref,
        remove_restrictions,
        decrypt,
        options,
        linearize,
        linearize_pass1,
        image_options,
        coalesce_contents,
        generate_appearances,
        flatten_annotations_mode,
        flatten_rotation,
        verbose,
        no_warn,
    )
}

/// Run qpdf's `--empty --pages` route with an empty primary document.
///
/// qpdf's empty primary has no input filename and all page specifications are
/// therefore secondary sources. Keep source-count policy, collate order, and
/// copying on `QPDFJob::create_qpdf`'s page-spec lifecycle so this command
/// shape cannot drift from qpdf's ordinary multi-source extraction.
#[allow(clippy::too_many_arguments)]
fn run_empty_page_extraction(
    output: &Path,
    password: &PasswordArgs,
    update_from_json: Option<&Path>,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    verbose: bool,
    no_warn: bool,
) -> CliResult<()> {
    let standard_output = prepare_page_operation_standard_output(output, page_ops)?;
    let raw_specs = configured_page_specs(page_ops)?;
    if raw_specs
        .iter()
        .any(|spec| spec.file_token == OsStr::new("."))
    {
        return Err("--pages: '.' cannot refer to a primary input with --empty".into());
    }
    // Parse the page segment at the CLI boundary for the same usage errors as
    // the former route, but leave source identity, opening, password policy,
    // and copying to QPDFJob's createQPDF page-spec lifecycle.
    let _validated_inputs = resolve_page_specs(&raw_specs, Path::new("<empty>"))?;
    let _validated_collate = parse_collate_values(&page_ops.collate)?;

    let mut job = new_cli_job(no_warn);
    job.set_output_file(output.to_path_buf())?;
    job.set_suppress_recovery(password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    job.set_password_mode(password.password_mode.into());
    job.set_password_is_hex_key(password.password_is_hex_key);
    job.set_suppress_password_recovery(password.suppress_password_recovery);
    job.set_allow_weak_crypto(options.allow_weak_crypto);
    job.set_allow_insecure(options.allow_insecure);
    job.set_accessibility_disabled(options.accessibility_disabled);
    job.set_verbose(verbose);
    configure_keep_files_open(&mut job, page_ops)?;
    {
        let mut configuration = job.config();
        // qpdf's createQPDF constructs the empty primary, applies
        // update-from-JSON, then resolves and copies every page spec before
        // returning the prepared merged document
        // (QPDFJob.cc:428-480,2360-2633).
        configuration.empty_input()?;
        if let Some(update_from_json) = update_from_json {
            configuration.update_from_json(update_from_json.to_path_buf());
        }
        for spec in &raw_specs {
            let source_password = spec.raw_password.clone().or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password))
            });
            configuration.add_page_spec(
                PathBuf::from(&spec.file_token),
                &spec.range,
                source_password,
            )?;
        }
        for parameter in &page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        configuration.remove_unreferenced_resources(remove_unref.into());
    }
    job.set_writer_configuration(writer_configuration_unnormalized(
        &options,
        linearize,
        linearize_pass1,
    )?);
    // `check_configuration` runs inside `create_qpdf`, so the create-stage
    // job needs the flag too -- the writer configuration above carries the
    // encryption parameters it gates on.
    job.set_allow_insecure(options.allow_insecure);
    job.set_accessibility_disabled(options.accessibility_disabled);

    let mut merged = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    let source_warnings = job.has_warnings();
    // qpdf accumulates the maximum source version during createQPDF and
    // applies it only at the writer boundary. Carry that snapshot into the
    // existing post-plan writer without reopening any page source.
    let mut options = options;
    if let Some(floor) = job.input_version_floor() {
        options.input_version_floor = Some(
            options
                .input_version_floor
                .map_or(floor, |current| current.max(floor)),
        );
    }
    let selected_pages = pages::page_refs(&mut merged)?;

    let result = run_page_extraction_after_plan(
        &mut merged,
        output,
        Path::new("<empty>"),
        password,
        page_ops,
        overlay_specs,
        remove_unref,
        remove_restrictions,
        decrypt,
        options,
        linearize,
        linearize_pass1,
        verbose,
        standard_output,
        source_warnings,
        None,
        selected_pages,
        image_options,
        coalesce_contents,
        generate_appearances,
        flatten_annotations_mode,
        flatten_rotation,
        no_warn,
    );
    // The create-stage job retains page-source providers through the later
    // post-plan writer. Drop it only after that writer has consumed the
    // merged document, matching qpdf's page-heap lifetime at write time.
    drop(job);
    result
}

/// Run qpdf's ordinary multi-source page-spec path through
/// `QPDFJob::create_qpdf`'s canonical page-spec lifecycle, the same job/CLI
/// boundary [`run_empty_page_extraction`] and the top-level `--pages` route
/// (`run_page_operations_with_qpdf_job`) already use. This matches qpdf's own
/// `createQPDF` → `handlePageSpecs` call order (`QPDFJob.cc:428-467`): the
/// primary and every distinct secondary source are opened by the job itself,
/// keyed by literal filename exactly as qpdf's page heap is, and
/// `prepare_document` resolves and applies every page spec to the primary
/// document in place before returning (`QPDFJob.cc:2359-2632`). The final
/// write below uses a separate Job for CLI-specific completion, but receives
/// that same primary document, including its `/Encrypt` state.
#[allow(clippy::too_many_arguments)]
fn run_page_extraction_from_multiple_sources(
    primary_input: &Path,
    output: &Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    raw_specs: Vec<PageSegmentSpec>,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    verbose: bool,
    no_warn: bool,
    standard_output: Option<PipelineWriter>,
) -> CliResult<()> {
    let mut job = new_cli_job(no_warn);
    job.set_input_file(primary_input.to_path_buf())?;
    job.set_suppress_recovery(password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    job.set_password_mode(password.password_mode.into());
    job.set_password_is_hex_key(password.password_is_hex_key);
    job.set_suppress_password_recovery(password.suppress_password_recovery);
    job.set_verbose(verbose);
    let input_options = pdf_open_options(repair, password)?;
    job.set_password(input_options.password);
    configure_keep_files_open(&mut job, page_ops)?;
    {
        let mut configuration = job.config();
        for spec in raw_specs {
            let spec_password = spec.raw_password.or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password))
            });
            configuration.add_page_spec(
                PathBuf::from(spec.file_token),
                &spec.range,
                spec_password,
            )?;
        }
        for parameter in &page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        configuration.remove_unreferenced_resources(remove_unref.into());
    }
    // `prepare_document`'s merge branch reads the writer's
    // `preserve_unreferenced_objects` bit directly (`lifecycle.rs`'s
    // `configuration.writer.preserves_unreferenced_objects()`) to decide
    // whether the primary's page-tree-unreferenced objects survive the copy,
    // so it must be set before `create_qpdf` runs (mirrors
    // `run_empty_page_extraction`, the other create-stage-then-separate-write
    // multi-source route). The rest of this writer configuration is unused by
    // `create_qpdf`/`prepare_document` and is superseded by the separate
    // writer configuration `run_page_extraction_after_plan` builds for the
    // actual write.
    let mut create_stage_writer =
        writer_configuration_unnormalized(&options, linearize, linearize_pass1)?;
    if split_pages_active(page_ops.split_pages.as_deref()) {
        // `QPDFJob::doSplitPages` (`libqpdf/QPDFJob.cc:2940-3027`) builds
        // every chunk from a fresh `QPDF`/`emptyPDF()` populated only by
        // `addPage(page, false)`, so the primary's page-tree-unreferenced
        // objects never reach a chunk's object cache and the writer option
        // it re-applies per chunk (`QPDFJob.cc:3021` reaching
        // `QPDFJob.cc:2856`) has nothing extra to enqueue. Copying that
        // object graph into the merged intermediate below would be resolved
        // and then discarded, so clear the bit for the create stage only. The
        // per-chunk writers `run_page_extraction_after_plan` configures keep
        // it, exactly as qpdf's `setWriterOptions` does.
        create_stage_writer.set_preserve_unreferenced_objects(false);
    }
    job.set_writer_configuration(create_stage_writer);
    // `check_configuration` runs inside `create_qpdf`, so the create-stage
    // job needs the flag too -- the writer configuration above carries the
    // encryption parameters it gates on.
    job.set_allow_insecure(options.allow_insecure);
    job.set_accessibility_disabled(options.accessibility_disabled);

    let mut merged = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    let source_warnings = job.has_warnings();
    // 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`).
    // `create_qpdf` already accumulated it from the primary and every
    // secondary source opened by `prepare_document`; carry that snapshot
    // into the separate post-plan writer without reopening any source.
    let mut options = options;
    if let Some(floor) = job.input_version_floor() {
        options.input_version_floor = Some(
            options
                .input_version_floor
                .map_or(floor, |current| current.max(floor)),
        );
    }

    // The Job has already mutated the primary page tree and copied selected
    // foreign pages into that same document. Use its resulting page list for
    // the CLI-specific post-selection transformations.
    let selected_pages = pages::page_refs(&mut merged)?;

    let result = run_page_extraction_after_plan(
        &mut merged,
        output,
        primary_input,
        password,
        page_ops,
        overlay_specs,
        // QPDFJob has already applied the page-copy resource policy to each
        // The page-copy job has already applied its source-side resource
        // policy. Retain the original mode for the later doSplitPages
        // preflight; the post-copy completion boundary itself remains a
        // no-op for resource pruning.
        remove_unref,
        remove_restrictions,
        decrypt,
        options,
        linearize,
        linearize_pass1,
        verbose,
        standard_output,
        source_warnings,
        None,
        selected_pages,
        image_options,
        coalesce_contents,
        generate_appearances,
        flatten_annotations_mode,
        flatten_rotation,
        no_warn,
    );
    // The create-stage job retains page-source providers through the later
    // post-plan writer. Drop it only after that writer has consumed the
    // merged document, matching qpdf's page-heap lifetime at write time (see
    // run_empty_page_extraction).
    drop(job);
    result
}

/// Run the single-source (in-place) `--pages` extraction through
/// `QPDFJob::create_qpdf`'s canonical page-spec lifecycle, the same job/CLI
/// boundary [`run_empty_page_extraction`] and the top-level `--pages` route
/// (`run_page_operations_with_qpdf_job`) already use. This matches qpdf's own
/// `createQPDF` → `handlePageSpecs` call order (`QPDFJob.cc:428-467`): the
/// primary is opened by the job itself, and `create_qpdf` resolves and
/// copies every page spec (including qpdf's in-place resource-pruning
/// decision, `QPDFJob.cc:2452-2455`) before returning, so no separate
/// `handle_page_specs` call or rebuild is needed here.
#[allow(clippy::too_many_arguments)]
fn run_page_extraction_from_single_source(
    primary_input: &Path,
    output: &Path,
    repair: bool,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    raw_specs: Vec<PageSegmentSpec>,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    verbose: bool,
    no_warn: bool,
) -> CliResult<()> {
    let mut job = new_cli_job(no_warn);
    job.set_input_file(primary_input.to_path_buf())?;
    job.set_suppress_recovery(password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    job.set_password_mode(password.password_mode.into());
    job.set_password_is_hex_key(password.password_is_hex_key);
    job.set_suppress_password_recovery(password.suppress_password_recovery);
    job.set_verbose(verbose);
    let input_options = pdf_open_options(repair, password)?;
    job.set_password(input_options.password);
    configure_keep_files_open(&mut job, page_ops)?;
    {
        let mut configuration = job.config();
        for spec in raw_specs {
            let spec_password = spec.raw_password.or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password))
            });
            configuration.add_page_spec(
                PathBuf::from(spec.file_token),
                &spec.range,
                spec_password,
            )?;
        }
        for parameter in &page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        configuration.remove_unreferenced_resources(remove_unref.into());
    }

    let mut pdf = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    pdf.set_suppress_warnings(no_warn);
    let source_warnings = job.has_warnings();

    finish_page_extraction(
        &mut pdf,
        output,
        primary_input,
        password,
        page_ops,
        overlay_specs,
        remove_unref,
        remove_restrictions,
        decrypt,
        options,
        linearize,
        linearize_pass1,
        verbose,
        source_warnings,
        image_options,
        coalesce_contents,
        generate_appearances,
        flatten_annotations_mode,
        flatten_rotation,
        no_warn,
    )
}

#[allow(clippy::too_many_arguments)]
fn run_page_extraction_after_plan<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    output: &Path,
    input_path: &Path,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    verbose: bool,
    _standard_output: Option<PipelineWriter>,
    prior_warnings: bool,
    page_job_result: Option<(RebuildResult, RemoveUnreferencedResources)>,
    selected_pages: Vec<ObjectRef>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    no_warn: bool,
) -> CliResult<()> {
    pdf.set_suppress_warnings(no_warn);
    let selected = selected_pages;

    let (result, prune_mode) = if let Some((result, prune_mode)) = page_job_result {
        (result, prune_mode)
    } else {
        // Multi-source and empty-primary page jobs already performed qpdf's
        // Auto|Yes|No resource decision on each source before copying pages
        // (`QPDFJob.cc:2251-2455`). The primary is only being presented
        // to the shared completion boundary here; running the page-local
        // resource pass again would mutate shared page/appearance resources
        // a second time and split identities that qpdf preserves. Keep the
        // original mode for the later doSplitPages preflight, but make this
        // post-copy completion a resource no-op.
        let mut copy_duplicate_annotations = |pdf: &mut Pdf<R>,
                                              source_page_ref: ObjectRef,
                                              new_page: ObjectRef|
         -> flpdf::Result<()> {
            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");
            PageObjectHelper::new(new_page, pdf).copy_annotations(source_page, Matrix::default())
        };
        let result =
            rebuild_page_tree_with_duplicate_hook(pdf, &selected, &mut copy_duplicate_annotations)?;
        (result, RemoveUnreferencedResources::No)
    };
    QPDFJob::complete_in_place_page_selection(pdf, &result, prune_mode)?;

    finish_page_extraction(
        pdf,
        output,
        input_path,
        password,
        page_ops,
        overlay_specs,
        remove_unref,
        remove_restrictions,
        decrypt,
        options,
        linearize,
        linearize_pass1,
        verbose,
        prior_warnings,
        image_options,
        coalesce_contents,
        generate_appearances,
        flatten_annotations_mode,
        flatten_rotation,
        no_warn,
    )
}

/// Shared writer/transform completion for a fully page-selected document:
/// preserve-encryption/copy-encryption policy, the transform job (rotate,
/// overlay/underlay, image, appearance, annotation, coalesce, flatten), and
/// the final split or ordinary write. Called once page selection (rebuild and
/// `QPDFJob::complete_in_place_page_selection`, or `create_qpdf`'s equivalent
/// internal step for the single-source route) has already finished.
#[allow(clippy::too_many_arguments)]
fn finish_page_extraction<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    output: &Path,
    input_path: &Path,
    password: &PasswordArgs,
    page_ops: &PageOpArgs,
    overlay_specs: &[OverlaySpec],
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    verbose: bool,
    prior_warnings: bool,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    no_warn: bool,
) -> CliResult<()> {
    let mut options = options;
    let split_pages = page_ops
        .split_pages
        .as_deref()
        .map(parse_split_n)
        .transpose()?;
    let split_pages_active = split_pages.is_some_and(|size| size > 0);
    options.preserve_encryption =
        options.preserve_encryption && pdf.is_encrypted() && !split_pages_active && !decrypt;
    // The selected page graph still belongs to qpdf's primary document, so
    // the writer reads its live `/Encrypt` state directly. Split chunks and
    // explicit decryption remain cleartext (`QPDFJob.cc:2847-2877`).
    // 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.
    // 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 one
    // canonical Job and its opened overlay sources through the in-memory
    // writer for the same reason. The job records the overlay source version
    // floor while it performs that one canonical open (`QPDFJob.cc:1695-1716`);
    // the final page-operation writer consumes the exposed snapshot below.
    let has_transformations = !overlay_specs.is_empty()
        || !page_ops.rotate.is_empty()
        || image_options.externalize_inline_images
        || image_options.optimize_images
        || remove_restrictions
        || coalesce_contents
        || generate_appearances
        || flatten_annotations_mode.is_some()
        || flatten_rotation;
    let mut transform_job = if has_transformations {
        if !overlay_specs.is_empty() {
            update_input_version_floor(&mut options.input_version_floor, pdf)?;
        }

        let mut job = new_cli_job(no_warn);
        job.set_password_mode(password.password_mode.into());
        job.set_password_is_hex_key(password.password_is_hex_key);
        job.set_suppress_password_recovery(password.suppress_password_recovery);
        job.set_suppress_recovery(password.recovery.suppress_recovery);
        job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
        job.set_verbose(verbose);
        configure_cli_overlay_specs(&mut job, overlay_specs)?;
        {
            let mut configuration = job.config();
            for parameter in &page_ops.rotate {
                configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
            }
            if image_options.optimize_images {
                let mut optimization = image_options.image_options;
                if image_options.externalize_inline_images {
                    optimization.keep_inline_images = false;
                }
                configuration.optimize_images(optimization);
            } else if image_options.externalize_inline_images {
                configuration
                    .externalize_inline_images(image_options.image_options.inline_min_bytes);
            }
            if remove_restrictions {
                configuration.remove_restrictions();
            }
            if generate_appearances {
                configuration.generate_appearances();
            }
            if let Some(mode) = flatten_annotations_mode {
                configuration.flatten_annotations(FlattenAnnotationsMode::from(mode));
            }
            if coalesce_contents {
                configuration.coalesce_contents();
            }
            if flatten_rotation {
                configuration.flatten_rotation();
            }
        }
        Some(job)
    } else {
        None
    };
    if let Some(job) = transform_job.as_mut() {
        // QPDFJob applies rotations before its underlay/overlay stage and then
        // runs image, appearance, annotation, coalesce, and flatten-rotation
        // transformations in qpdf order (`QPDFJob.cc:466-473,2137-2194`).
        apply_transformations_for_cli(job, pdf)?;
        if let Some(floor) = job.input_version_floor() {
            options.input_version_floor = Some(
                options
                    .input_version_floor
                    .map_or(floor, |current| current.max(floor)),
            );
        }
    }

    let split_progress = split_pages_active && options.progress;
    if split_pages.is_some_and(|size| size > 0) {
        // qpdf keeps split dispatch inside the one job's writeQPDF boundary
        // (`QPDFJob.cc:483-503`). The page-selection pipeline has already
        // prepared this live document, so configure only the writer-stage
        // state here and let write_qpdf own the split/resource/warning/status
        // boundary rather than creating a second split helper route.
        let mut split_job = new_cli_job(no_warn);
        split_job.set_input_file(input_path.to_path_buf())?;
        split_job.set_output_file(output.to_path_buf())?;
        split_job.set_verbose(verbose);
        split_job.set_progress(split_progress);
        split_job.set_report_memory_usage(options.report_memory_usage);
        split_job.set_password_mode(options.password_mode);
        split_job.set_allow_weak_crypto(options.allow_weak_crypto);
        split_job.set_allow_insecure(options.allow_insecure);
        split_job.set_accessibility_disabled(options.accessibility_disabled);
        split_job.set_linearization(linearize, linearize_pass1.map(std::path::Path::to_path_buf));
        {
            let mut configuration = split_job.config();
            configuration.split_pages(
                page_ops
                    .split_pages
                    .as_deref()
                    .expect("positive split_pages has a raw CLI value")
                    .as_bytes(),
            )?;
            configuration.remove_unreferenced_resources(remove_unref.into());
        }
        split_job.set_writer_configuration(writer_configuration_unnormalized(
            &options,
            linearize,
            linearize_pass1,
        )?);
        // Preserve warnings raised while preparing the source before the
        // canonical write boundary starts.
        if prior_warnings {
            split_job.record_warnings();
        }
        match split_job.write_qpdf(pdf) {
            Ok(()) => finish_job_exit_status(split_job.get_exit_code()),
            Err(_) => Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            })),
        }
    } else {
        // qpdf keeps the ordinary page-operation output on the same
        // QPDFJob::writeQPDF -> writeOutfile boundary as a plain rewrite
        // (`QPDFJob.cc:483-511,3029-3091`). The page-selection and
        // post-plan transformation stages above already mutated this live
        // document; this final Job only owns writer setup, completion, and
        // status so no CLI-local PdfWriter route remains.
        let mut write_job = new_cli_job(no_warn);
        write_job.set_input_file(input_path.to_path_buf())?;
        write_job.set_output_file(output.to_path_buf())?;
        write_job.set_verbose(verbose);
        write_job.set_progress(options.progress);
        write_job.set_report_memory_usage(options.report_memory_usage);
        write_job.set_password_mode(options.password_mode);
        write_job.set_allow_weak_crypto(options.allow_weak_crypto);
        write_job.set_allow_insecure(options.allow_insecure);
        write_job.set_accessibility_disabled(options.accessibility_disabled);
        write_job.set_linearization(linearize, linearize_pass1.map(std::path::Path::to_path_buf));
        write_job.set_writer_configuration(writer_configuration_unnormalized(
            &options,
            linearize,
            linearize_pass1,
        )?);
        if prior_warnings {
            write_job.record_warnings();
        }
        match write_job.write_qpdf(pdf) {
            Ok(()) => finish_job_exit_status(write_job.get_exit_code()),
            Err(_) => Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            })),
        }
    }
}

/// 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 non-negative integer, got {raw:?}"))?;
    Ok(n)
}

/// Whether `--split-pages` selects qpdf's chunk-writing path.
///
/// qpdf stores the parsed value in a signed field and dispatches only when it
/// is truthy (`if (m->split_pages)`). The value comes from
/// `Config::splitPages` (`libqpdf/QPDFJob_config.cc:604-609`): an empty
/// parameter is one page, and anything else goes through
/// `QUtil::string_to_int`, whose `strtoll` stage (`libqpdf/QUtil.cc:373-393`)
/// reads a leading digit run and performs no conversion at all -- returning
/// zero -- for a value that has none. `--split-pages=garbage` is therefore an
/// ordinary unsplit write in qpdf, not a usage error, while
/// `--split-pages=2x` really is a split of two. A value that overflows stays
/// active so `parse_split_n` reports the same range error qpdf's
/// `QIntC::to_int` raises.
fn split_pages_active(raw: Option<&str>) -> bool {
    raw.is_some_and(|value| {
        if value.is_empty() {
            return true;
        }
        qpdf_selector_integer(value).map_or(true, |size| size != 0)
    })
}

/// 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,
    remove_unref: CliRemoveUnreferencedResources,
    remove_restrictions: bool,
    decrypt: bool,
    options: WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    image_options: ImageTransformOptions,
    coalesce_contents: bool,
    generate_appearances: bool,
    flatten_annotations_mode: Option<CliFlattenMode>,
    flatten_rotation: bool,
    verbose: bool,
    no_warn: bool,
) -> CliResult<()> {
    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(),
        );
    }
    // qpdf's no-`--pages` page-operation path still uses the same QPDFJob
    // create/write lifecycle: `handleRotations` runs before
    // `handleTransformations`, and `writeQPDF` owns ordinary or split output
    // (`QPDFJob.cc:466-491`). Queue the raw page-operation parameters on that
    // canonical job instead of reopening a second direct PdfWriter route.
    run_rewrite_with_qpdf_job(
        input,
        output,
        false,
        repair,
        password,
        json_input,
        update_from_json,
        linearize,
        linearize_pass1,
        remove_restrictions,
        decrypt,
        options.content_normalization,
        coalesce_contents,
        generate_appearances,
        image_options,
        flatten_annotations_mode,
        flatten_rotation,
        PageLabelOptions::default(),
        &[],
        verbose,
        no_warn,
        options,
        &page_ops.rotate,
        page_ops.split_pages.as_deref(),
        remove_unref.into(),
    )
}

/// 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()
        || split_pages_active(p.split_pages.as_deref())
        || 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);
    let contents = page.try_get_key(b"/Contents")?;
    let contents_ref = contents.object_ref();

    let mut streams = Vec::new();
    if contents.try_is_stream_of_type(b"", b"")? {
        if let Some(stream_ref) = contents_ref {
            streams.push((stream_ref, contents));
        }
    } else if contents.try_is_array()? {
        let items = contents.as_array().unwrap_or_default();
        for item in items {
            let item_ref = item.object_ref();
            if item.try_is_stream_of_type(b"", b"")? {
                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(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(
    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 the canonical live writer observes the updated stream.
    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();
    Ok(warning)
}

fn run_qdf(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    preserve_unreferenced: bool,
) -> CliResult<()> {
    let input = input.ok_or_else(missing_input_usage_error)?;
    let output = output.ok_or_else(missing_output_usage_error)?;
    // qpdf's qdf command is the ordinary QPDFJob writer with qdf mode set;
    // keep this alias on the same create/write lifecycle as `rewrite --qdf`
    // instead of opening a Pdf and bypassing the Job boundary.
    let options = WriterOptions {
        qdf: true,
        preserve_unreferenced_objects: preserve_unreferenced,
        password_mode: password.password_mode.into(),
        ..WriterOptions::default()
    };
    run_rewrite(
        Some(input),
        Some(output),
        false,
        repair,
        password,
        false,
        None,
        false,
        None,
        false,
        false,
        false,
        false,
        CliRemoveUnreferencedResources::Auto,
        false,
        ImageTransformOptions::default(),
        None,
        false,
        PageLabelOptions::default(),
        &[],
        false,
        false,
        options,
        false,
    )?;
    Ok(())
}

/// `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 is_zlib_flate_program(program: &OsStr) -> bool {
    Path::new(program).file_name().is_some_and(|name| {
        name == OsStr::new("zlib-flate") || name == OsStr::new("zlib-flate.exe")
    })
}

fn zlib_flate_usage(usage_name: &str) -> CliResult<()> {
    emit_logger_error(format!(
        "Usage: {usage_name} {{ -uncompress | -compress[=n] }}\n\
If n is specified with -compress, it is a zlib compression level from\n\
1 to 9 where lower numbers are faster and less compressed and higher\n\
numbers are slower and more compressed\n"
    ));
    Err(Box::new(CliExitError {
        code: ExitCode::Errors,
        message: String::new(),
    }))
}

fn zlib_flate_failure(whoami: &str, error: impl std::fmt::Display) -> CliResult<()> {
    emit_logger_error(format!("{whoami}: {error}\n"));
    Err(Box::new(CliExitError {
        code: ExitCode::Errors,
        message: String::new(),
    }))
}

/// Run qpdf's raw zlib stdin/stdout utility over the canonical Flate pipeline.
fn run_zlib_flate(args: &[OsString], whoami: &str, usage_name: &str) -> CliResult<()> {
    if args.len() == 1 && args[0] == OsStr::new("--version") {
        emit_logger_info(format!(
            "{whoami} from qpdf version {}\n",
            flpdf::qpdf_version()
        ));
        return Ok(());
    }
    if args.len() != 1 {
        return zlib_flate_usage(usage_name);
    }

    let Some(mode) = args[0].to_str() else {
        return zlib_flate_usage(usage_name);
    };
    let (action, compression_level) = match mode {
        "-uncompress" => (FlateAction::Inflate, None),
        "-compress" => (FlateAction::Deflate, None),
        value => match value.strip_prefix("-compress=") {
            Some(level) => {
                let level = match qpdf_selector_integer(level) {
                    Ok(level) => level,
                    Err(error) => return zlib_flate_failure(whoami, error),
                };
                (FlateAction::Deflate, Some(level))
            }
            None => return zlib_flate_usage(usage_name),
        },
    };

    let input = std::io::stdin();
    let mut input = input.lock();
    let output = std::io::stdout();
    let mut output = output.lock();
    let mut sink = PlStdioFile::new("stdout", &mut output);
    let flate_result = match compression_level {
        Some(level) => PlFlate::new_with_compression_level("flate", &mut sink, action, level),
        None => PlFlate::new("flate", &mut sink, action),
    };
    let mut flate = match flate_result {
        Ok(flate) => flate,
        // cov:ignore-start: both constructors use a fixed valid output buffer size
        Err(error) => return zlib_flate_failure(whoami, error),
        // cov:ignore-end
    };
    let warned = std::rc::Rc::new(std::cell::Cell::new(false));
    let warned_for_callback = std::rc::Rc::clone(&warned);
    let warning_whoami = whoami.to_owned();
    flate.set_warn_callback(move |message, code| {
        warned_for_callback.set(true);
        emit_logger_error(format!(
            "{warning_whoami}: WARNING: zlib code {code}, msg = {message}\n"
        ));
        Ok(())
    });

    let mut buffer = [0u8; 10_000];
    loop {
        let length = match input.read(&mut buffer) {
            Ok(length) => length,
            // cov:ignore-start: integration processes cannot inject a stdin read error
            Err(error) => {
                drop(flate);
                return zlib_flate_failure(whoami, error);
                // cov:ignore-end
            }
        };
        if length == 0 {
            break;
        }
        if let Err(error) = flate.write(&buffer[..length]) {
            drop(flate);
            return zlib_flate_failure(whoami, error);
        }
    }

    let finish = flate.finish();
    drop(flate);
    // cov:ignore-start: closed stdout/flush failure is owned by the host process boundary
    if let Err(error) = finish {
        return zlib_flate_failure(whoami, error);
    }
    // cov:ignore-end
    if warned.get() {
        return Err(Box::new(CliExitError {
            code: ExitCode::Warnings,
            message: String::new(),
        }));
    }
    Ok(())
}

/// 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`). Keep qpdf's `--replace-input` guidance because
/// flpdf supports the same escape hatch on the write routes.
///
/// 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 --replace-input to intentionally overwrite the input file",
        "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(UsageError::new(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 qpdf_json_input_open_error(input: &Path, error: std::io::Error) -> Box<dyn std::error::Error> {
    // qpdf-deviation: for a directory job-JSON path, qpdf 11.9.0 leaks
    // libstdc++'s basic_string::_M_create; that toolchain artifact has no
    // qpdf semantic contract to reproduce in Rust, so this shares
    // qpdf_open_io_error_message's own portable "Is a directory" wording
    // instead like every other kind here.
    let message = qpdf_open_io_error_message(&error);
    let mut raw_message = b"open ".to_vec();
    raw_message.extend_from_slice(&path_description(input));
    raw_message.extend_from_slice(b": ");
    raw_message.extend_from_slice(message.as_bytes());
    Box::new(flpdf::Error::SystemBytes(raw_message))
}

/// qpdf's `QUtil::string_to_int` uses `strtoll`: it accepts a signed decimal
/// prefix and returns zero when no digits are present. Used by
/// `--compress=N`/`-compress=N` (`run_zlib_flate`) and `--compression-level`
/// (`parse_compression_level`).
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"
        ))
    })?)
}

/// `flpdf pages FILE --show-npages`: the flpdf-native subcommand form. No
/// qpdf argv counterpart (qpdf has no subcommand grammar), so it keeps its
/// own standalone document-open/report sequence.
fn run_show_npages(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    suppress_warnings: bool,
    empty: bool,
    transform_options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    if empty {
        reject_empty_inspection_output(input.as_deref())?;
        let mut job = new_cli_job(suppress_warnings);
        let mut pdf = create_empty_primary_document(&mut job, None)?;
        apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
        return finish_job_exit_status(job.show_npages(&mut pdf)?);
    }
    let input = input.ok_or_else(missing_input_usage_error)?;
    let mut pdf = open_pdf_with_suppression(&input, repair, password, suppress_warnings)?;
    let mut job = new_cli_job(suppress_warnings);
    apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
    finish_job_exit_status(job.show_npages(&mut pdf)?)
}

/// `flpdf pages FILE` (default, without `--show-npages`): the flpdf-native
/// subcommand form -- same qpdf-grammar-free scope as `run_show_npages`.
#[allow(clippy::too_many_arguments)]
fn run_show_pages(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    with_images: bool,
    suppress_warnings: bool,
    empty: bool,
    transform_options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    if empty {
        reject_empty_inspection_output(input.as_deref())?;
        let mut job = new_cli_job(suppress_warnings);
        job.set_with_images(with_images);
        let mut pdf = create_empty_primary_document(&mut job, None)?;
        apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
        return finish_job_exit_status(job.show_pages(&mut pdf)?);
    }
    let input = input.ok_or_else(missing_input_usage_error)?;
    let mut pdf = open_pdf_with_suppression(&input, repair, password, suppress_warnings)?;
    let mut job = new_cli_job(suppress_warnings);
    job.set_with_images(with_images);
    apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
    finish_job_exit_status(job.show_pages(&mut pdf)?)
}

// ---------------------------------------------------------------------------
// Encryption inspection subcommands
//
// 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,
    suppress_warnings: bool,
) -> CliResult<EncryptionProbe> {
    let file = File::open(input).map_err(|error| open_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());
    job.set_suppress_warnings(suppress_warnings);
    match job.open_with_description(BufReader::new(file), path_description(input), 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(error_with_file(input, actionable_password_error(other))),
    }
}

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)
    )
}

/// `--empty --is-encrypted`/`--empty --requires-password`: silently exit 2.
///
/// qpdf's `createQPDF` still builds an empty document for `--empty` before
/// the encryption-status early return (`QPDFJob.cc:429-456,535-557`); an
/// empty document is necessarily unencrypted, so both flags exit 2 without
/// opening any file.
fn run_empty_document_encryption_status() -> CliResult<()> {
    Err(Box::new(CliExitError {
        code: ExitCode::Errors,
        message: String::new(),
    }))
}

/// `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. A
/// supplied password is still forwarded because qpdf passes its configured
/// password to `processFile`; it does not change the classification of an
/// encrypted input, but password-file parsing and diagnostics remain visible.
fn run_is_encrypted(
    input: &PathBuf,
    repair: bool,
    password: &PasswordArgs,
    suppress_warnings: bool,
) -> CliResult<()> {
    let encrypted = match probe_encryption(input, repair, password, suppress_warnings)? {
        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,
    suppress_warnings: bool,
) -> CliResult<()> {
    match probe_encryption(input, repair, password, suppress_warnings)? {
        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)
        }
        None if pdf.is_encrypted() => Err("invalid password".into()),
        None => Err("file is not encrypted; no encryption key to show".into()),
    }
}

/// `flpdf show-encryption FILE`: the flpdf-native subcommand form. No qpdf
/// argv counterpart, so it keeps its own standalone document-open/report
/// sequence rather than routing through [`run_combined_top_level_inspection`].
///
/// 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.
#[allow(clippy::too_many_arguments)]
fn run_show_encryption(
    input: Option<PathBuf>,
    repair: bool,
    password: &PasswordArgs,
    no_warn: bool,
    show_encryption_key: bool,
    empty: bool,
    transform_options: InspectionTransformOptions<'_>,
    verbose: bool,
) -> CliResult<()> {
    if empty {
        reject_empty_inspection_output(input.as_deref())?;
        let mut job = new_cli_job(no_warn);
        job.set_show_encryption_key(show_encryption_key);
        let mut pdf = create_empty_primary_document(&mut job, None)?;
        apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
        return finish_show_encryption(&mut job, &mut pdf, password.password_is_hex_key);
    }
    let input = input.ok_or_else(missing_input_usage_error)?;
    let file = File::open(&input).map_err(|error| open_error_with_file(&input, error.into()))?;
    let mut job = new_cli_job(no_warn);
    job.set_show_encryption_key(show_encryption_key);
    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_with_description(
            BufReader::new(file),
            path_description(&input),
            options,
        )
        .map_err(|error| error_with_file(&input, actionable_password_error(error)))?;
    // qpdf's password-error catch returns from `createQPDF` before it reaches
    // `handleTransformations` (`QPDFJob.cc:437-448,473`), so `--show-encryption`
    // on a file whose password did not authenticate prints the report and stops
    // -- it never walks the still-encrypted streams. Running the image phase
    // here instead would raise decode warnings qpdf does not raise and turn the
    // exit status into 3.
    if !(pdf.is_encrypted() && pdf.encryption_file_key().is_none()) {
        apply_inspection_transformations(&mut job, &mut pdf, transform_options, verbose)?;
    }
    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. qpdf's
/// wrong-password `createQPDF` path returns before `writeQPDF` transfers the
/// partially opened document's warnings to the job, so this path retains their
/// live output without using them to select the exit code.
fn finish_show_encryption<R: Read + Seek>(
    job: &mut QPDFJob,
    pdf: &mut Pdf<R>,
    password_is_hex_key: bool,
) -> CliResult<()> {
    let authentication_failed = pdf.is_encrypted() && pdf.encryption_file_key().is_none();
    job.show_encryption(pdf, password_is_hex_key)?;
    if !authentication_failed {
        job.record_document_warnings(pdf);
    }
    finish_job_exit_status(job.complete_report()?)
}

/// 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
}

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_description(path))
            .map_err(|error| json_error_with_file(path, Box::new(error)))?;
    }
    Ok(())
}

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

/// 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| open_error_with_file(input, error.into()))?;
    open_pdf_file_impl(input, file, repair, password, false, 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| open_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());
    job.set_suppress_warnings(suppress_warnings);
    let pdf = if encryption_inspection {
        job.open_for_encryption_inspection_with_description(
            BufReader::new(file),
            path_description(input),
            options,
        )
    } else {
        job.open_with_description(BufReader::new(file), path_description(input), 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_bytes() {
        password
    } else if let Some(path) = &password.password_file {
        read_password_file(path)?
    } else {
        Vec::new()
    };

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

/// Read qpdf's `--password-file` value as raw bytes.
///
/// qpdf 11.9.0 calls `QUtil::read_lines_from_file` and uses only `lines.front()`
/// (`QUtil.cc:1231-1286`, `QPDFJob_config.cc:661-679`). The line reader splits
/// on `\n`, removes only a preceding `\r`, retains arbitrary non-UTF-8 bytes,
/// and does not create an extra line for a final newline. qpdf also treats
/// `-` as stdin and warns about every line after the first; that warning is a
/// configuration diagnostic, so it is emitted even for `--no-warn`.
fn read_password_file(path: &Path) -> CliResult<Vec<u8>> {
    let open_usage_error = |error: std::io::Error| {
        let mut message = b"open ".to_vec();
        message.extend_from_slice(&path_description(path));
        message.extend_from_slice(b": ");
        message.extend_from_slice(qpdf_open_io_error_message(&error).as_bytes());
        Box::new(UsageError::new(message)) as Box<dyn std::error::Error>
    };
    let bytes = if path == Path::new("-") {
        let mut bytes = Vec::new();
        std::io::stdin()
            .read_to_end(&mut bytes)
            .map_err(open_usage_error)?;
        bytes
    } else {
        // qpdf's `QUtil::read_lines_from_file(char const*)` opens with
        // `safe_fopen` and only reads afterward (`libqpdf/QUtil.cc:1231-1239`).
        // `fopen(..., "rb")` on a directory succeeds on Unix; the failure
        // surfaces only on the first `fread`, which reports a fixed,
        // path-less message with no `open <path>:` prefix
        // (`read_char_from_FILE`, `QUtil.cc:1217-1228`: `ferror(f)` throws
        // `std::runtime_error("failure reading character from file")`).
        // `std::fs::File::open` mirrors that same open/read split on Unix, so
        // the two stages are kept separate here instead of using
        // `std::fs::read`, which would blame the read-stage failure on
        // `open_usage_error`.
        let mut file = File::open(path).map_err(open_usage_error)?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes).map_err(|_error| {
            Box::new(UsageError::new("failure reading character from file"))
                as Box<dyn std::error::Error>
        })?;
        bytes
    };

    let first_newline = bytes.iter().position(|&byte| byte == b'\n');
    let first_line_len = first_newline.unwrap_or(bytes.len());
    let mut first_line = bytes[..first_line_len].to_vec();
    if first_line.ends_with(b"\r") {
        first_line.pop();
    }
    if first_newline.is_some_and(|index| index + 1 < bytes.len()) {
        emit_logger_error(format!(
            "{}: WARNING: all but the first line of the password file are ignored\n",
            progname()
        ));
    }
    Ok(first_line)
}

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,
        verbose: password.verbose,
        message_prefix: progname().into_bytes(),
        ..PdfOpenOptions::default()
    }
}

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

/// The qpdf CLI creates one QPDFJob for an invocation, but flpdf's top-level
/// dispatch creates that same job at several route-specific boundaries. Keep
/// the argv-owned warning-exit policy in one process-local slot so every
/// canonical QPDFJob created by this invocation receives the same
/// `Config::warningExitZero` state.
///
/// Every route that can decide the process exit status has to read it: qpdf
/// derives that status once, from the single job's `warnings_exit_zero`
/// (`QPDFJob.cc:560-563`).
static CLI_WARNING_EXIT_ZERO: OnceLock<bool> = OnceLock::new();

fn cli_warning_exit_zero() -> bool {
    CLI_WARNING_EXIT_ZERO.get().copied().unwrap_or(false)
}

/// qpdf's `--report-memory-usage` sets one `m->report_mem_usage` bit on the
/// `QPDFJob` the run uses, and every route that finishes a run prints the
/// line from it (`QPDFJob.cc:505-509`) -- writes and inspections alike.
/// Every job this CLI builds goes through `new_cli_job`, so carrying the flag
/// the same way `--warning-exit-0` is carried reaches all of them, rather
/// than only the routes that happen to thread `WriterOptions` through.
static CLI_REPORT_MEMORY_USAGE: OnceLock<bool> = OnceLock::new();

fn cli_report_memory_usage() -> bool {
    CLI_REPORT_MEMORY_USAGE.get().copied().unwrap_or(false)
}

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::new(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() == "-" && split_pages_active(page_ops.split_pages.as_deref()) {
        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 emit_logger_info(data: impl AsRef<[u8]>) {
    let _ = logger_info(data);
}

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
    }
}

#[cfg(unix)]
fn path_description(input: &Path) -> Vec<u8> {
    use std::os::unix::ffi::OsStrExt;

    input.as_os_str().as_bytes().to_vec()
}

#[cfg(not(unix))]
fn path_description(input: &Path) -> Vec<u8> {
    input.to_string_lossy().into_owned().into_bytes()
}

/// 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.
fn finish_operation_warnings<R: Read + Seek>(pdf: &Pdf<R>) -> CliResult<()> {
    finish_operation_warnings_with_prior(pdf, 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>,
    prior_warnings: bool,
) -> CliResult<()> {
    finish_warning_state(
        prior_warnings || !pdf.repair_diagnostics().entries().is_empty(),
        pdf.suppress_warnings(),
    )
}

fn finish_job_exit_status(status: JobExitCode) -> CliResult<()> {
    cli_logger().flush()?;
    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(),
        })),
    }
}

/// Complete a standalone warning/status boundary after a report-only consumer
/// has recorded its warning state.
///
/// A report-only consumer never writes a PDF, so qpdf's `createsOutput()`
/// (`libqpdf/QPDFJob.cc:528-531`) is false for every route that reaches here
/// and the summary always takes the bare spelling. Routes that do create
/// output complete through `QPDFJob::write_qpdf` instead, which queries the
/// job that performed the write.
fn finish_warning_state(has_warnings: bool, no_warn: bool) -> CliResult<()> {
    let mut job = QPDFJob::new();
    job.set_warnings_exit_zero(cli_warning_exit_zero());
    // This route builds its job directly rather than through `new_cli_job`,
    // so it needs the same carry (`QPDFJob.cc:505-509` prints from whichever
    // job finished the run, and `--json` finishes one like any other route).
    job.set_report_memory_usage(cli_report_memory_usage());
    job.set_logger(cli_logger());
    job.set_message_prefix(progname());
    job.set_suppress_warnings(no_warn);
    if has_warnings {
        job.record_warnings();
    }

    finish_job_exit_status(job.complete_report()?)
}

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)
}

/// Prefix a fatal post-open error with the input path so main() renders the
/// qpdf shape `<progname>: <file>: <msg>` for path-scoped 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> {
    let message = qpdf_path_error_message(error.as_ref());
    Box::new(CliPathError {
        path: path_description(input),
        operation: None,
        message,
        source: error,
    })
}

/// Preserve qpdf's `QPDFExc::createWhat` message when the terminal recovery
/// failure has no object or positive offset (`libqpdf/QPDFExc.cc:16-48`). The
/// public `Error::Parse` display includes a Rust-oriented byte prefix, but the
/// CLI path wrapper already supplies the source filename and must not add a
/// second location layer.
fn qpdf_path_error_message(error: &(dyn std::error::Error + 'static)) -> String {
    let Some(flpdf_error) = error.downcast_ref::<flpdf::Error>() else {
        return error.to_string();
    };
    let terminal = flpdf_error
        .open_failure()
        .map_or(flpdf_error, |(source, _)| source);
    match terminal {
        flpdf::Error::Parse { offset: 0, message }
            if message == "unable to find trailer dictionary while recovering damaged file" =>
        {
            message.clone()
        }
        _ => error.to_string(),
    }
}

/// Prefix a fatal input-open error with qpdf's `open ` operation and normalize
/// Rust's platform-specific I/O rendering. This mirrors `QUtil::safe_fopen`
/// (`libqpdf/QUtil.cc:512-515`) and `QPDFSystemError::createWhat`
/// (`libqpdf/QPDFSystemError.cc:13-29`). The path is kept as raw bytes so the
/// CLI preserves non-UTF-8 Unix arguments just as qpdf's `std::string`
/// boundary does.
fn open_error_with_file(
    input: &Path,
    error: Box<dyn std::error::Error>,
) -> Box<dyn std::error::Error> {
    let io_error = error.downcast_ref::<std::io::Error>().or_else(|| {
        match error.downcast_ref::<flpdf::Error>() {
            Some(flpdf::Error::FileIo {
                operation: "open",
                source,
                ..
            }) => Some(source),
            _ => None,
        }
    });
    let Some(io_error) = io_error else {
        return error_with_file(input, error);
    };
    let message = qpdf_open_io_error_message(io_error);
    Box::new(CliPathError {
        path: path_description(input),
        operation: Some("open"),
        message,
        source: error,
    })
}

/// Match qpdf's `QPDFSystemError::createWhat`: use the C-runtime wording and
/// omit Rust's numeric `(os error N)` suffix. qpdf uses the portable
/// not-found wording on every supported host.
fn qpdf_open_io_error_message(error: &std::io::Error) -> String {
    // A real syscall failure on a `strerror`-rendering host already carries
    // exactly the text qpdf prints, so use it rather than the table below.
    // The table keys on `ErrorKind`, which is coarser than `errno`: `EPERM`
    // and `EACCES` share `PermissionDenied` but print "Operation not
    // permitted" and "Permission denied" respectively, and only the raw code
    // tells them apart. The table still covers synthetic errors carrying no
    // `errno`, and every host whose `Display` is not `strerror` -- which is
    // the Windows wording this table exists for.
    #[cfg(unix)]
    if error.raw_os_error().is_some() {
        return strerror_from_display(error);
    }
    let message = match error.kind() {
        std::io::ErrorKind::NotFound => Some("No such file or directory"),
        std::io::ErrorKind::PermissionDenied => Some("Permission denied"),
        std::io::ErrorKind::AlreadyExists => Some("File exists"),
        std::io::ErrorKind::InvalidInput => Some("Invalid argument"),
        std::io::ErrorKind::IsADirectory => Some("Is a directory"),
        std::io::ErrorKind::NotADirectory => Some("Not a directory"),
        _ => None,
    };
    if let Some(message) = message {
        return message.to_owned();
    }
    strerror_from_display(error)
}

/// Render `error` through its own `Display`, less the ` (os error N)` suffix
/// Rust appends and `strerror` does not.
fn strerror_from_display(error: &std::io::Error) -> String {
    let rendered = error.to_string();
    error
        .raw_os_error()
        .and_then(|code| rendered.strip_suffix(&format!(" (os error {code})")))
        .unwrap_or(&rendered)
        .to_owned()
}

fn json_error_with_file(
    input: &Path,
    error: Box<dyn std::error::Error>,
) -> Box<dyn std::error::Error> {
    let path = path_description(input);
    let lossy_path = String::from_utf8_lossy(&path);
    let message = error
        .to_string()
        .strip_prefix(&format!("{lossy_path}: "))
        .map_or_else(|| error.to_string(), str::to_owned);
    Box::new(CliPathError {
        path,
        operation: None,
        message,
        source: error,
    })
}

fn actionable_password_error(error: flpdf::Error) -> Box<dyn std::error::Error> {
    if is_bad_password_error(&error) {
        return "invalid password".into();
    }
    error.into()
}

// ── Attachment helpers ──────────────────────────────────────────

/// Parse and retain the PDF timestamp syntax accepted by qpdf's
/// `QUtil::pdf_time_to_qpdf_time` (`libqpdf/QUtil.cc:960-983`). qpdf checks
/// only this exact regex and does not validate calendar ranges. Keep the raw
/// value so the spelling written to `/Params` remains unchanged.
fn parse_pdf_date_arg(value: &str) -> CliResult<Vec<u8>> {
    let bytes = value.as_bytes();
    let valid_body =
        bytes.len() >= 16 && bytes[..2] == *b"D:" && bytes[2..16].iter().all(u8::is_ascii_digit);
    let valid_suffix = match bytes.len() {
        16 => true,
        17 => bytes[16] == b'Z',
        23 => {
            matches!(bytes[16], b'+' | b'-')
                && bytes[17].is_ascii_digit()
                && bytes[18].is_ascii_digit()
                && bytes[19] == b'\''
                && bytes[20].is_ascii_digit()
                && bytes[21].is_ascii_digit()
                && bytes[22] == b'\''
        }
        _ => false,
    };
    if !valid_body || !valid_suffix {
        return Err(format!("{value} is not a valid PDF timestamp").into());
    }
    Ok(bytes.to_vec())
}

/// 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<T: RawCliArg>(tokens: Vec<T>) -> CliResult<AddAttachmentArgs> {
    let mut iter = tokens.into_iter();
    let file: PathBuf = iter
        .next()
        .ok_or("add attachment: no file specified")?
        .os_string()
        .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 {
        let token_bytes = token.raw_bytes();
        if let Some(v) = token_bytes.strip_prefix(b"--key=") {
            key = Some(v.to_vec());
        } else if let Some(v) = token_bytes.strip_prefix(b"--filename=") {
            filename = Some(v.to_vec());
        } else if let Some(v) = token_bytes.strip_prefix(b"--mimetype=") {
            let bytes = v.to_vec();
            if !bytes.contains(&b'/') {
                return Err("mime type should be specified as type/subtype".into());
            }
            mimetype = Some(bytes);
        } else if let Some(v) = token_bytes.strip_prefix(b"--description=") {
            description = Some(v.to_vec());
        } else if let Some(v) = token_bytes.strip_prefix(b"--creationdate=") {
            let value = std::str::from_utf8(v)
                .map_err(|_| "--add-attachment --creationdate must be valid UTF-8")?;
            creation_date = Some(parse_pdf_date_arg(value)?);
        } else if let Some(v) = token_bytes.strip_prefix(b"--moddate=") {
            let value = std::str::from_utf8(v)
                .map_err(|_| "--add-attachment --moddate must be valid UTF-8")?;
            mod_date = Some(parse_pdf_date_arg(value)?);
        } else if token_bytes == b"--replace" {
            replace = true;
        } else {
            return Err(format!(
                "--add-attachment: unknown sub-flag or unexpected token {:?}",
                token.os_string()
            )
            .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<T: RawCliArg>(tokens: Vec<T>) -> CliResult<CopyAttachmentsArgs> {
    let mut iter = tokens.into_iter();
    let file: PathBuf = iter
        .next()
        .ok_or("--copy-attachments-from: missing FILE argument")?
        .os_string()
        .into();

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

    for token in iter {
        let token_bytes = token.raw_bytes();
        if let Some(v) = token_bytes.strip_prefix(b"--password=") {
            password = v.to_vec();
        } else if let Some(v) = token_bytes.strip_prefix(b"--prefix=") {
            prefix = Some(v.to_vec());
        } else {
            return Err(format!(
                "--copy-attachments-from: unknown sub-flag or unexpected token {:?}",
                token.os_string()
            )
            .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(arg_parser::os_bytes)
}

#[allow(clippy::too_many_arguments)]
fn configure_attachment_job(
    input: Option<&Path>,
    output: Option<&Path>,
    page_ops: &PageOpArgs,
    copy_encryption: Option<(&Path, Vec<u8>)>,
    remove_unreferenced_resources: CliRemoveUnreferencedResources,
    replace_input: bool,
    repair: bool,
    password: &PasswordArgs,
    verbose: bool,
    suppress_warnings: bool,
    remove_restrictions: bool,
    linearize: bool,
    linearize_pass1: Option<&Path>,
    writer_options: &WriterOptions,
    transform_options: InspectionTransformOptions<'_>,
) -> CliResult<QPDFJob> {
    let mut job = new_cli_job(suppress_warnings);
    if page_ops.empty {
        job.config().empty_input()?;
    } else {
        let input = input.ok_or_else(missing_input_usage_error)?;
        job.set_input_file(input.to_path_buf())?;
    }
    if replace_input {
        // Selecting replacement mode without looking at `output` would discard
        // a second positional path and overwrite the input instead, which is
        // the one outcome the user cannot undo. qpdf refuses the combination
        // (`QPDFJob_config.cc:59`), and so do the other replace-input routes
        // in this binary.
        if output.is_some() {
            return Err(UsageError::new(
                "replace-input can't be used since output file has already been given",
            )
            .into());
        }
        job.config().replace_input()?;
    } else {
        job.set_output_file(output.ok_or_else(missing_output_usage_error)?.to_path_buf())?;
    }

    // qpdf runs handlePageSpecs and handleRotations before
    // handleTransformations, which is where addAttachments/copyAttachments
    // live (`libqpdf/QPDFJob.cc:465-474,2243,2246`). Queue both on the job so
    // the attachment routes observe the same ordering the rewrite route does.
    configure_keep_files_open(&mut job, page_ops)?;
    {
        // qpdf calls handlePageSpecs only when page_specs is non-empty
        // (`libqpdf/QPDFJob.cc:466`); an empty list must not initialize the
        // page-selection machinery at all.
        let raw_specs = if page_ops.parsed_page_specs.is_none() {
            Vec::new()
        } else {
            configured_page_specs(page_ops)?
        };
        let mut configuration = job.config();
        // qpdf falls back to --encryption-file-password for a page source that
        // names the copy-encryption file without its own password, so the job
        // needs these fields, not only the already-opened writer source.
        if let Some((path, password)) = copy_encryption {
            // Only the page-spec fallback needs these: the writer
            // configuration this route installs already carries the opened
            // donor, so letting the job reopen it would parse the same file a
            // second time and repeat every repair warning.
            configuration.copy_encryption(path.to_path_buf(), password);
            configuration.clear_copy_encryption_for_writer();
        }
        configuration.remove_unreferenced_resources(remove_unreferenced_resources.into());
        for spec in raw_specs {
            let password = spec.raw_password.or_else(|| {
                spec.password
                    .as_ref()
                    .map(|password| arg_parser::os_bytes(password.as_os_str()))
            });
            configuration.add_page_spec(PathBuf::from(spec.file_token), &spec.range, password)?;
        }
        for parameter in &page_ops.rotate {
            configuration.rotate(arg_parser::os_bytes(parameter.as_os_str()))?;
        }
        // `--collate` is consumed inside handlePageSpecs itself
        // (`libqpdf/QPDFJob.cc:2474-2502`), so it has to reach the job
        // alongside the specs rather than with the later transformations.
        for parameter in &page_ops.collate {
            configuration.collate(parameter.as_bytes())?;
        }
        // qpdf dispatches split-pages after all transformations, including
        // attachment mutation (`QPDFJob.cc:473,483-489`). Keep the output
        // path installed above as the split filename template and let the
        // canonical Job writer create each numbered chunk.
        if let Some(parameter) = page_ops.split_pages.as_deref() {
            configuration.split_pages(parameter.as_bytes())?;
        }
    }

    let input_options = pdf_open_options(repair, password)?;
    job.set_password(input_options.password);
    job.set_password_mode(password.password_mode.into());
    job.set_password_is_hex_key(password.password_is_hex_key);
    job.set_suppress_password_recovery(password.suppress_password_recovery);
    job.set_suppress_recovery(password.recovery.suppress_recovery);
    job.set_ignore_xref_streams(password.recovery.ignore_xref_streams);
    job.set_allow_weak_crypto(writer_options.allow_weak_crypto);
    job.set_allow_insecure(writer_options.allow_insecure);
    job.set_accessibility_disabled(writer_options.accessibility_disabled);
    job.set_progress(writer_options.progress);
    job.set_report_memory_usage(writer_options.report_memory_usage);
    job.set_verbose(verbose);
    job.set_linearization(linearize, linearize_pass1.map(Path::to_path_buf));
    configure_top_level_inspection_transformations(
        &mut job,
        transform_options,
        verbose,
        remove_restrictions,
        false,
    )?;
    Ok(job)
}

fn run_configured_attachment_job(
    mut job: QPDFJob,
    writer_options: &WriterOptions,
    linearize: bool,
    linearize_pass1: Option<&Path>,
) -> CliResult<()> {
    // The page merge inside `create_qpdf` consults the writer configuration
    // (for instance `preserves_unreferenced_objects`), so it has to be
    // installed first -- otherwise the merge runs against the defaults and
    // silently discards orphans despite an explicit `--preserve-unreferenced`.
    job.set_writer_configuration(writer_configuration_unnormalized(
        writer_options,
        linearize,
        linearize_pass1,
    )?);
    let mut pdf = match job.create_qpdf()? {
        Some(pdf) => pdf,
        None => {
            return Err(Box::new(CliExitError {
                code: ExitCode::Errors,
                message: String::new(),
            }))
        }
    };
    match job.write_qpdf(&mut pdf) {
        Ok(()) => finish_job_exit_status(job.get_exit_code()),
        Err(_) => Err(Box::new(CliExitError {
            code: ExitCode::Errors,
            message: String::new(),
        })),
    }
}

/// `--add-attachment FILE [sub-flags] -- output.pdf`
#[allow(clippy::too_many_arguments)]
/// qpdf lets a page spec that names the `--copy-encryption` file fall back to
/// `--encryption-file-password`, so the job needs these fields even when the
/// writer already holds the opened encryption source.
///
/// qpdf keeps the two uses apart: `--decrypt` and `--encrypt` clear only the
/// `copy_encryption` flag that gates the writer
/// (`libqpdf/QPDFJob_config.cc:146-148,155-157,1164-1166`), while
/// `encryption_file` and its password are never cleared and stay available to
/// the page-spec fallback at `QPDFJob.cc:2405-2410`. The attachment routes
/// need only that fallback -- their writer configuration already owns the
/// opened donor -- so the caller disables the job's writer side outright.
fn cli_copy_encryption(args: &Cli) -> Option<(&Path, Vec<u8>)> {
    let path = args.copy_encryption.as_deref()?;
    let password = args
        .raw_encryption_file_password
        .clone()
        .or_else(|| {
            args.encryption_file_password
                .as_ref()
                .map(|password| arg_parser::os_bytes(password))
        })
        .unwrap_or_default();
    Some((path, password))
}

/// Apply qpdf's `--empty` positional remapping to attachment output routes.
/// `Config::emptyInput` consumes the primary-input slot, so with one
/// positional path qpdf treats it as the output; two paths are a usage error.
fn attachment_input_output(
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    page_ops: &PageOpArgs,
    replace_input: bool,
) -> CliResult<(Option<PathBuf>, Option<PathBuf>)> {
    if !page_ops.empty {
        return Ok((input, output));
    }
    if replace_input && (input.is_some() || output.is_some()) {
        return Err(UsageError::new(
            "replace-input can't be used since output file has already been given",
        )
        .into());
    }
    if replace_input {
        return Err(UsageError::new("--replace-input may not be used with --empty").into());
    }
    match (input, output) {
        (Some(output), None) | (None, Some(output)) => Ok((None, Some(output))),
        (Some(_), Some(_)) => Err(UsageError::new(
            "empty input can't be used since input file has already been given",
        )
        .into()),
        (None, None) => Err(missing_output_usage_error().into()),
    }
}

/// Run every top-level attachment mutation through one qpdf-shaped job.
/// qpdf queues remove, add, and copy operations independently and applies them
/// after page/overlay preparation, so the CLI must not select one operation by
/// an `else if` branch or reject the combination at argument parsing time.
fn run_all_attachment_mutations(
    args: &Cli,
    overlay_specs: &[OverlaySpec],
    attachment_segments: &[Vec<Vec<u8>>],
    writer_options: WriterOptions,
    transform_options: InspectionTransformOptions<'_>,
) -> CliResult<()> {
    let (input, output) = attachment_input_output(
        args.input.clone(),
        args.output.clone(),
        &args.page_ops,
        args.replace_input,
    )?;
    if let Some(output) = output.as_deref() {
        let _ = prepare_pdf_standard_output(output)?;
    }

    let copy_encryption_storage =
        cli_copy_encryption(args).map(|(path, password)| (path.to_path_buf(), password));
    let copy_encryption = copy_encryption_storage
        .as_ref()
        .map(|(path, password)| (path.as_path(), password.clone()));
    let mut job = configure_attachment_job(
        input.as_deref(),
        output.as_deref(),
        &args.page_ops,
        copy_encryption,
        args.remove_unreferenced_resources,
        args.replace_input,
        args.repair,
        &args.password,
        args.verbose,
        args.no_warn,
        args.remove_restrictions,
        args.linearize,
        args.linearize_pass1.as_deref(),
        &writer_options,
        transform_options,
    )?;
    {
        let mut configuration = job.config();
        if args.json_input {
            configuration.json_input();
        }
        if let Some(update_from_json) = args.update_from_json.as_ref() {
            configuration.update_from_json(update_from_json.clone());
        }
        if args.coalesce_contents {
            configuration.coalesce_contents();
        }
        if args.remove_page_labels {
            configuration.remove_page_labels();
        }
        if let Some(specs) = args.set_page_labels.as_ref() {
            configuration.set_page_labels(
                specs
                    .iter()
                    .map(|spec| arg_parser::os_bytes(spec.as_os_str())),
            )?;
        }
    }
    configure_cli_overlay_specs(&mut job, overlay_specs)?;
    configure_top_level_attachment_mutations(&mut job, args, attachment_segments)?;
    run_configured_attachment_job(
        job,
        &writer_options,
        args.linearize,
        args.linearize_pass1.as_deref(),
    )
}

#[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(())
        }
    }

    struct FailingPasswordNoticeSink;

    impl Pipeline for FailingPasswordNoticeSink {
        // cov:ignore-start: the injected failure test only reaches write; the
        // logger does not query the sink identifier.
        fn identifier(&self) -> &str {
            "failing password notice sink"
        }
        // cov:ignore-end

        fn write(&mut self, _data: &[u8]) -> PipelineResult<()> {
            Err(flpdf::PipelineError::runtime(
                "password notice sink failure",
            ))
        }

        // cov:ignore-start: the injected failure test aborts during write.
        fn finish(&mut self) -> PipelineResult<()> {
            Ok(())
        }
        // cov:ignore-end
    }

    #[test]
    fn direct_password_notice_logging_propagates_info_sink_failure() {
        let logger = QPDFLogger::create();
        logger.set_info(Some(PipelineHandle::new(FailingPasswordNoticeSink)));

        let error =
            emit_password_write_notices(&logger, "flpdf", [PasswordWriteNotice::Info], true)
                .expect_err("direct CLI password notice logging must be fallible");
        assert_eq!(error.to_string(), "password notice sink failure");
    }

    #[test]
    fn direct_password_notice_logging_propagates_warning_sink_failure() {
        let logger = QPDFLogger::create();
        logger.set_error(Some(PipelineHandle::new(FailingPasswordNoticeSink)));

        let error =
            emit_password_write_notices(&logger, "flpdf", [PasswordWriteNotice::Warning], true)
                .expect_err("direct CLI warning logging must be fallible");
        assert_eq!(error.to_string(), "password notice sink failure");
    }

    #[test]
    fn direct_password_notice_logging_routes_warning_to_error_sink() {
        let chunks = Arc::new(Mutex::new(Vec::<Vec<u8>>::new()));
        let logger = QPDFLogger::create();
        logger.set_error(Some(PipelineHandle::new(ChunkRecordingSink {
            chunks: Arc::clone(&chunks),
        })));

        emit_password_write_notices(&logger, "flpdf", [PasswordWriteNotice::Warning], true)
            .expect("warning notice must be written to the error sink");
        assert_eq!(
            chunks.lock().unwrap().concat(),
            b"flpdf: WARNING: supplied password looks like a Unicode password with characters not allowed in passwords for 40-bit and 128-bit encryption; most readers will not be able to open this file with the supplied password. (Use --password-mode=bytes to suppress this warning and use the password anyway.)\n"
        );
    }

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

    fn os_strs(v: &[&str]) -> Vec<OsString> {
        v.iter().map(|s| OsString::from(*s)).collect()
    }

    fn empty_page_ops() -> PageOpArgs {
        PageOpArgs {
            empty: true,
            ..PageOpArgs::default()
        }
    }

    #[test]
    fn attachment_input_output_maps_empty_positional_to_output() {
        let page_ops = empty_page_ops();
        let output = PathBuf::from("out.pdf");
        assert_eq!(
            attachment_input_output(Some(output.clone()), None, &page_ops, false).unwrap(),
            (None, Some(output.clone()))
        );
        assert_eq!(
            attachment_input_output(None, Some(output.clone()), &page_ops, false).unwrap(),
            (None, Some(output))
        );
    }

    #[test]
    fn attachment_input_output_preserves_nonempty_input_and_output() {
        let page_ops = PageOpArgs::default();
        let input = PathBuf::from("in.pdf");
        let output = PathBuf::from("out.pdf");
        assert_eq!(
            attachment_input_output(Some(input.clone()), Some(output.clone()), &page_ops, false,)
                .unwrap(),
            (Some(input), Some(output))
        );
    }

    #[test]
    fn attachment_input_output_matches_empty_usage_errors() {
        let page_ops = empty_page_ops();
        let error = attachment_input_output(
            Some(PathBuf::from("in.pdf")),
            Some(PathBuf::from("out.pdf")),
            &page_ops,
            false,
        )
        .err()
        .unwrap()
        .to_string();
        assert_eq!(
            error,
            "empty input can't be used since input file has already been given"
        );

        let error = attachment_input_output(Some(PathBuf::from("out.pdf")), None, &page_ops, true)
            .err()
            .unwrap()
            .to_string();
        assert_eq!(
            error,
            "replace-input can't be used since output file has already been given"
        );

        let error = attachment_input_output(None, None, &page_ops, true)
            .err()
            .unwrap()
            .to_string();
        assert_eq!(error, "--replace-input may not be used with --empty");

        let error = attachment_input_output(None, None, &page_ops, false)
            .err()
            .unwrap()
            .to_string();
        assert_eq!(
            error,
            "an output file name is required; use - for standard output"
        );
    }

    #[test]
    fn cli_flatten_modes_use_the_canonical_job_masks() {
        assert_eq!(
            CliFlattenMode::All.flags(),
            FlattenAnnotationsMode::All.qpdf_flags()
        );
        assert_eq!(
            CliFlattenMode::Screen.flags(),
            FlattenAnnotationsMode::Screen.qpdf_flags()
        );
        assert_eq!(
            CliFlattenMode::Print.flags(),
            FlattenAnnotationsMode::Print.qpdf_flags()
        );
    }

    #[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, os_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 preprocess_qpdf_args_keeps_raw_top_level_password_for_clap_override() {
        let directory = tempfile::tempdir().expect("create argument-file directory");
        let path = directory.path().join("args");
        std::fs::write(&path, b"--password=top-\xff\ninput.pdf\n").expect("write argument file");
        let preprocessed = preprocess_qpdf_args(vec![
            OsString::from("flpdf"),
            OsString::from(format!("@{}", path.display())),
        ])
        .expect("qpdf preprocessing should preserve raw password bytes");
        let expected = b"top-\xff".to_vec();
        assert_eq!(
            preprocessed.raw_overrides.password.as_deref(),
            Some(expected.as_slice())
        );

        let mut args = cli_parse_from(preprocessed.residual_args);
        apply_raw_overrides(&mut args, preprocessed.raw_overrides);
        assert_eq!(args.password.password_bytes(), Some(expected));
    }

    #[test]
    fn raw_password_override_reaches_pdf_open_options_without_projection() {
        let mut password = PasswordArgs {
            password: Some(OsString::from("replacement")),
            ..PasswordArgs::default()
        };
        password.raw_password = Some(b"raw-\xff".to_vec());

        let options = pdf_open_options(false, &password).expect("password options should build");
        assert_eq!(options.password, b"raw-\xff");
    }

    #[test]
    fn preprocess_qpdf_args_keeps_raw_encrypt_and_donor_passwords() {
        let directory = tempfile::tempdir().expect("create argument-file directory");
        let encrypt_path = directory.path().join("encrypt-args");
        std::fs::write(
            &encrypt_path,
            b"--encrypt\nuser-\xff\nowner\n128\n--\ninput.pdf\noutput.pdf\n",
        )
        .expect("write encryption argument file");
        let preprocessed = preprocess_qpdf_args(vec![
            OsString::from("flpdf"),
            OsString::from(format!("@{}", encrypt_path.display())),
        ])
        .expect("qpdf encryption segment should be expanded");
        assert_eq!(
            preprocessed.raw_overrides.raw_encrypt.as_ref().unwrap()[0],
            b"user-\xff"
        );
        let parsed_encrypt =
            parse_encrypt_segment(preprocessed.raw_overrides.raw_encrypt.as_ref().unwrap())
                .expect("raw encrypt passwords should reach the byte parser");
        assert_eq!(parsed_encrypt.params.user_password, b"user-\xff");

        let donor_path = directory.path().join("donor-args");
        std::fs::write(
            &donor_path,
            b"--encryption-file-password=donor-\xff\ninput.pdf\noutput.pdf\n",
        )
        .expect("write donor argument file");
        let donor = preprocess_qpdf_args(vec![
            OsString::from("flpdf"),
            OsString::from(format!("@{}", donor_path.display())),
        ])
        .expect("qpdf donor password should be expanded");
        assert_eq!(
            donor.raw_overrides.encryption_file_password.as_deref(),
            Some(b"donor-\xff".as_slice())
        );
    }

    #[test]
    fn preprocess_qpdf_args_rejects_a_second_pages_group_like_qpdf() {
        let error = match preprocess_qpdf_args(strs(&[
            "flpdf", "--pages", "a.pdf", "1", "--", "--pages", "a.pdf", "2", "--", "in.pdf",
            "out.pdf",
        ])) {
            Ok(_) => panic!("qpdf rejects a second --pages group"),
            Err(error) => error,
        };
        let usage = find_usage_error(error.as_ref()).expect("a qpdf usage error");
        assert_eq!(usage.to_string(), "--pages may only be specified one time");
    }

    #[test]
    fn preprocess_qpdf_args_preserves_every_copy_attachments_group() {
        let preprocessed = preprocess_qpdf_args(strs(&[
            "flpdf",
            "--copy-attachments-from",
            "don0.pdf",
            "--",
            "--copy-attachments-from",
            "don1.pdf",
            "--",
            "in.pdf",
            "out.pdf",
        ]))
        .expect("qpdf accepts repeated donor groups");
        assert_eq!(
            preprocessed.raw_overrides.raw_copy_attachments_from,
            Some(vec![vec![b"don0.pdf".to_vec()], vec![b"don1.pdf".to_vec()],])
        );
    }

    #[test]
    fn preprocess_qpdf_args_preserves_every_add_attachment_group_in_raw_residual_args() {
        // The `--job-json-file` route (`preflight_qpdf_cli_events`) parses
        // `raw_residual_args` through the qpdf-compatible argv parser
        // directly, unlike every other route, which reads attachment data
        // from `attachment_segments` instead. Every `--add-attachment` group
        // must therefore survive in `raw_residual_args`, the same as every
        // `--copy-attachments-from` group already does.
        let preprocessed = preprocess_qpdf_args(strs(&[
            "flpdf",
            "--job-json-file=job.json",
            "--add-attachment",
            "a1.txt",
            "--",
            "--add-attachment",
            "a2.txt",
            "--",
        ]))
        .expect("qpdf accepts repeated add-attachment groups");
        let count = preprocessed
            .raw_residual_args
            .iter()
            .filter(|argument| argument.as_bytes() == b"--add-attachment")
            .count();
        assert_eq!(
            count, 2,
            "raw_residual_args must retain every --add-attachment group"
        );
    }

    #[test]
    fn preprocess_qpdf_args_retains_overlay_group_in_raw_residual_args_under_job_json() {
        // Unlike every other segment kind, `--overlay`/`--underlay` are
        // stripped from `raw_residual_args` outside job-json mode
        // (flpdf-cli's own native overlay application reads `overlay_specs`
        // from `SegmentHandler`, not from the reconstructed residual
        // tokens), because flpdf-cli's own subcommand routing -- not
        // qpdf -- rejects `--overlay`/`--underlay` on subcommands other than
        // `rewrite`, and clap must not see the raw token there. Under
        // `--job-json-file`, though, `preflight_qpdf_cli_events` parses
        // `raw_residual_args` through the qpdf-compatible unified argv
        // parser directly, so a group left out here is silently dropped
        // instead of applied (this was flpdf-g9uy9).
        let preprocessed = preprocess_qpdf_args(strs(&[
            "flpdf",
            "--job-json-file=job.json",
            "--overlay",
            "src.pdf",
            "--",
            "in.pdf",
            "out.pdf",
        ]))
        .expect("qpdf accepts an overlay group under --job-json-file");
        let count = preprocessed
            .raw_residual_args
            .iter()
            .filter(|argument| argument.as_bytes() == b"--overlay")
            .count();
        assert_eq!(
            count, 1,
            "raw_residual_args must retain the --overlay group under --job-json-file"
        );
    }

    #[test]
    fn preprocess_qpdf_args_retains_overlay_group_under_the_single_dash_job_json_spelling() {
        // `QPDFArgParser::parseArgs` strips one leading `-` and then one
        // more if it is there (`libqpdf/QPDFArgParser.cc:460-476`), so
        // `-job-json-file=` names the same option as `--job-json-file=` and
        // real qpdf applies the overlay under both. A scan keyed to the
        // double-dash spelling alone left the single-dash form dropping the
        // group again, silently.
        for spelling in ["--job-json-file=job.json", "-job-json-file=job.json"] {
            let preprocessed = preprocess_qpdf_args(strs(&[
                "flpdf",
                spelling,
                "--overlay",
                "src.pdf",
                "--",
                "in.pdf",
                "out.pdf",
            ]))
            .expect("qpdf accepts an overlay group under either spelling");
            let count = preprocessed
                .raw_residual_args
                .iter()
                .filter(|argument| argument.as_bytes() == b"--overlay")
                .count();
            assert_eq!(
                count, 1,
                "raw_residual_args must retain the --overlay group under `{spelling}`"
            );
        }
    }

    #[test]
    fn preprocess_qpdf_args_drops_overlay_group_from_raw_residual_args_without_job_json() {
        // Outside job-json mode the native route applies overlay via
        // `overlay_specs`, and retaining the raw tokens here would leak an
        // `--overlay` token into clap's view of a subcommand that never
        // declared it (see the job-json variant above).
        let preprocessed = preprocess_qpdf_args(strs(&[
            "flpdf",
            "--overlay",
            "src.pdf",
            "--",
            "in.pdf",
            "out.pdf",
        ]))
        .expect("qpdf accepts a bare overlay group");
        let count = preprocessed
            .raw_residual_args
            .iter()
            .filter(|argument| argument.as_bytes() == b"--overlay")
            .count();
        assert_eq!(
            count, 0,
            "raw_residual_args must not retain --overlay outside job-json mode"
        );
    }

    #[test]
    fn preprocess_qpdf_args_does_not_promote_segment_password_to_top_level() {
        let directory = tempfile::tempdir().expect("create argument-file directory");
        let path = directory.path().join("pages-args");
        std::fs::write(
            &path,
            b"--pages\nsource.pdf\n--password=page-\xff\n--\ninput.pdf\noutput.pdf\n",
        )
        .expect("write page argument file");

        let preprocessed = preprocess_qpdf_args(vec![
            OsString::from("flpdf"),
            OsString::from(format!("@{}", path.display())),
        ])
        .expect("qpdf page segment should be expanded");
        assert!(preprocessed.raw_overrides.password.is_none());
        assert_eq!(
            preprocessed.raw_overrides.raw_pages.as_ref().unwrap()[1],
            b"--password=page-\xff"
        );
    }

    #[test]
    fn raw_passwords_reach_pages_overlay_and_copy_segment_parsers() {
        let page_tokens = vec![b"source.pdf".to_vec(), b"--password=page-\xff".to_vec()];
        let pages = parse_pages_segment(&page_tokens).expect("page segment should parse");
        assert_eq!(pages[0].raw_password, Some(b"page-\xff".to_vec()));

        let overlay = parse_overlay_segment(
            OverlayKind::Overlay,
            &[b"source.pdf".to_vec(), b"--password=overlay-\xff".to_vec()],
        )
        .expect("overlay segment should parse");
        assert_eq!(overlay.raw_password, Some(b"overlay-\xff".to_vec()));

        let copy = parse_copy_attachments_segment(vec![
            b"source.pdf".to_vec(),
            b"--password=copy-\xff".to_vec(),
        ])
        .expect("copy-attachments segment should parse");
        assert_eq!(copy.password, b"copy-\xff".to_vec());
    }

    #[test]
    fn pages_empty_range_can_be_replaced_before_a_nonempty_range() {
        let pages = parse_pages_segment(&[
            b"source.pdf".to_vec(),
            b"--range=".to_vec(),
            b"--range=1".to_vec(),
        ])
        .expect("qpdf permits an empty range sentinel before a replacement");
        assert_eq!(pages[0].range, "1");
    }

    #[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"
        );
    }

    /// The four kinds this helper previously fell through on. It now shares
    /// `qpdf_open_io_error_message`'s table, which renders qpdf's portable
    /// `strerror` wording on every host rather than Rust's native text.
    /// A synthetic error carries no `errno`, so this exercises the table
    /// itself rather than the raw-code path a real syscall failure takes.
    #[test]
    fn json_input_open_error_uses_qpdf_wording_for_every_kind() {
        for (kind, expected) in [
            (std::io::ErrorKind::PermissionDenied, "Permission denied"),
            (std::io::ErrorKind::AlreadyExists, "File exists"),
            (std::io::ErrorKind::InvalidInput, "Invalid argument"),
            (std::io::ErrorKind::NotADirectory, "Not a directory"),
        ] {
            let error =
                qpdf_json_input_open_error(Path::new("in.json"), std::io::Error::from(kind));
            assert_eq!(
                error.to_string(),
                format!("open in.json: {expected}"),
                "{kind:?}"
            );
        }
    }

    #[test]
    fn open_error_with_file_keeps_non_io_errors_outside_open_prefix() {
        let error = open_error_with_file(
            Path::new("bad.pdf"),
            flpdf::Error::parse(0, "malformed PDF").into(),
        );

        assert_eq!(
            error.to_string(),
            "bad.pdf: parse error at byte 0: malformed PDF"
        );
    }

    /// `ErrorKind` is coarser than `errno`: `EPERM` and `EACCES` both map to
    /// `PermissionDenied`, but `strerror` prints "Operation not permitted"
    /// for the first and "Permission denied" for the second, and qpdf prints
    /// whichever `strerror(errno)` returns
    /// (`QPDFSystemError::createWhat`, `QPDFSystemError.cc:13-29`). A real
    /// syscall failure carries the raw code, so it must not be flattened
    /// through the `ErrorKind` table.
    #[cfg(unix)]
    #[test]
    fn qpdf_open_io_error_keeps_errno_wording_error_kind_cannot_distinguish() {
        for (code, expected) in [(1, "Operation not permitted"), (13, "Permission denied")] {
            let error = std::io::Error::from_raw_os_error(code);
            assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
            assert_eq!(qpdf_open_io_error_message(&error), expected, "errno {code}");
        }
    }

    #[test]
    fn qpdf_open_io_error_uses_portable_permission_text() {
        let error = std::io::Error::from(std::io::ErrorKind::PermissionDenied);

        assert_eq!(qpdf_open_io_error_message(&error), "Permission denied");
        let error = std::io::Error::from(std::io::ErrorKind::AlreadyExists);
        assert_eq!(qpdf_open_io_error_message(&error), "File exists");
        let error = std::io::Error::other("native fallback");
        assert_eq!(qpdf_open_io_error_message(&error), "native fallback");
    }

    #[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"
        );
    }

    #[cfg(unix)]
    #[test]
    fn attachment_segment_paths_preserve_non_utf8_bytes() {
        use std::os::unix::ffi::{OsStrExt, OsStringExt};

        let add =
            parse_add_attachment_segment(vec![OsString::from_vec(b"payload-\xff.bin".to_vec())])
                .expect("raw attachment path should parse");
        assert_eq!(add.file.as_os_str().as_bytes(), b"payload-\xff.bin");

        let copy =
            parse_copy_attachments_segment(vec![OsString::from_vec(b"source-\xff.pdf".to_vec())])
                .expect("raw copy source path should parse");
        assert_eq!(copy.file.as_os_str().as_bytes(), b"source-\xff.pdf");
    }

    #[cfg(unix)]
    #[test]
    fn overlay_file_option_preserves_non_utf8_bytes() {
        use std::os::unix::ffi::{OsStrExt, OsStringExt};

        let token = OsString::from_vec(b"--file=overlay-\xff.pdf".to_vec());
        let spec = parse_overlay_segment(OverlayKind::Overlay, &[token])
            .expect("raw overlay path should parse");
        assert_eq!(spec.file.as_bytes(), b"overlay-\xff.pdf");
    }

    #[test]
    fn cli_command_builds_on_a_small_stack() {
        let command = std::thread::Builder::new()
            .name("small-stack-cli-command".to_owned())
            .stack_size(512 * 1024)
            .spawn(cli_command)
            .expect("small-stack thread should start")
            .join()
            .expect("Cli::command must not overflow a small stack");

        assert_eq!(command.get_name(), "flpdf");
    }

    #[test]
    fn every_migrated_inspection_flag_requests_the_combined_route_on_its_own() {
        // qpdf uses one `run()` call sequence for every flag combination
        // (`qpdf/qpdf.cc:26-44`), so each of these flags must reach the
        // canonical job route even when it is the only one given. The
        // end-to-end oracle tests compare output; this pins the predicate
        // itself, which is what decides the route.
        for flag in [
            "--check",
            "--show-npages",
            "--show-pages",
            "--show-xref",
            "--check-linearization",
            "--show-linearization",
            "--show-encryption",
            "--list-attachments",
            "--show-attachment=attachment.txt",
            "--show-object=1",
        ] {
            let args = cli_parse_from(vec![
                OsString::from("flpdf"),
                OsString::from(flag),
                OsString::from("in.pdf"),
            ]);
            assert!(
                top_level_inspection_combination_requested(&args, false, false),
                "{flag} alone must route through the combined job lifecycle"
            );
        }
    }

    #[test]
    fn a_bare_invocation_does_not_request_the_combined_route() {
        let args = cli_parse_from(vec![
            OsString::from("flpdf"),
            OsString::from("in.pdf"),
            OsString::from("out.pdf"),
        ]);
        assert!(!top_level_inspection_combination_requested(
            &args, false, false
        ));
    }

    #[test]
    fn cli_parse_from_builds_on_a_small_stack() {
        let args = std::thread::Builder::new()
            .name("small-stack-cli-parse".to_owned())
            .stack_size(512 * 1024)
            .spawn(|| cli_parse_from(vec![OsString::from("flpdf")]))
            .expect("small-stack thread should start")
            .join()
            .expect("Cli::parse_from must not overflow a small stack");

        assert!(args.command.is_none());
    }

    #[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(), 3);
        assert_eq!(chunks.concat(), b"page 1: 3 0 R\n  content:\n    7 0 R\n");
    }

    #[test]
    fn update_input_version_floor_clamps_an_overflow_extension_level() {
        // Measured with qpdf 11.9.0's `getVersionAsPDFVersion` (which
        // `QPDFJob::doProcessOnce` feeds into `max_input_version`,
        // `QPDFJob.cc:1712-1714`): a huge `/ExtensionLevel` is clamped to
        // `i32::MAX` and warns via `getExtensionLevel`
        // (`libqpdf/QPDF.cc:2328-2346`). The raw `adobe_extension_level`
        // accessor this replaced kept the full 64-bit value and never
        // warned, so the accumulated floor would silently carry an
        // extension level qpdf itself could never produce.
        let mut body = b"%PDF-1.7\n".to_vec();
        let mut offsets = Vec::new();
        offsets.push(body.len());
        body.extend_from_slice(
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Extensions << /ADBE << /ExtensionLevel 5000000000 >> >> >>\nendobj\n",
        );
        offsets.push(body.len());
        body.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Count 0 /Kids [] >>\nendobj\n");
        let xref_offset = body.len();
        let n = offsets.len() + 1;
        let mut xref = format!("xref\n0 {n}\n0000000000 65535 f \n").into_bytes();
        for offset in &offsets {
            xref.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        body.extend_from_slice(&xref);
        body.extend_from_slice(
            format!("trailer\n<< /Size {n} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
                .as_bytes(),
        );
        let mut pdf = Pdf::open_mem_owned(body).expect("well-formed overflow fixture must parse");

        let mut floor = None;
        update_input_version_floor(&mut floor, &mut pdf).expect("floor update should succeed");

        assert_eq!(floor, Some(PdfVersion::new(1, 7, i64::from(i32::MAX))));
        assert!(pdf.repair_diagnostics().entries().iter().any(|entry| {
            String::from_utf8_lossy(entry.what_bytes())
                .contains("requested value of integer is too big; returning INT_MAX")
        }));
    }

    #[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().into()),
                ..PasswordArgs::default()
            },
            false,
        );

        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(), false) 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"));
    }

    // --- 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,
                raw_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, &[] as &[String])
            .unwrap_err()
            .to_string();
        assert_eq!(err, "overlay file not specified");
    }

    #[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_eq!(err, "overlay file not specified");
    }

    #[test]
    fn overlay_duplicate_file_bare_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["a.pdf", "b.pdf"]))
            .unwrap_err()
            .to_string();
        assert_eq!(err, "overlay file already specified");
    }

    #[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_eq!(err, "overlay file already specified");
    }

    #[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_eq!(err, "overlay file already specified");
    }

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

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

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

    #[test]
    fn overlay_unknown_flag_error() {
        let err = parse_overlay_segment(OverlayKind::Overlay, &strs(&["src.pdf", "--bogus=x"]))
            .unwrap_err()
            .to_string();
        assert_eq!(
            err,
            "unrecognized argument --bogus=x (underlay/overlay options must be terminated with --)"
        );
    }

    #[test]
    fn underlay_unknown_flag_error_prefix() {
        let err = parse_overlay_segment(OverlayKind::Underlay, &strs(&["src.pdf", "--unknown"]))
            .unwrap_err()
            .to_string();
        assert_eq!(
            err,
            "unrecognized argument --unknown (underlay/overlay options must be terminated with --)"
        );
    }

    #[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_repeated_to_before_file_uses_last_value() {
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["--to=1", "src.pdf", "--to=2"]),
        )
        .unwrap();
        assert_eq!(spec.to.as_deref(), Some("2"));
    }

    #[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_repeated_password_uses_last_value() {
        let spec = parse_overlay_segment(
            OverlayKind::Overlay,
            &strs(&["src.pdf", "--password=a", "--password=b"]),
        )
        .unwrap();
        assert_eq!(spec.password.as_deref(), Some(OsStr::new("b")));
    }

    // --- 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",
        ]);
        assert_eq!(normalize_qpdf_bare_equals(args.clone()), args);
    }

    #[test]
    fn newline_before_endstream_discards_every_equals_value_spelling() {
        // `QPDFArgParser::addBare` leaves `choices` empty, and the dispatch
        // loop only rejects a supplied parameter when `choices` is non-empty
        // (`QPDFArgParser.cc:99-103,505-534`), so qpdf discards the suffix for
        // every spelling alike -- `never` included, which is why flpdf keeps
        // no `=never` value of its own.
        for value in ["y", "n", "never", "garbage", ""] {
            let args = strs(&["flpdf", &format!("--newline-before-endstream={value}")]);

            assert_eq!(
                normalize_qpdf_bare_equals(args),
                strs(&["flpdf", "--newline-before-endstream"]),
                "`=({value})` should normalize to the bare flag"
            );
        }
    }

    #[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_survives_top_level_section_reset() {
        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_resets_to_main_parser() {
        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, os_strs(&["flpdf"]));
        assert_eq!(parsed.named_segments[0].option, "overlay");
        assert_eq!(
            parsed.named_segments[0].tokens,
            os_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 auxiliary_named_segment_classifier_covers_every_segment_kind() {
        let openers: &[&[u8]] = &[
            b"--encrypt",
            b"--pages",
            b"--add-attachment",
            b"--copy-attachments-from",
            b"--overlay",
            b"--underlay",
            b"--set-page-labels",
        ];
        for opener in openers {
            assert!(
                is_named_segment_option(opener),
                "every SegmentKind opener must be recognized by auxiliary scans"
            );
        }
        assert!(!is_named_segment_option(b"--ordinary-option"));
        assert!(!is_named_segment_option(b"--pages=value"));
    }

    #[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, os_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"]))
            .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"]))
            .unwrap()
            .params;
        assert_eq!(params.user_password, b"-");
        assert_eq!(params.owner_password, b"-");
    }

    #[test]
    fn encrypt_parser_accepts_dashed_passwords_and_bits_before_the_terminator() {
        let params = parse_encrypt_segment(&strs(&[
            "--user-password=u",
            "--bits=256",
            "--allow-insecure",
        ]))
        .expect("qpdf dashed encryption form")
        .params;
        assert_eq!(params.method, EncryptMethod::V5R6Aes256);
        assert_eq!(params.user_password, b"u");
        assert!(params.owner_password.is_empty());
    }

    #[test]
    fn encrypt_parser_rejects_mixed_positional_and_dashed_passwords() {
        let error = parse_encrypt_segment(&strs(&["user", "--owner-password=owner", "128"]))
            .expect_err("mixed encryption form");
        assert!(error
            .to_string()
            .contains("positional and dashed encryption arguments may not be mixed"));
    }

    #[test]
    fn encrypt_parser_keeps_r2_permissions_separate_from_r3_permissions() {
        let parsed = parse_encrypt_segment(&strs(&[
            "user",
            "owner",
            "40",
            "-print=n",
            "-modify=y",
            "-extract=n",
            "-annotate=y",
        ]))
        .expect("R=2 encryption options");
        assert_eq!(parsed.params.method, EncryptMethod::V1Rc440);
        assert!(!parsed.params.r2_permissions.print);
        assert!(parsed.params.r2_permissions.modify);
        assert!(!parsed.params.r2_permissions.extract);
        assert!(parsed.params.r2_permissions.annotate);
        assert_eq!(parsed.params.permissions, PermissionsConfig::default());
    }

    #[test]
    fn encrypt_parser_reports_ignored_accessibility_for_modern_revisions() {
        let parsed = parse_encrypt_segment(&strs(&[
            "user",
            "owner",
            "128",
            "--force-V4",
            "--accessibility=n",
        ]))
        .expect("modern encryption options");
        assert!(parsed.accessibility_warning);
        assert_eq!(parsed.params.method, EncryptMethod::V4Rc4128);
        assert!(parsed.params.permissions.accessibility);
    }

    #[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();

        // Every `--add-attachment` group is retained in `residual_args`, not
        // just the first: the `--job-json-file` route
        // (`preflight_qpdf_cli_events`) parses `raw_residual_args` through
        // the qpdf-compatible argv parser directly and needs every group,
        // matching `--copy-attachments-from`'s existing (never-truncated)
        // retention.
        assert_eq!(
            residual,
            strs(&[
                "flpdf",
                "in.pdf",
                "--add-attachment",
                "one.txt",
                "--key=one",
                "--",
                "--add-attachment",
                "two.txt",
                "--key=two",
                "--",
                "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(), "missing -- at end of attachment options");
    }

    #[test]
    fn extract_attachment_groups_discards_the_equals_value_like_qpdfs_bare_option() {
        // qpdf's `--add-attachment` is a bare option (auto_job_init.hh: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(OsStr::new("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 put the trailing top-level flag in the wrong
        // parser group and make clap report it as an unknown option.
        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 reports the active table name.
        let argv = strs(&["--overlay", "over.pdf", "out.pdf"]);
        let err = extract_overlay_groups(argv).unwrap_err().to_string();
        assert_eq!(err, "missing -- at end of underlay/overlay options");
    }

    #[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_eq!(err, "overlay file not specified");
    }

    #[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_eq!(err, "underlay file not specified");
    }

    #[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(OsStr::new("--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_eq!(error, "missing -- at end of encryption options");
    }

    #[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").into(),
            password: None,
            raw_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").into(),
            password: None,
            raw_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,
            raw_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().into(),
                password: None,
                raw_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().into(),
                password: None,
                raw_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().into(),
                password: None,
                raw_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").into(),
            password: Some("user-v2".into()),
            raw_password: None,
            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_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.
        // `run_combined_top_level_inspection` preserves this ordering: it
        // calls `configure_top_level_inspection_job` (which parses
        // `--show-object` eagerly through `configuration.show_object`)
        // before it checks for a missing input file.
        let args = cli_parse_from(vec![
            OsString::from("flpdf"),
            OsString::from("--show-object=2147483648"),
        ]);
        assert!(args.input.is_none());
        let mut job = new_cli_job(false);
        let error = configure_top_level_inspection_job(&mut job, &args)
            .expect_err("overflow selector with no input file");
        assert!(
            find_usage_error(error.as_ref()).is_some(),
            "got {error} instead of a UsageError -- the missing-input-file check must not \
             run before selector parsing"
        );
    }
}