oxideav-cli-convert 0.0.8

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

use crate::op::{
    AlphaOp, CameraSpec, ConvertPlan, Dither, GltfFormatChoice, LightSpec, Mesh3DOptions,
    Mesh3DRenderMode, Op, PageAtom, PageSelector, PrintfTemplate, ProjectionMode, ResizeMode,
    StlFormatChoice,
};
use oxideav_core::Error;

/// Every flag the parser below recognises, stored without the leading
/// dash(es). Single-dash IM-style ops AND the double-dash GNU-style
/// modes (`--probe`, `--json`, `--watch`) both land in here; the
/// caller reattaches whichever lead the user typed when rendering a
/// suggestion. Kept as a flat sorted slice rather than a `HashSet`
/// because the list is small (~55 entries), the lookup is a single
/// scan inside the Levenshtein helper, and a sorted slice is trivial
/// to keep aligned with the `match` arms below.
///
/// MUST stay in sync with the `match flag.as_str()` arms in [`parse`].
/// A flag missing from this table downgrades the suggestion quality
/// (the user mistypes a real flag and gets no hint) but doesn't break
/// parsing, so the worst case is a quiet UX regression — easy to spot
/// in review.
const KNOWN_FLAG_NAMES: &[&str] = &[
    "aa",
    "alpha",
    "auto-gamma",
    "background",
    "bg",
    "blur",
    "brightness-contrast",
    "camera",
    "colorize",
    "colors",
    "colorspace",
    "contrast",
    "crop",
    "define",
    "density",
    "depth",
    "dither",
    "edge",
    "equalize",
    "extent",
    "flip",
    "flop",
    "format",
    "fov",
    "fuzz",
    "gamma",
    "gltf-format",
    "help",
    "json",
    "level",
    "light",
    "modulate",
    "monochrome",
    "negate",
    "normalize",
    "opt",
    "ping",
    "posterize",
    "probe",
    "projection",
    "quality",
    "render",
    "resize",
    "roll",
    "rotate",
    "sepia",
    "sharpen",
    "solarize",
    "stl-format",
    "strip",
    "thumbnail",
    "threads",
    "threshold",
    "trim",
    "unsharp",
    "vignette",
    "watch",
];

/// Parse the slice that comes after `oxideav convert`.
///
/// Returns a `ConvertPlan` on success or an `Error::Invalid` /
/// `Error::Unsupported` tagged with the specific `-flag` so callers
/// can print the offending argument.
pub fn parse(args: &[String]) -> Result<ConvertPlan, Error> {
    if args.is_empty() {
        return Err(Error::invalid(
            "convert: no input file given (usage: convert [-op VALUE]... INPUT [-op VALUE]... OUTPUT)",
        ));
    }

    // ImageMagick allows ops to appear before AND after the input
    // (e.g. `convert -density 300 in.pdf -resize 800x600 out.png`).
    // Walk every arg in order: anything starting with `-` is a flag
    // (which may consume the following arg as its value); everything
    // else is a positional. After parsing, the FIRST positional is the
    // input and the LAST is the output. Multi-input is a documented
    // round-2 follow-up; we error if more than two positionals are
    // present.
    let mut ops: Vec<Op> = Vec::new();
    let mut positionals: Vec<String> = Vec::new();
    let mut pending_dither = Dither::None;
    let mut help = false;
    let mut ping = false;
    let mut probe = false;
    let mut probe_json = false;
    let mut probe_watch = false;
    let mut mesh3d_options = Mesh3DOptions::default();
    // Track the most recent `-background` colour in source order so
    // `-extent` (which paints padding pixels with the active background)
    // captures the correct value at parse time. Defaults to IM's opaque
    // white when the user didn't set `-background` before `-extent`.
    let mut current_bg: [u8; 4] = [255, 255, 255, 255];
    // Track the most recent `-fuzz N[%]` value in source order so a
    // following `-trim` reads this tolerance. IM treats `-fuzz` as a
    // state setting that survives until the next `-fuzz`; pinning the
    // value onto each emitted `Op::Trim` at parse time preserves the
    // source-order semantics for the plan walker and side-channel
    // (a later `-fuzz` does NOT retroactively rewrite an earlier
    // `-trim`'s tolerance).
    let mut current_fuzz: u8 = 0;

    // `--` end-of-flags marker: everything after it is a positional,
    // even when it starts with `-`. Lets users name files like
    // `-weird.png` (`convert -- -weird.png out.jpg`).
    let mut no_more_flags = false;

    let mut i = 0;
    while i < args.len() {
        let flag = &args[i];
        let val = |k: usize| -> Result<&str, Error> {
            args.get(k)
                .map(|s| s.as_str())
                .ok_or_else(|| Error::invalid(format!("convert: {flag}: missing value")))
        };

        // Non-flag → positional. An empty argument can only be a
        // mistake (usually an unquoted empty shell variable) — reject
        // it here with a convert-speak message instead of letting an
        // unopenable "" filename fail somewhere deep in a runner.
        if no_more_flags || !flag.starts_with('-') {
            if flag.is_empty() {
                return Err(Error::invalid(
                    "convert: empty argument (positional filenames must be non-empty; check for an unset shell variable)",
                ));
            }
            positionals.push(flag.clone());
            i += 1;
            continue;
        }

        match flag.as_str() {
            // GNU-style end-of-flags marker.
            "--" => {
                no_more_flags = true;
                i += 1;
            }
            "-resize" => {
                let v = val(i + 1)?;
                let (mode, core) = ResizeMode::split_suffix(v);
                let (w, h) = parse_resize_geometry(core, mode)
                    .map_err(|e| Error::invalid(format!("convert: -resize: {e}")))?;
                ops.push(Op::Resize {
                    width: w,
                    height: h,
                    mode,
                });
                i += 2;
            }
            // `-thumbnail` is IM's "make a small representative image"
            // convenience flag. Same geometry grammar as `-resize`;
            // semantics differ in that IM also strips metadata and
            // (for JPEG inputs) honours EXIF orientation. We unroll it
            // into [`Op::Thumbnail`] which the runners expand to
            // `Resize { mode } + Strip` (auto-orient is documented as
            // a follow-up — needs an EXIF reader on the source side).
            "-thumbnail" => {
                let v = val(i + 1)?;
                let (mode, core) = ResizeMode::split_suffix(v);
                let (w, h) = parse_resize_geometry(core, mode)
                    .map_err(|e| Error::invalid(format!("convert: -thumbnail: {e}")))?;
                ops.push(Op::Thumbnail {
                    width: w,
                    height: h,
                    mode,
                });
                i += 2;
            }
            // `-define KEY[=VALUE]` — opaque codec-specific tunable.
            // Forwarded literally to the sink encoder; the encoder
            // ignores keys it doesn't recognise. IM's grammar uses `:`
            // inside the key as a namespace separator (e.g.
            // `jpeg:dct-method=float`); we don't parse that — the key
            // is preserved verbatim.
            "-define" => {
                let v = val(i + 1)?;
                let (key, value) = match v.split_once('=') {
                    Some((k, val)) => (k.to_string(), Some(val.to_string())),
                    None => (v.to_string(), None),
                };
                if key.is_empty() {
                    return Err(Error::invalid(format!(
                        "convert: -define: '{v}' has an empty KEY (expected KEY[=VALUE])"
                    )));
                }
                ops.push(Op::Define { key, value });
                i += 2;
            }
            "-blur" => {
                let v = val(i + 1)?;
                let (radius, sigma) =
                    parse_blur(v).map_err(|e| Error::invalid(format!("convert: -blur: {e}")))?;
                ops.push(Op::Blur { radius, sigma });
                i += 2;
            }
            "-edge" => {
                let v = val(i + 1)?;
                let r: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -edge: '{v}' is not a non-negative integer"
                    ))
                })?;
                ops.push(Op::Edge { radius: r });
                i += 2;
            }
            "-colors" => {
                let v = val(i + 1)?;
                let n: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -colors: '{v}' is not a non-negative integer"
                    ))
                })?;
                if !(2..=256).contains(&n) {
                    return Err(Error::invalid(format!(
                        "convert: -colors {n} out of range (2..=256)"
                    )));
                }
                ops.push(Op::Colors {
                    count: n,
                    dither: pending_dither,
                });
                i += 2;
            }
            "-dither" => {
                let v = val(i + 1)?;
                pending_dither = Dither::parse(v).map_err(Error::invalid)?;
                i += 2;
            }
            // `-monochrome` (no value) — IM's "make me a 1-bit dithered
            // black-and-white image" convenience flag. Equivalent to the
            // chain `-colorspace gray -colors 2 -dither floyd_steinberg`,
            // so we lower it to those three primitive ops here rather
            // than carving out a dedicated runner path. The order
            // matters: grayscale-first means the palette-builder sees
            // luminance values rather than colour, so the 2-entry
            // palette lands on black + white instead of two arbitrary
            // colour samples. Floyd-Steinberg is IM's documented
            // default for the 1-bit reduction (newer IM exposes
            // `-define dither:` to override; we don't yet plumb that).
            // A user who wants the un-dithered "Atkinson cut" behaviour
            // can still write the chain by hand with `-dither none`.
            "-monochrome" => {
                ops.push(Op::Colorspace("gray".to_string()));
                ops.push(Op::Colors {
                    count: 2,
                    dither: Dither::FloydSteinberg,
                });
                i += 1;
            }
            "-format" => {
                let v = val(i + 1)?;
                ops.push(Op::Format(v.to_string()));
                i += 2;
            }
            // `-depth N` — IM's per-channel output depth. Only the
            // two storage depths still-image encoders carry are
            // meaningful; anything else is a typo worth surfacing.
            "-depth" => {
                let v = val(i + 1)?;
                let d: u8 = match v.parse() {
                    Ok(d @ (8 | 16)) => d,
                    _ => {
                        return Err(Error::invalid(format!(
                            "convert: -depth: '{v}' must be 8 or 16"
                        )))
                    }
                };
                ops.push(Op::Depth(d));
                i += 2;
            }
            // `--opt KEY=VALUE` — encoder option for still-image
            // sinks. GNU-style double dash: it is not an IM op. The
            // key is validated against the target encoder's schema at
            // plan time (the parser does not know the output codec).
            "--opt" | "-opt" => {
                let v = val(i + 1)?;
                let (key, value) = v.split_once('=').ok_or_else(|| {
                    Error::invalid(format!("convert: --opt: '{v}' is not KEY=VALUE"))
                })?;
                if key.is_empty() {
                    return Err(Error::invalid(format!(
                        "convert: --opt: '{v}' has an empty KEY (expected KEY=VALUE)"
                    )));
                }
                ops.push(Op::EncoderOpt {
                    key: key.to_string(),
                    value: value.to_string(),
                });
                i += 2;
            }
            // `-threads N` — pipeline-route thread budget (0 = auto).
            "-threads" => {
                let v = val(i + 1)?;
                let n: usize = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -threads: '{v}' is not a non-negative integer (0 = auto)"
                    ))
                })?;
                ops.push(Op::Threads(n));
                i += 2;
            }
            "-quality" => {
                let v = val(i + 1)?;
                let q: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -quality: '{v}' is not a non-negative integer"
                    ))
                })?;
                // IM-conventional cap: every lossy codec convert
                // forwards `-quality` to (JPEG, WebP, AVIF, …) expects
                // `0..=100`. Without this guard `-quality 9999` and
                // `-quality 150` silently propagate and the encoder
                // drops the key — looking to the user like the flag
                // was honoured. Reject up-front with a clear range so
                // the typo (`-quality 1000` instead of `-quality 100`)
                // surfaces at parse time. The 0/100 endpoints stay
                // accepted: 0 is "smallest acceptable" on JPEG and
                // 100 is "highest". Out-of-band values were never
                // useful — codecs ignore them.
                if q > 100 {
                    return Err(Error::invalid(format!(
                        "convert: -quality: {q} out of range (must be in 0..=100; common values: 75 default, 85 web, 95 archival)"
                    )));
                }
                ops.push(Op::Quality(q));
                i += 2;
            }
            "-strip" => {
                ops.push(Op::Strip);
                i += 1;
            }
            "-ping" => {
                ping = true;
                i += 1;
            }
            // `--help` (GNU-style) and `-help` (IM-style) both print
            // the usage synopsis. Recognised anywhere on the line and
            // outranks everything else — positional validation is
            // skipped so a bare `convert --help` works.
            "--help" | "-help" => {
                help = true;
                i += 1;
            }
            // `--probe` is GNU-style double-dash because it's a
            // session-scope mode switch (no value, no per-input
            // semantics) — same shape as `--help` / `--version` would
            // have if the convert verb owned them. Single-dash `-probe`
            // is reserved as a future IM-style probe-OP that might
            // legitimately want an argument.
            "--probe" => {
                probe = true;
                i += 1;
            }
            // `--json` selects a machine-readable output flavour for
            // the probe summary. It's only meaningful paired with
            // `--probe`; the validation runs after the loop so we can
            // emit a clear "needs --probe" error rather than a generic
            // "unknown flag" one.
            "--json" => {
                probe_json = true;
                i += 1;
            }
            // `--watch` re-runs the probe whenever the input file's
            // mtime changes. Like `--json`, it's only meaningful paired
            // with `--probe` (there's no other long-running mode for it
            // to attach to); the post-loop validation surfaces a clear
            // "needs --probe" error rather than a generic "unknown
            // flag" one.
            "--watch" => {
                probe_watch = true;
                i += 1;
            }
            "-density" => {
                let v = val(i + 1)?;
                let n: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -density: '{v}' is not a non-negative integer"
                    ))
                })?;
                if n == 0 {
                    return Err(Error::invalid("convert: -density must be > 0"));
                }
                ops.push(Op::Density(n));
                i += 2;
            }
            "-background" => {
                let v = val(i + 1)?;
                let rgba = parse_color(v).map_err(Error::invalid)?;
                // Bake the current background into the parse state so a
                // subsequent `-extent` reads this value rather than the
                // initial IM-default white.
                current_bg = rgba;
                ops.push(Op::Background(rgba));
                i += 2;
            }
            "-alpha" => {
                let v = val(i + 1)?;
                let a = AlphaOp::parse(v).map_err(Error::invalid)?;
                ops.push(Op::Alpha(a));
                i += 2;
            }
            "-rotate" => {
                let v = val(i + 1)?;
                let n: i32 = v.parse().map_err(|_| {
                    Error::invalid(format!("convert: -rotate: '{v}' is not an integer"))
                })?;
                // Round-1 supports only quarter-turn rotations.
                // Other angles need a real resampler (bilinear / lanczos
                // sample at non-integer coordinates), which we'll wire
                // through oxideav-image-filter once it lands.
                if !matches!(n, 90 | 180 | 270 | -90 | -180 | -270) {
                    return Err(Error::invalid(format!(
                        "convert: -rotate: only multiples of 90 supported (got {n})"
                    )));
                }
                ops.push(Op::Rotate { degrees: n });
                i += 2;
            }
            "-flip" => {
                ops.push(Op::Flip);
                i += 1;
            }
            "-flop" => {
                ops.push(Op::Flop);
                i += 1;
            }
            "-negate" => {
                ops.push(Op::Negate);
                i += 1;
            }
            "-crop" => {
                let v = val(i + 1)?;
                let (w, h, x, y) =
                    parse_crop(v).map_err(|e| Error::invalid(format!("convert: -crop: {e}")))?;
                ops.push(Op::Crop { x, y, w, h });
                i += 2;
            }
            "-extent" => {
                // IM-style canvas re-window: `WxH`, `WxH+X+Y`, `WxH-X-Y`,
                // or any mix of signs on the two offsets. The background
                // colour painted under padding pixels is the one set by
                // the most recent `-background` op in source order — we
                // bake it into the op here so the plan walker / inline
                // pixel-xform path don't need to track parser state.
                let v = val(i + 1)?;
                let (w, h, x, y) = parse_extent(v)
                    .map_err(|e| Error::invalid(format!("convert: -extent: {e}")))?;
                ops.push(Op::Extent {
                    width: w,
                    height: h,
                    x,
                    y,
                    bg: current_bg,
                });
                i += 2;
            }
            // `-fuzz N[%]` updates the in-band fuzz state. IM's grammar
            // accepts either a raw byte value (`0..=255`) or a percent
            // (`N%`, `0..=100`) — share the `-threshold` / `-solarize`
            // parser. The flag itself produces no `Op`; it only mutates
            // `current_fuzz`, which a following `-trim` reads.
            "-fuzz" => {
                let v = val(i + 1)?;
                current_fuzz = parse_threshold_pct(v)
                    .map_err(|e| Error::invalid(format!("convert: -fuzz: {e}")))?;
                i += 2;
            }
            // `-trim` (valueless) — auto-crop the bounding box of pixels
            // differing from the corner-pixel reference background by
            // more than the active `-fuzz` tolerance. The tolerance is
            // captured at parse time so source-order semantics survive
            // through the plan walker and the inline side-channel.
            "-trim" => {
                ops.push(Op::Trim { fuzz: current_fuzz });
                i += 1;
            }
            // `-roll ±X±Y` — IM-style circular pixel shift. Both X and
            // Y offsets must be present and signed; columns wrap around
            // the right edge when `dx > 0`, rows wrap around the bottom
            // edge when `dy > 0`. Width / height stay unchanged. Shares
            // the signed-offset parser used by `-extent`'s `±X±Y` tail.
            "-roll" => {
                let v = val(i + 1)?;
                let (dx, dy) =
                    parse_roll(v).map_err(|e| Error::invalid(format!("convert: -roll: {e}")))?;
                ops.push(Op::Roll { dx, dy });
                i += 2;
            }
            // ---- Round-next: IM-style image-filter flags wired
            // through to the matching `oxideav-image-filter` factory. ----
            "-sharpen" => {
                let v = val(i + 1)?;
                let (radius, sigma) =
                    parse_blur(v).map_err(|e| Error::invalid(format!("convert: -sharpen: {e}")))?;
                ops.push(Op::Sharpen { radius, sigma });
                i += 2;
            }
            "-unsharp" => {
                let v = val(i + 1)?;
                let (radius, sigma, amount, threshold) = parse_unsharp(v)
                    .map_err(|e| Error::invalid(format!("convert: -unsharp: {e}")))?;
                ops.push(Op::Unsharp {
                    radius,
                    sigma,
                    amount,
                    threshold,
                });
                i += 2;
            }
            "-gamma" => {
                let v = val(i + 1)?;
                let g: f32 = v.parse().map_err(|_| {
                    Error::invalid(format!("convert: -gamma: '{v}' is not a finite float"))
                })?;
                if !g.is_finite() || g <= 0.0 {
                    return Err(Error::invalid(format!(
                        "convert: -gamma: value must be > 0 (got {g})"
                    )));
                }
                ops.push(Op::Gamma { value: g });
                i += 2;
            }
            "-brightness-contrast" => {
                let v = val(i + 1)?;
                let (b, c) = parse_brightness_contrast(v)
                    .map_err(|e| Error::invalid(format!("convert: -brightness-contrast: {e}")))?;
                ops.push(Op::BrightnessContrast {
                    brightness: b,
                    contrast: c,
                });
                i += 2;
            }
            "-contrast" => {
                // IM's `-contrast` takes no arg and applies a single
                // small contrast bump. Repeated `-contrast` accumulates.
                ops.push(Op::Contrast { delta: 1 });
                i += 1;
            }
            "-sepia" => {
                let v = val(i + 1)?;
                let t = parse_percent_or_unit(v)
                    .map_err(|e| Error::invalid(format!("convert: -sepia: {e}")))?;
                ops.push(Op::Sepia { threshold: t });
                i += 2;
            }
            "-modulate" => {
                let v = val(i + 1)?;
                let (b, s, h) = parse_modulate(v)
                    .map_err(|e| Error::invalid(format!("convert: -modulate: {e}")))?;
                ops.push(Op::Modulate {
                    brightness: b,
                    saturation: s,
                    hue: h,
                });
                i += 2;
            }
            "-level" => {
                let v = val(i + 1)?;
                let (b, g, w) =
                    parse_level(v).map_err(|e| Error::invalid(format!("convert: -level: {e}")))?;
                ops.push(Op::Level {
                    black: b,
                    gamma: g,
                    white: w,
                });
                i += 2;
            }
            "-normalize" => {
                ops.push(Op::Normalize);
                i += 1;
            }
            "-threshold" => {
                let v = val(i + 1)?;
                let n = parse_threshold_pct(v)
                    .map_err(|e| Error::invalid(format!("convert: -threshold: {e}")))?;
                ops.push(Op::Threshold { value: n });
                i += 2;
            }
            "-posterize" => {
                let v = val(i + 1)?;
                let n: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!(
                        "convert: -posterize: '{v}' is not a non-negative integer"
                    ))
                })?;
                if n < 2 {
                    return Err(Error::invalid(format!(
                        "convert: -posterize: levels must be >= 2 (got {n})"
                    )));
                }
                ops.push(Op::Posterize { levels: n });
                i += 2;
            }
            "-solarize" => {
                let v = val(i + 1)?;
                let n = parse_threshold_pct(v)
                    .map_err(|e| Error::invalid(format!("convert: -solarize: {e}")))?;
                ops.push(Op::Solarize { value: n });
                i += 2;
            }
            "-vignette" => {
                let v = val(i + 1)?;
                let (radius, sigma, x, y) = parse_vignette(v)
                    .map_err(|e| Error::invalid(format!("convert: -vignette: {e}")))?;
                ops.push(Op::Vignette {
                    radius,
                    sigma,
                    x,
                    y,
                });
                i += 2;
            }
            "-colorize" => {
                let v = val(i + 1)?;
                let (color, amount) = parse_colorize(v)
                    .map_err(|e| Error::invalid(format!("convert: -colorize: {e}")))?;
                ops.push(Op::Colorize { color, amount });
                i += 2;
            }
            "-equalize" => {
                ops.push(Op::Equalize);
                i += 1;
            }
            "-auto-gamma" => {
                ops.push(Op::AutoGamma);
                i += 1;
            }
            "-colorspace" => {
                let v = val(i + 1)?;
                let cs = v.trim().to_string();
                // Round-1 only routes `gray`/`grey` to the grayscale
                // factory; other colourspaces become a recorded no-op
                // (the input keeps its native colourspace).
                let lower = cs.to_ascii_lowercase();
                if !matches!(lower.as_str(), "gray" | "grey" | "rgb" | "srgb") {
                    return Err(Error::unsupported(format!(
                        "convert: -colorspace '{cs}' is not yet wired (round-1 supports gray/grey/rgb/srgb)"
                    )));
                }
                ops.push(Op::Colorspace(cs));
                i += 2;
            }
            // ---- Per-format encoder option flags for the 3D
            //      side-channel. Stored on `ConvertPlan::mesh3d_options`,
            //      not as `Op` entries, since they're plan-level
            //      switches that only the mesh3d_runner consumes
            //      (raster ops have no analogous notion). The flags
            //      are accepted on every input shape (PDF / raster /
            //      etc.) and silently ignored when the side-channel
            //      doesn't fire — matches IM's tolerant-of-irrelevant-
            //      flags posture.
            "-stl-format" => {
                let v = val(i + 1)?;
                let choice = StlFormatChoice::parse(v).map_err(Error::invalid)?;
                mesh3d_options.stl_format = Some(choice);
                i += 2;
            }
            "-gltf-format" => {
                let v = val(i + 1)?;
                let choice = GltfFormatChoice::parse(v).map_err(Error::invalid)?;
                mesh3d_options.gltf_format = Some(choice);
                i += 2;
            }
            // `-render flat|wireframe` selects the 3D→raster surface
            // model. Stored on `Mesh3DOptions` (sister to `-stl-format`
            // and `-gltf-format`) so it never leaks into the regular
            // pipeline path. Silently ignored when the input/output
            // pair doesn't trigger the 3D→raster side-channel.
            "-render" => {
                let v = val(i + 1)?;
                let mode = Mesh3DRenderMode::parse(v).map_err(Error::invalid)?;
                mesh3d_options.render_mode = Some(mode);
                i += 2;
            }
            // `-light AZIMUTH,ELEVATION,INTENSITY` — directional light
            // override for the 3D→raster renderer's Gouraud / Phong
            // shading paths. Stored on `Mesh3DOptions::light`; silently
            // ignored when the input/output pair doesn't trigger 3D
            // rendering.
            "-light" => {
                let v = val(i + 1)?;
                let spec = LightSpec::parse(v).map_err(Error::invalid)?;
                mesh3d_options.light = Some(spec);
                i += 2;
            }
            // `-camera ELEVATION,AZIMUTH,DISTANCE` — camera override for
            // the 3D→raster renderer (replaces the auto-framed default).
            "-camera" => {
                let v = val(i + 1)?;
                let spec = CameraSpec::parse(v).map_err(Error::invalid)?;
                mesh3d_options.camera = Some(spec);
                i += 2;
            }
            // `-projection perspective|orthographic` — projection mode
            // for the 3D→raster renderer. Default is perspective.
            "-projection" => {
                let v = val(i + 1)?;
                let mode = ProjectionMode::parse(v).map_err(Error::invalid)?;
                mesh3d_options.projection = Some(mode);
                i += 2;
            }
            // `-fov DEGREES` — vertical field of view for the 3D→raster
            // renderer's perspective projection. Default is 60°. Ignored
            // for orthographic projection.
            "-fov" => {
                let v = val(i + 1)?;
                let fov: f32 = v
                    .parse()
                    .map_err(|_| Error::invalid(format!("convert: -fov: '{v}' is not a number")))?;
                if !fov.is_finite() || fov <= 0.0 || fov >= 180.0 {
                    return Err(Error::invalid(format!(
                        "convert: -fov: {fov} must be in (0, 180) degrees"
                    )));
                }
                mesh3d_options.fov_deg = Some(fov);
                i += 2;
            }
            // `-bg COLOR` — background fill for the 3D render canvas.
            // Default is transparent black. Distinct from `-background`
            // which is the IM canvas-fill for alpha-remove + PDF.
            "-bg" => {
                let v = val(i + 1)?;
                let colour = parse_color(v).map_err(Error::invalid)?;
                mesh3d_options.bg = Some(colour);
                i += 2;
            }
            // `-aa N` — supersampling factor for the 3D→raster
            // renderer (rasterise at N × output, box-filter back to
            // 1 × output). `1` means no supersampling. `>= 2` trades
            // memory + CPU for smoother triangle edges. Stored on
            // `Mesh3DOptions::aa`; silently ignored when the
            // input/output pair doesn't trigger 3D rendering. We
            // cap at 8 to keep memory bounded — at 8× a 1024²
            // render needs ~80 MB just for the framebuffer + z-buffer
            // and that already costs more than most users want.
            "-aa" => {
                let v = val(i + 1)?;
                let factor: u32 = v.parse().map_err(|_| {
                    Error::invalid(format!("convert: -aa: '{v}' is not a positive integer"))
                })?;
                if !(1..=8).contains(&factor) {
                    return Err(Error::invalid(format!(
                        "convert: -aa: factor {factor} out of range (must be in 1..=8)"
                    )));
                }
                mesh3d_options.aa = Some(factor);
                i += 2;
            }
            other => {
                // Reach here only on `-`-prefixed args (non-`-` was
                // pushed to `positionals` above). Add a "did you mean?"
                // hint when the bogus token is a close edit of a known
                // flag — same Levenshtein-cutoff helper the mesh3d-runner
                // uses for extension typos. We strip the leading dashes
                // before comparing so `-quailty` matches `-quality` at a
                // 2-edit distance (transposition) instead of being
                // scored 3 because of the dash overhead, and we
                // reattach the same dash flavour (single or double) the
                // user typed when rendering the suggestion. Unknown
                // tokens that aren't close to any flag (e.g. `-fnord`)
                // produce the bare error, exactly as before.
                let (lead, bare) = if let Some(rest) = other.strip_prefix("--") {
                    ("--", rest)
                } else {
                    ("-", other.strip_prefix('-').unwrap_or(other))
                };
                let hint = crate::suggest::closest_match(bare, KNOWN_FLAG_NAMES)
                    .map(|s| format!(" (did you mean '{lead}{s}'?)"))
                    .unwrap_or_default();
                return Err(Error::invalid(format!(
                    "convert: unknown flag '{other}'{hint}"
                )));
            }
        }
    }

    // `--help` short-circuits every validation below: the user asked
    // for the synopsis, not a conversion, so missing/extra positionals
    // are irrelevant.
    if help {
        return Ok(ConvertPlan {
            input: String::new(),
            input_pages: None,
            ops,
            output: String::new(),
            output_template: None,
            help: true,
            ping,
            probe,
            probe_json,
            probe_watch,
            mesh3d_options,
        });
    }

    if positionals.is_empty() {
        return Err(Error::invalid(
            "convert: no input file given (usage: convert [-op VALUE]... INPUT [-op VALUE]... OUTPUT)",
        ));
    }
    // `--probe` is mutually exclusive with an output positional —
    // probing means "describe, don't write", and the user passing both
    // is almost always a mistake (typo'd a flag, copy-pasted from a
    // real conversion). Surface it as a clear actionable error rather
    // than silently writing or silently dropping the output arg.
    if probe && positionals.len() >= 2 {
        return Err(Error::invalid(format!(
            "convert: --probe cannot be combined with an output file ('{}'); use either --probe OR an output file, not both",
            positionals[1]
        )));
    }
    if positionals.len() < 2 && !ping && !probe {
        return Err(Error::invalid(
            "convert: no output file given (usage: convert [-op VALUE]... INPUT [-op VALUE]... OUTPUT)",
        ));
    }
    if positionals.len() > 2 {
        return Err(Error::unsupported(format!(
            "convert: {} positional arguments given but multi-input is not yet supported (round-2 follow-up); pass exactly INPUT OUTPUT",
            positionals.len()
        )));
    }
    // `--json` is only meaningful as a formatting modifier on
    // `--probe`. Without `--probe` there's no probe summary to
    // serialise, so we'd otherwise silently swallow the flag.
    if probe_json && !probe {
        return Err(Error::invalid(
            "convert: --json requires --probe (today --json only formats the probe summary)",
        ));
    }
    // `--watch` re-runs the probe on mtime change; only meaningful
    // paired with `--probe`. Without `--probe` there's no long-running
    // mode for it to attach to.
    if probe_watch && !probe {
        return Err(Error::invalid(
            "convert: --watch requires --probe (today --watch only re-runs the probe on input mtime change)",
        ));
    }

    let (raw_input, input_pages) = split_input_selector(&positionals[0])?;
    let input = translate_input_shorthand(raw_input);
    let output = positionals.get(1).cloned().unwrap_or_default();
    let output_template = if output.is_empty() {
        None
    } else {
        parse_printf_template(&output)?
    };

    Ok(ConvertPlan {
        input,
        input_pages,
        ops,
        output,
        output_template,
        help: false,
        ping,
        probe,
        probe_json,
        probe_watch,
        mesh3d_options,
    })
}

/// Human-readable usage synopsis for the convert verb.
///
/// The flag list is generated from [`KNOWN_FLAG_NAMES`] — the same
/// table that powers "did you mean?" hints and is sync-tested against
/// the parser's `match` arms — so the help text cannot drift from
/// what the parser actually accepts.
pub fn usage() -> String {
    let mut s = String::new();
    s.push_str("usage: oxideav convert [-op VALUE]... INPUT [-op VALUE]... OUTPUT\n");
    s.push_str("       oxideav convert --probe [--json] [--watch] INPUT\n");
    s.push_str("       oxideav convert -ping INPUT\n");
    s.push_str("       oxideav convert --help\n");
    s.push('\n');
    s.push_str("Ops may appear before AND after the input; the first non-flag\n");
    s.push_str("positional is the input, the last is the output. `--` ends flag\n");
    s.push_str("parsing so filenames may start with `-`. PDF inputs accept a\n");
    s.push_str("[N] / [N-M] / [A,B,...] page-selector suffix; `%d` output\n");
    s.push_str("templates fan out one file per selected page.\n");
    s.push('\n');
    s.push_str("Recognised flags (see the crate README for per-flag grammar):\n");
    for chunk in KNOWN_FLAG_NAMES.chunks(5) {
        s.push(' ');
        for name in chunk {
            // The four GNU-style mode switches take a double dash;
            // everything else is a single-dash IM-style op.
            let lead = if matches!(*name, "probe" | "json" | "watch" | "help" | "opt") {
                "--"
            } else {
                "-"
            };
            s.push(' ');
            s.push_str(lead);
            s.push_str(name);
        }
        s.push('\n');
    }
    s
}

/// Strip an ImageMagick-style `[N]` / `[N-M]` / `[A,B,…]` page-selector
/// suffix from the input path. Examples:
///
/// * `input.pdf[0]` → `("input.pdf", Some(Single(0)))`
/// * `input.pdf[2-5]` → `("input.pdf", Some(Range(2, 5)))`
/// * `input.pdf[-1]` → `("input.pdf", Some(Single(-1)))` (resolves to last page)
/// * `input.pdf[5--1]` → `("input.pdf", Some(Range(5, -1)))` (page 5 to last)
/// * `input.pdf[0,2,4]` → `("input.pdf", Some(List([Single(0), Single(2), Single(4)])))`
/// * `input.pdf[0-2,5,-1]` → `("input.pdf", Some(List([Range(0,2), Single(5), Single(-1)])))`
///
/// Inputs with no `[…]` suffix return `(input, None)`.
///
/// Returns an `Err` for malformed selectors (`[abc]`, `[1-2-3]`, `[]`,
/// `[,]`, `[0,,1]`, unbalanced brackets, etc.) so the user gets a
/// clear message.
pub(crate) fn split_input_selector(s: &str) -> Result<(&str, Option<PageSelector>), Error> {
    if !s.ends_with(']') {
        return Ok((s, None));
    }
    let open = match s.rfind('[') {
        Some(i) => i,
        None => {
            return Err(Error::invalid(format!(
                "convert: input '{s}' has a closing `]` with no matching `[`"
            )));
        }
    };
    let body = &s[open + 1..s.len() - 1];
    if body.is_empty() {
        return Err(Error::invalid(format!(
            "convert: input '{s}' has an empty `[]` page selector"
        )));
    }
    let sel = parse_page_selector_body(s, body)?;
    Ok((&s[..open], Some(sel)))
}

/// Parse the inside of a `[…]` page-selector. Splits on `,`, then each
/// piece on a single `-` (taking care to keep a LEADING `-` as the
/// sign of a negative endpoint, not a range separator). One atom →
/// `Single`/`Range` variant; multiple atoms → `List`.
fn parse_page_selector_body(input: &str, body: &str) -> Result<PageSelector, Error> {
    // Comma-separated list of atoms. IM accepts `[0,2,4]` for "pages
    // 0, 2, and 4"; we extend to ranges-within-lists (`[0-2,5,-1]`).
    let pieces: Vec<&str> = body.split(',').collect();
    let mut atoms: Vec<PageAtom> = Vec::with_capacity(pieces.len());
    for piece in &pieces {
        let trimmed = piece.trim();
        if trimmed.is_empty() {
            return Err(Error::invalid(format!(
                "convert: input '{input}': page selector '{body}' has an empty atom (between commas)"
            )));
        }
        atoms.push(parse_page_atom(input, trimmed)?);
    }
    Ok(if atoms.len() == 1 {
        // Preserve the single-atom variants — most callers only care
        // about the one-atom case and matching `Single(2)` is far
        // friendlier than walking a one-element `List([Single(2)])`.
        match atoms.into_iter().next().unwrap() {
            PageAtom::Single(n) => PageSelector::Single(n),
            PageAtom::Range(a, b) => PageSelector::Range(a, b),
        }
    } else {
        PageSelector::List(atoms)
    })
}

/// Parse one atom of a page selector. Accepts `N`, `-N`, `N-M`,
/// `-N-M`, `N--M`, `-N--M`. Returns `Single(n)` for plain indices
/// (possibly negative) and `Range(a, b)` for two-endpoint specs.
///
/// The trick: `-` is both the unary sign for negative indices AND the
/// range separator. We split off a leading `-` first (so `-1` doesn't
/// look like a range with an empty start), then look for the next `-`
/// as the range delimiter, treating a leading `-` on the second
/// endpoint the same way.
fn parse_page_atom(input: &str, atom: &str) -> Result<PageAtom, Error> {
    // Peel off a leading `-` as the sign of the first endpoint (if any).
    let (first_sign, rest) = if let Some(rest) = atom.strip_prefix('-') {
        ("-", rest)
    } else {
        ("", atom)
    };
    if rest.is_empty() {
        return Err(Error::invalid(format!(
            "convert: input '{input}': page selector atom '{atom}' is just a sign with no digits"
        )));
    }
    // Now look for a `-` separator (range). Anything past the first
    // digit-run that's `-` opens the second endpoint.
    match rest.find('-') {
        None => {
            // Single atom — `first_sign + rest` is a plain integer.
            let n: isize = format!("{first_sign}{rest}").parse().map_err(|_| {
                Error::invalid(format!(
                    "convert: input '{input}': page selector atom '{atom}' is not an integer page index"
                ))
            })?;
            Ok(PageAtom::Single(n))
        }
        Some(sep) => {
            // Range. Left endpoint is `first_sign + rest[..sep]`.
            let left = format!("{first_sign}{}", &rest[..sep]);
            let right_raw = &rest[sep + 1..];
            if left.is_empty() || left == "-" {
                return Err(Error::invalid(format!(
                    "convert: input '{input}': page selector atom '{atom}' has no left endpoint"
                )));
            }
            if right_raw.is_empty() {
                return Err(Error::invalid(format!(
                    "convert: input '{input}': page selector atom '{atom}' has no right endpoint"
                )));
            }
            // The right side may itself start with `-` to mark a
            // negative endpoint (e.g. `5--1` = page 5 to last). After
            // splitting on the FIRST `-`, anything beyond that
            // shouldn't carry yet ANOTHER unparseable `-`.
            let a: isize = left.parse().map_err(|_| {
                Error::invalid(format!(
                    "convert: input '{input}': page selector atom '{atom}': left endpoint '{left}' is not an integer"
                ))
            })?;
            let b: isize = right_raw.parse().map_err(|_| {
                Error::invalid(format!(
                    "convert: input '{input}': page selector atom '{atom}': right endpoint '{right_raw}' is not an integer (expected `N-M`, `-N-M`, or `N--M`)"
                ))
            })?;
            Ok(PageAtom::Range(a, b))
        }
    }
}

/// Scan an output filename for a single `%[0-9]*d` token.
///
/// Returns `Ok(Some(template))` when exactly one such token is found;
/// `Ok(None)` when there is no `%` at all (the literal-filename case);
/// `Err` when there are multiple `%d` tokens or any unsupported format
/// specifier (`%s`, `%x`, `%%`, …). The two-pass design keeps the
/// invariant that `output_template == None` iff the filename is a plain
/// path that should be written to verbatim.
pub(crate) fn parse_printf_template(s: &str) -> Result<Option<PrintfTemplate>, Error> {
    let bytes = s.as_bytes();
    let mut i = 0usize;
    let mut found: Option<(usize, u8, usize)> = None; // (start, width, end)
    while i < bytes.len() {
        if bytes[i] != b'%' {
            i += 1;
            continue;
        }
        let start = i;
        i += 1;
        let mut width: u8 = 0;
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            // Cap width to a sensible limit to avoid pathological inputs.
            let d = (bytes[i] - b'0') as u32;
            let next = (width as u32) * 10 + d;
            if next > 20 {
                return Err(Error::invalid(format!(
                    "convert: output template '{s}' has an unreasonable width specifier"
                )));
            }
            width = next as u8;
            i += 1;
        }
        if i >= bytes.len() {
            return Err(Error::invalid(format!(
                "convert: output template '{s}' has a `%` with no format specifier"
            )));
        }
        match bytes[i] {
            b'd' => {
                if found.is_some() {
                    return Err(Error::invalid(format!(
                        "convert: output template '{s}' has more than one `%d` token (expected exactly one)"
                    )));
                }
                found = Some((start, width, i + 1));
                i += 1;
            }
            other => {
                return Err(Error::invalid(format!(
                    "convert: output template '{s}' uses unsupported format specifier '%{}' (only `%d`, `%03d`, etc. are accepted)",
                    other as char
                )));
            }
        }
    }
    Ok(found.map(|(start, width, end)| PrintfTemplate {
        prefix: s[..start].to_string(),
        width,
        suffix: s[end..].to_string(),
    }))
}

/// CSS L3 named colours + `#hex` 3/4/6/8 form. Same grammar as
/// `oxideav-generator`'s `xc:` parser. Kept local to convert so we
/// don't have to pull `oxideav-generator` in when the `generator`
/// feature is off.
fn parse_color(s: &str) -> Result<[u8; 4], String> {
    let s = s.trim();
    if let Some(hex) = s.strip_prefix('#') {
        return parse_hex_color(hex);
    }
    match s.to_ascii_lowercase().as_str() {
        "transparent" | "none" => Ok([0, 0, 0, 0]),
        "black" => Ok([0, 0, 0, 255]),
        "white" => Ok([255, 255, 255, 255]),
        "red" => Ok([255, 0, 0, 255]),
        "green" => Ok([0, 128, 0, 255]),
        "lime" => Ok([0, 255, 0, 255]),
        "blue" => Ok([0, 0, 255, 255]),
        "yellow" => Ok([255, 255, 0, 255]),
        "cyan" | "aqua" => Ok([0, 255, 255, 255]),
        "magenta" | "fuchsia" => Ok([255, 0, 255, 255]),
        "gray" | "grey" => Ok([128, 128, 128, 255]),
        "silver" => Ok([192, 192, 192, 255]),
        "maroon" => Ok([128, 0, 0, 255]),
        "olive" => Ok([128, 128, 0, 255]),
        "purple" => Ok([128, 0, 128, 255]),
        "teal" => Ok([0, 128, 128, 255]),
        "navy" => Ok([0, 0, 128, 255]),
        "orange" => Ok([255, 165, 0, 255]),
        other => Err(format!(
            "convert: unknown colour '{other}' (try a `#hex` value or one of: black/white/red/green/blue/yellow/cyan/magenta/gray/transparent/…)"
        )),
    }
}

fn parse_hex_color(hex: &str) -> Result<[u8; 4], String> {
    fn hex_digit(c: u8) -> Result<u8, String> {
        match c {
            b'0'..=b'9' => Ok(c - b'0'),
            b'a'..=b'f' => Ok(c - b'a' + 10),
            b'A'..=b'F' => Ok(c - b'A' + 10),
            _ => Err(format!("'{}' is not a hex digit", c as char)),
        }
    }
    let h = hex.as_bytes();
    let pair = |a: u8, b: u8| -> Result<u8, String> { Ok(hex_digit(a)? * 16 + hex_digit(b)?) };
    let dup = |a: u8| -> Result<u8, String> {
        let d = hex_digit(a)?;
        Ok(d * 16 + d)
    };
    match h.len() {
        3 => Ok([dup(h[0])?, dup(h[1])?, dup(h[2])?, 255]),
        4 => Ok([dup(h[0])?, dup(h[1])?, dup(h[2])?, dup(h[3])?]),
        6 => Ok([pair(h[0], h[1])?, pair(h[2], h[3])?, pair(h[4], h[5])?, 255]),
        8 => Ok([
            pair(h[0], h[1])?,
            pair(h[2], h[3])?,
            pair(h[4], h[5])?,
            pair(h[6], h[7])?,
        ]),
        _ => Err(format!(
            "'#{hex}' is not a valid hex colour (expected 3/4/6/8 hex digits)"
        )),
    }
}

/// Apply the `oxideav-generator` shorthand translator when it's
/// linked in; otherwise return the input verbatim. Keeping the call
/// behind a feature gate means the convert verb still works (with a
/// clear error from the source registry) when the generator crate is
/// excluded.
#[cfg(feature = "generator")]
fn translate_input_shorthand(input: &str) -> String {
    oxideav_generator::shorthand::translate(input)
}

#[cfg(not(feature = "generator"))]
fn translate_input_shorthand(input: &str) -> String {
    input.to_string()
}

/// Parse the geometry-without-suffix portion of a `-resize` /
/// `-thumbnail` arg, branching on the scaling mode the suffix already
/// selected.
///
/// Most modes parse exactly like `WxH` (two positive integers). A few
/// modes have looser grammar:
///
/// - [`ResizeMode::Percent`] — `N`, `Nx`, `xN`, `NxN`. A bare `N`
///   applies to both axes; missing axes default to the other one
///   (`200x` → `200x200`; `x200` → `200x200`). Components must be
///   integer percentages > 0.
/// - [`ResizeMode::Area`] — same `WxH` shape; the runtime treats
///   `W*H` as the target pixel area.
/// - Everything else — strict `WxH`, both > 0.
fn parse_resize_geometry(s: &str, mode: ResizeMode) -> Result<(u32, u32), String> {
    if matches!(mode, ResizeMode::Percent) {
        // `N` / `Nx` / `xN` / `NxN`. Single-number form replicates.
        let s = s.trim();
        let (w_str, h_str) = match s.split_once(['x', 'X']) {
            None => (s, s), // bare N → both axes
            Some((w, h)) => {
                let w = if w.is_empty() { h } else { w };
                let h = if h.is_empty() { w } else { h };
                (w, h)
            }
        };
        let w: u32 = w_str
            .parse()
            .map_err(|_| format!("'{w_str}' is not a non-negative integer percent"))?;
        let h: u32 = h_str
            .parse()
            .map_err(|_| format!("'{h_str}' is not a non-negative integer percent"))?;
        if w == 0 || h == 0 {
            return Err("percent values must both be > 0".into());
        }
        return Ok((w, h));
    }
    parse_wxh(s)
}

/// Parse `WxH` — width × height. Accepts either lowercase `x` or
/// uppercase `X`. Both parts must be non-negative integers.
fn parse_wxh(s: &str) -> Result<(u32, u32), String> {
    let (w, h) = s
        .split_once(['x', 'X'])
        .ok_or_else(|| format!("'{s}' is not in WxH form"))?;
    let w: u32 = w
        .parse()
        .map_err(|_| format!("'{w}' is not a non-negative integer"))?;
    let h: u32 = h
        .parse()
        .map_err(|_| format!("'{h}' is not a non-negative integer"))?;
    if w == 0 || h == 0 {
        return Err("width and height must both be positive".into());
    }
    Ok((w, h))
}

/// Parse `-crop WxH+X+Y` (and the simpler `WxH+X+Y` permutations IM
/// also accepts). All four numbers are required; IM-style geometry
/// modifiers (`%`, `!`, `^`, `<`, `>`, `@`, `-X-Y` negative offsets)
/// are NOT yet supported in round-1 — they'd need centering / aspect
/// math we don't have. Bbox bounds checking against the actual image
/// dims happens at apply time, not here.
fn parse_crop(s: &str) -> Result<(u32, u32, u32, u32), String> {
    // Reject IM modifiers up front with a clear message, otherwise
    // they'd be silently swallowed by parse() of `0` etc.
    for mark in ['%', '!', '^', '<', '>', '@'] {
        if s.contains(mark) {
            return Err(format!(
                "'{s}' uses IM modifier '{mark}' (round-1 supports plain WxH+X+Y only)"
            ));
        }
    }
    // IM also accepts `-X` for negative offsets; round-1 sticks to
    // `+X+Y` only.
    let mut parts = s.split('+');
    let wh = parts
        .next()
        .ok_or_else(|| format!("'{s}' is missing the WxH component"))?;
    let x_str = parts
        .next()
        .ok_or_else(|| format!("'{s}' is missing the +X offset (expected WxH+X+Y)"))?;
    let y_str = parts
        .next()
        .ok_or_else(|| format!("'{s}' is missing the +Y offset (expected WxH+X+Y)"))?;
    if parts.next().is_some() {
        return Err(format!("'{s}' has more than two `+` separators"));
    }
    let (w, h) = parse_wxh(wh)?;
    let x: u32 = x_str
        .parse()
        .map_err(|_| format!("'{x_str}' is not a non-negative integer X offset"))?;
    let y: u32 = y_str
        .parse()
        .map_err(|_| format!("'{y_str}' is not a non-negative integer Y offset"))?;
    Ok((w, h, x, y))
}

/// Parse `-extent WxH[±X±Y]` — IM's canvas re-window.
///
/// Accepts `WxH` (offset defaults to `(0, 0)`), `WxH+X+Y`, `WxH-X-Y`,
/// `WxH+X-Y`, or `WxH-X+Y`. Width / height must both be positive (a
/// zero-area canvas has nothing to paint); offsets are signed so the
/// IM convention of negative translation (moving the source toward the
/// upper-left so its right or bottom edge can fit inside the window)
/// rides through unchanged.
///
/// We deliberately reject the geometry modifiers (`%`, `!`, `^`, `<`,
/// `>`, `@`) the same way `parse_crop` does — `-extent` in IM accepts
/// some of those but their semantics are source-size-dependent and
/// would need a runtime resolution pass that hasn't landed yet.
fn parse_extent(s: &str) -> Result<(u32, u32, i32, i32), String> {
    for mark in ['%', '!', '^', '<', '>', '@'] {
        if s.contains(mark) {
            return Err(format!(
                "'{s}' uses IM modifier '{mark}' (-extent currently supports plain WxH[±X±Y] only)"
            ));
        }
    }
    // Find the boundary between `WxH` and the first signed offset (if
    // any). The first `+` or `-` AFTER the initial character marks
    // where the offset section starts; we keep position 0 untouched so
    // a leading `-` on `WxH` (illegal — `W` must be positive) is
    // surfaced by `parse_wxh`'s unsigned parse rather than mis-split as
    // an offset.
    let head_end = s
        .char_indices()
        .skip(1)
        .find(|(_, c)| *c == '+' || *c == '-')
        .map(|(i, _)| i)
        .unwrap_or(s.len());
    let head = &s[..head_end];
    let tail = &s[head_end..];
    let (w, h) = parse_wxh(head)?;
    let (x, y) = parse_extent_offsets(tail)?;
    Ok((w, h, x, y))
}

/// Parse the `±X±Y` tail of an `-extent` geometry string. Returns
/// `(0, 0)` for an empty tail. Both signs are required when any
/// offset is given — `WxH+X` (single offset) is rejected so the user
/// gets a clearer message than "parse failed on empty Y".
fn parse_extent_offsets(s: &str) -> Result<(i32, i32), String> {
    if s.is_empty() {
        return Ok((0, 0));
    }
    // Walk char-by-char to find the start of the Y offset — the
    // SECOND sign character in the tail. Splitting on `+`/`-` directly
    // would mishandle the mix-of-signs cases (`+X-Y`, `-X+Y`).
    let bytes = s.as_bytes();
    if bytes[0] != b'+' && bytes[0] != b'-' {
        return Err(format!(
            "'{s}' offset section must start with `+` or `-` (expected WxH+X+Y, WxH-X-Y, or mixed)"
        ));
    }
    let mut split = None;
    for (i, b) in bytes.iter().enumerate().skip(1) {
        if *b == b'+' || *b == b'-' {
            split = Some(i);
            break;
        }
    }
    let split = split
        .ok_or_else(|| format!("'{s}' has a single offset; expected both X and Y (WxH±X±Y)"))?;
    let x_str = &s[..split];
    let y_str = &s[split..];
    // Reject IM's `WxH+X+Y+Z` accidental extra-offset case.
    if y_str[1..].contains('+') || y_str[1..].contains('-') {
        return Err(format!("'{s}' has more than two signed offsets"));
    }
    let x: i32 = x_str
        .parse()
        .map_err(|_| format!("'{x_str}' is not a signed integer X offset"))?;
    let y: i32 = y_str
        .parse()
        .map_err(|_| format!("'{y_str}' is not a signed integer Y offset"))?;
    Ok((x, y))
}

/// Parse the value after `-roll`. IM's canonical grammar is
/// `±X±Y` — both offsets present, each prefixed by an explicit sign.
/// Reuses [`parse_extent_offsets`] for the actual signed-int split so
/// the two flags stay grammar-identical; rejects the empty / single-
/// offset cases with the same shape of error the user sees on
/// `-extent`. Negative offsets are accepted as-is — the inline /
/// pipeline shift routines wrap them mod width / height.
fn parse_roll(s: &str) -> Result<(i32, i32), String> {
    if s.is_empty() {
        return Err("empty offset (expected ±X±Y, e.g. +5+10)".to_string());
    }
    parse_extent_offsets(s)
}

/// Parse `-blur RxS` or `-blur R`. When sigma is omitted we follow
/// IM's convention of `sigma = radius / 2.0`. Unlike IM we don't
/// accept floats for radius — `Blur::new` takes `u32`.
fn parse_blur(s: &str) -> Result<(u32, f32), String> {
    let (radius_str, sigma_str) = match s.split_once(['x', 'X']) {
        Some((r, s)) => (r, Some(s)),
        None => (s, None),
    };
    let radius: u32 = radius_str
        .parse()
        .map_err(|_| format!("'{radius_str}' is not a non-negative integer"))?;
    let sigma: f32 = match sigma_str {
        Some(s) => s
            .parse()
            .map_err(|_| format!("'{s}' is not a non-negative float"))?,
        None => (radius as f32) / 2.0,
    };
    Ok((radius, sigma))
}

/// Parse `-unsharp RxS+amount+threshold` (any subset accepted in
/// source order: `R`, `RxS`, `RxS+A`, `RxS+A+T`).
///
/// Defaults match `oxideav_image_filter::Unsharp`'s conventions:
/// sigma = radius/2, amount = 1.0, threshold = 0 (out of 255).
fn parse_unsharp(s: &str) -> Result<(u32, f32, f32, u8), String> {
    // `+` separates the three optional tail components. Keep the
    // first chunk (radius / sigma) intact.
    let mut parts = s.splitn(3, '+');
    let head = parts.next().unwrap_or(s);
    let amount_str = parts.next();
    let threshold_str = parts.next();
    let (radius, sigma) = parse_blur(head)?;
    let amount: f32 = match amount_str {
        Some(a) => a
            .parse()
            .map_err(|_| format!("'{a}' is not a finite float"))?,
        None => 1.0,
    };
    let threshold: u8 = match threshold_str {
        // IM lets the threshold be either an integer 0..=255 or a
        // percentage. Accept both shapes; cap to u8.
        Some(t) => parse_threshold_pct(t)?,
        None => 0,
    };
    Ok((radius, sigma, amount, threshold))
}

/// Parse `-brightness-contrast B[xC]` / `B[,C]` / `B`. IM uses both
/// `x` and `,` as separators in different docs; accept either.
/// Range is `[-100..=100]` per IM.
fn parse_brightness_contrast(s: &str) -> Result<(f32, f32), String> {
    let (bs, cs) = match s.split_once(['x', 'X', ',']) {
        Some((a, b)) => (a, Some(b)),
        None => (s, None),
    };
    let b: f32 = bs
        .parse()
        .map_err(|_| format!("'{bs}' is not a finite float"))?;
    let c: f32 = match cs {
        Some(s) if !s.is_empty() => s
            .parse()
            .map_err(|_| format!("'{s}' is not a finite float"))?,
        _ => 0.0,
    };
    if !(-100.0..=100.0).contains(&b) {
        return Err(format!("brightness {b} out of range (-100..=100)"));
    }
    if !(-100.0..=100.0).contains(&c) {
        return Err(format!("contrast {c} out of range (-100..=100)"));
    }
    Ok((b, c))
}

/// Parse a value that's either a percentage (`50%`) or a unit-range
/// scalar (`0.5`). Used by `-sepia`. Returns the scalar in 0..=1.
fn parse_percent_or_unit(s: &str) -> Result<f32, String> {
    let s = s.trim();
    if let Some(p) = s.strip_suffix('%') {
        let v: f32 = p
            .parse()
            .map_err(|_| format!("'{p}' is not a finite float"))?;
        if !(0.0..=100.0).contains(&v) {
            return Err(format!("'{s}' is out of range (0%..=100%)"));
        }
        return Ok(v / 100.0);
    }
    let v: f32 = s
        .parse()
        .map_err(|_| format!("'{s}' is not a finite float"))?;
    if !(0.0..=1.0).contains(&v) {
        return Err(format!("'{s}' is out of range (0.0..=1.0)"));
    }
    Ok(v)
}

/// Parse `-modulate B[,S[,H]]`. Each element is percent-of-base
/// (100 = identity). Missing tail elements default to 100 / 100 / 100.
fn parse_modulate(s: &str) -> Result<(f32, f32, f32), String> {
    let mut parts = s.split(',').map(|p| p.trim());
    let b = parts
        .next()
        .ok_or_else(|| format!("'{s}' is missing the brightness value"))?;
    let s_field = parts.next();
    let h_field = parts.next();
    if parts.next().is_some() {
        return Err(format!(
            "'{s}' has more than 3 components (expected B[,S[,H]])"
        ));
    }
    let bv: f32 = b
        .parse()
        .map_err(|_| format!("'{b}' is not a finite float"))?;
    let sv: f32 = match s_field {
        Some(t) if !t.is_empty() => t
            .parse()
            .map_err(|_| format!("'{t}' is not a finite float"))?,
        _ => 100.0,
    };
    let hv: f32 = match h_field {
        Some(t) if !t.is_empty() => t
            .parse()
            .map_err(|_| format!("'{t}' is not a finite float"))?,
        _ => 100.0,
    };
    Ok((bv, sv, hv))
}

/// Parse `-level B[/G[/W]]` or `-level B,G,W`. IM accepts both
/// separators. Black/white are 0..=255 (or `N%` for a percentage).
/// Gamma is `> 0`.
fn parse_level(s: &str) -> Result<(u8, f32, u8), String> {
    let parts: Vec<&str> = s.split(['/', ',']).map(|p| p.trim()).collect();
    if parts.is_empty() || parts.len() > 3 {
        return Err(format!("'{s}' is not in B[/G[/W]] form (1..=3 components)"));
    }
    let black = parse_byte_or_percent(parts[0])?;
    let gamma: f32 = if parts.len() >= 2 && !parts[1].is_empty() {
        let g: f32 = parts[1]
            .parse()
            .map_err(|_| format!("'{}' is not a finite float", parts[1]))?;
        if !g.is_finite() || g <= 0.0 {
            return Err(format!("gamma {g} must be > 0"));
        }
        g
    } else {
        1.0
    };
    let white = if parts.len() == 3 && !parts[2].is_empty() {
        parse_byte_or_percent(parts[2])?
    } else {
        255
    };
    if black > white {
        return Err(format!(
            "black point ({black}) must be <= white point ({white})"
        ));
    }
    Ok((black, gamma, white))
}

/// Parse `0..=255` or `N%` → byte. Used by `-level`.
fn parse_byte_or_percent(s: &str) -> Result<u8, String> {
    if let Some(p) = s.strip_suffix('%') {
        let v: f32 = p
            .parse()
            .map_err(|_| format!("'{p}' is not a finite float"))?;
        if !(0.0..=100.0).contains(&v) {
            return Err(format!("'{s}' is out of range (0%..=100%)"));
        }
        return Ok((v * 2.55).round().clamp(0.0, 255.0) as u8);
    }
    let n: u32 = s
        .parse()
        .map_err(|_| format!("'{s}' is not a non-negative integer"))?;
    if n > 255 {
        return Err(format!("'{s}' is out of range (0..=255)"));
    }
    Ok(n as u8)
}

/// Parse `-threshold N%` / `-threshold N` / `-solarize N%` —
/// returns the resulting 0..=255 byte value.
fn parse_threshold_pct(s: &str) -> Result<u8, String> {
    parse_byte_or_percent(s.trim())
}

/// Parse `-vignette R[+S][+X[+Y]]`.
///
/// Mirrors IM's `-vignette geometry`-style argument. `R+S` are the
/// Gaussian radius and sigma in pixels; `S` defaults to `R / 2.0` when
/// omitted (matching IM and our `-blur RxS` convention). `+X+Y` are the
/// **normalised** image-relative centre offsets in `[0.0, 1.0]`
/// (default `0.5 / 0.5` = image centre). IM's `-vignette R+S+X+Y` uses
/// pixel offsets for `X+Y`, but the image-filter `Vignette` factory is
/// resolution-independent and takes them normalised; document the
/// difference here. To target the centre — by far the common case —
/// pass just `R` (e.g. `-vignette 50`).
fn parse_vignette(s: &str) -> Result<(f32, f32, f32, f32), String> {
    let mut parts = s.split('+');
    let r_str = parts
        .next()
        .ok_or_else(|| format!("'{s}' is missing the radius component"))?;
    let radius: f32 = r_str
        .parse()
        .map_err(|_| format!("'{r_str}' is not a finite float radius"))?;
    if !radius.is_finite() || radius < 0.0 {
        return Err(format!("radius {radius} must be >= 0"));
    }
    let s_part = parts.next();
    let sigma: f32 = match s_part {
        Some(t) if !t.is_empty() => t
            .parse()
            .map_err(|_| format!("'{t}' is not a finite float sigma"))?,
        _ => radius / 2.0,
    };
    if !sigma.is_finite() || sigma < 0.0 {
        return Err(format!("sigma {sigma} must be >= 0"));
    }
    let x: f32 = match parts.next() {
        Some(t) if !t.is_empty() => t
            .parse()
            .map_err(|_| format!("'{t}' is not a finite float x"))?,
        _ => 0.5,
    };
    let y: f32 = match parts.next() {
        Some(t) if !t.is_empty() => t
            .parse()
            .map_err(|_| format!("'{t}' is not a finite float y"))?,
        _ => 0.5,
    };
    if parts.next().is_some() {
        return Err(format!("'{s}' has more than 4 components"));
    }
    if !x.is_finite() || !y.is_finite() {
        return Err(format!("x/y must be finite (got x={x}, y={y})"));
    }
    Ok((radius, sigma, x, y))
}

/// Parse `-colorize C[xC[xC]]/A%`.
///
/// The colour part `C[xC[xC]]` accepts the same grammar as
/// [`parse_color`] — CSS L3 named colours and `#hex` 3/4/6/8 forms —
/// PLUS the IM-style `R[xG[xB]]` per-channel byte triplet. When only
/// `/A%` is given (no colour part), the target defaults to white. The
/// `A%` portion is a percentage in `[0%..=100%]`; we accept either
/// `N%` or a unit scalar `0.0..=1.0`.
fn parse_colorize(s: &str) -> Result<([u8; 4], f32), String> {
    let s = s.trim();
    let (color_part, amount_part) = match s.split_once('/') {
        Some((c, a)) => (c, a),
        // No `/A%` — interpret the whole string as the amount, with a
        // white default colour. IM's rare "single-arg" form.
        None => ("", s),
    };
    let color = if color_part.is_empty() {
        [255, 255, 255, 255]
    } else if color_part.contains('x') || color_part.contains('X') {
        // R[xG[xB]] per-channel byte triplet.
        let mut parts = color_part.split(['x', 'X']);
        let r_str = parts
            .next()
            .ok_or_else(|| format!("'{color_part}' is missing the R component"))?;
        let r: u32 = r_str
            .parse()
            .map_err(|_| format!("'{r_str}' is not a non-negative integer"))?;
        if r > 255 {
            return Err(format!("R component {r} out of range (0..=255)"));
        }
        let g: u32 = match parts.next() {
            Some(t) if !t.is_empty() => t
                .parse()
                .map_err(|_| format!("'{t}' is not a non-negative integer"))?,
            _ => r,
        };
        if g > 255 {
            return Err(format!("G component {g} out of range (0..=255)"));
        }
        let b: u32 = match parts.next() {
            Some(t) if !t.is_empty() => t
                .parse()
                .map_err(|_| format!("'{t}' is not a non-negative integer"))?,
            _ => g,
        };
        if b > 255 {
            return Err(format!("B component {b} out of range (0..=255)"));
        }
        if parts.next().is_some() {
            return Err(format!(
                "'{color_part}' has more than 3 components (expected R[xG[xB]])"
            ));
        }
        [r as u8, g as u8, b as u8, 255]
    } else {
        // CSS named / `#hex`.
        parse_color(color_part)?
    };
    let amount = parse_percent_or_unit(amount_part)?;
    Ok((color, amount))
}

#[cfg(test)]
mod tests {
    use super::*;

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

    #[test]
    fn minimal_input_output() {
        let p = parse(&to_vec(&["in.png", "out.jpg"])).unwrap();
        assert_eq!(p.input, "in.png");
        assert_eq!(p.output, "out.jpg");
        assert!(p.ops.is_empty());
    }

    #[test]
    fn resize_bilinear_basic() {
        let p = parse(&to_vec(&["a.png", "-resize", "800x600", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 800,
                height: 600,
                mode: ResizeMode::Default,
            }]
        );
    }

    #[test]
    fn resize_bang_flag() {
        let p = parse(&to_vec(&["a.png", "-resize", "64x32!", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 64,
                height: 32,
                mode: ResizeMode::Force,
            }]
        );
    }

    #[test]
    fn resize_fill_caret_suffix() {
        let p = parse(&to_vec(&["a.png", "-resize", "200x100^", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 200,
                height: 100,
                mode: ResizeMode::Fill,
            }]
        );
    }

    #[test]
    fn resize_shrink_only_suffix() {
        let p = parse(&to_vec(&["a.png", "-resize", "100x100>", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 100,
                height: 100,
                mode: ResizeMode::Shrink,
            }]
        );
    }

    #[test]
    fn resize_grow_only_suffix() {
        let p = parse(&to_vec(&["a.png", "-resize", "1024x1024<", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 1024,
                height: 1024,
                mode: ResizeMode::Grow,
            }]
        );
    }

    #[test]
    fn resize_percent_two_axis() {
        let p = parse(&to_vec(&["a.png", "-resize", "50x200%", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 50,
                height: 200,
                mode: ResizeMode::Percent,
            }]
        );
    }

    #[test]
    fn resize_percent_single_value_replicates() {
        // IM lets a bare `N%` mean "N percent on both axes"; we follow.
        let p = parse(&to_vec(&["a.png", "-resize", "75%", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 75,
                height: 75,
                mode: ResizeMode::Percent,
            }]
        );
    }

    #[test]
    fn resize_area_at_suffix() {
        let p = parse(&to_vec(&["a.png", "-resize", "640x480@", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Resize {
                width: 640,
                height: 480,
                mode: ResizeMode::Area,
            }]
        );
    }

    #[test]
    fn thumbnail_with_geometry_modifier() {
        let p = parse(&to_vec(&["a.png", "-thumbnail", "128x128^", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Thumbnail {
                width: 128,
                height: 128,
                mode: ResizeMode::Fill,
            }]
        );
    }

    #[test]
    fn thumbnail_default_mode() {
        let p = parse(&to_vec(&["a.png", "-thumbnail", "100x100", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Thumbnail {
                width: 100,
                height: 100,
                mode: ResizeMode::Default,
            }]
        );
    }

    #[test]
    fn define_with_value_round_trips_namespaced_key() {
        let p = parse(&to_vec(&[
            "a.png",
            "-define",
            "jpeg:dct-method=float",
            "b.jpg",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Define {
                key: "jpeg:dct-method".into(),
                value: Some("float".into()),
            }]
        );
    }

    #[test]
    fn define_bare_key_no_value() {
        // `-define KEY` (no `=VALUE`) sets the flag-style key to JSON true.
        let p = parse(&to_vec(&[
            "a.png",
            "-define",
            "png:strip-comments",
            "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Define {
                key: "png:strip-comments".into(),
                value: None,
            }]
        );
    }

    #[test]
    fn define_empty_key_rejected() {
        let err = parse(&to_vec(&["a.png", "-define", "=value", "b.png"])).unwrap_err();
        assert!(
            format!("{err:?}").contains("empty KEY"),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn blur_sigma_defaults_to_half_radius() {
        let p = parse(&to_vec(&["a.png", "-blur", "4", "b.jpg"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Blur {
                radius: 4,
                sigma: 2.0
            }]
        );
    }

    #[test]
    fn blur_explicit_sigma() {
        let p = parse(&to_vec(&["a.png", "-blur", "3x1.5", "b.jpg"])).unwrap();
        match p.ops.as_slice() {
            [Op::Blur { radius: 3, sigma }] => assert!((sigma - 1.5).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colors_picks_up_prior_dither() {
        let p = parse(&to_vec(&[
            "a.png",
            "-dither",
            "floyd_steinberg",
            "-colors",
            "64",
            "b.gif",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Colors {
                count: 64,
                dither: Dither::FloydSteinberg
            }]
        );
    }

    // ---- -monochrome ----

    /// `-monochrome` expands to the canonical IM chain `-colorspace
    /// gray -colors 2 -dither floyd_steinberg` so existing IM scripts
    /// (`convert in.png -monochrome out.png`) lower to the same op
    /// records the parser would have produced for the explicit form.
    /// We pin both the count and the ORDER (grayscale must come first
    /// so the 2-entry palette lands on black + white rather than two
    /// arbitrary colour samples).
    #[test]
    fn monochrome_expands_to_gray_2_colors_floyd_steinberg() {
        let p = parse(&to_vec(&["a.png", "-monochrome", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::Colorspace("gray".to_string()),
                Op::Colors {
                    count: 2,
                    dither: Dither::FloydSteinberg
                },
            ]
        );
    }

    /// `-monochrome` takes no value — the next positional after it
    /// must be the output filename. Verifies the valueless-flag wiring
    /// (no consumption of the input file as a "value").
    #[test]
    fn monochrome_is_valueless() {
        let p = parse(&to_vec(&["a.png", "-monochrome", "b.png"])).unwrap();
        assert_eq!(p.input, "a.png");
        assert_eq!(p.output, "b.png");
    }

    /// Source-order semantics: a `-dither none` placed BEFORE
    /// `-monochrome` does NOT bleed into the expansion — the flag
    /// always emits its own `FloydSteinberg` choice. This pins the
    /// "monochrome is a self-contained shorthand" contract; users who
    /// want `-dither none` semantics write the chain by hand.
    #[test]
    fn monochrome_ignores_prior_pending_dither() {
        let p = parse(&to_vec(&[
            "a.png",
            "-dither",
            "none",
            "-monochrome",
            "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::Colorspace("gray".to_string()),
                Op::Colors {
                    count: 2,
                    dither: Dither::FloydSteinberg
                },
            ]
        );
    }

    /// `-monochrome` is composable with other ops in source order:
    /// upstream ops keep their record, the two expanded entries appear
    /// at the position where `-monochrome` was given, and downstream
    /// ops follow. Catches a regression where someone might be tempted
    /// to push the expanded ops at the front of the vec.
    #[test]
    fn monochrome_keeps_source_order_with_neighbours() {
        let p = parse(&to_vec(&[
            "a.png",
            "-resize",
            "100x100",
            "-monochrome",
            "-strip",
            "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::Resize {
                    width: 100,
                    height: 100,
                    mode: ResizeMode::Default,
                },
                Op::Colorspace("gray".to_string()),
                Op::Colors {
                    count: 2,
                    dither: Dither::FloydSteinberg
                },
                Op::Strip,
            ]
        );
    }

    #[test]
    fn rotate_90_parses() {
        let p = parse(&to_vec(&["a.png", "-rotate", "90", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Rotate { degrees: 90 }]);
    }

    #[test]
    fn rotate_negative_270_parses() {
        let p = parse(&to_vec(&["a.png", "-rotate", "-270", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Rotate { degrees: -270 }]);
    }

    #[test]
    fn rotate_45_rejected() {
        let err = parse(&to_vec(&["a.png", "-rotate", "45", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("only multiples of 90 supported"),
            "unexpected message: {msg}"
        );
        assert!(msg.contains("got 45"));
    }

    #[test]
    fn rotate_non_integer_rejected() {
        let err = parse(&to_vec(&["a.png", "-rotate", "abc", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("not an integer"));
    }

    #[test]
    fn flip_and_flop_are_valueless() {
        let p = parse(&to_vec(&["a.png", "-flip", "-flop", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Flip, Op::Flop]);
    }

    #[test]
    fn negate_is_valueless() {
        let p = parse(&to_vec(&["a.png", "-negate", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Negate]);
    }

    #[test]
    fn crop_basic() {
        let p = parse(&to_vec(&["a.png", "-crop", "10x20+3+4", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Crop {
                x: 3,
                y: 4,
                w: 10,
                h: 20
            }]
        );
    }

    #[test]
    fn crop_zero_offset() {
        let p = parse(&to_vec(&["a.png", "-crop", "32x32+0+0", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Crop {
                x: 0,
                y: 0,
                w: 32,
                h: 32
            }]
        );
    }

    #[test]
    fn crop_missing_offset_rejected() {
        let err = parse(&to_vec(&["a.png", "-crop", "32x32", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("missing the +X offset"));
    }

    #[test]
    fn crop_im_modifier_rejected() {
        let err = parse(&to_vec(&["a.png", "-crop", "50%+0+0", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("IM modifier"));
    }

    // ---- -extent ----
    //
    // Default canvas (no offset section) → `(0, 0)` offsets and the
    // IM-default opaque white background (alpha 255) because no
    // `-background` was set.
    #[test]
    fn extent_default_offset_and_background() {
        let p = parse(&to_vec(&["a.png", "-extent", "100x80", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Extent {
                width: 100,
                height: 80,
                x: 0,
                y: 0,
                bg: [255, 255, 255, 255],
            }]
        );
    }

    // `WxH+X+Y` lands as positive signed offsets — basic case.
    #[test]
    fn extent_positive_offsets() {
        let p = parse(&to_vec(&["a.png", "-extent", "120x90+10+5", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Extent {
                width: 120,
                height: 90,
                x: 10,
                y: 5,
                bg: _,
            }] => {}
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    // `WxH-X-Y` lands as negative signed offsets — exercises the
    // IM convention of translating the source toward the upper-left.
    #[test]
    fn extent_negative_offsets() {
        let p = parse(&to_vec(&["a.png", "-extent", "200x150-25-30", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Extent {
                width: 200,
                height: 150,
                x: -25,
                y: -30,
                bg: _,
            }] => {}
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    // Mixed signs `WxH+X-Y` / `WxH-X+Y` ride through unchanged — IM
    // accepts every combination.
    #[test]
    fn extent_mixed_signs() {
        let p = parse(&to_vec(&["a.png", "-extent", "64x64+10-5", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Extent {
                width: 64,
                height: 64,
                x: 10,
                y: -5,
                bg: _,
            }] => {}
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    // A `-background` op preceding `-extent` is captured into the
    // resulting `Op::Extent.bg` so the plan walker stays stateless.
    #[test]
    fn extent_picks_up_prior_background() {
        let p = parse(&to_vec(&[
            "a.png",
            "-background",
            "red",
            "-extent",
            "50x50",
            "b.png",
        ]))
        .unwrap();
        // Two ops emitted: the explicit Background, then Extent
        // carrying the captured colour.
        assert_eq!(p.ops.len(), 2);
        assert!(matches!(p.ops[0], Op::Background([255, 0, 0, 255])));
        match &p.ops[1] {
            Op::Extent { bg, .. } => assert_eq!(*bg, [255, 0, 0, 255]),
            other => panic!("expected Extent, got {other:?}"),
        }
    }

    // A `-background` AFTER the `-extent` must NOT retroactively
    // change the captured padding colour — source order matters.
    #[test]
    fn extent_ignores_subsequent_background() {
        let p = parse(&to_vec(&[
            "a.png",
            "-extent",
            "50x50",
            "-background",
            "red",
            "b.png",
        ]))
        .unwrap();
        // First Op is Extent with the IM-default white.
        match &p.ops[0] {
            Op::Extent { bg, .. } => assert_eq!(*bg, [255, 255, 255, 255]),
            other => panic!("expected Extent, got {other:?}"),
        }
    }

    // A second `-extent` after a different `-background` picks up
    // the new colour while the earlier Extent retains the original.
    #[test]
    fn extent_two_calls_capture_independent_backgrounds() {
        let p = parse(&to_vec(&[
            "a.png",
            "-background",
            "red",
            "-extent",
            "50x50",
            "-background",
            "blue",
            "-extent",
            "60x60",
            "b.png",
        ]))
        .unwrap();
        let extents: Vec<&Op> = p
            .ops
            .iter()
            .filter(|o| matches!(o, Op::Extent { .. }))
            .collect();
        assert_eq!(extents.len(), 2);
        match extents[0] {
            Op::Extent { width: 50, bg, .. } => assert_eq!(*bg, [255, 0, 0, 255]),
            other => panic!("unexpected first extent: {other:?}"),
        }
        match extents[1] {
            Op::Extent { width: 60, bg, .. } => assert_eq!(*bg, [0, 0, 255, 255]),
            other => panic!("unexpected second extent: {other:?}"),
        }
    }

    // Single-offset `WxH+X` is rejected with a clear message rather
    // than silently treating it as `WxH+X+0`.
    #[test]
    fn extent_single_offset_rejected() {
        let err = parse(&to_vec(&["a.png", "-extent", "64x64+10", "b.png"])).unwrap_err();
        assert!(
            format!("{err:?}").contains("single offset"),
            "unexpected error: {err:?}"
        );
    }

    // Geometry modifiers (`%`, `!`, `^`, `<`, `>`, `@`) are rejected
    // identically to `-crop`.
    #[test]
    fn extent_im_modifier_rejected() {
        let err = parse(&to_vec(&["a.png", "-extent", "50%+0+0", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("IM modifier"));
    }

    #[test]
    fn sharpen_basic() {
        let p = parse(&to_vec(&["a.png", "-sharpen", "1x0.5", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Sharpen { radius: 1, sigma }] => assert!((sigma - 0.5).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn sharpen_radius_only_defaults_sigma() {
        let p = parse(&to_vec(&["a.png", "-sharpen", "4", "b.png"])).unwrap();
        // Sigma defaults to radius/2 (matches IM and parse_blur).
        assert_eq!(
            p.ops,
            vec![Op::Sharpen {
                radius: 4,
                sigma: 2.0
            }]
        );
    }

    #[test]
    fn unsharp_full_grammar() {
        let p = parse(&to_vec(&["a.png", "-unsharp", "2x1.5+0.8+5", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Unsharp {
                radius: 2,
                sigma,
                amount,
                threshold: 5,
            }] => {
                assert!((sigma - 1.5).abs() < 1e-6);
                assert!((amount - 0.8).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn unsharp_partial_defaults() {
        let p = parse(&to_vec(&["a.png", "-unsharp", "3", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Unsharp {
                radius: 3,
                sigma,
                amount,
                threshold: 0,
            }] => {
                assert!((sigma - 1.5).abs() < 1e-6, "sigma = {sigma}");
                assert!((amount - 1.0).abs() < 1e-6, "amount = {amount}");
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn gamma_basic() {
        let p = parse(&to_vec(&["a.png", "-gamma", "1.8", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Gamma { value }] => assert!((value - 1.8).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn gamma_zero_rejected() {
        let err = parse(&to_vec(&["a.png", "-gamma", "0", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("must be > 0"));
    }

    #[test]
    fn gamma_negative_rejected() {
        let err = parse(&to_vec(&["a.png", "-gamma", "-1.5", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("must be > 0"));
    }

    #[test]
    fn brightness_contrast_basic_comma() {
        let p = parse(&to_vec(&["a.png", "-brightness-contrast", "10,5", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::BrightnessContrast {
                brightness: 10.0,
                contrast: 5.0
            }]
        );
    }

    #[test]
    fn brightness_contrast_basic_x_separator() {
        let p = parse(&to_vec(&[
            "a.png",
            "-brightness-contrast",
            "20x-15",
            "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![Op::BrightnessContrast {
                brightness: 20.0,
                contrast: -15.0
            }]
        );
    }

    #[test]
    fn brightness_contrast_brightness_only() {
        let p = parse(&to_vec(&["a.png", "-brightness-contrast", "30", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::BrightnessContrast {
                brightness: 30.0,
                contrast: 0.0
            }]
        );
    }

    #[test]
    fn brightness_contrast_out_of_range_rejected() {
        let err = parse(&to_vec(&[
            "a.png",
            "-brightness-contrast",
            "150,0",
            "b.png",
        ]))
        .unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    #[test]
    fn contrast_step_default_one() {
        let p = parse(&to_vec(&["a.png", "-contrast", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Contrast { delta: 1 }]);
    }

    #[test]
    fn contrast_repeated_accumulates_via_chain() {
        // IM accumulates `-contrast` across repeated flags. We capture
        // each as a separate Op; the executor sums them.
        let p = parse(&to_vec(&["a.png", "-contrast", "-contrast", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Contrast { delta: 1 }, Op::Contrast { delta: 1 }]
        );
    }

    #[test]
    fn sepia_percent_form() {
        let p = parse(&to_vec(&["a.png", "-sepia", "80%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Sepia { threshold }] => assert!((threshold - 0.8).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn sepia_unit_form() {
        let p = parse(&to_vec(&["a.png", "-sepia", "0.5", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Sepia { threshold }] => assert!((threshold - 0.5).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn modulate_full_triplet() {
        let p = parse(&to_vec(&["a.png", "-modulate", "120,80,150", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Modulate {
                brightness: 120.0,
                saturation: 80.0,
                hue: 150.0,
            }]
        );
    }

    #[test]
    fn modulate_brightness_only_defaults_other_components() {
        let p = parse(&to_vec(&["a.png", "-modulate", "150", "b.png"])).unwrap();
        assert_eq!(
            p.ops,
            vec![Op::Modulate {
                brightness: 150.0,
                saturation: 100.0,
                hue: 100.0,
            }]
        );
    }

    #[test]
    fn level_full_triplet() {
        let p = parse(&to_vec(&["a.png", "-level", "10/1.2/250", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Level {
                black: 10,
                gamma,
                white: 250,
            }] => assert!((gamma - 1.2).abs() < 1e-6),
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn level_percent_endpoints() {
        let p = parse(&to_vec(&["a.png", "-level", "10%/1.0/90%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Level {
                black,
                gamma: _,
                white,
            }] => {
                // 10% of 255 ≈ 26; 90% ≈ 230.
                assert_eq!(*black, 26);
                assert_eq!(*white, 230);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn level_inverted_endpoints_rejected() {
        let err = parse(&to_vec(&["a.png", "-level", "200/1.0/100", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("must be <="));
    }

    #[test]
    fn normalize_is_valueless() {
        let p = parse(&to_vec(&["a.png", "-normalize", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Normalize]);
    }

    #[test]
    fn threshold_percent() {
        let p = parse(&to_vec(&["a.png", "-threshold", "50%", "b.png"])).unwrap();
        // 50% of 255 ≈ 128.
        assert_eq!(p.ops, vec![Op::Threshold { value: 128 }]);
    }

    #[test]
    fn threshold_byte() {
        let p = parse(&to_vec(&["a.png", "-threshold", "200", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Threshold { value: 200 }]);
    }

    #[test]
    fn posterize_basic() {
        let p = parse(&to_vec(&["a.png", "-posterize", "4", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Posterize { levels: 4 }]);
    }

    #[test]
    fn posterize_one_rejected() {
        let err = parse(&to_vec(&["a.png", "-posterize", "1", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("levels must be >= 2"));
    }

    #[test]
    fn solarize_percent() {
        let p = parse(&to_vec(&["a.png", "-solarize", "100", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Solarize { value: 100 }]);
    }

    #[test]
    fn colorspace_gray_recognised() {
        let p = parse(&to_vec(&["a.png", "-colorspace", "Gray", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Colorspace("Gray".into())]);
    }

    #[test]
    fn colorspace_rgb_recognised() {
        let p = parse(&to_vec(&["a.png", "-colorspace", "rgb", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Colorspace("rgb".into())]);
    }

    #[test]
    fn colorspace_unsupported_rejected() {
        let err = parse(&to_vec(&["a.png", "-colorspace", "CMYK", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("not yet wired"));
    }

    #[test]
    fn unknown_flag_errors() {
        let err = parse(&to_vec(&["a.png", "-fnord", "42", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("unknown flag"));
        // `-fnord` isn't close enough to any known flag — no hint clause.
        assert!(
            !msg.contains("did you mean"),
            "distant token should not get a hint, got: {msg}"
        );
    }

    #[test]
    fn unknown_flag_typo_suggests_close_match() {
        // Single-letter transposition of `-quality`.
        let err = parse(&to_vec(&["a.png", "-quailty", "90", "b.jpg"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("unknown flag"), "got: {msg}");
        assert!(
            msg.contains("did you mean '-quality'?"),
            "expected quality suggestion, got: {msg}"
        );
    }

    #[test]
    fn unknown_flag_typo_preserves_single_vs_double_dash() {
        // `--prbe` is a 1-edit miss of `--probe`. The suggestion must
        // reattach the same `--` lead the user typed, not a single dash.
        let err = parse(&to_vec(&["--prbe", "in.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("unknown flag"), "got: {msg}");
        assert!(
            msg.contains("did you mean '--probe'?"),
            "expected --probe suggestion with two dashes, got: {msg}"
        );
    }

    #[test]
    fn unknown_flag_typo_resize_transposition() {
        let err = parse(&to_vec(&["a.png", "-reszie", "100x100", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("did you mean '-resize'?"),
            "expected resize suggestion, got: {msg}"
        );
    }

    #[test]
    fn missing_output_errors() {
        let err = parse(&to_vec(&["in.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("no output file given"));
    }

    #[test]
    fn quality_strip() {
        let p = parse(&to_vec(&["a.png", "-quality", "85", "-strip", "b.jpg"])).unwrap();
        assert_eq!(p.ops, vec![Op::Quality(85), Op::Strip]);
    }

    #[test]
    fn quality_zero_and_hundred_accepted() {
        // Endpoints stay accepted: 0 is JPEG's "smallest acceptable",
        // 100 is "highest"; both round-trip through the parser.
        let p0 = parse(&to_vec(&["a.png", "-quality", "0", "b.jpg"])).unwrap();
        assert_eq!(p0.ops, vec![Op::Quality(0)]);
        let p100 = parse(&to_vec(&["a.png", "-quality", "100", "b.jpg"])).unwrap();
        assert_eq!(p100.ops, vec![Op::Quality(100)]);
    }

    #[test]
    fn quality_out_of_range_rejected() {
        // The common typo case (1000 instead of 100); without this
        // guard the encoder silently dropped the over-range value.
        let err = parse(&to_vec(&["a.png", "-quality", "1000", "b.jpg"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("-quality") && msg.contains("out of range"),
            "got: {msg}"
        );
        assert!(
            msg.contains("0..=100"),
            "must point at the legal range; got: {msg}"
        );
        // And the tame just-over-100 case (150 instead of 100):
        let err = parse(&to_vec(&["a.png", "-quality", "150", "b.jpg"])).unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    #[test]
    fn quality_non_numeric_rejected() {
        // Negative integers + non-numeric strings still hit the
        // pre-cap parse-error branch with the existing message.
        let err = parse(&to_vec(&["a.png", "-quality", "-5", "b.jpg"])).unwrap_err();
        assert!(format!("{err:?}").contains("not a non-negative integer"));
        let err = parse(&to_vec(&["a.png", "-quality", "high", "b.jpg"])).unwrap_err();
        assert!(format!("{err:?}").contains("not a non-negative integer"));
    }

    #[test]
    fn density_background_alpha_chain() {
        let p = parse(&to_vec(&[
            "in.pdf",
            "-density",
            "300",
            "-background",
            "white",
            "-alpha",
            "remove",
            "-alpha",
            "off",
            "page-%03d.png",
        ]))
        .unwrap();
        assert_eq!(p.input, "in.pdf");
        assert_eq!(p.output, "page-%03d.png");
        assert_eq!(
            p.ops,
            vec![
                Op::Density(300),
                Op::Background([255, 255, 255, 255]),
                Op::Alpha(AlphaOp::Remove),
                Op::Alpha(AlphaOp::Off),
            ]
        );
    }

    #[test]
    fn density_zero_rejected() {
        let err = parse(&to_vec(&["a.png", "-density", "0", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("-density must be > 0"));
    }

    #[test]
    fn alpha_unknown_subcommand_rejected() {
        let err = parse(&to_vec(&["a.png", "-alpha", "fnord", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("unknown subcommand"));
    }

    #[test]
    fn background_hex_color() {
        let p = parse(&to_vec(&["a.png", "-background", "#ff8000", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Background([255, 128, 0, 255])]);
    }

    #[test]
    fn background_hex_with_alpha() {
        let p = parse(&to_vec(&["a.png", "-background", "#80808040", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Background([128, 128, 128, 64])]);
    }

    #[test]
    fn printf_template_zero_padded() {
        let t = parse_printf_template("page-%03d.png").unwrap().unwrap();
        assert_eq!(t.prefix, "page-");
        assert_eq!(t.width, 3);
        assert_eq!(t.suffix, ".png");
    }

    #[test]
    fn printf_template_unpadded() {
        let t = parse_printf_template("out%d.jpg").unwrap().unwrap();
        assert_eq!(t.prefix, "out");
        assert_eq!(t.width, 0);
        assert_eq!(t.suffix, ".jpg");
    }

    #[test]
    fn printf_template_absent_returns_none() {
        assert!(parse_printf_template("out.png").unwrap().is_none());
        assert!(parse_printf_template("/some/dir/out.jpg")
            .unwrap()
            .is_none());
    }

    #[test]
    fn printf_template_multiple_d_rejected() {
        let err = parse_printf_template("page-%d-frame-%d.png").unwrap_err();
        assert!(format!("{err:?}").contains("more than one"));
    }

    #[test]
    fn printf_template_unsupported_specifier_rejected() {
        let err = parse_printf_template("out-%s.png").unwrap_err();
        assert!(format!("{err:?}").contains("unsupported format specifier"));
    }

    #[test]
    fn parse_populates_output_template_when_present() {
        let p = parse(&to_vec(&["in.pdf", "page-%02d.png"])).unwrap();
        let t = p.output_template.unwrap();
        assert_eq!(t.prefix, "page-");
        assert_eq!(t.width, 2);
        assert_eq!(t.suffix, ".png");
    }

    #[test]
    fn parse_leaves_output_template_none_for_literal_path() {
        let p = parse(&to_vec(&["in.png", "out.jpg"])).unwrap();
        assert!(p.output_template.is_none());
    }

    #[test]
    fn ping_flag_off_by_default() {
        let p = parse(&to_vec(&["in.png", "out.jpg"])).unwrap();
        assert!(!p.ping);
    }

    #[test]
    fn ping_flag_set_when_present() {
        let p = parse(&to_vec(&["-ping", "in.png", "out.jpg"])).unwrap();
        assert!(p.ping);
    }

    #[test]
    fn ping_makes_output_optional() {
        let p = parse(&to_vec(&["-ping", "in.png"])).unwrap();
        assert!(p.ping);
        assert_eq!(p.output, "");
        assert!(p.output_template.is_none());
    }

    #[test]
    fn missing_output_without_ping_still_errors() {
        let err = parse(&to_vec(&["in.png"])).unwrap_err();
        // Should be Invalid, not Unsupported.
        assert!(format!("{err:?}").contains("no output file"));
    }

    #[test]
    fn input_selector_single_page() {
        let (path, sel) = split_input_selector("input.pdf[0]").unwrap();
        assert_eq!(path, "input.pdf");
        assert_eq!(sel, Some(PageSelector::Single(0)));
    }

    #[test]
    fn input_selector_range() {
        let (path, sel) = split_input_selector("foo.pdf[2-5]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(sel, Some(PageSelector::Range(2, 5)));
    }

    #[test]
    fn input_selector_absent_passes_through() {
        let (path, sel) = split_input_selector("plain.pdf").unwrap();
        assert_eq!(path, "plain.pdf");
        assert_eq!(sel, None);
    }

    #[test]
    fn input_selector_empty_brackets_rejected() {
        assert!(split_input_selector("foo.pdf[]").is_err());
    }

    #[test]
    fn input_selector_non_numeric_rejected() {
        assert!(split_input_selector("foo.pdf[abc]").is_err());
        assert!(split_input_selector("foo.pdf[1-x]").is_err());
    }

    #[test]
    fn input_selector_extra_dash_rejected() {
        assert!(split_input_selector("foo.pdf[1-2-3]").is_err());
    }

    #[test]
    fn parse_pulls_selector_into_input_pages() {
        let p = parse(&to_vec(&["in.pdf[0]", "out.png"])).unwrap();
        assert_eq!(p.input, "in.pdf");
        assert_eq!(p.input_pages, Some(PageSelector::Single(0)));
    }

    #[test]
    fn parse_pulls_range_selector_into_input_pages() {
        let p = parse(&to_vec(&["in.pdf[2-4]", "page-%02d.png"])).unwrap();
        assert_eq!(p.input, "in.pdf");
        assert_eq!(p.input_pages, Some(PageSelector::Range(2, 4)));
        assert!(p.output_template.is_some());
    }

    // ---- Round-after-next: comma-separated and negative page indices ----

    #[test]
    fn input_selector_negative_index_parses() {
        let (path, sel) = split_input_selector("foo.pdf[-1]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(sel, Some(PageSelector::Single(-1)));
    }

    #[test]
    fn input_selector_negative_range_endpoint_parses() {
        // `5--1` = page 5 through the last page.
        let (path, sel) = split_input_selector("foo.pdf[5--1]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(sel, Some(PageSelector::Range(5, -1)));
    }

    #[test]
    fn input_selector_negative_range_both_endpoints() {
        // `-3--1` = last three pages.
        let (path, sel) = split_input_selector("foo.pdf[-3--1]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(sel, Some(PageSelector::Range(-3, -1)));
    }

    #[test]
    fn input_selector_comma_list_of_singles() {
        let (path, sel) = split_input_selector("foo.pdf[0,2,4]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(
            sel,
            Some(PageSelector::List(vec![
                PageAtom::Single(0),
                PageAtom::Single(2),
                PageAtom::Single(4),
            ]))
        );
    }

    #[test]
    fn input_selector_comma_list_with_ranges_and_negatives() {
        // `0-2,5,-1` = "pages 0..=2, plus 5, plus the last page".
        let (path, sel) = split_input_selector("foo.pdf[0-2,5,-1]").unwrap();
        assert_eq!(path, "foo.pdf");
        assert_eq!(
            sel,
            Some(PageSelector::List(vec![
                PageAtom::Range(0, 2),
                PageAtom::Single(5),
                PageAtom::Single(-1),
            ]))
        );
    }

    #[test]
    fn input_selector_single_atom_list_collapses_to_single_variant() {
        // A list with exactly one atom collapses to the single-atom
        // variant — most callers only ever inspect Single/Range.
        let (_, sel) = split_input_selector("foo.pdf[3]").unwrap();
        assert!(matches!(sel, Some(PageSelector::Single(3))));
    }

    #[test]
    fn input_selector_empty_atom_in_list_rejected() {
        assert!(split_input_selector("foo.pdf[0,,1]").is_err());
        assert!(split_input_selector("foo.pdf[,0]").is_err());
        assert!(split_input_selector("foo.pdf[0,]").is_err());
    }

    #[test]
    fn input_selector_bare_dash_rejected() {
        assert!(split_input_selector("foo.pdf[-]").is_err());
    }

    #[test]
    fn page_selector_negative_single_resolves_to_last_page() {
        let s = PageSelector::Single(-1);
        assert_eq!(s.resolve(5).unwrap(), vec![4]);
        let s = PageSelector::Single(-2);
        assert_eq!(s.resolve(5).unwrap(), vec![3]);
        // Negative index out of range.
        assert!(PageSelector::Single(-6).resolve(5).is_err());
    }

    #[test]
    fn page_selector_negative_range_endpoint_resolves() {
        // `5--1` against 8 pages → 5..=7.
        let s = PageSelector::Range(5, -1);
        assert_eq!(s.resolve(8).unwrap(), vec![5, 6, 7]);
        // `-3--1` against 8 pages → 5..=7 (last three).
        let s = PageSelector::Range(-3, -1);
        assert_eq!(s.resolve(8).unwrap(), vec![5, 6, 7]);
    }

    #[test]
    fn page_selector_list_resolves_in_source_order() {
        let s = PageSelector::List(vec![
            PageAtom::Single(0),
            PageAtom::Single(2),
            PageAtom::Range(4, 5),
            PageAtom::Single(-1),
        ]);
        assert_eq!(s.resolve(8).unwrap(), vec![0, 2, 4, 5, 7]);
    }

    #[test]
    fn page_selector_list_preserves_duplicates() {
        // IM convention: `[0,0,0]` writes the same page three times.
        let s = PageSelector::List(vec![
            PageAtom::Single(0),
            PageAtom::Single(0),
            PageAtom::Single(0),
        ]);
        assert_eq!(s.resolve(3).unwrap(), vec![0, 0, 0]);
    }

    #[test]
    fn page_selector_list_propagates_out_of_range() {
        let s = PageSelector::List(vec![PageAtom::Single(0), PageAtom::Single(99)]);
        assert!(s.resolve(3).is_err());
    }

    // ---- Round-after-next: -vignette / -colorize / -equalize / -auto-gamma ----

    #[test]
    fn vignette_radius_only_defaults_sigma_and_centre() {
        let p = parse(&to_vec(&["a.png", "-vignette", "50", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Vignette {
                radius,
                sigma,
                x,
                y,
            }] => {
                assert!((radius - 50.0).abs() < 1e-6);
                // Sigma defaults to radius / 2.
                assert!((sigma - 25.0).abs() < 1e-6);
                // X/Y default to image centre (0.5, 0.5).
                assert!((x - 0.5).abs() < 1e-6);
                assert!((y - 0.5).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn vignette_radius_and_sigma() {
        let p = parse(&to_vec(&["a.png", "-vignette", "50+10", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Vignette {
                radius,
                sigma,
                x,
                y,
            }] => {
                assert!((radius - 50.0).abs() < 1e-6);
                assert!((sigma - 10.0).abs() < 1e-6);
                assert!((x - 0.5).abs() < 1e-6);
                assert!((y - 0.5).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn vignette_full_grammar_with_xy() {
        let p = parse(&to_vec(&["a.png", "-vignette", "50+10+0.25+0.75", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Vignette {
                radius,
                sigma,
                x,
                y,
            }] => {
                assert!((radius - 50.0).abs() < 1e-6);
                assert!((sigma - 10.0).abs() < 1e-6);
                assert!((x - 0.25).abs() < 1e-6);
                assert!((y - 0.75).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn vignette_too_many_components_rejected() {
        let err = parse(&to_vec(&["a.png", "-vignette", "1+2+3+4+5", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("more than 4"));
    }

    #[test]
    fn vignette_negative_radius_rejected() {
        let err = parse(&to_vec(&["a.png", "-vignette", "-5", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("not a finite float radius") || msg.contains("must be >= 0"));
    }

    #[test]
    fn colorize_named_color_with_percent_amount() {
        let p = parse(&to_vec(&["a.png", "-colorize", "red/40%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount }] => {
                assert_eq!(*color, [255, 0, 0, 255]);
                assert!((amount - 0.4).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_hex_color() {
        let p = parse(&to_vec(&["a.png", "-colorize", "#ff8000/50%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount }] => {
                assert_eq!(*color, [255, 128, 0, 255]);
                assert!((amount - 0.5).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_per_channel_triplet() {
        let p = parse(&to_vec(&["a.png", "-colorize", "200x100x50/25%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount }] => {
                assert_eq!(*color, [200, 100, 50, 255]);
                assert!((amount - 0.25).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_single_channel_replicated() {
        // `100/50%` → no `x`, but contains `/`. The colour is the
        // string before `/`; "100" lacks `x`, so we fall through to
        // parse_color which won't match (it's not named / hex). Test
        // that we get a clean error.
        let err = parse(&to_vec(&["a.png", "-colorize", "100/50%", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("unknown colour") || msg.contains("not a valid hex"));
    }

    #[test]
    fn colorize_per_channel_one_value_replicates() {
        // `100x` (or `100xx`) — single value means R = G = B = 100.
        let p = parse(&to_vec(&["a.png", "-colorize", "100x100x100/30%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount: _ }] => {
                assert_eq!(*color, [100, 100, 100, 255]);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_amount_only_defaults_white() {
        // `/40%` form — IM accepts it; default colour is white.
        let p = parse(&to_vec(&["a.png", "-colorize", "/40%", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount }] => {
                assert_eq!(*color, [255, 255, 255, 255]);
                assert!((amount - 0.4).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_amount_unit_scalar() {
        // Without `%`, parse_percent_or_unit accepts a unit scalar.
        let p = parse(&to_vec(&["a.png", "-colorize", "red/0.6", "b.png"])).unwrap();
        match p.ops.as_slice() {
            [Op::Colorize { color, amount }] => {
                assert_eq!(*color, [255, 0, 0, 255]);
                assert!((amount - 0.6).abs() < 1e-6);
            }
            other => panic!("unexpected ops: {other:?}"),
        }
    }

    #[test]
    fn colorize_out_of_range_channel_rejected() {
        let err = parse(&to_vec(&["a.png", "-colorize", "300x0x0/50%", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    #[test]
    fn equalize_is_valueless() {
        let p = parse(&to_vec(&["a.png", "-equalize", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Equalize]);
    }

    #[test]
    fn auto_gamma_is_valueless() {
        let p = parse(&to_vec(&["a.png", "-auto-gamma", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::AutoGamma]);
    }

    #[test]
    fn vignette_rejects_negative_sigma() {
        let err = parse(&to_vec(&["a.png", "-vignette", "5+-1", "b.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("not a finite float sigma") || msg.contains("must be >= 0"),
            "unexpected message: {msg}"
        );
    }

    // ---- Per-format encoder option flags (`-stl-format`,
    //      `-gltf-format`). End-to-end coverage lives in
    //      `tests/format_flags.rs`; the unit tests here only check
    //      that the parser populates `ConvertPlan::mesh3d_options`
    //      correctly and rejects malformed values up-front. ----

    #[test]
    fn stl_format_default_is_none() {
        let p = parse(&to_vec(&["in.stl", "out.stl"])).unwrap();
        assert!(p.mesh3d_options.stl_format.is_none());
        assert!(p.ops.is_empty(), "no -stl-format → no Op pushed");
    }

    #[test]
    fn stl_format_ascii_parses() {
        let p = parse(&to_vec(&["in.stl", "-stl-format", "ascii", "out.stl"])).unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Ascii));
    }

    #[test]
    fn stl_format_binary_parses() {
        let p = parse(&to_vec(&["in.stl", "-stl-format", "binary", "out.stl"])).unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Binary));
    }

    #[test]
    fn stl_format_aliases_parse() {
        // `bin` → Binary, `text` → Ascii.
        let p = parse(&to_vec(&["in.stl", "-stl-format", "bin", "out.stl"])).unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Binary));
        let p = parse(&to_vec(&["in.stl", "-stl-format", "text", "out.stl"])).unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Ascii));
    }

    #[test]
    fn stl_format_case_insensitive() {
        let p = parse(&to_vec(&["in.stl", "-stl-format", "ASCII", "out.stl"])).unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Ascii));
    }

    #[test]
    fn stl_format_unknown_value_rejected() {
        let err = parse(&to_vec(&["in.stl", "-stl-format", "xml", "out.stl"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("unknown flavour 'xml'") && msg.contains("expected 'binary'"),
            "unexpected message: {msg}"
        );
    }

    #[test]
    fn stl_format_missing_value_rejected() {
        let err = parse(&to_vec(&["in.stl", "-stl-format"])).unwrap_err();
        assert!(format!("{err:?}").contains("-stl-format: missing value"));
    }

    #[test]
    fn gltf_format_default_is_none() {
        let p = parse(&to_vec(&["in.stl", "out.gltf"])).unwrap();
        assert!(p.mesh3d_options.gltf_format.is_none());
    }

    #[test]
    fn gltf_format_glb_parses() {
        let p = parse(&to_vec(&["in.stl", "-gltf-format", "glb", "out.glb"])).unwrap();
        assert_eq!(p.mesh3d_options.gltf_format, Some(GltfFormatChoice::Glb));
    }

    #[test]
    fn gltf_format_embedded_parses() {
        let p = parse(&to_vec(&["in.stl", "-gltf-format", "embedded", "out.gltf"])).unwrap();
        assert_eq!(
            p.mesh3d_options.gltf_format,
            Some(GltfFormatChoice::JsonEmbedded)
        );
    }

    #[test]
    fn gltf_format_external_parses_even_though_runtime_rejects() {
        // The parser accepts the token; runtime emits the gltf-rN
        // follow-up message. Decouples the user-facing error from the
        // arg parser's "unknown flag" path.
        let p = parse(&to_vec(&["in.stl", "-gltf-format", "external", "out.gltf"])).unwrap();
        assert_eq!(
            p.mesh3d_options.gltf_format,
            Some(GltfFormatChoice::JsonExternal)
        );
    }

    #[test]
    fn gltf_format_aliases_parse() {
        // `binary` → Glb (matches IM-style synonym tolerance).
        let p = parse(&to_vec(&["in.stl", "-gltf-format", "binary", "out.glb"])).unwrap();
        assert_eq!(p.mesh3d_options.gltf_format, Some(GltfFormatChoice::Glb));
        // `json-embedded` → JsonEmbedded.
        let p = parse(&to_vec(&[
            "in.stl",
            "-gltf-format",
            "json-embedded",
            "out.gltf",
        ]))
        .unwrap();
        assert_eq!(
            p.mesh3d_options.gltf_format,
            Some(GltfFormatChoice::JsonEmbedded)
        );
    }

    #[test]
    fn gltf_format_unknown_value_rejected() {
        let err = parse(&to_vec(&["in.stl", "-gltf-format", "obj", "out.gltf"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("unknown flavour 'obj'") && msg.contains("expected 'glb'"),
            "unexpected message: {msg}"
        );
    }

    #[test]
    fn render_gouraud_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "gouraud", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::Gouraud)
        );
    }

    #[test]
    fn render_phong_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "phong", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.render_mode, Some(Mesh3DRenderMode::Phong));
    }

    #[test]
    fn render_wire_alias_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "wire", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::Wireframe)
        );
    }

    #[test]
    fn render_unknown_mode_rejected_lists_all_options() {
        let err = parse(&to_vec(&["in.stl", "-render", "raytrace", "out.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("unknown mode 'raytrace'")
                && msg.contains("'gouraud'")
                && msg.contains("'phong'"),
            "unexpected message: {msg}"
        );
    }

    #[test]
    fn light_parses_three_components() {
        let p = parse(&to_vec(&["in.stl", "-light", "30,45,1.5", "out.png"])).unwrap();
        let light = p.mesh3d_options.light.expect("-light should populate");
        assert_eq!(light.azimuth_deg, 30.0);
        assert_eq!(light.elevation_deg, 45.0);
        assert_eq!(light.intensity, 1.5);
    }

    #[test]
    fn light_rejects_negative_intensity() {
        let err = parse(&to_vec(&["in.stl", "-light", "0,0,-1", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("intensity"));
    }

    #[test]
    fn light_rejects_two_component_input() {
        let err = parse(&to_vec(&["in.stl", "-light", "30,45", "out.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("AZIMUTH,ELEVATION,INTENSITY"),
            "expected grammar hint, got: {msg}"
        );
    }

    #[test]
    fn camera_parses_three_components() {
        let p = parse(&to_vec(&["in.stl", "-camera", "20,30,2.0", "out.png"])).unwrap();
        let cam = p.mesh3d_options.camera.expect("-camera should populate");
        assert_eq!(cam.elevation_deg, 20.0);
        assert_eq!(cam.azimuth_deg, 30.0);
        assert_eq!(cam.distance, 2.0);
    }

    #[test]
    fn camera_rejects_zero_distance() {
        let err = parse(&to_vec(&["in.stl", "-camera", "0,0,0", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("distance"));
    }

    #[test]
    fn projection_orthographic_parses() {
        let p = parse(&to_vec(&[
            "in.stl",
            "-projection",
            "orthographic",
            "out.png",
        ]))
        .unwrap();
        assert_eq!(
            p.mesh3d_options.projection,
            Some(ProjectionMode::Orthographic)
        );
    }

    #[test]
    fn projection_perspective_default_is_unset() {
        let p = parse(&to_vec(&["in.stl", "out.png"])).unwrap();
        assert!(p.mesh3d_options.projection.is_none());
    }

    #[test]
    fn projection_alias_parses() {
        let p = parse(&to_vec(&["in.stl", "-projection", "ortho", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.projection,
            Some(ProjectionMode::Orthographic)
        );
    }

    #[test]
    fn projection_unknown_rejected() {
        let err = parse(&to_vec(&["in.stl", "-projection", "isometric", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("unknown mode 'isometric'"));
    }

    #[test]
    fn fov_parses_within_range() {
        let p = parse(&to_vec(&["in.stl", "-fov", "45", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.fov_deg, Some(45.0));
    }

    #[test]
    fn fov_rejects_zero() {
        let err = parse(&to_vec(&["in.stl", "-fov", "0", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("(0, 180)"));
    }

    #[test]
    fn fov_rejects_180_or_above() {
        let err = parse(&to_vec(&["in.stl", "-fov", "180", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("(0, 180)"));
    }

    #[test]
    fn bg_named_colour_parses() {
        let p = parse(&to_vec(&["in.stl", "-bg", "black", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.bg, Some([0, 0, 0, 255]));
    }

    #[test]
    fn bg_hex_colour_parses() {
        let p = parse(&to_vec(&["in.stl", "-bg", "#abcdef", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.bg, Some([0xab, 0xcd, 0xef, 255]));
    }

    #[test]
    fn bg_transparent_parses() {
        let p = parse(&to_vec(&["in.stl", "-bg", "transparent", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.bg, Some([0, 0, 0, 0]));
    }

    #[test]
    fn mesh3d_flags_can_appear_before_input() {
        // IM grammar lets ops appear on either side of the positional;
        // confirm the per-format flags follow the same rule.
        let p = parse(&to_vec(&[
            "-stl-format",
            "ascii",
            "-gltf-format",
            "glb",
            "in.stl",
            "out.stl",
        ]))
        .unwrap();
        assert_eq!(p.mesh3d_options.stl_format, Some(StlFormatChoice::Ascii));
        assert_eq!(p.mesh3d_options.gltf_format, Some(GltfFormatChoice::Glb));
        assert_eq!(p.input, "in.stl");
        assert_eq!(p.output, "out.stl");
    }

    // ---- Round 45: -render normal-debug / depth-debug + -aa N --------

    #[test]
    fn render_normal_debug_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "normal-debug", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::NormalDebug)
        );
    }

    #[test]
    fn render_depth_debug_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "depth-debug", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::DepthDebug)
        );
    }

    #[test]
    fn render_normal_alias_parses() {
        // `normal` (singular) and `normals` (plural) both map to
        // NormalDebug; convenience for the common typo.
        let p = parse(&to_vec(&["in.stl", "-render", "normal", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::NormalDebug)
        );
        let p = parse(&to_vec(&["in.stl", "-render", "normals", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::NormalDebug)
        );
    }

    #[test]
    fn render_depth_alias_parses() {
        let p = parse(&to_vec(&["in.stl", "-render", "depth", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::DepthDebug)
        );
        let p = parse(&to_vec(&["in.stl", "-render", "z", "out.png"])).unwrap();
        assert_eq!(
            p.mesh3d_options.render_mode,
            Some(Mesh3DRenderMode::DepthDebug)
        );
    }

    #[test]
    fn render_unknown_mode_lists_debug_modes() {
        // Round 45 added two new modes; the error message should
        // mention them so users don't have to grep the docs.
        let err = parse(&to_vec(&["in.stl", "-render", "raytrace", "out.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("normal-debug") && msg.contains("depth-debug"),
            "expected new debug-mode names in error, got: {msg}"
        );
    }

    #[test]
    fn aa_default_is_unset() {
        let p = parse(&to_vec(&["in.stl", "out.png"])).unwrap();
        assert!(p.mesh3d_options.aa.is_none());
    }

    #[test]
    fn aa_factor_parses() {
        let p = parse(&to_vec(&["in.stl", "-aa", "4", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.aa, Some(4));
    }

    #[test]
    fn aa_factor_one_is_allowed_meaning_no_supersampling() {
        // 1× is the documented "off" value — allowed so callers can
        // unconditionally set the flag from a config without special-
        // casing the disabled state.
        let p = parse(&to_vec(&["in.stl", "-aa", "1", "out.png"])).unwrap();
        assert_eq!(p.mesh3d_options.aa, Some(1));
    }

    #[test]
    fn aa_factor_zero_rejected() {
        let err = parse(&to_vec(&["in.stl", "-aa", "0", "out.png"])).unwrap_err();
        let msg = format!("{err:?}");
        assert!(
            msg.contains("out of range") && msg.contains("1..=8"),
            "expected range hint, got: {msg}"
        );
    }

    #[test]
    fn aa_factor_above_cap_rejected() {
        let err = parse(&to_vec(&["in.stl", "-aa", "16", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("1..=8"));
    }

    #[test]
    fn aa_non_integer_rejected() {
        let err = parse(&to_vec(&["in.stl", "-aa", "2.5", "out.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("not a positive integer"));
    }

    // ---- -trim / -fuzz ----

    /// Bare `-trim` (no preceding `-fuzz`) lands as `Op::Trim { fuzz: 0 }` —
    /// IM's default exact-match background detection.
    #[test]
    fn trim_default_fuzz_is_zero() {
        let p = parse(&to_vec(&["a.png", "-trim", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Trim { fuzz: 0 }]);
    }

    /// `-fuzz N` updates state but emits no op of its own; the next
    /// `-trim` captures the value.
    #[test]
    fn fuzz_byte_then_trim_captures_value() {
        let p = parse(&to_vec(&["a.png", "-fuzz", "12", "-trim", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Trim { fuzz: 12 }]);
    }

    /// `-fuzz N%` accepts the IM percent grammar and maps `100%` to
    /// `255`. `10%` ≈ `26` (`10 × 2.55` rounded).
    #[test]
    fn fuzz_percent_then_trim_captures_scaled_value() {
        let p = parse(&to_vec(&["a.png", "-fuzz", "10%", "-trim", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Trim { fuzz: 26 }]);
        let p = parse(&to_vec(&["a.png", "-fuzz", "100%", "-trim", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Trim { fuzz: 255 }]);
    }

    /// A `-fuzz` placed AFTER a `-trim` does NOT retroactively rewrite
    /// the earlier trim's tolerance (source-order semantics, identical to
    /// `-background` + `-extent`). The second `-trim` then captures the
    /// new fuzz.
    #[test]
    fn fuzz_after_trim_only_affects_following_trim() {
        let p = parse(&to_vec(&[
            "a.png", "-fuzz", "5", "-trim", "-fuzz", "20", "-trim", "b.png",
        ]))
        .unwrap();
        assert_eq!(p.ops, vec![Op::Trim { fuzz: 5 }, Op::Trim { fuzz: 20 }]);
    }

    /// `-fuzz` with no preceding-or-following `-trim` is a recorded
    /// state-only setting — no Op emitted, no error.
    #[test]
    fn fuzz_without_trim_is_no_op() {
        let p = parse(&to_vec(&["a.png", "-fuzz", "30", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![]);
    }

    /// `-fuzz` requires a value; missing → clean "missing value" error.
    #[test]
    fn fuzz_missing_value_rejected() {
        let err = parse(&to_vec(&["a.png", "-fuzz"])).unwrap_err();
        assert!(format!("{err:?}").contains("missing value"));
    }

    /// `-fuzz` rejects garbage with the same shape as `-threshold`.
    #[test]
    fn fuzz_garbage_rejected() {
        let err = parse(&to_vec(&["a.png", "-fuzz", "xyz", "-trim", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("-fuzz"));
    }

    /// `-fuzz N%` with `N` outside `[0, 100]` is rejected (same shape as
    /// `-threshold` / `-solarize`).
    #[test]
    fn fuzz_percent_out_of_range_rejected() {
        let err = parse(&to_vec(&["a.png", "-fuzz", "150%", "-trim", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    /// `-fuzz N` with `N > 255` is rejected (raw bytes only go up to
    /// `255`; the percent grammar is the documented escape hatch).
    #[test]
    fn fuzz_byte_above_255_rejected() {
        let err = parse(&to_vec(&["a.png", "-fuzz", "300", "-trim", "b.png"])).unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    /// `-trim` composes with surrounding ops in source order — typical
    /// IM idiom `convert in.png -trim +repage out.png` would land trim
    /// between any prior `-resize` and a downstream `-strip`. Pins the
    /// no-implicit-reorder contract.
    #[test]
    fn trim_keeps_source_order_with_neighbours() {
        let p = parse(&to_vec(&[
            "a.png", "-resize", "100x100", "-fuzz", "8", "-trim", "-strip", "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::Resize {
                    width: 100,
                    height: 100,
                    mode: ResizeMode::Default,
                },
                Op::Trim { fuzz: 8 },
                Op::Strip,
            ]
        );
    }

    // ---- -roll +X+Y ----

    /// Plain `-roll +X+Y` lands as `Op::Roll { dx, dy }` with both
    /// offsets positive.
    #[test]
    fn roll_positive_offsets() {
        let p = parse(&to_vec(&["a.png", "-roll", "+5+10", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Roll { dx: 5, dy: 10 }]);
    }

    /// `-roll -X-Y` accepts negative offsets unchanged — the inline
    /// shift handles the modulo wrap, so the args layer doesn't
    /// normalise.
    #[test]
    fn roll_negative_offsets() {
        let p = parse(&to_vec(&["a.png", "-roll", "-3-7", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Roll { dx: -3, dy: -7 }]);
    }

    /// Mixed signs (`+X-Y`, `-X+Y`) ride through the same
    /// `parse_extent_offsets` helper as `-extent`.
    #[test]
    fn roll_mixed_signs() {
        let p = parse(&to_vec(&["a.png", "-roll", "+5-10", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Roll { dx: 5, dy: -10 }]);
    }

    /// Single-offset `+X` is rejected — IM requires both X and Y
    /// signed. Mirrors the `-extent +X` rejection path.
    #[test]
    fn roll_single_offset_rejected() {
        let err = parse(&to_vec(&["a.png", "-roll", "+5", "b.png"])).unwrap_err();
        assert!(
            format!("{err:?}").contains("single offset"),
            "unexpected error: {err:?}"
        );
    }

    /// Empty value (e.g. `-roll ""`) is rejected with a clear
    /// message rather than silently treated as `0,0`.
    #[test]
    fn roll_empty_value_rejected() {
        let err = parse(&to_vec(&["a.png", "-roll", "", "b.png"])).unwrap_err();
        assert!(
            format!("{err:?}").contains("empty offset"),
            "unexpected error: {err:?}"
        );
    }

    /// Unsigned `5+10` (missing leading sign) is rejected with the
    /// IM "must start with `+` or `-`" message — IM grammar requires
    /// the explicit sign.
    #[test]
    fn roll_unsigned_value_rejected() {
        let err = parse(&to_vec(&["a.png", "-roll", "5+10", "b.png"])).unwrap_err();
        let s = format!("{err:?}");
        assert!(
            s.contains("must start with `+` or `-`") || s.contains("not a signed integer"),
            "unexpected error: {err:?}"
        );
    }

    /// `-roll` preserves source order alongside neighbours — same
    /// no-reorder contract as `-trim` / `-flip` / `-extent`.
    #[test]
    fn roll_keeps_source_order_with_neighbours() {
        let p = parse(&to_vec(&[
            "a.png", "-resize", "100x100", "-roll", "+5+5", "-strip", "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::Resize {
                    width: 100,
                    height: 100,
                    mode: ResizeMode::Default,
                },
                Op::Roll { dx: 5, dy: 5 },
                Op::Strip,
            ]
        );
    }

    // ---- adversarial argv: typed errors, never panics ----

    /// Whatever garbage arrives, `parse` must return `Ok` or a typed
    /// error — never panic. The corpus concentrates on the value
    /// grammars with the most parsing surface (geometry, page
    /// selectors, colours, numeric ranges) plus token-shape edge
    /// cases (unicode, oversized strings, lone dashes, truncated
    /// flag/value pairs).
    #[test]
    fn adversarial_argv_never_panics() {
        let long = "x".repeat(10_000);
        let long_selector = format!("in.pdf[{}]", "9".repeat(5_000));
        let cases: Vec<Vec<&str>> = vec![
            // Geometry grammar abuse.
            vec!["in.png", "-resize", "x", "out.png"],
            vec!["in.png", "-resize", "0x0", "out.png"],
            vec!["in.png", "-resize", "-1x-1", "out.png"],
            vec!["in.png", "-resize", "99999999999999999999x1", "out.png"],
            vec!["in.png", "-resize", "8x", "out.png"],
            vec!["in.png", "-resize", "!", "out.png"],
            vec!["in.png", "-crop", "1x1", "out.png"],
            vec!["in.png", "-crop", "1x1+", "out.png"],
            vec!["in.png", "-crop", "1x1+1+1+1", "out.png"],
            vec!["in.png", "-extent", "+5+5", "out.png"],
            vec!["in.png", "-roll", "++", "out.png"],
            vec!["in.png", "-roll", "5", "out.png"],
            vec!["in.png", "-vignette", "+", "out.png"],
            vec!["in.png", "-vignette", "1+2+3+4+5", "out.png"],
            // Page-selector abuse.
            vec!["in.pdf[", "out.png"],
            vec!["in.pdf[]", "out.png"],
            vec!["in.pdf[1-2-3]", "out.png"],
            vec!["in.pdf[,]", "out.png"],
            vec!["in.pdf[0,,1]", "out.png"],
            vec!["in.pdf[abc]", "out.png"],
            vec!["in.pdf[999999999999999999999]", "out.png"],
            vec!["]", "out.png"],
            vec!["[0]", "out.png"],
            // Colour grammar abuse.
            vec!["in.png", "-background", "#", "out.png"],
            vec!["in.png", "-background", "#12345", "out.png"],
            vec!["in.png", "-background", "#gggggg", "out.png"],
            vec!["in.png", "-background", "notacolor", "out.png"],
            vec!["in.png", "-colorize", "/", "out.png"],
            vec!["in.png", "-colorize", "300x300x300/2", "out.png"],
            // Numeric range / special-float abuse.
            vec!["in.png", "-quality", "-1", "out.png"],
            vec!["in.png", "-quality", "99999999999", "out.png"],
            vec!["in.png", "-gamma", "NaN", "out.png"],
            vec!["in.png", "-gamma", "inf", "out.png"],
            vec!["in.png", "-gamma", "-0.0", "out.png"],
            vec!["in.png", "-fov", "NaN", "out.png"],
            vec!["in.png", "-modulate", ",,,", "out.png"],
            vec!["in.png", "-modulate", "1,2,3,4", "out.png"],
            vec!["in.png", "-level", "//", "out.png"],
            vec!["in.png", "-fuzz", "300%", "out.png"],
            vec!["in.png", "-aa", "0", "out.png"],
            // Define / token-shape abuse.
            vec!["in.png", "-define", "=v", "out.png"],
            vec!["in.png", "-define", "=", "out.png"],
            vec!["in.png", "--opt", "=", "out.png"],
            vec!["in.png", "--opt", "==", "out.png"],
            vec!["in.png", "--opt"],
            vec!["in.png", "-depth", "", "out.png"],
            vec!["in.png", "-threads", "-1", "out.png"],
            vec!["in.png", "-threads", "99999999999999999999", "out.png"],
            vec!["in.png", "-depth", "99999999999", "out.png"],
            vec!["日本語.png", "出力.jpg"],
            vec!["in.png", "-résize", "8x8", "out.png"],
            vec![&long, "out.png"],
            vec!["in.png", &long_selector, "out.png"],
            // Truncated flag/value pairs and lone dashes.
            vec!["in.png", "-resize"],
            vec!["-"],
            vec!["--"],
            vec!["in.png", "-", "out.png"],
        ];
        for argv in cases {
            // Must not panic; Ok vs Err is case-specific and pinned
            // by the focused tests elsewhere in this module.
            let _ = parse(&to_vec(&argv));
        }
    }

    // ---- `--help` mode + usage synopsis ----

    #[test]
    fn help_parses_with_no_positionals() {
        for argv in [vec!["--help"], vec!["-help"]] {
            let p = parse(&to_vec(&argv)).unwrap();
            assert!(p.help, "argv={argv:?}");
        }
    }

    #[test]
    fn help_anywhere_on_a_full_line_still_wins() {
        // Positional validation is skipped: even a line that would
        // otherwise error (probe + output) parses once --help is on it.
        let p = parse(&to_vec(&["in.png", "--help", "--probe", "out.png"])).unwrap();
        assert!(p.help);
    }

    /// The usage text must mention every recognised flag — it is
    /// generated from [`KNOWN_FLAG_NAMES`], so this pins the
    /// generation (right dash flavour included) rather than the table.
    #[test]
    fn usage_lists_every_known_flag_with_correct_lead() {
        let text = usage();
        for name in KNOWN_FLAG_NAMES {
            let lead = if matches!(*name, "probe" | "json" | "watch" | "help" | "opt") {
                "--"
            } else {
                "-"
            };
            let rendered = format!(" {lead}{name}");
            assert!(
                text.contains(&rendered),
                "usage text is missing '{rendered}':\n{text}"
            );
        }
        assert!(text.starts_with("usage: oxideav convert"));
    }

    // ---- `--` end-of-flags marker + empty-argument hardening ----

    #[test]
    fn double_dash_treats_following_dash_args_as_positionals() {
        // A file literally named `-weird.png` is expressible.
        let p = parse(&to_vec(&["--", "-weird.png", "-out.jpg"])).unwrap();
        assert_eq!(p.input, "-weird.png");
        assert_eq!(p.output, "-out.jpg");
        assert!(p.ops.is_empty());
    }

    #[test]
    fn flags_before_double_dash_still_parse() {
        let p = parse(&to_vec(&["-resize", "64x64", "--", "-in.png", "out.png"])).unwrap();
        assert_eq!(p.input, "-in.png");
        assert_eq!(p.output, "out.png");
        assert_eq!(p.ops.len(), 1);
    }

    #[test]
    fn flags_after_double_dash_are_positionals_not_flags() {
        // Three positionals (`-resize` is a filename after `--`) →
        // multi-input error, NOT an op.
        let err = parse(&to_vec(&["--", "-resize", "64x64", "out.png"])).unwrap_err();
        let s = format!("{err}");
        assert!(s.contains("multi-input"), "got: {err}");
    }

    #[test]
    fn empty_positional_is_rejected_with_actionable_message() {
        for argv in [
            vec!["", "out.png"],
            vec!["in.png", ""],
            vec!["--", "", "out.png"],
        ] {
            let err = parse(&to_vec(&argv)).unwrap_err();
            let s = format!("{err}");
            assert!(s.contains("empty argument"), "argv={argv:?} got: {err}");
        }
    }

    /// Every entry in [`KNOWN_FLAG_NAMES`] must be accepted by the
    /// parser's `match` — a table entry the parser rejects as an
    /// unknown flag means the two drifted apart (the table exists to
    /// power "did you mean?" hints for exactly these names, so a
    /// stale entry would SUGGEST a flag that then errors).
    ///
    /// The value column supplies a minimal valid argument per flag so
    /// the whole line parses `Ok` — catching not just unknown-flag
    /// drift but accidental value-grammar breakage too.
    #[test]
    fn opt_parses_key_value_pairs_in_order() {
        let p = parse(&to_vec(&[
            "a.png",
            "--opt",
            "filter=none",
            "--opt",
            "tiles=2x2",
            "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::EncoderOpt {
                    key: "filter".into(),
                    value: "none".into()
                },
                Op::EncoderOpt {
                    key: "tiles".into(),
                    value: "2x2".into()
                },
            ]
        );
        // `=` inside the value is kept verbatim; an empty value is legal.
        let p = parse(&to_vec(&[
            "a.png", "--opt", "k=a=b", "--opt", "e=", "b.png",
        ]))
        .unwrap();
        assert_eq!(
            p.ops,
            vec![
                Op::EncoderOpt {
                    key: "k".into(),
                    value: "a=b".into()
                },
                Op::EncoderOpt {
                    key: "e".into(),
                    value: String::new()
                },
            ]
        );
        for bad in ["novalue", "=v"] {
            let err = parse(&to_vec(&["a.png", "--opt", bad, "b.png"])).unwrap_err();
            assert!(format!("{err}").contains("--opt"), "{bad}: {err}");
        }
    }

    #[test]
    fn threads_parses_a_count_and_zero_for_auto() {
        let p = parse(&to_vec(&["a.png", "-threads", "4", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Threads(4)]);
        let p = parse(&to_vec(&["a.png", "-threads", "0", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Threads(0)]);
        let err = parse(&to_vec(&["a.png", "-threads", "many", "b.png"])).unwrap_err();
        assert!(format!("{err}").contains("-threads"), "{err}");
    }

    #[test]
    fn depth_accepts_the_two_storage_depths() {
        let p = parse(&to_vec(&["a.heic", "-depth", "8", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Depth(8)]);
        let p = parse(&to_vec(&["a.heic", "-depth", "16", "b.png"])).unwrap();
        assert_eq!(p.ops, vec![Op::Depth(16)]);
        for bad in ["12", "0", "abc", "-8", "256"] {
            let err = parse(&to_vec(&["a.heic", "-depth", bad, "b.png"])).unwrap_err();
            assert!(
                format!("{err}").contains("-depth") && format!("{err}").contains("8 or 16"),
                "{bad}: {err}"
            );
        }
    }

    #[test]
    fn every_known_flag_name_is_accepted_by_the_parser() {
        // (flag-as-typed, extra args, needs_probe)
        let cases: &[(&str, &[&str])] = &[
            ("-aa", &["2"]),
            ("-alpha", &["on"]),
            ("-auto-gamma", &[]),
            ("-background", &["white"]),
            ("-bg", &["white"]),
            ("-blur", &["1x1"]),
            ("-brightness-contrast", &["10,5"]),
            ("-camera", &["30,45,1.5"]),
            ("-colorize", &["red/50%"]),
            ("-colors", &["16"]),
            ("-colorspace", &["gray"]),
            ("-contrast", &[]),
            ("-crop", &["1x1+0+0"]),
            ("-define", &["k=v"]),
            ("-density", &["72"]),
            ("-depth", &["8"]),
            ("-dither", &["none"]),
            ("-edge", &["1"]),
            ("-equalize", &[]),
            ("-extent", &["10x10"]),
            ("-flip", &[]),
            ("-flop", &[]),
            ("-format", &["png"]),
            ("-fov", &["60"]),
            ("-fuzz", &["5"]),
            ("-gamma", &["1.2"]),
            ("-gltf-format", &["glb"]),
            ("-level", &["16"]),
            ("-light", &["45,45,1.0"]),
            ("-modulate", &["100,100,100"]),
            ("-monochrome", &[]),
            ("-negate", &[]),
            ("-normalize", &[]),
            ("--opt", &["filter=none"]),
            ("-ping", &[]),
            ("-posterize", &["4"]),
            ("-projection", &["persp"]),
            ("-quality", &["85"]),
            ("-render", &["flat"]),
            ("-resize", &["64x64"]),
            ("-roll", &["+1+1"]),
            ("-rotate", &["90"]),
            ("-sepia", &["80%"]),
            ("-sharpen", &["1x0.5"]),
            ("-solarize", &["50%"]),
            ("-stl-format", &["binary"]),
            ("-strip", &[]),
            ("-thumbnail", &["64x64"]),
            ("-threads", &["2"]),
            ("-threshold", &["50%"]),
            ("-trim", &[]),
            ("-unsharp", &["1x1"]),
            ("-vignette", &["50"]),
        ];
        // Double-dash mode switches need their own argv shapes
        // (`--json` / `--watch` require `--probe`; `--probe` forbids
        // an output positional).
        let mode_cases: &[&[&str]] = &[
            &["--probe", "in.png"],
            &["--probe", "--json", "in.png"],
            &["--probe", "--watch", "in.png"],
            &["--help"],
        ];

        let mut covered: Vec<&str> = Vec::new();
        for (flag, extra) in cases {
            let mut argv: Vec<&str> = vec!["in.png"];
            argv.push(flag);
            argv.extend_from_slice(extra);
            argv.push("out.png");
            let res = parse(&to_vec(&argv));
            assert!(
                res.is_ok(),
                "flag {flag} rejected with sample value {extra:?}: {:?}",
                res.err()
            );
            covered.push(flag.trim_start_matches('-'));
        }
        for argv in mode_cases {
            let res = parse(&to_vec(argv));
            assert!(res.is_ok(), "argv {argv:?} rejected: {:?}", res.err());
        }
        covered.extend(["probe", "json", "watch", "help"]);

        // Table completeness: every advertised name has a test case…
        for name in KNOWN_FLAG_NAMES {
            assert!(
                covered.contains(name),
                "KNOWN_FLAG_NAMES entry '{name}' has no acceptance case — add one above"
            );
        }
        // …and every test case is advertised (no hidden flags that a
        // typo could never get a hint for).
        for name in &covered {
            assert!(
                KNOWN_FLAG_NAMES.contains(name),
                "flag '{name}' parses but is missing from KNOWN_FLAG_NAMES"
            );
        }
    }
}