ballistics-engine 0.47.0

High-performance ballistics trajectory engine with professional physics
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
//! Transport-free card-generation services (come-ups, range table, wind card).
//!
//! These replicate the CLI's card commands exactly — same zero solve, same sampled
//! trajectory, same nearest-sample row selection, same adjustment/bias/CF/click
//! ordering via [`crate::adjustment`] — as versioned request/response types the
//! bridge can expose to embedded consumers. The CLI remains the reference
//! implementation; `tests/card_bridge_golden.rs` asserts row-for-row agreement.
//!
//! ## Unit convention
//!
//! Unlike solve-json (explicit SI), card requests are denominated in the shooter's own
//! units, exactly like the CLI flags they mirror: imperial = fps, grains, inches, yards,
//! °F, inHg, mph; metric = m/s, grams, mm, meters, °C, hPa, m/s. A DOPE card is a display
//! artifact; its inputs and outputs share the shooter's unit world, and this keeps the
//! request shape identical to the documented CLI surface.
//!
//! ### Per-dimension units (MBA-1519)
//!
//! Nobody shoots in one system. A Finnish shooter ranges in metres, dials MIL, and buys
//! bullets labelled in grains, because that is how the industry sells them; European makers
//! dual-print `grams / grains` rather than replacing one with the other, and mix within a
//! single table. So the denominating state on this request is a unit PER DIMENSION, and
//! [`CardUnits`] is a one-shot preset that fills in every dimension the request does not
//! state for itself — not a mode the card is "in".
//!
//! Concretely: an explicit per-dimension field wins; an absent one falls back to what
//! `units` implies. A request written before those fields existed states none of them, so
//! every dimension falls back and the card is byte-for-byte the card it always was
//! (`tests/card_units_per_dimension.rs` pins that against a stored document).
//!
//! The response needed no new FIELD for any of this: [`CardUnitsBlockV1`] has always carried
//! seven independent label fields, so a card whose distance is metres and whose velocity is
//! fps already had somewhere to say so. It did need the two angular labels to become
//! requestable: `elevation_adjustment`/`windage_adjustment` print `"MIL"`/`"MOA"`/`"SMOA"`/
//! `"IPHY"`/`"CLICKS"` and [`AdjustmentUnit`] deserialized lowercase only, so those two were
//! the only fields of the block a caller could not echo back. They take the uppercase
//! spellings as aliases now, which makes "echo the units block into the next request" true
//! of all seven fields rather than five of them.
//!
//! Three candidates do NOT get a new field, and each for its own reason:
//!
//! * **Scope adjustment** is already per-dimension, and was first: `adjustment_unit` and
//!   `windage_unit` are separate fields with separate click graduations, because a shooter
//!   with a MIL rifle and an MOA rifle has two scopes rather than a preference. SMOA (and
//!   its `iphy` spelling) is already one of the values they take.
//! * **Clicks** is not a units dimension. A click is meaningless without a graduation, and
//!   this module already enforces that: `adjustment_unit == Clicks` without an
//!   `elevation_click_value` is a refusal. The graduation belongs beside the turret's
//!   MIL/MOA/SMOA marking, not in a units picker.
//! * **Twist rate** is a dimension of the design but not of this request — a card request
//!   carries no twist, so there is nothing here for a twist unit to denominate.
//!
//! And the linear-at-distance spellings are NOT units: "inches@100yd" IS SMOA — the same
//! 1/3600 rad, the same printed number, no conversion — and "cm/100m" is 0.1 mrad, i.e. MIL
//! with a factor-of-ten display. They are alternate HEADER TEXT for units this request
//! already has, and adding them as values would give a caller two spellings that produce
//! identical numbers.
//!
//! ### What the response does NOT tell a caller
//!
//! Like every other default on this request — `sight_height`, `temperature`, `pressure`,
//! `humidity`, `windage_unit` — a per-dimension unit taken from the preset is applied
//! silently, and this surface has no notice channel at all (there is no `assumptions` array
//! on [`CardResponseV1`], unlike solve-json's `SolveSuccessV1`).
//!
//! Be precise about what that costs, because a paragraph of prose can argue it away. The `units`
//! block names the unit of the SEVEN OUTPUT COLUMNS and nothing else. It says nothing about
//! the six dimensions that are input-only — `mass`, `diameter`, `sight_height`,
//! `temperature`, `pressure`, `altitude` — so for those a caller cannot read back off the
//! card which unit the engine settled on.
//!
//! `altitude` is the sharp one, because it is the dimension whose fallback is deliberately
//! NOT the preset's: an imperial `card.range_table` carrying `altitude: 5000` and no
//! `altitude_unit` — which a US caller writing an imperial card means as feet — is solved at
//! 5000 METRES, and no field of the response says so. On a .308 175 gr that is ~1.9 MIL of
//! elevation at 1000 yd against the same card with `altitude_unit: "feet"`. The BEHAVIOUR
//! predates the per-dimension fields (`altitude` has always reached
//! [`AtmosphericConditions`] unconverted); what is new is that the request can now name the
//! dimension, so the gap is describable instead of merely present.
//!
//! No notice was added here, and the reason is narrow rather than principled: any notice —
//! an `assumptions` array, or extra label fields on the units block — is a change to the
//! RESPONSE bytes of every card, including the stored documents the reprint path compares
//! label-for-label and the six goldens that are the whole evidence for this change being
//! additive on the wire. A response-schema change belongs to a ticket that can move those
//! goldens honestly. Until then the remedy is on the request: a caller that cares which
//! altitude it got states `altitude_unit`, and a card built by an app should state every
//! dimension rather than lean on a preset.

use serde::{Deserialize, Serialize};

use crate::adjustment::{
    adjustment_display, adjustment_unit_label, parse_click_value, windage_adjustment_display,
    AdjustmentUnit, ClickValue,
};
use crate::hold_curve::{
    card_sample_max_range_m, range_not_sampled_message, run_sampled_flight, sample_at_range,
    CardTruncation, SampledFlight, CARD_SAMPLE_INTERVAL_M,
};
use crate::{AtmosphericConditions, BCSegmentData, BallisticInputs, DragModel, WindConditions};

/// Schema version of the card request/response contract.
pub const CARD_SCHEMA_VERSION_V1: u32 = 1;

const GRAINS_TO_KG: f64 = crate::constants::GRAINS_TO_KG;

/// The unit PRESET for a card request: a one-shot bulk action that fills in every
/// per-dimension unit the request does not state for itself, not a mode the card is in.
///
/// It stays because it is the whole of the pre-MBA-1519 contract and because "give me an
/// imperial card" remains the overwhelmingly common request. What changed is its standing:
/// it is now the FALLBACK for each dimension rather than the denominator of all of them.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardUnits {
    #[default]
    Imperial,
    Metric,
}

// --- Per-dimension units (MBA-1519) ------------------------------------------------------
//
// One enum per dimension the card request actually denominates. Each is a plain value list;
// the mapping from a value to a conversion factor and to a printed label lives in exactly
// one place, `Units` below, so a dimension cannot convert one way and be labelled another.
//
// Every enum carries serde aliases for the spelling the RESPONSE prints for that unit
// (`"m/s"`, `"ft-lb"`, `"in"`, `"yd"`, ...), and so does [`AdjustmentUnit`] over in
// `adjustment.rs` for the two uppercase dial labels. A caller that reads a card's `units`
// block and writes those strings straight back into the next request is doing the obvious
// thing, and it now works — for all seven fields of the block — instead of failing on a
// request that denies unknown values.

/// Range axis: what `zero_distance`, `start`/`end`/`step` and every row's `range` are in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardDistanceUnit {
    #[serde(alias = "yd", alias = "yard")]
    Yards,
    #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
    Meters,
}

/// Speed of the bullet: `muzzle_velocity`, `bc_segments` band edges, the `velocity` column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardVelocityUnit {
    #[serde(alias = "ft/s")]
    Fps,
    #[serde(alias = "m/s")]
    Mps,
}

/// Bullet weight. Grains and grams differ by 15.43x, and on the BC path mass never enters
/// the drag denominator — it touches energy and stability only — so a grams-for-grains slip
/// yields a trajectory that looks entirely normal. Which is exactly why the unit has to be
/// stated per-dimension rather than inferred: the dual-printed `g / gr` box a European
/// shooter is holding is the normal case, not an edge one.
///
/// The one-character wire tokens `"g"` and `"gr"` are deliberately NOT accepted, though
/// `"gram"`/`"grams"` and `"grain"`/`"grains"` are. Those two tokens are the slip this
/// dimension exists to prevent: a 175-grain load sent as `"g"` solves to bit-identical
/// dials, drift, velocity and time — only the energy column moves, 1009 ft-lb to 15575 — and
/// the response has no mass label for a reader to catch it on. Nor can a plausibility guard
/// catch it: bullets run roughly 5–800 grains and roughly 0.3–52 grams, so the two ranges
/// OVERLAP across 5–52, where 48 grains (a .22 varmint bullet) and 48 grams (a .50 BMG) are
/// both ordinary. There is no threshold to put a guard at, so the defence has to be the
/// spelling, and the spelled-out name is the one thing a caller cannot typo into the other
/// unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardMassUnit {
    #[serde(alias = "grain")]
    Grains,
    #[serde(alias = "gram")]
    Grams,
}

/// A small linear length. Shared by the request's two TARGET-SIDE linear dimensions
/// (sight-to-bore geometry and the linear drop column) because they take the same values,
/// never because they are the same setting: they are separate fields and resolve
/// independently.
///
/// Bullet diameter is NOT one of them — it has [`CardDiameterUnit`], a narrower vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardLinearUnit {
    #[serde(alias = "in", alias = "inch")]
    Inches,
    #[serde(alias = "centimeters", alias = "centimetres")]
    Cm,
    #[serde(alias = "millimeters", alias = "millimetres")]
    Mm,
}

/// Bullet diameter: inches or millimetres, the two units a calibre is ever quoted in.
///
/// Its own enum rather than a third user of [`CardLinearUnit`], which would also accept
/// `cm`. The design's dimension table lists inches and mm for this dimension and no third
/// value, and a wire vocabulary on a `deny_unknown_fields` paid contract is far cheaper to
/// widen later than to narrow: nobody quotes a calibre in centimetres, so `0.782` cm is
/// likelier to be a slipped `7.82` mm than a request anyone meant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardDiameterUnit {
    #[serde(alias = "in", alias = "inch")]
    Inches,
    #[serde(alias = "millimeters", alias = "millimetres")]
    Mm,
}

/// Wind and crossing-target speed. Four values, not two: a European card reads km/h and a
/// coastal one reads knots, and neither is expressible by picking a system.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardWindSpeedUnit {
    Mph,
    #[serde(alias = "m/s")]
    Mps,
    #[serde(alias = "km/h", alias = "kmh")]
    Kph,
    #[serde(alias = "kn", alias = "kt", alias = "knot")]
    Knots,
}

/// Air temperature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardTemperatureUnit {
    #[serde(alias = "f", alias = "degf")]
    Fahrenheit,
    #[serde(alias = "c", alias = "degc")]
    Celsius,
}

/// Station pressure. `hpa` and `mbar` are the same number, which is why mbar is an alias
/// rather than a value of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardPressureUnit {
    #[serde(alias = "in-hg", alias = "inchesofmercury")]
    InHg,
    #[serde(alias = "mbar", alias = "millibar")]
    HPa,
}

/// Terminal energy column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardEnergyUnit {
    #[serde(alias = "ft-lb", alias = "ftlbs", alias = "footpounds")]
    FtLb,
    // "J" as well as "j": the response's energy label is the capitalized SI symbol, and the
    // aliases exist precisely so a caller can echo a card's own labels back at it.
    #[serde(alias = "j", alias = "J", alias = "joule")]
    Joules,
}

/// Site elevation. See [`CardRequestV1::altitude_unit`] for why this one dimension's
/// default does not come from the preset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardAltitudeUnit {
    #[serde(alias = "ft", alias = "foot")]
    Feet,
    #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
    Meters,
}

/// Everything the three card surfaces share: load, zero, atmosphere, display axes.
///
/// Field values are in this request's PER-DIMENSION units: each dimensional field names the
/// `*_unit` field that denominates it, and each of those falls back to what `units` implies
/// when it is absent (see the module docs). Stating none of them is the pre-MBA-1519 shape
/// and reproduces the pre-MBA-1519 card exactly.
///
/// ## Adding a field here is additive on the WIRE and breaking in RUST
///
/// This is a deserialization target: the supported way to build one is
/// `serde_json::from_str`/`from_value` on a JSON document, which is what the bridge and every
/// binding do, and an optional new field costs such a caller nothing. A downstream Rust crate
/// that constructs it with a struct literal has no such luck — every added field is an
/// `E0063: missing fields` against code that compiled before, which is exactly what MBA-1519's
/// eleven fields do to a crate written against 0.39.x. The remedy is one line per field
/// (`altitude_unit: None`, and so on for the rest); the intended path is to deserialize.
///
/// `#[non_exhaustive]` was considered and NOT applied. It would break the same callers in the
/// same release, and — with no `Default` and no builder on this type — it would leave a
/// downstream crate no way to construct the request at all, trading one fixable compile error
/// for a permanent one. So the breakage is stated in the CHANGELOG for the release that causes
/// it rather than encoded in the type, and a future field will be stated the same way.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CardRequestV1 {
    /// The preset that fills in every `*_unit` field below that this request leaves absent.
    #[serde(default)]
    pub units: CardUnits,

    // Load
    /// Muzzle speed, in `velocity_unit`.
    pub muzzle_velocity: f64,
    pub ballistic_coefficient: f64,
    /// Bullet weight, in `mass_unit`.
    pub mass: f64,
    /// Bullet diameter, in `diameter_unit`.
    pub diameter: f64,
    #[serde(default)]
    pub drag_model: DragModelV1,
    /// Sight height over bore, in `sight_height_unit`; CLI default 1.5 in.
    #[serde(default = "sight_height_unset")]
    pub sight_height: f64,

    // Zero
    /// Zero range, in `distance_unit`.
    pub zero_distance: f64,
    /// Deliberate POI offset at the zero range, in `drop_unit` — it is a displacement on
    /// the target, which is the dimension the drop column reports; 0 = zeroed dead-on.
    #[serde(default)]
    pub zero_poi_vertical: f64,
    /// Deliberate lateral POI offset at the zero range, in `drop_unit`.
    #[serde(default)]
    pub zero_poi_horizontal: f64,
    /// Lateral sight-to-bore mount offset, in `sight_height_unit` — it is rifle geometry
    /// measured beside the sight height, not a figure read off a target.
    #[serde(default)]
    pub sight_offset_lateral: f64,

    // Atmosphere (CLI defaults: 59 °F / 15 °C, 29.92 inHg / 1013.25 hPa, 50 %, 0 alt)
    /// Station temperature, in `temperature_unit`.
    #[serde(default)]
    pub temperature: Option<f64>,
    /// Station pressure, in `pressure_unit`.
    #[serde(default)]
    pub pressure: Option<f64>,
    /// Relative humidity, percent. Dimensionless, so no unit field governs it.
    #[serde(default = "default_humidity")]
    pub humidity: f64,
    /// Site elevation, in `altitude_unit` — which defaults to METRES whatever `units` says.
    #[serde(default)]
    pub altitude: f64,

    // Wind for the flight (in `wind_speed_unit`; wind-FROM degrees). The wind card ignores
    // these and sweeps its own speed list.
    #[serde(default)]
    pub wind_speed: f64,
    #[serde(default)]
    pub wind_direction_deg: f64,

    // Card domain, in `distance_unit`
    pub start: f64,
    pub end: f64,
    pub step: f64,

    // --- Per-dimension units (MBA-1519) --------------------------------------------------
    //
    // Every one of these is `Option`al and `#[serde(default)]`: `CardRequestV1` denies
    // unknown fields and backs paid surfaces (the Pro DOPE card, the saved-card reprint, the
    // PDF export), so a stored request written before they existed has to keep parsing and
    // keep producing the identical document. `None` means "take it from `units`", which is
    // what every such request says about every dimension.
    //
    // What is deliberately NOT here: a scope-adjustment unit (`adjustment_unit` /
    // `windage_unit` below already are that dimension, SMOA included), a clicks unit (a
    // click needs a graduation, which is `elevation_click_value`), a twist-rate unit (this
    // request carries no twist), and the linear-at-distance spellings (header text for SMOA
    // and MIL, not units). The module docs give the full reasoning.
    /// Unit of `zero_distance`, `start`, `end`, `step` and every row's `range`.
    /// Default: yards (imperial) / metres (metric).
    ///
    /// Distance is the dimension where reinterpreting the number does the most damage the
    /// most quietly: "300" yards and "300" metres are targets 9.36% apart, and a stored zero,
    /// a DOPE row and a target-size hold are all attached to a PHYSICAL distance rather than
    /// to a unit-free label. So a card's distance unit is stated, never inferred from a
    /// neighbouring dimension.
    #[serde(default)]
    pub distance_unit: Option<CardDistanceUnit>,
    /// Unit of `muzzle_velocity`, the `bc_segments` band edges and the `velocity` column.
    /// Default: fps (imperial) / m/s (metric).
    #[serde(default)]
    pub velocity_unit: Option<CardVelocityUnit>,
    /// Unit of `mass`. Default: grains (imperial) / grams (metric).
    #[serde(default)]
    pub mass_unit: Option<CardMassUnit>,
    /// Unit of `diameter`. Default: inches (imperial) / mm (metric). Those two values and no
    /// others — see [`CardDiameterUnit`].
    #[serde(default)]
    pub diameter_unit: Option<CardDiameterUnit>,
    /// Unit of `sight_height` and `sight_offset_lateral` — the sight-to-bore geometry.
    /// Default: inches (imperial) / mm (metric).
    ///
    /// This is a dimension the design's table does not contain, added deliberately rather
    /// than by oversight: without it, the only home for the sight height would be
    /// `drop_unit`, and then asking for a drop column in centimetres would silently reread a
    /// 1.5-inch sight height as 1.5 cm. It is a twelfth field on a `deny_unknown_fields`
    /// contract that cannot be withdrawn without a breaking change, which is the cost being
    /// accepted here.
    ///
    /// Separate from `drop_unit` on purpose. They are the same unit today only because both
    /// presets happen to give them the same value; they are different measurements (one is
    /// taken on the rifle with calipers, the other is read off a target downrange), and
    /// folding them together would mean a caller who asks for a drop column in centimetres
    /// silently reinterprets a 1.5-inch sight height as 1.5 cm.
    #[serde(default)]
    pub sight_height_unit: Option<CardLinearUnit>,
    /// Unit of the `drop_linear` / `wind_linear` columns and of `zero_poi_vertical` /
    /// `zero_poi_horizontal`. Default: inches (imperial) / mm (metric).
    ///
    /// The ANGULAR half of the design's drop dimension is `adjustment_unit` /
    /// `windage_unit`, which have always been separate fields; this is the linear half, and
    /// `cm` is available here because a metric card prints 250 cm of drop, not 2500 mm.
    #[serde(default)]
    pub drop_unit: Option<CardLinearUnit>,
    /// Unit of `wind_speed`, of every entry in `wind_speeds`, and of `pdf.target_speed`.
    /// Default: mph (imperial) / m/s (metric).
    #[serde(default)]
    pub wind_speed_unit: Option<CardWindSpeedUnit>,
    /// Unit of `temperature` and of the temperature default. Default: °F (imperial) / °C
    /// (metric).
    #[serde(default)]
    pub temperature_unit: Option<CardTemperatureUnit>,
    /// Unit of `pressure` and of the pressure default. Default: inHg (imperial) / hPa
    /// (metric).
    #[serde(default)]
    pub pressure_unit: Option<CardPressureUnit>,
    /// Unit of the `energy` column. Default: ft-lb (imperial) / J (metric).
    #[serde(default)]
    pub energy_unit: Option<CardEnergyUnit>,
    /// Unit of `altitude`. Default: **metres, whatever `units` says** — this is the one
    /// dimension whose fallback is not the preset's.
    ///
    /// `altitude` has ignored the `units` scalar since this module was written: it is passed
    /// to [`AtmosphericConditions`] unconverted, and that field is documented metres, so an
    /// imperial card's altitude has always been metres too (the PDF header divides it by
    /// 0.3048 regardless of `units` for exactly that reason). Letting the imperial preset
    /// start filling this with `feet` would therefore not be additive: every stored imperial
    /// card carrying `altitude: 1000` would silently become a card shot at 304.8 m instead
    /// of 1000 m, which is a different density altitude and a different trajectory.
    ///
    /// So the preset does not reach this field. A caller that wants feet says `"feet"`, and
    /// gets the first way this request has ever had to express one.
    #[serde(default)]
    pub altitude_unit: Option<CardAltitudeUnit>,

    // Display axes
    #[serde(default)]
    pub adjustment_unit: AdjustmentUnit,
    /// Windage axis unit; defaults to the elevation axis.
    #[serde(default)]
    pub windage_unit: Option<AdjustmentUnit>,
    /// Turret graduations as suffixed strings ("0.1mil", "0.25moa"); required when
    /// the corresponding axis unit is `clicks`. Windage falls back to elevation.
    #[serde(default)]
    pub elevation_click_value: Option<String>,
    #[serde(default)]
    pub windage_click_value: Option<String>,
    /// Scope tracking correction factors (MBA-1358); 1.0 = tracks true.
    #[serde(default = "default_cf")]
    pub elevation_cf: f64,
    #[serde(default = "default_cf")]
    pub windage_cf: f64,
    /// Selected zero set's dial corrections, true angular MIL (MBA-1360).
    #[serde(default)]
    pub zero_set_elevation_bias_mil: f64,
    #[serde(default)]
    pub zero_set_windage_bias_mil: f64,

    /// Wind card only: the sweep of wind speeds, each in `wind_speed_unit` (so km/h and
    /// knots are available here too), one output column each.
    #[serde(default)]
    pub wind_speeds: Vec<f64>,
    /// Wind card only: wind-FROM angles in degrees; default `[90]` (full-value from
    /// the right), matching the CLI.
    #[serde(default)]
    pub wind_angles_deg: Vec<f64>,

    /// Explicit velocity-banded BC schedule, mirroring the CLI's repeatable
    /// `--bc-segment VMIN:VMAX:BC`. Velocities are in the request's `velocity_unit`,
    /// exactly like the CLI flag. When supplied it
    /// wins over `bc5d_table_path`, and — CLI parity — the scalar
    /// `ballistic_coefficient` remains the interior-gap fallback unchanged. The
    /// schedule feeds BOTH the zero solve and every sampled trajectory.
    ///
    /// Bands may be listed in any order and may touch or leave gaps, but must not overlap; at
    /// most [`crate::solve_json::MAX_BC_SEGMENTS_V1`] bands; each `bc` within 0.0001..=100, the
    /// bound solve-json puts on a BC. `[]` and `null` mean no ladder (MBA-1600).
    #[serde(default)]
    pub bc_segments: Option<Vec<CardBcSegmentV1>>,
    /// Filesystem path to a caliber-specific BC5D correction table
    /// (`bc5d_<caliber>.bin`, the exact format the CLI's `--bc-table-dir`
    /// consumes). The table is CRC-verified, a velocity-keyed BC schedule is
    /// generated for this load (same ladder as the CLI), and the scalar BC gets the
    /// table's muzzle correction as the interior-gap fallback. Ignored when
    /// `bc_segments` is supplied. Not available on wasm32 builds (no filesystem);
    /// there it is rejected with an invalid-request error.
    #[serde(default)]
    pub bc5d_table_path: Option<String>,

    /// Presentation-only options for the printable PDF dope card (`card.pdf`). Nothing in
    /// here touches the ballistics: the numbers in the PDF are the rows
    /// [`range_table_v1`] returns, computed by the same call.
    ///
    /// It lives on the shared request — rather than in a `card.pdf`-only wrapper type — so
    /// an app stores ONE `CardRequestV1` per saved card and replays that exact document
    /// against either surface: `card.range_table` for the screen, `card.pdf` for the
    /// printout. The on-screen commands ignore this block.
    ///
    /// Deliberately NOT `#[cfg(feature = "pdf")]`, even though everything that consumes it
    /// is: `CardRequestV1` denies unknown fields, so gating the field would make a
    /// pdf-less build REJECT a stored request that carries it, breaking exactly the
    /// round-trip the field exists to support. A pdf-less build parses it and never reads
    /// it; only the `card.pdf` command itself disappears.
    #[serde(default)]
    pub pdf: Option<PdfCardOptionsV1>,
}

/// Presentation knobs for the PDF dope card: the header/footer labels the printed card
/// carries and the table's font size. The ballistics axes it prints (elevation unit,
/// windage unit, click graduations, tracking CFs, zero-set biases) are NOT here — they are
/// already fields on [`CardRequestV1`], shared with the on-screen card, precisely so the
/// two cannot disagree about what a row means.
///
/// Every field is optional and defaults to the CLI dope card's own default.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PdfCardOptionsV1 {
    /// Leading text of header line 1 — the CLI's rifle/profile name. Default
    /// `"Dope Card"`. Long headers are truncated to fit the page.
    #[serde(default)]
    pub title: Option<String>,
    /// Header `Loc:` label. Default empty.
    #[serde(default)]
    pub location: Option<String>,
    /// Footer `Powder:` label. Default empty.
    #[serde(default)]
    pub powder: Option<String>,
    /// Footer `Bullet:` label. Default empty.
    #[serde(default)]
    pub bullet: Option<String>,
    /// Crossing-target speed for the Lead column, in the request's `wind_speed_unit` — the
    /// same convention as the CLI's `--target-speed`
    /// (MBA-1325). The lead is `speed * time-of-flight` for a full-value 90° crossing,
    /// held on the windage axis, exactly as `trajectory -o pdf` computes it.
    ///
    /// Absent means "this card carries no lead data": the Lead column renders as em-dashes
    /// rather than a column of confident-looking zeroes. An explicit `0.0` is a different
    /// statement — a stationary target, whose lead genuinely is zero — and prints zeroes,
    /// matching the CLI's `--target-speed 0` default.
    #[serde(default)]
    pub target_speed: Option<f64>,
    /// Data-table font scale. Must be finite and within
    /// [`crate::pdf_dope_card::FONT_SCALE_RANGE`] (0.5..=3.0); out-of-band values are
    /// rejected rather than silently clamped, so what a stored request asks for is what it
    /// gets. Mutually exclusive with `font_preset`. Default 1.0.
    #[serde(default)]
    pub font_scale: Option<f64>,
    /// Named font scale: `"small"` (0.8), `"medium"` (1.0), `"large"` (1.4) — the CLI's
    /// `--font-preset` vocabulary, single-letter aliases included. An unrecognized preset
    /// is an error here (the CLI warns and falls back to medium; a stored request should
    /// not silently render at a size it did not ask for). Mutually exclusive with
    /// `font_scale`.
    #[serde(default)]
    pub font_preset: Option<String>,
    /// Render the data rows in bold. Default false.
    #[serde(default)]
    pub bold_data: bool,
}

/// One velocity band of an explicit velocity-keyed BC schedule
/// (`CardRequestV1::bc_segments`). `velocity_min`/`velocity_max` are in the
/// request's `velocity_unit` and must satisfy `velocity_min < velocity_max`;
/// `bc` is the BC (for the request's `drag_model`) that applies inside the band.
/// `bc` must lie in 0.0001..=100. Responses state the bands a card flew in the same shape,
/// in [`CardBcLadderV1::segments`] (MBA-1601).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CardBcSegmentV1 {
    pub velocity_min: f64,
    pub velocity_max: f64,
    pub bc: f64,
}

/// The BC ladder a card's rows flew (MBA-1601): [`CardResponseV1::bc_ladder`].
///
/// Under a ladder the scalar [`CardResponseV1::bc_for_solve`] is only the interior-gap
/// fallback, so this block is what states the BCs the card actually flew.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CardBcLadderV1 {
    /// Where the ladder came from: `"bc_segments"` (the request's own bands) or
    /// `"bc5d_table"` (the ladder `bc5d_table_path` generated for this load).
    pub source: &'static str,
    /// The bands as flown, `velocity_min`/`velocity_max` in the response's `units.velocity`.
    /// For `bc_segments` these are the request's bands verbatim and in request order; for
    /// `bc5d_table` the generated ladder, fastest band first.
    pub segments: Vec<CardBcSegmentV1>,
    /// True when some airspeed between the slowest and the fastest band lies in no band: there,
    /// and blended into the bands within up to 25 fps either side of a gap edge, `bc_for_solve`
    /// flies. False means `bc_for_solve` never flew on this card. It describes the ladder, not
    /// the flight: a gap the card's airspeeds never reach still reads true.
    pub interior_gap: bool,
}

/// The `sight_height` sentinel for "not supplied".
///
/// A serde field default is a nullary function: it cannot see the request, so it cannot know
/// which `sight_height_unit` the figure would have to be in. NaN stands in until `resolve()`
/// swaps it for `Units::default_sight_height`, which does know.
fn sight_height_unset() -> f64 {
    f64::NAN
}
fn default_humidity() -> f64 {
    50.0
}
fn default_cf() -> f64 {
    1.0
}

/// Drag model selector mirroring the CLI's `--drag-model` strings.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DragModelV1 {
    G1,
    #[default]
    G7,
    G2,
    G5,
    G6,
    G8,
    GI,
    GS,
    RA4,
}

impl From<DragModelV1> for DragModel {
    fn from(v: DragModelV1) -> Self {
        match v {
            DragModelV1::G1 => DragModel::G1,
            DragModelV1::G7 => DragModel::G7,
            DragModelV1::G2 => DragModel::G2,
            DragModelV1::G5 => DragModel::G5,
            DragModelV1::G6 => DragModel::G6,
            DragModelV1::G8 => DragModel::G8,
            DragModelV1::GI => DragModel::GI,
            DragModelV1::GS => DragModel::GS,
            DragModelV1::RA4 => DragModel::RA4,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CardRowV1 {
    /// Range in the request's `distance_unit`; `CardUnitsBlockV1::distance` names it.
    pub range: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drop_linear: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drop_adj: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub come_up: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wind_linear: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wind_adj: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub velocity: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub energy: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<f64>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub wind_columns: Vec<f64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CardUnitsBlockV1 {
    pub distance: &'static str,
    pub velocity: &'static str,
    pub energy: &'static str,
    pub drop: &'static str,
    pub wind_speed: &'static str,
    pub elevation_adjustment: String,
    pub windage_adjustment: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct CardResponseV1 {
    pub schema_version: u32,
    pub kind: &'static str,
    pub zero_distance: f64,
    /// The scalar BC fed to the zero solve and every sampled flight: the request's published
    /// `ballistic_coefficient`, or, when `bc5d_table_path` generated a ladder, that BC with
    /// the table's muzzle-velocity correction applied.
    ///
    /// With no [`Self::bc_ladder`] it is the BC every row flew, and the printed footer's
    /// `BC:`. With a `bc_ladder` it is only the interior-gap fallback: it flies only where
    /// `bc_ladder.interior_gap` allows, and never under a gapless ladder (every ladder a
    /// correction table builds), so it must not be presented as the card's BC (MBA-1601).
    pub bc_for_solve: f64,
    /// The BC ladder these rows flew, present only when one fed the solve: the request's
    /// `bc_segments`, or the ladder its `bc5d_table_path` generated (MBA-1601).
    ///
    /// Additive and absent on every card without a ladder, so those responses are
    /// byte-identical to before. A saved card has to be able to state the BCs its numbers
    /// came from long after the correction table has been replaced on disk, and under a
    /// ladder `bc_for_solve` alone does not do that.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub bc_ladder: Option<CardBcLadderV1>,
    pub units: CardUnitsBlockV1,
    /// Wind card only: the swept speeds, one per `wind_columns` entry.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub wind_speeds: Vec<f64>,
    /// Wind card only: one block of rows per wind angle.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub wind_angles_deg: Vec<f64>,
    pub rows: Vec<CardRowV1>,
    /// Wind card with multiple angles: rows for angles beyond the first.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub extra_angle_rows: Vec<Vec<CardRowV1>>,
    /// Present ONLY when the solved flight stopped short of the rows requested, in which case
    /// `rows` holds every row it did reach and nothing past them (MBA-1476 follow-up).
    ///
    /// Additive and absent on every card that ran to its requested `end`, so a caller reading
    /// an untruncated card sees byte-identical JSON to before. It is a field rather than only
    /// a log line because the apps and the Flask layer consume this shape: a card that quietly
    /// returns fewer rows than were asked for, with nothing on the response saying so, is the
    /// same class of silent failure as the substituted row this work removed.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub truncation: Option<CardTruncationV1>,
}

/// The wire form of [`CardTruncation`]: the rows a card could not print and why.
/// Distances are in the response's own `units.distance`.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct CardTruncationV1 {
    /// The furthest row the request asked for.
    pub requested_end: f64,
    /// The last row actually present in `rows`.
    pub last_row: f64,
    /// How far the solved flight got — a property of the load, not of the request.
    pub reach: f64,
}

impl CardTruncationV1 {
    fn new(truncation: CardTruncation) -> Self {
        Self {
            requested_end: truncation.requested_end,
            last_row: truncation.last_row,
            reach: truncation.reach,
        }
    }
}

/// Back to the engine type, so the wording lives on [`CardTruncation`] alone and no surface
/// has to restate the field mapping in order to say the same sentence.
impl From<CardTruncationV1> for CardTruncation {
    fn from(wire: CardTruncationV1) -> Self {
        Self {
            requested_end: wire.requested_end,
            last_row: wire.last_row,
            reach: wire.reach,
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CardServiceError {
    #[error("invalid request: {0}")]
    InvalidRequest(String),
    #[error("zero solve failed: {0}")]
    ZeroSolve(String),
    #[error("trajectory failed: {0}")]
    Trajectory(String),
    /// PDF rendering itself failed (font load/parse, or an empty row set). Gated with the
    /// only code path that can produce it, so a build without `pdf` sees an unchanged enum.
    #[cfg(feature = "pdf")]
    #[error("pdf generation failed: {0}")]
    Pdf(String),
    /// The card is too big to print ([`MAX_PDF_ROWS`] / [`MAX_PDF_PAGES`]). A resource
    /// refusal, not a failure: the request was well formed and the caller can be told
    /// exactly what is true of the card (how many rows, how many pages), so the message is
    /// carried verbatim rather than prefixed.
    #[cfg(feature = "pdf")]
    #[error("{0}")]
    TooLarge(String),
}

// --- Unit conversions: byte-identical constants to the CLI's UnitConverter ---
//
// One resolved unit per dimension, and one place where a unit becomes a factor. Every
// imperial arm and every metric arm below is the SAME EXPRESSION the single-scalar version
// of this module used for that dimension — the imperial arm for the dimensions the imperial
// preset fills, the metric arm for the metric preset's — so a request that states no
// per-dimension unit performs exactly the multiplications it always performed, in the same
// order, and lands on the same bits. The only genuinely new arms are the values neither
// preset produces (cm, km/h, knots, and feet of altitude), which no pre-existing request can
// select.
//
// The reverse conversions are deliberately NOT expressed as `to_metric` composed with a
// division. `Mph -> v` and `Mph -> (v * 0.44704) / 0.44704` are not the same f64, and the
// pre-existing behaviour is the former.

/// m/s per km/h.
const KPH_TO_MPS: f64 = 1.0 / 3.6;
/// m/s per knot: one nautical mile (1852 m) per hour, exactly.
const KNOTS_TO_MPS: f64 = 1852.0 / 3600.0;

struct Units {
    distance: CardDistanceUnit,
    velocity: CardVelocityUnit,
    mass: CardMassUnit,
    diameter: CardDiameterUnit,
    sight_height: CardLinearUnit,
    drop: CardLinearUnit,
    wind_speed: CardWindSpeedUnit,
    temperature: CardTemperatureUnit,
    pressure: CardPressureUnit,
    energy: CardEnergyUnit,
    altitude: CardAltitudeUnit,
}

impl Units {
    /// Settle every dimension: the request's own field where it states one, otherwise what
    /// the [`CardUnits`] preset implies.
    ///
    /// Pure, cheap, and free of validation, so the PDF path can settle the axes it prints in
    /// the header without repeating the request checks `resolve_inner` performs.
    fn resolve(req: &CardRequestV1) -> Self {
        let imperial = req.units == CardUnits::Imperial;
        let linear = if imperial {
            CardLinearUnit::Inches
        } else {
            CardLinearUnit::Mm
        };
        Self {
            distance: req.distance_unit.unwrap_or(if imperial {
                CardDistanceUnit::Yards
            } else {
                CardDistanceUnit::Meters
            }),
            velocity: req.velocity_unit.unwrap_or(if imperial {
                CardVelocityUnit::Fps
            } else {
                CardVelocityUnit::Mps
            }),
            mass: req.mass_unit.unwrap_or(if imperial {
                CardMassUnit::Grains
            } else {
                CardMassUnit::Grams
            }),
            diameter: req.diameter_unit.unwrap_or(if imperial {
                CardDiameterUnit::Inches
            } else {
                CardDiameterUnit::Mm
            }),
            sight_height: req.sight_height_unit.unwrap_or(linear),
            drop: req.drop_unit.unwrap_or(linear),
            wind_speed: req.wind_speed_unit.unwrap_or(if imperial {
                CardWindSpeedUnit::Mph
            } else {
                CardWindSpeedUnit::Mps
            }),
            temperature: req.temperature_unit.unwrap_or(if imperial {
                CardTemperatureUnit::Fahrenheit
            } else {
                CardTemperatureUnit::Celsius
            }),
            pressure: req.pressure_unit.unwrap_or(if imperial {
                CardPressureUnit::InHg
            } else {
                CardPressureUnit::HPa
            }),
            energy: req.energy_unit.unwrap_or(if imperial {
                CardEnergyUnit::FtLb
            } else {
                CardEnergyUnit::Joules
            }),
            // NOT `imperial`-dependent: `altitude` has always been metres in both systems.
            // See CardRequestV1::altitude_unit for why the preset must never reach it.
            altitude: req.altitude_unit.unwrap_or(CardAltitudeUnit::Meters),
        }
    }

    // --- into SI, for the solver ---

    fn velocity_to_metric(&self, v: f64) -> f64 {
        match self.velocity {
            CardVelocityUnit::Fps => v * 0.3048,
            CardVelocityUnit::Mps => v,
        }
    }
    fn mass_to_kg(&self, v: f64) -> f64 {
        match self.mass {
            CardMassUnit::Grains => v * GRAINS_TO_KG,
            CardMassUnit::Grams => v * 0.001,
        }
    }
    fn distance_to_metric(&self, v: f64) -> f64 {
        match self.distance {
            CardDistanceUnit::Yards => v * 0.9144,
            CardDistanceUnit::Meters => v,
        }
    }
    fn linear_to_metric(unit: CardLinearUnit, v: f64) -> f64 {
        match unit {
            CardLinearUnit::Inches => v * 0.0254,
            CardLinearUnit::Cm => v * 0.01,
            CardLinearUnit::Mm => v * 0.001,
        }
    }
    fn diameter_to_metric(&self, v: f64) -> f64 {
        match self.diameter {
            CardDiameterUnit::Inches => v * 0.0254,
            CardDiameterUnit::Mm => v * 0.001,
        }
    }
    fn sight_height_to_metric(&self, v: f64) -> f64 {
        Self::linear_to_metric(self.sight_height, v)
    }
    fn drop_to_metric(&self, v: f64) -> f64 {
        Self::linear_to_metric(self.drop, v)
    }
    fn wind_to_metric(&self, v: f64) -> f64 {
        match self.wind_speed {
            CardWindSpeedUnit::Mph => v * 0.44704,
            CardWindSpeedUnit::Mps => v,
            CardWindSpeedUnit::Kph => v * KPH_TO_MPS,
            CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS,
        }
    }
    fn temperature_to_metric(&self, v: f64) -> f64 {
        match self.temperature {
            CardTemperatureUnit::Fahrenheit => (v - 32.0) * 5.0 / 9.0,
            CardTemperatureUnit::Celsius => v,
        }
    }
    fn pressure_to_metric(&self, v: f64) -> f64 {
        match self.pressure {
            CardPressureUnit::InHg => v * 33.8639,
            CardPressureUnit::HPa => v,
        }
    }
    /// `altitude` in metres, which is what [`AtmosphericConditions::altitude`] wants and
    /// what every request that predates `altitude_unit` already supplied.
    fn altitude_to_metric(&self, v: f64) -> f64 {
        match self.altitude {
            CardAltitudeUnit::Feet => v * 0.3048,
            CardAltitudeUnit::Meters => v,
        }
    }

    // --- back out, for the printed row ---

    fn velocity_from_metric(&self, v: f64) -> f64 {
        match self.velocity {
            CardVelocityUnit::Fps => v / 0.3048,
            CardVelocityUnit::Mps => v,
        }
    }
    fn distance_from_metric(&self, v: f64) -> f64 {
        match self.distance {
            CardDistanceUnit::Yards => v / 0.9144,
            CardDistanceUnit::Meters => v,
        }
    }
    fn energy_from_metric(&self, v: f64) -> f64 {
        match self.energy {
            CardEnergyUnit::FtLb => v * 0.737562,
            CardEnergyUnit::Joules => v,
        }
    }
    fn drop_linear_from_metric(&self, v: f64) -> f64 {
        match self.drop {
            CardLinearUnit::Inches => v / 0.0254,
            CardLinearUnit::Cm => v * 100.0,
            CardLinearUnit::Mm => v * 1000.0,
        }
    }

    // --- column labels; the response's `units` block IS this, field for field ---

    /// Label for the distance axis, for error messages that must name a range.
    fn distance_label(&self) -> &'static str {
        match self.distance {
            CardDistanceUnit::Yards => "yd",
            CardDistanceUnit::Meters => "m",
        }
    }
    fn velocity_label(&self) -> &'static str {
        match self.velocity {
            CardVelocityUnit::Fps => "fps",
            CardVelocityUnit::Mps => "m/s",
        }
    }
    fn energy_label(&self) -> &'static str {
        match self.energy {
            CardEnergyUnit::FtLb => "ft-lb",
            CardEnergyUnit::Joules => "J",
        }
    }
    fn drop_label(&self) -> &'static str {
        match self.drop {
            CardLinearUnit::Inches => "in",
            CardLinearUnit::Cm => "cm",
            CardLinearUnit::Mm => "mm",
        }
    }
    fn wind_speed_label(&self) -> &'static str {
        match self.wind_speed {
            CardWindSpeedUnit::Mph => "mph",
            CardWindSpeedUnit::Mps => "m/s",
            CardWindSpeedUnit::Kph => "km/h",
            CardWindSpeedUnit::Knots => "kn",
        }
    }

    // --- the CLI's own axes, for the call sites that are pinned to CLI constants ---
    //
    // These do NOT reuse the conversions above. The BC5D path and the PDF header each
    // hardcode a factor that `main.rs` hardcodes at the same call site (3.280_839_895 vs
    // 1/0.3048; 15.4324 vs the exact grains-per-gram), and the golden tests pin the CLI's
    // digits. Sharing one factor between them would change numbers this work must not.
    //
    // Each of these helpers is compiled exactly where its call site is, rather than being
    // blanket-allowed as dead code, so that a helper which stops being called anywhere is
    // still a warning. For most of them that means a cfg attribute; `velocity_to_fps_bc5d`
    // carries none because its call site is the always-compiled `bc_segments` arm of
    // `resolve_bc_schedule`, so it is reached in every build.

    /// Display velocity -> fps using `parse_bc_segment`'s factor.
    fn velocity_to_fps_bc5d(&self, v: f64) -> f64 {
        match self.velocity {
            CardVelocityUnit::Fps => v,
            CardVelocityUnit::Mps => v * 3.280_839_895,
        }
    }
    /// fps -> display velocity, the inverse of [`Self::velocity_to_fps_bc5d`], for the band
    /// edges of a generated BC5D ladder (which no wasm32 build has).
    #[cfg(not(target_arch = "wasm32"))]
    fn velocity_from_fps_bc5d(&self, v: f64) -> f64 {
        match self.velocity {
            CardVelocityUnit::Fps => v,
            CardVelocityUnit::Mps => v / 3.280_839_895,
        }
    }
    /// Bullet weight -> grains using the CLI's BC5D/PDF factor.
    #[cfg(any(feature = "pdf", not(target_arch = "wasm32")))]
    fn mass_to_grains_cli(&self, v: f64) -> f64 {
        match self.mass {
            CardMassUnit::Grains => v,
            CardMassUnit::Grams => v * 15.4324,
        }
    }
    /// Bullet diameter -> inches, the BC5D table's caliber axis (which no wasm32 build has,
    /// there being no filesystem to read a table from).
    #[cfg(not(target_arch = "wasm32"))]
    fn diameter_to_inches(&self, v: f64) -> f64 {
        match self.diameter {
            CardDiameterUnit::Inches => v,
            CardDiameterUnit::Mm => v / 25.4,
        }
    }
    /// Muzzle velocity -> fps for the PDF header (`main.rs` divides by 0.3048 here).
    #[cfg(feature = "pdf")]
    fn velocity_to_fps_pdf(&self, v: f64) -> f64 {
        match self.velocity {
            CardVelocityUnit::Fps => v,
            CardVelocityUnit::Mps => v / 0.3048,
        }
    }
    /// Pressure -> inHg for the PDF header (`main.rs` uses 33.8639 on both PDF call sites,
    /// NOT `pdf_dope_card::INHG_TO_HPA`).
    #[cfg(feature = "pdf")]
    fn pressure_to_inhg(&self, v: f64) -> f64 {
        match self.pressure {
            CardPressureUnit::InHg => v,
            CardPressureUnit::HPa => v / 33.8639,
        }
    }
    /// Pressure -> hPa for the PDF header, same factor.
    #[cfg(feature = "pdf")]
    fn pressure_to_hpa(&self, v: f64) -> f64 {
        match self.pressure {
            CardPressureUnit::InHg => v * 33.8639,
            CardPressureUnit::HPa => v,
        }
    }
    /// Temperature -> °F for the PDF header.
    #[cfg(feature = "pdf")]
    fn temperature_to_fahrenheit(&self, v: f64) -> f64 {
        match self.temperature {
            CardTemperatureUnit::Fahrenheit => v,
            CardTemperatureUnit::Celsius => v * 9.0 / 5.0 + 32.0,
        }
    }
    /// Wind or crossing speed -> mph for the PDF header.
    #[cfg(feature = "pdf")]
    fn wind_to_mph(&self, v: f64) -> f64 {
        match self.wind_speed {
            CardWindSpeedUnit::Mph => v,
            CardWindSpeedUnit::Mps => v / 0.44704,
            CardWindSpeedUnit::Kph => v * KPH_TO_MPS / 0.44704,
            CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS / 0.44704,
        }
    }
    /// Altitude -> feet for the PDF header, which reports the altitude the SOLVE used.
    #[cfg(feature = "pdf")]
    fn altitude_to_feet(&self, v: f64) -> f64 {
        match self.altitude {
            CardAltitudeUnit::Feet => v,
            CardAltitudeUnit::Meters => v / 0.3048,
        }
    }

    // --- defaults that are themselves denominated ---

    /// The CLI's 1.5-inch sight height, restated in this request's `sight_height_unit`.
    /// The millimetre figure is the module's long-standing 38.0 (a rounded 1.5 in, not a
    /// conversion of it), and the centimetre figure is that same length, exactly.
    fn default_sight_height(&self) -> f64 {
        match self.sight_height {
            CardLinearUnit::Inches => 1.5,
            CardLinearUnit::Cm => 3.8,
            CardLinearUnit::Mm => 38.0,
        }
    }
    /// The CLI's 59 °F / 15 °C standard temperature, in this request's `temperature_unit`.
    fn default_temperature(&self) -> f64 {
        match self.temperature {
            CardTemperatureUnit::Fahrenheit => 59.0,
            CardTemperatureUnit::Celsius => 15.0,
        }
    }
    /// The CLI's 29.92 inHg / 1013.25 hPa standard pressure, in this request's
    /// `pressure_unit`.
    fn default_pressure(&self) -> f64 {
        match self.pressure {
            CardPressureUnit::InHg => 29.92,
            CardPressureUnit::HPa => 1013.25,
        }
    }
}

struct Resolved {
    u: Units,
    velocity_m: f64,
    mass_kg: f64,
    diameter_m: f64,
    sight_height_m: f64,
    zero_distance_m: f64,
    zero_poi_vertical_m: f64,
    zero_poi_horizontal_m: f64,
    sight_offset_lateral_m: f64,
    temperature_c: f64,
    pressure_hpa: f64,
    /// Site elevation in metres — which is what `altitude` already was for every request
    /// that states no `altitude_unit`, so this is a rename of an identity, not a conversion.
    altitude_m: f64,
    end_m: f64,
    elevation_click: Option<ClickValue>,
    windage_click: Option<ClickValue>,
    windage_unit: AdjustmentUnit,
    drag_model: DragModel,
    /// Scalar BC actually fed to the zero solve and every sampled run. Equals the
    /// request's `ballistic_coefficient` unless a BC5D table applied its muzzle
    /// correction (CLI parity: the scalar is the schedule's interior-gap fallback).
    bc_for_solve: f64,
    /// Velocity-keyed BC schedule (velocities in fps, the unit the solver compares
    /// against), from explicit `bc_segments` or generated from `bc5d_table_path`.
    bc_segments_fps: Option<Vec<BCSegmentData>>,
    /// The same schedule as the response states it ([`CardResponseV1::bc_ladder`]).
    bc_ladder: Option<CardBcLadderV1>,
}

fn resolve(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
    resolve_inner(req, true)
}

/// [`resolve`] WITHOUT the BC-schedule step — the request's declared axes, click
/// graduations and unit conversions, and nothing that touches the filesystem.
///
/// This is the resolve `card.pdf` performs when it prints caller-supplied rows: those rows
/// were computed elsewhere (they are the stored `card.range_table` response), so opening
/// `bc5d_table_path` here would do nothing but couple a reprint to whether that file is
/// still on the device — which is exactly the coupling printing stored rows exists to
/// break. `bc_for_solve` is left at the request's published BC and `bc_ladder` at `None`;
/// neither is used for the footer on that path (the stored card's own are).
#[cfg(feature = "pdf")]
fn resolve_axes_only(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
    resolve_inner(req, false)
}

fn resolve_inner(
    req: &CardRequestV1,
    load_bc_schedule: bool,
) -> Result<Resolved, CardServiceError> {
    let u = Units::resolve(req);

    for (name, v) in [
        ("muzzle_velocity", req.muzzle_velocity),
        ("ballistic_coefficient", req.ballistic_coefficient),
        ("mass", req.mass),
        ("diameter", req.diameter),
        ("zero_distance", req.zero_distance),
        ("start", req.start),
        ("end", req.end),
        ("step", req.step),
    ] {
        if !v.is_finite() || v <= 0.0 {
            return Err(CardServiceError::InvalidRequest(format!(
                "{name} must be finite and positive, got {v}"
            )));
        }
    }
    if req.end < req.start {
        return Err(CardServiceError::InvalidRequest(
            "end must be >= start".into(),
        ));
    }
    if !(0.5..=1.5).contains(&req.elevation_cf) || !(0.5..=1.5).contains(&req.windage_cf) {
        return Err(CardServiceError::InvalidRequest(
            "tracking correction factors must lie in (0.5, 1.5)".into(),
        ));
    }

    // Each of these three defaults is itself denominated, so it is taken from the dimension
    // that governs the field rather than from the preset (`Units` restates the CLI's own
    // figures per unit). `sight_height`'s sentinel is NaN because a serde field default
    // cannot see the request it belongs to.
    let sight_height = if req.sight_height.is_nan() {
        u.default_sight_height()
    } else {
        req.sight_height
    };
    let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
    let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());

    let parse_click =
        |label: &str, s: &Option<String>| -> Result<Option<ClickValue>, CardServiceError> {
            s.as_deref()
                .map(|raw| {
                    parse_click_value(raw)
                        .map_err(|e| CardServiceError::InvalidRequest(format!("{label}: {e}")))
                })
                .transpose()
        };
    let elevation_click = parse_click("elevation_click_value", &req.elevation_click_value)?;
    let windage_click =
        parse_click("windage_click_value", &req.windage_click_value)?.or(elevation_click);

    if req.adjustment_unit == AdjustmentUnit::Clicks && elevation_click.is_none() {
        return Err(CardServiceError::InvalidRequest(
            "adjustment_unit 'clicks' requires elevation_click_value".into(),
        ));
    }
    let windage_unit = req.windage_unit.unwrap_or(req.adjustment_unit);
    if windage_unit == AdjustmentUnit::Clicks && windage_click.is_none() {
        return Err(CardServiceError::InvalidRequest(
            "windage_unit 'clicks' requires a click graduation".into(),
        ));
    }

    let (bc_for_solve, bc_segments_fps, bc_ladder) = if load_bc_schedule {
        resolve_bc_schedule(req, &u)?
    } else {
        (req.ballistic_coefficient, None, None)
    };

    Ok(Resolved {
        bc_for_solve,
        bc_segments_fps,
        bc_ladder,
        velocity_m: u.velocity_to_metric(req.muzzle_velocity),
        mass_kg: u.mass_to_kg(req.mass),
        diameter_m: u.diameter_to_metric(req.diameter),
        sight_height_m: u.sight_height_to_metric(sight_height),
        zero_distance_m: u.distance_to_metric(req.zero_distance),
        zero_poi_vertical_m: u.drop_to_metric(req.zero_poi_vertical),
        zero_poi_horizontal_m: u.drop_to_metric(req.zero_poi_horizontal),
        sight_offset_lateral_m: u.sight_height_to_metric(req.sight_offset_lateral),
        temperature_c: u.temperature_to_metric(temperature),
        pressure_hpa: u.pressure_to_metric(pressure),
        altitude_m: u.altitude_to_metric(req.altitude),
        end_m: u.distance_to_metric(req.end),
        elevation_click,
        windage_click,
        windage_unit,
        drag_model: req.drag_model.into(),
        u,
    })
}

/// `(scalar BC for the solve, optional fps-keyed schedule, the same schedule as the response
/// states it)`. The last two are both present or both absent.
type BcSchedule = (f64, Option<Vec<BCSegmentData>>, Option<CardBcLadderV1>);

/// Resolve the velocity-keyed BC schedule for a card request, mirroring the CLI's
/// precedence exactly: explicit `bc_segments` win outright (and leave the scalar BC
/// untouched, like `--bc-segment` restoring the pre-table BC); otherwise a
/// `bc5d_table_path` generates the same segment ladder `--bc-table-dir` does and
/// applies the table's muzzle correction to the scalar fallback BC.
///
/// Returns a [`BcSchedule`].
fn resolve_bc_schedule(req: &CardRequestV1, u: &Units) -> Result<BcSchedule, CardServiceError> {
    if let Some(segments) = req.bc_segments.as_ref().filter(|s| !s.is_empty()) {
        if segments.len() > crate::solve_json::MAX_BC_SEGMENTS_V1 {
            return Err(CardServiceError::InvalidRequest(format!(
                "bc_segments must have at most {} bands, got {}",
                crate::solve_json::MAX_BC_SEGMENTS_V1,
                segments.len()
            )));
        }
        let (bc_min, bc_max) = crate::solve_json::limits::BALLISTIC_COEFFICIENT;
        let mut converted = Vec::with_capacity(segments.len());
        for (index, segment) in segments.iter().enumerate() {
            if !segment.velocity_min.is_finite()
                || !segment.velocity_max.is_finite()
                || !segment.bc.is_finite()
            {
                return Err(CardServiceError::InvalidRequest(format!(
                    "bc_segments[{index}]: velocity_min, velocity_max, and bc must be finite"
                )));
            }
            if segment.velocity_min >= segment.velocity_max {
                return Err(CardServiceError::InvalidRequest(format!(
                    "bc_segments[{index}]: velocity_min must be < velocity_max"
                )));
            }
            if segment.bc <= 0.0 {
                return Err(CardServiceError::InvalidRequest(format!(
                    "bc_segments[{index}]: bc must be > 0"
                )));
            }
            if !(bc_min..=bc_max).contains(&segment.bc) {
                return Err(CardServiceError::InvalidRequest(format!(
                    "bc_segments[{index}]: bc must be between {bc_min} and {bc_max}, got {}",
                    segment.bc
                )));
            }
            converted.push(BCSegmentData {
                // Display velocity -> fps with the exact factor the CLI's parse_bc_segment
                // uses; the band edges are in `velocity_unit`, like `muzzle_velocity`.
                velocity_min: u.velocity_to_fps_bc5d(segment.velocity_min),
                velocity_max: u.velocity_to_fps_bc5d(segment.velocity_max),
                bc_value: segment.bc,
            });
        }
        reject_overlapping_bc_segments(segments, u)?;
        // Built only once the ladder has passed every check above.
        let ladder = CardBcLadderV1 {
            source: "bc_segments",
            segments: segments.clone(),
            interior_gap: crate::bc_estimation::has_interior_gap(&converted),
        };
        return Ok((req.ballistic_coefficient, Some(converted), Some(ladder)));
    }

    let Some(path) = req.bc5d_table_path.as_deref() else {
        return Ok((req.ballistic_coefficient, None, None));
    };

    #[cfg(target_arch = "wasm32")]
    {
        let _ = (path, u);
        Err(CardServiceError::InvalidRequest(
            "bc5d_table_path is not supported on this target (no filesystem); supply \
             bc_segments instead"
                .into(),
        ))
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        // The table's CONTENT must be for this shot's caliber, not merely CRC-valid: a
        // wrong-caliber table silently biases every row of the card (see
        // Bc5dTable::ensure_caliber_matches), so a mismatch is refused here rather than
        // applied — and rather than quietly falling back to an uncorrected card, which
        // the caller could not distinguish from a corrected one.
        let diameter_in = u.diameter_to_inches(req.diameter);
        let table = crate::bc_table_5d::path_cache::load_verified_for_caliber(
            std::path::Path::new(path),
            diameter_in,
        )
        .map_err(|e| CardServiceError::InvalidRequest(format!("bc5d_table_path: {e}")))?;

        // The BC5D axes are grains + fps; convert from the request's units the same
        // way the CLI does. The v2 tables carry only G1/G7 planes — anything else is
        // typed as G1, matching the CLI/WASM coercion.
        let weight_grains = u.mass_to_grains_cli(req.mass);
        let muzzle_fps = u.velocity_to_fps_bc5d(req.muzzle_velocity);
        let drag_type = if req.drag_model == DragModelV1::G7 {
            "G7"
        } else {
            "G1"
        };
        let base_bc = req.ballistic_coefficient;

        match table.generate_segments(base_bc, drag_type, weight_grains, Some(muzzle_fps)) {
            Some(segments) => {
                // CLI parity: the scalar BC becomes the muzzle-corrected fallback for
                // interior coverage gaps (main.rs: trued_bc = base * muzzle_correction).
                let fallback_bc = table.get_effective_bc(
                    weight_grains,
                    base_bc,
                    muzzle_fps,
                    muzzle_fps,
                    drag_type,
                );
                // The generated ladder, stated in the request's own velocity unit.
                let ladder = CardBcLadderV1 {
                    source: "bc5d_table",
                    segments: segments
                        .iter()
                        .map(|s| CardBcSegmentV1 {
                            velocity_min: u.velocity_from_fps_bc5d(s.velocity_min),
                            velocity_max: u.velocity_from_fps_bc5d(s.velocity_max),
                            bc: s.bc_value,
                        })
                        .collect(),
                    interior_gap: crate::bc_estimation::has_interior_gap(&segments),
                };
                Ok((fallback_bc, Some(segments), Some(ladder)))
            }
            // A neutral table (every sampled cell ~= 1.0) carries no correction:
            // keep the published scalar BC, exactly like the CLI.
            None => Ok((base_bc, None, None)),
        }
    }
}

/// Refuse a card ladder whose bands overlap (MBA-1600). Card accepts bands in any order, so they
/// are compared in `velocity_min` order; touching edges and gaps are legal. The engine's lookup
/// flies the FIRST listed band containing a speed and blends nothing across an overlap
/// (`bc_estimation.rs`), so an overlapping ladder would fly differently by listing order.
/// Compared in the request's `velocity_unit`: the fps conversion is monotonic, so a ladder that
/// does not overlap here cannot overlap after it. Messages quote the caller's own indices.
fn reject_overlapping_bc_segments(
    segments: &[CardBcSegmentV1],
    u: &Units,
) -> Result<(), CardServiceError> {
    let mut order: Vec<usize> = (0..segments.len()).collect();
    // Stable sort: equal velocity_min keep request order, so the later-listed band is reported.
    order.sort_by(|&a, &b| {
        segments[a]
            .velocity_min
            .total_cmp(&segments[b].velocity_min)
    });
    for pair in order.windows(2) {
        let (lower, upper) = (pair[0], pair[1]);
        let (lo, hi) = (&segments[lower], &segments[upper]);
        if hi.velocity_min < lo.velocity_max {
            let unit = u.velocity_label();
            return Err(CardServiceError::InvalidRequest(format!(
                "bc_segments[{upper}] ({} to {} {unit}) overlaps bc_segments[{lower}] ({} to {} \
                 {unit}): bands may touch or leave gaps but must not overlap",
                hi.velocity_min, hi.velocity_max, lo.velocity_min, lo.velocity_max
            )));
        }
    }
    Ok(())
}

fn solve_zero(req: &CardRequestV1, r: &Resolved) -> Result<f64, CardServiceError> {
    let zero_inputs = BallisticInputs {
        bc_value: r.bc_for_solve,
        bc_type: r.drag_model,
        bullet_mass: r.mass_kg,
        muzzle_velocity: r.velocity_m,
        bullet_diameter: r.diameter_m,
        bullet_length: crate::truing::fallback_bullet_length_m(r.diameter_m, r.mass_kg),
        sight_height: r.sight_height_m,
        use_rk4: true,
        zero_poi_vertical_m: r.zero_poi_vertical_m,
        zero_poi_horizontal_m: r.zero_poi_horizontal_m,
        sight_offset_lateral_m: r.sight_offset_lateral_m,
        // The zero MUST be solved with the same velocity-keyed BC schedule the
        // sampled flights use (the 0.22.11 auto-zero lesson: a schedule that changes
        // early-flight drag would otherwise mis-zero every row).
        use_bc_segments: r.bc_segments_fps.is_some(),
        bc_segments_data: r.bc_segments_fps.clone(),
        ..Default::default()
    };
    let atmosphere = AtmosphericConditions {
        temperature: r.temperature_c,
        pressure: r.pressure_hpa,
        humidity: req.humidity,
        altitude: r.altitude_m,
    };
    crate::calculate_zero_angle_with_conditions(
        zero_inputs,
        r.zero_distance_m,
        r.sight_height_m,
        WindConditions::default(),
        atmosphere,
    )
    .map_err(|e| CardServiceError::ZeroSolve(e.to_string()))
}

#[allow(clippy::too_many_arguments)]
fn sampled(
    req: &CardRequestV1,
    r: &Resolved,
    wind_speed_m: f64,
    wind_direction_deg: f64,
    zero_angle: f64,
) -> Result<SampledFlight, CardServiceError> {
    run_sampled_flight(
        r.velocity_m,
        r.bc_for_solve,
        r.mass_kg,
        r.diameter_m,
        r.drag_model,
        r.sight_height_m,
        r.temperature_c,
        r.pressure_hpa,
        req.humidity,
        r.altitude_m,
        wind_speed_m,
        wind_direction_deg,
        // MBA-1476: at least one whole grid cell past the last row asked for — see
        // card_sample_max_range_m for why that headroom decides reachability.
        card_sample_max_range_m(r.end_m),
        // MBA-1476: the engine's own card grid, never the request's row spacing.
        CARD_SAMPLE_INTERVAL_M,
        zero_angle,
        // The same schedule as the zero solve above, on every card surface
        // (come-ups, range table, wind card) consistently.
        r.bc_segments_fps.clone(),
        None,
        None,
        r.zero_poi_vertical_m,
        r.zero_poi_horizontal_m,
        r.sight_offset_lateral_m,
        Some(r.zero_distance_m),
    )
    .map_err(|e| CardServiceError::Trajectory(e.to_string()))
}

/// Read one card row's sample off a solved flight, or `None` when the flight does not span it
/// (MBA-1476).
///
/// The nearest-sample-within-one-and-a-half-steps search this replaces answered a range the
/// flight had no sample for with a neighbour's numbers, invisibly. There is no tolerance to
/// tune here: [`sample_at_range`] interpolates exactly at the requested range whenever the
/// flight spans it, and a range it cannot span yields nothing at all. The caller ends the card
/// there and records a [`CardTruncation`] — it never substitutes, and it never drops the row
/// without saying so.
fn row_sample(
    samples: &[crate::trajectory_sampling::TrajectorySample],
    range_m: f64,
) -> Option<crate::trajectory_sampling::TrajectorySample> {
    sample_at_range(samples, range_m)
}

/// The error a card returns when its flight reaches NONE of the rows requested — there is no
/// card to truncate, so this stays a refusal (MBA-1476 follow-up).
fn no_rows_error(first_row_display: f64, reach_m: f64, u: &Units) -> CardServiceError {
    CardServiceError::Trajectory(range_not_sampled_message(
        first_row_display,
        u.distance_from_metric(reach_m),
        u.distance_label(),
    ))
}

/// Record the truncation of a card whose row loop stopped early, in display units.
fn truncation_of(
    requested_end: f64,
    last_row: f64,
    reach_m: f64,
    u: &Units,
) -> Option<CardTruncationV1> {
    Some(CardTruncationV1::new(CardTruncation {
        requested_end,
        last_row,
        reach: u.distance_from_metric(reach_m),
    }))
}

/// The response's per-dimension label block: one label per dimension, read off the same
/// resolved [`Units`] the rows were converted with, so a column cannot be computed in one
/// unit and headed with another.
fn units_block(req: &CardRequestV1, u: &Units, windage_unit: AdjustmentUnit) -> CardUnitsBlockV1 {
    CardUnitsBlockV1 {
        distance: u.distance_label(),
        velocity: u.velocity_label(),
        energy: u.energy_label(),
        drop: u.drop_label(),
        wind_speed: u.wind_speed_label(),
        elevation_adjustment: adjustment_unit_label(req.adjustment_unit),
        windage_adjustment: adjustment_unit_label(windage_unit),
    }
}

/// Come-ups: elevation dial per range plus the incremental come-up between rows.
/// Mirrors the CLI's `come-ups` command row-for-row.
pub fn come_ups_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
    let r = resolve(req)?;
    let zero_angle = solve_zero(req, &r)?;
    let flight = sampled(
        req,
        &r,
        r.u.wind_to_metric(req.wind_speed),
        req.wind_direction_deg,
        zero_angle,
    )?;

    let mut rows: Vec<CardRowV1> = Vec::new();
    let mut truncation = None;
    let mut prev_drop_adj: f64 = 0.0;
    let mut current_range = req.start;
    while current_range <= req.end + 0.1 {
        let range_m = r.u.distance_to_metric(current_range);
        let Some(sample) = row_sample(&flight.samples, range_m) else {
            let Some(last) = rows.last() else {
                return Err(no_rows_error(current_range, flight.reach_m, &r.u));
            };
            truncation = truncation_of(req.end, last.range, flight.reach_m, &r.u);
            break;
        };
        let drop_yd = r.u.distance_from_metric(sample.drop_m);
        // MBA-1476: the row's OWN range, not a nearby sample's — the angular conversion
        // divides by the distance the row is labelled with.
        let drop_adj = adjustment_display(
            drop_yd,
            current_range,
            req.adjustment_unit,
            r.elevation_click,
            req.zero_set_elevation_bias_mil,
            req.elevation_cf,
        )
        .value;
        rows.push(CardRowV1 {
            range: current_range,
            drop_linear: None,
            drop_adj: Some(drop_adj),
            come_up: Some(drop_adj - prev_drop_adj),
            wind_linear: None,
            wind_adj: None,
            velocity: Some(r.u.velocity_from_metric(sample.velocity_mps)),
            energy: Some(r.u.energy_from_metric(sample.energy_j)),
            time: Some(sample.time_s),
            wind_columns: Vec::new(),
        });
        prev_drop_adj = drop_adj;
        current_range += req.step;
    }

    Ok(CardResponseV1 {
        schema_version: CARD_SCHEMA_VERSION_V1,
        kind: "come_ups",
        zero_distance: req.zero_distance,
        bc_for_solve: r.bc_for_solve,
        bc_ladder: r.bc_ladder.clone(),
        units: units_block(req, &r.u, req.adjustment_unit),
        wind_speeds: Vec::new(),
        wind_angles_deg: Vec::new(),
        rows,
        extra_angle_rows: Vec::new(),
        truncation,
    })
}

/// Range table: drop and wind on possibly different display axes.
/// Mirrors the CLI's `range-table` command row-for-row (two solves: with wind for
/// drift, without wind for the pure elevation axis).
pub fn range_table_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
    // Discards the PDF-only extras; see `range_table_rows`.
    range_table_rows(req, None).map(|(card, _lead, _bc)| card)
}

/// The one range-table computation, shared by the on-screen `card.range_table` and the
/// printable `card.pdf`.
///
/// Returns `(the card, the Lead column, the scalar BC the solve ran with)`:
///
/// * The card is exactly what `card.range_table` serializes — `range_table_v1` is a
///   discarding wrapper, so the PDF's Range/Drop/Wind figures ARE the on-screen figures.
///   They are taken from here rather than recomputed because recomputing them is the one
///   way the printed card could ever disagree with the rows the shooter already read.
/// * The Lead column parallels `card.rows` one-to-one. `lead_target_speed` is in the
///   request's `wind_speed_unit`; `None` (no lead requested) yields all `None`, which the
///   PDF renders as em-dashes rather than fake zeroes.
/// * The BC is `Resolved::bc_for_solve` — the published BC unless a BC5D table applied its
///   muzzle correction — which the PDF footer prints when the card flew no ladder. The
///   footer must state the BC the numbers above it came from, not the one the request
///   nominated; under a ladder that is the card's `bc_ladder` range (MBA-1601), and this
///   scalar is only its interior-gap fallback.
fn range_table_rows(
    req: &CardRequestV1,
    lead_target_speed: Option<f64>,
) -> Result<(CardResponseV1, Vec<Option<f64>>, f64), CardServiceError> {
    let r = resolve(req)?;
    let zero_angle = solve_zero(req, &r)?;
    let wind_flight = sampled(
        req,
        &r,
        r.u.wind_to_metric(req.wind_speed),
        req.wind_direction_deg,
        zero_angle,
    )?;
    let no_wind_flight = sampled(req, &r, 0.0, 0.0, zero_angle)?;
    // Both flights feed every row, so the card can only run as far as the shorter of them.
    let reach_m = wind_flight.reach_m.min(no_wind_flight.reach_m);
    let lead_speed_mps = lead_target_speed.map(|speed| r.u.wind_to_metric(speed));

    let mut rows: Vec<CardRowV1> = Vec::new();
    let mut lead_adj = Vec::new();
    let mut truncation = None;
    let mut current_range = req.start;
    while current_range <= req.end + 0.1 {
        let range_m = r.u.distance_to_metric(current_range);
        let (Some(nw), Some(w)) = (
            row_sample(&no_wind_flight.samples, range_m),
            row_sample(&wind_flight.samples, range_m),
        ) else {
            let Some(last) = rows.last() else {
                return Err(no_rows_error(current_range, reach_m, &r.u));
            };
            truncation = truncation_of(req.end, last.range, reach_m, &r.u);
            break;
        };
        // MBA-1476: the row's OWN range on both axes.
        let range_display = current_range;
        let drop_yd = r.u.distance_from_metric(nw.drop_m);
        let drop_adj = adjustment_display(
            drop_yd,
            range_display,
            req.adjustment_unit,
            r.elevation_click,
            req.zero_set_elevation_bias_mil,
            req.elevation_cf,
        )
        .value;
        let drift_yd = r.u.distance_from_metric(w.wind_drift_m);
        let wind_adj = windage_adjustment_display(
            drift_yd,
            range_display,
            r.windage_unit,
            r.windage_click,
            req.zero_set_windage_bias_mil,
            req.windage_cf,
        )
        .value;
        // Lead is the windage-axis hold for a full-value 90° crossing target:
        // `speed * time-of-flight` (MBA-1287's shared moving-target math), on the
        // no-wind sample whose time this row already reports. It is a COMPONENT
        // hold composed on top of the wind dial, which already carries the
        // zero-set bias, so it stays bias-free (bias 0.0) while still being
        // divided by the windage tracking CF — the same treatment
        // `main.rs::dope_card_row_from_sample` gives the CLI's Lead column.
        lead_adj.push(lead_speed_mps.map(|speed_mps| {
            let lead_display = r.u.distance_from_metric(
                crate::lead_from_tof(speed_mps, 90.0, nw.time_s, nw.distance_m).lead_m,
            );
            windage_adjustment_display(
                lead_display,
                range_display,
                r.windage_unit,
                r.windage_click,
                0.0,
                req.windage_cf,
            )
            .value
        }));
        rows.push(CardRowV1 {
            range: current_range,
            drop_linear: Some(r.u.drop_linear_from_metric(nw.drop_m)),
            drop_adj: Some(drop_adj),
            come_up: None,
            wind_linear: Some(r.u.drop_linear_from_metric(w.wind_drift_m)),
            wind_adj: Some(wind_adj),
            velocity: Some(r.u.velocity_from_metric(nw.velocity_mps)),
            energy: Some(r.u.energy_from_metric(nw.energy_j)),
            time: Some(nw.time_s),
            wind_columns: Vec::new(),
        });
        current_range += req.step;
    }

    debug_assert_eq!(rows.len(), lead_adj.len(), "Lead column must parallel rows");
    Ok((
        CardResponseV1 {
            schema_version: CARD_SCHEMA_VERSION_V1,
            kind: "range_table",
            zero_distance: req.zero_distance,
            bc_for_solve: r.bc_for_solve,
            bc_ladder: r.bc_ladder.clone(),
            units: units_block(req, &r.u, r.windage_unit),
            wind_speeds: Vec::new(),
            wind_angles_deg: Vec::new(),
            rows,
            extra_angle_rows: Vec::new(),
            truncation,
        },
        lead_adj,
        r.bc_for_solve,
    ))
}

/// Wind card: drift matrix, ranges x wind speeds, per wind-FROM angle.
/// Mirrors the CLI's `wind-card` command cell-for-cell. The windage axis uses
/// `adjustment_unit` (the CLI's wind-card has a single unit for the matrix).
pub fn wind_card_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
    if req.wind_speeds.is_empty() {
        return Err(CardServiceError::InvalidRequest(
            "wind_card requires at least one entry in wind_speeds".into(),
        ));
    }
    let r = resolve(req)?;
    let zero_angle = solve_zero(req, &r)?;

    let angles: Vec<f64> = if req.wind_angles_deg.is_empty() {
        vec![90.0]
    } else {
        req.wind_angles_deg.clone()
    };

    let mut ranges: Vec<f64> = Vec::new();
    let mut current = req.start;
    while current <= req.end + 0.1 {
        ranges.push(current);
        current += req.step;
    }

    // Every angle/speed combination is its own flight and they do not all reach equally far
    // (a crosswind bleeds a little velocity), but the matrix has ONE range axis. So the card
    // runs to the shortest of them: `reachable` is the number of leading ranges every flight
    // supplies, and the ragged tails are trimmed once, below.
    let mut reachable = ranges.len();
    let mut reach_m = f64::INFINITY;
    let mut per_angle_drifts: Vec<Vec<Vec<f64>>> = Vec::new();
    for &angle_deg in &angles {
        let mut all_drifts: Vec<Vec<f64>> = vec![Vec::new(); ranges.len()];
        for &ws in &req.wind_speeds {
            let flight = sampled(req, &r, r.u.wind_to_metric(ws), angle_deg, zero_angle)?;
            reach_m = reach_m.min(flight.reach_m);
            for (ri, &range_display) in ranges.iter().enumerate().take(reachable) {
                let range_m = r.u.distance_to_metric(range_display);
                // MBA-1476: a range the flight cannot supply used to become a 0.0 cell —
                // indistinguishable from "no drift at all" on a wind card.
                let Some(sample) = row_sample(&flight.samples, range_m) else {
                    reachable = ri;
                    break;
                };
                let drift_yd = r.u.distance_from_metric(sample.wind_drift_m);
                let drift_adj = adjustment_display(
                    drift_yd,
                    range_display,
                    req.adjustment_unit,
                    r.windage_click,
                    req.zero_set_windage_bias_mil,
                    req.windage_cf,
                )
                .value;
                all_drifts[ri].push(drift_adj);
            }
        }
        per_angle_drifts.push(all_drifts);
    }

    let truncation = if reachable < ranges.len() {
        if reachable == 0 {
            return Err(no_rows_error(ranges[0], reach_m, &r.u));
        }
        let last = ranges[reachable - 1];
        ranges.truncate(reachable);
        truncation_of(req.end, last, reach_m, &r.u)
    } else {
        None
    };

    let mut per_angle_rows: Vec<Vec<CardRowV1>> = per_angle_drifts
        .into_iter()
        .map(|all_drifts| {
            ranges
                .iter()
                .zip(all_drifts)
                .map(|(&range, wind_columns)| CardRowV1 {
                    range,
                    drop_linear: None,
                    drop_adj: None,
                    come_up: None,
                    wind_linear: None,
                    wind_adj: None,
                    velocity: None,
                    energy: None,
                    time: None,
                    wind_columns,
                })
                .collect()
        })
        .collect();

    let first = per_angle_rows.remove(0);
    Ok(CardResponseV1 {
        schema_version: CARD_SCHEMA_VERSION_V1,
        kind: "wind_card",
        zero_distance: req.zero_distance,
        bc_for_solve: r.bc_for_solve,
        bc_ladder: r.bc_ladder.clone(),
        units: units_block(req, &r.u, req.adjustment_unit),
        wind_speeds: req.wind_speeds.clone(),
        wind_angles_deg: angles,
        rows: first,
        extra_angle_rows: per_angle_rows,
        truncation,
    })
}

// ---------------------------------------------------------------------------------------
// Printable PDF dope card (`card.pdf`), feature `pdf`.
//
// Two ways in, one renderer:
//
// * REPRINT — the caller supplies the rows: `StoredCardV1` carries the stored
//   `card.range_table` response verbatim. Nothing is solved, no correction table is opened,
//   and the footer's BC and provenance come from that document. Only under this construction
//   is a reprint of a saved card actually a reprint: it cannot drift when the engine is
//   bumped, or when the BC5D table file at the stored path is overwritten in place by a
//   table-set refresh.
// * SOLVE — no rows supplied: `range_table_rows` runs, which is the same call
//   `card.range_table` makes (`range_table_v1` is a discarding wrapper over it). This is the
//   pre-existing behaviour, unchanged, and what the CLI-shaped caller gets.
//
// Neither path recomputes an adjustment, a unit conversion or a trajectory that the card it
// prints already performed.
// ---------------------------------------------------------------------------------------

/// The one card kind `card.pdf` can print, in the `kind` spelling
/// [`CardResponseV1::kind`] uses.
///
/// A come-ups card's Come-Up column and a wind card's swept drift matrix are not columns a
/// range-table card has, so a request for either is REFUSED rather than answered with a
/// range table — an `ok` response whose defining field was silently ignored is the defect
/// (a stored wind card exported as a range table asserted 0.0 drift on every row while the
/// screen showed up to -0.42 MIL).
#[cfg(feature = "pdf")]
pub const PDF_CARD_KIND: &str = "range_table";

/// Rows a printable card may carry.
///
/// Checked from the row count itself, before a document exists — the byte cap
/// (`bridge::MAX_PDF_BYTES`) can only refuse a 26 MB `Vec<u8>` that has already been built
/// and paginated. At ~0.5 KiB/row over the ~815 KiB font floor this bound keeps every
/// accepted card comfortably inside that cap, which remains the backstop for the other way
/// to make a huge document: header/footer labels, which are drawn verbatim on every page.
#[cfg(feature = "pdf")]
pub const MAX_PDF_ROWS: usize = 5_000;

/// Pages a printable card may run to. Bounds the one row set the row cap above cannot:
/// few enough rows, but at a font scale that fits very few of them per page.
#[cfg(feature = "pdf")]
pub const MAX_PDF_PAGES: usize = 60;

/// Where the printed rows came from — reported so a caller can verify it got a reprint
/// rather than a re-solve, which is otherwise indistinguishable from the document.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PdfRowSource {
    /// Solved by this call, exactly as `card.range_table` would for the same request.
    Solve,
    /// Supplied by the caller: a stored `card.range_table` response, printed as-is.
    StoredRows,
}

#[cfg(feature = "pdf")]
impl PdfRowSource {
    /// Wire spelling for the bridge's `source` field.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Solve => "solve",
            Self::StoredRows => "stored_rows",
        }
    }
}

/// A card whose rows already exist: print THESE numbers instead of solving.
///
/// `card` is the stored `card.range_table` response, pasted verbatim — an app keeps that
/// document for every saved card and shows it on screen, so handing the same bytes back is
/// what makes the paper and the screen the same card by construction rather than by
/// coincidence. The two provenance strings are printed in the footer so a card in a
/// shooter's pocket can be reconciled with a screen afterwards; both are optional, and an
/// absent or empty one prints nothing at all rather than a placeholder.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StoredCardV1 {
    /// The stored response, exactly as this engine emitted it.
    pub card: StoredCardResponseV1,
    /// Engine version that produced the rows (`engine_version` from the bridge envelope of
    /// the call that produced them). Absent/empty prints no engine line.
    #[serde(default)]
    pub engine_version: Option<String>,
    /// Correction-table version the rows were solved against — the published BC5D table-set
    /// version an app records at save time. Absent/empty prints no table line, which is the
    /// honest rendering of "this card used no correction table".
    #[serde(default)]
    pub bc5d_table_version: Option<String>,
}

/// A stored [`CardResponseV1`], as a deserializable mirror.
///
/// [`CardResponseV1`] is `Serialize` only (and its `units` block holds `&'static str`s), so
/// a stored response is read back through this twin. It accepts the response document
/// unchanged, field for field: `kind` and `units` are load-bearing here — they say what the
/// rows ARE and what a row MEANS — while the descriptive scalars are optional so a card
/// stored by an older engine still prints.
///
/// **Deliberately NOT `deny_unknown_fields`** (unlike [`CardRequestV1`], where the caller
/// really is the author of the document). What arrives here is this engine's own output,
/// round-tripped through an app's storage — never hand-written input — so strictness buys
/// no validation and costs a hard cross-version break: the FIRST field ever added to
/// `CardResponseV1` would make every card saved by the newer platform completely
/// unexportable on the older one. The two apps carry independent engine pins and ship
/// through separate stores, so that staggering is the normal case, not a downgrade. An
/// unknown field is therefore ignored, exactly as the apps' own decoders ignore it, and the
/// stored cells still reach the paper. The same reasoning applies to
/// [`StoredCardUnitsBlockV1`] and [`StoredCardRowV1`] below.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct StoredCardResponseV1 {
    /// Which card this is. Anything but [`PDF_CARD_KIND`] is refused.
    pub kind: String,
    /// Column labels and the range unit of the stored rows. The printed headings are
    /// these, not the request's, because these are what the rows were computed in.
    pub units: StoredCardUnitsBlockV1,
    /// The rows to print, in order.
    pub rows: Vec<StoredCardRowV1>,
    #[serde(default)]
    pub schema_version: Option<u32>,
    #[serde(default)]
    pub zero_distance: Option<f64>,
    /// The scalar BC the stored rows were computed with; printed in the footer when the card
    /// carries no `bc_ladder`. Absent (a card saved by an engine before
    /// [`CardResponseV1::bc_for_solve`] existed) falls back to the request's published
    /// `ballistic_coefficient`. Under a ladder it is only the interior-gap fallback, and the
    /// footer prints the ladder's range instead (MBA-1601).
    #[serde(default)]
    pub bc_for_solve: Option<f64>,
    /// The [`CardResponseV1::bc_ladder`] block, round-tripped (MBA-1601): present when the
    /// stored rows flew a BC ladder, and then the footer's `BC:` states the ladder's range.
    ///
    /// A card saved before the block existed has none, and reprints its stored scalar exactly
    /// as before: the reprint never re-derives a ladder from the request, so a solve and a
    /// reprint of the same document cannot be labelled differently. Regenerating such a card
    /// prints the range.
    #[serde(default)]
    pub bc_ladder: Option<StoredCardBcLadderV1>,
    /// Present only on a wind card, and therefore a refusal here.
    #[serde(default)]
    pub wind_speeds: Vec<f64>,
    #[serde(default)]
    pub wind_angles_deg: Vec<f64>,
    #[serde(default)]
    pub extra_angle_rows: Vec<Vec<StoredCardRowV1>>,
    /// Present only when the stored card itself stopped short of the rows its request asked
    /// for — the [`CardResponseV1::truncation`] block, round-tripped (MBA-1477).
    ///
    /// Without this the reprint path loses the notice: `StoredCardResponseV1` ignores unknown
    /// fields by design, so a saved card whose rows stopped short came back through here as an
    /// unremarkable short card and printed with nothing on the paper saying rows were missing.
    /// The screen it was saved from said so; the paper made from that very document did not.
    ///
    /// A card saved before this field existed simply has no block, which is indistinguishable
    /// from an untruncated card and is the best that can be said of it.
    #[serde(default)]
    pub truncation: Option<StoredCardTruncationV1>,
}

/// The truncation block of a stored response (see [`CardTruncationV1`], which this mirrors).
///
/// All three numbers are REQUIRED, unlike the descriptive scalars elsewhere in a stored card:
/// they are printed together as one sentence, and a block missing one of them would print
/// "TRUNCATED at 0 yd" on a field card. A card that was not truncated omits the whole block,
/// which is the only shape that means "nothing to say".
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
pub struct StoredCardTruncationV1 {
    pub requested_end: f64,
    pub last_row: f64,
    pub reach: f64,
}

/// The `bc_ladder` block of a stored response (see [`CardBcLadderV1`], which this mirrors).
/// Unknown fields are ignored, for the reason [`StoredCardResponseV1`] gives.
///
/// `segments` and `interior_gap` are REQUIRED, like the numbers of a stored truncation block:
/// the footer is printed from them together, and a block missing either cannot say which BCs
/// flew. A card that flew no ladder omits the whole block.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct StoredCardBcLadderV1 {
    pub segments: Vec<StoredCardBcSegmentV1>,
    pub interior_gap: bool,
    /// `"bc_segments"` or `"bc5d_table"`; informational, not printed.
    #[serde(default)]
    pub source: Option<String>,
}

/// One band of a stored `bc_ladder` (see [`CardBcSegmentV1`], which this mirrors). Unknown
/// fields are ignored, for the reason [`StoredCardResponseV1`] gives.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize)]
pub struct StoredCardBcSegmentV1 {
    pub velocity_min: f64,
    pub velocity_max: f64,
    pub bc: f64,
}

#[cfg(feature = "pdf")]
impl From<StoredCardTruncationV1> for CardTruncationV1 {
    fn from(stored: StoredCardTruncationV1) -> Self {
        Self {
            requested_end: stored.requested_end,
            last_row: stored.last_row,
            reach: stored.reach,
        }
    }
}

/// The `units` block of a stored response (see [`CardUnitsBlockV1`], which this mirrors).
/// Unknown fields are ignored, for the reason [`StoredCardResponseV1`] gives.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct StoredCardUnitsBlockV1 {
    /// `"yd"` / `"m"` — the unit the stored `range` values are in.
    pub distance: String,
    /// Drop column label ("MIL"/"MOA"/"SMOA"/"IPHY"/"CLICKS").
    pub elevation_adjustment: String,
    /// Wind and Lead column label; may differ from the elevation label (MBA-1410).
    pub windage_adjustment: String,
    #[serde(default)]
    pub velocity: Option<String>,
    #[serde(default)]
    pub energy: Option<String>,
    #[serde(default)]
    pub drop: Option<String>,
    #[serde(default)]
    pub wind_speed: Option<String>,
}

/// One stored row (see [`CardRowV1`], which this mirrors). Only `range` is required; a
/// column the stored card did not carry stays `None` and prints as an em-dash rather than a
/// fabricated zero. Unknown fields are ignored, for the reason [`StoredCardResponseV1`]
/// gives.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct StoredCardRowV1 {
    pub range: f64,
    #[serde(default)]
    pub drop_linear: Option<f64>,
    #[serde(default)]
    pub drop_adj: Option<f64>,
    #[serde(default)]
    pub come_up: Option<f64>,
    #[serde(default)]
    pub wind_linear: Option<f64>,
    #[serde(default)]
    pub wind_adj: Option<f64>,
    #[serde(default)]
    pub velocity: Option<f64>,
    #[serde(default)]
    pub energy: Option<f64>,
    /// Time of flight, seconds. The Lead column of a reprint is derived from this — pure
    /// arithmetic on a number the stored card already carries, not a new trajectory. A row
    /// without it prints an em-dash for Lead.
    #[serde(default)]
    pub time: Option<f64>,
    #[serde(default)]
    pub wind_columns: Vec<f64>,
}

/// A rendered PDF dope card: the document plus the facts a transport needs to describe it
/// without re-parsing the bytes.
#[cfg(feature = "pdf")]
#[derive(Debug, Clone)]
pub struct PdfCardV1 {
    pub pdf_bytes: Vec<u8>,
    /// Pages in `pdf_bytes`, from [`crate::pdf_dope_card::dope_card_page_count`] — the
    /// same function the generator paginated by, not a second estimate of it.
    pub page_count: usize,
    /// Rows printed. On the solve path this is the on-screen `card.range_table` row count;
    /// on the reprint path it is the stored row count, so a caller can confirm every stored
    /// row reached the paper.
    pub row_count: usize,
    /// Solved here, or printed from caller-supplied rows.
    pub source: PdfRowSource,
    /// Characters of the header title (`pdf.title`) the card's font could not draw —
    /// distinct, in order of first use, and empty when the title printed in full.
    ///
    /// Not an error: the document is complete and every ROW printed. But a title is how a
    /// shooter tells one card from another, and Liberation Sans covers no CJK, Arabic,
    /// Hebrew, Thai or emoji, so a name in any of those used to vanish from the paper with
    /// `ok: true` and nothing said. Each such character prints as
    /// [`crate::pdf_dope_card::UNPRINTABLE_SUBSTITUTE`] and is named here, so a caller that
    /// accepts any non-empty card name (both apps do) can warn at export time instead of
    /// handing over an unidentifiable card.
    pub unprintable_title_chars: String,
    /// Present ONLY when the printed rows stop short of the card that was asked for — the
    /// same block [`CardResponseV1::truncation`] carries, for the same reason (MBA-1477).
    ///
    /// Both paths fill it: a SOLVE takes the truncation of the very `card.range_table` rows
    /// it printed, and a REPRINT takes the one the stored card was saved with. Until this
    /// existed the PDF was the only card surface with no truncation signal at all — not the
    /// stderr warning a CLI reader gets, not the `truncated` block in CLI JSON, not
    /// `CardResponseV1::truncation` on the bridge — so a caller could not even tell that the
    /// document it was about to hand a shooter was short. It is also printed in the
    /// document's own footer, which is the half that survives being carried to a range.
    pub truncation: Option<CardTruncationV1>,
}

/// Resolve the effective table font scale from the mutually exclusive `font_scale` /
/// `font_preset` options.
#[cfg(feature = "pdf")]
fn resolve_font_scale(opts: &PdfCardOptionsV1) -> Result<f32, CardServiceError> {
    use crate::pdf_dope_card::{FontSizePreset, FONT_SCALE_RANGE};

    match (opts.font_scale, opts.font_preset.as_deref()) {
        (Some(_), Some(_)) => Err(CardServiceError::InvalidRequest(
            "pdf.font_scale and pdf.font_preset are mutually exclusive; supply one".into(),
        )),
        (Some(scale), None) => {
            let scale = scale as f32;
            if !scale.is_finite() || !FONT_SCALE_RANGE.contains(&scale) {
                return Err(CardServiceError::InvalidRequest(format!(
                    "pdf.font_scale must be finite and within {}..={}, got {}",
                    FONT_SCALE_RANGE.start(),
                    FONT_SCALE_RANGE.end(),
                    opts.font_scale.unwrap_or(f64::NAN)
                )));
            }
            Ok(scale)
        }
        (None, Some(preset)) => FontSizePreset::from_str(preset)
            .map(|p| p.scale())
            .ok_or_else(|| {
                CardServiceError::InvalidRequest(format!(
                    "pdf.font_preset '{preset}' is not one of small, medium, large"
                ))
            }),
        (None, None) => Ok(1.0),
    }
}

/// The rows to print plus everything the header/footer states about where they came from.
/// Filled by exactly one of the two paths in [`pdf_card_v1`], which then share one
/// renderer, so a reprint and a solve cannot be laid out or labelled differently.
#[cfg(feature = "pdf")]
struct RowsToPrint {
    rows: Vec<crate::card::CardRow>,
    source: PdfRowSource,
    /// Footer `BC:` — the scalar BC these rows were computed with, printed when `bc_label`
    /// is empty.
    bc: f64,
    /// Footer `BC:` text for a card that flew a BC ladder (its range, from
    /// [`crate::pdf_dope_card::ladder_bc_label`]); empty for a card that flew none (MBA-1601).
    bc_label: String,
    /// Footer `Engine:` — empty prints nothing.
    engine_version: String,
    /// Footer `Table:` — empty prints nothing.
    table_version: String,
    /// Drop column label.
    elevation_unit_label: String,
    /// Wind and Lead column label.
    windage_unit_label: String,
    /// Footer truncation notice — `None` on a card that reached every row it asked for.
    /// Both paths fill it, so the printed notice cannot depend on where the rows came from.
    truncation: Option<CardTruncationV1>,
}

/// Turn a stored response's rows into printable rows, deriving only the Lead column.
///
/// The Drop and Wind cells are the stored values, untouched. Lead is `target_speed x stored
/// ToF` held on the windage axis — the same [`crate::lead_from_tof`] arithmetic
/// `range_table_rows` performs, applied to the time of flight the stored row already
/// carries. No trajectory, no zero solve, no correction table.
#[cfg(feature = "pdf")]
fn stored_rows_to_print(
    stored: &StoredCardResponseV1,
    req: &CardRequestV1,
    r: &Resolved,
    target_speed: Option<f64>,
) -> Vec<crate::card::CardRow> {
    use crate::card::CardRow;

    let lead_speed_mps = target_speed.map(|speed| r.u.wind_to_metric(speed));
    stored
        .rows
        .iter()
        .map(|row| CardRow {
            range: row.range,
            drop_linear: row.drop_linear,
            drop_adj: row.drop_adj,
            come_up: row.come_up,
            wind_linear: row.wind_linear,
            wind_adj: row.wind_adj,
            velocity: row.velocity,
            energy: row.energy,
            time: row.time,
            lead_adj: lead_speed_mps.zip(row.time).map(|(speed_mps, tof_s)| {
                let range_m = r.u.distance_to_metric(row.range);
                let lead_display = r.u.distance_from_metric(
                    crate::lead_from_tof(speed_mps, 90.0, tof_s, range_m).lead_m,
                );
                // Bias-free (it composes on top of the wind dial, which carries the
                // zero-set bias) but still divided by the windage tracking CF — the exact
                // treatment `range_table_rows` and the CLI's Lead column give it.
                windage_adjustment_display(
                    lead_display,
                    row.range,
                    r.windage_unit,
                    r.windage_click,
                    0.0,
                    req.windage_cf,
                )
                .value
            }),
            wind_columns: row.wind_columns.clone(),
        })
        .collect()
}

/// Reject a stored card that is not the range table it must be, cell values included.
#[cfg(feature = "pdf")]
fn validate_stored_card(
    stored: &StoredCardV1,
    req: &CardRequestV1,
    r: &Resolved,
) -> Result<(), CardServiceError> {
    let card = &stored.card;
    if card.kind != PDF_CARD_KIND {
        return Err(CardServiceError::InvalidRequest(format!(
            "card.pdf prints a {PDF_CARD_KIND} card; the stored card's kind is '{}'. Its \
             columns are not a range table's, so it is refused rather than reprinted as one",
            card.kind
        )));
    }
    // The same "this is not a range table" test the REQUEST gets (see the `wind_speeds` /
    // `wind_angles_deg` loop in `pdf_card_v1`), field for field. The two halves used to
    // disagree — `wind_angles_deg` was refused on the request and accepted here — and the
    // stored half is the one that has to hold when a future kind starts emitting it.
    for (field, present) in [
        ("wind_speeds", !card.wind_speeds.is_empty()),
        ("wind_angles_deg", !card.wind_angles_deg.is_empty()),
        ("extra_angle_rows", !card.extra_angle_rows.is_empty()),
    ] {
        if present {
            return Err(CardServiceError::InvalidRequest(format!(
                "the stored card carries {field}, a wind card's defining field, so it is not the \
                 {PDF_CARD_KIND} response it claims to be"
            )));
        }
    }
    if card.rows.is_empty() {
        return Err(CardServiceError::InvalidRequest(
            "the stored card has no rows; an empty dope card is not a document".into(),
        ));
    }

    // A row means something only in a unit. If the stored labels and the request's own axes
    // disagree, the two are not the same card — printing anyway would put one unit's numbers
    // under another unit's heading, which is precisely the failure the shared request shape
    // exists to prevent.
    let elevation = adjustment_unit_label(req.adjustment_unit);
    let windage = adjustment_unit_label(r.windage_unit);
    let distance = r.u.distance_label();
    for (field, stored_label, request_label) in [
        ("units.distance", card.units.distance.as_str(), distance),
        (
            "units.elevation_adjustment",
            card.units.elevation_adjustment.as_str(),
            elevation.as_str(),
        ),
        (
            "units.windage_adjustment",
            card.units.windage_adjustment.as_str(),
            windage.as_str(),
        ),
    ] {
        if stored_label != request_label {
            return Err(CardServiceError::InvalidRequest(format!(
                "the stored card's {field} is '{stored_label}' but this request's own axes say \
                 '{request_label}' — the stored rows and the request are not the same card"
            )));
        }
    }

    // Same rule as the cells below: a non-finite figure would print "NaN"/"inf" — here in a
    // sentence telling a shooter where their card stops, which is worse than in a column.
    if let Some(t) = &card.truncation {
        for (field, value) in [
            ("requested_end", t.requested_end),
            ("last_row", t.last_row),
            ("reach", t.reach),
        ] {
            if !value.is_finite() {
                return Err(CardServiceError::InvalidRequest(format!(
                    "the stored card's truncation.{field} is not a finite number"
                )));
            }
        }
    }

    // The footer prints the ladder's BC range from this block, so a block with nothing to
    // print, or a BC no ladder could fly, is refused rather than printed (MBA-1601).
    if let Some(ladder) = &card.bc_ladder {
        if ladder.segments.is_empty() {
            return Err(CardServiceError::InvalidRequest(
                "the stored card's bc_ladder has no segments".into(),
            ));
        }
        for (index, segment) in ladder.segments.iter().enumerate() {
            if !(segment.bc.is_finite() && segment.bc > 0.0) {
                return Err(CardServiceError::InvalidRequest(format!(
                    "the stored card's bc_ladder.segments[{index}].bc is not a finite positive \
                     number"
                )));
            }
        }
    }

    // A non-finite cell would print "NaN"/"inf" on a field card.
    for (index, row) in card.rows.iter().enumerate() {
        for (field, value) in [
            ("range", Some(row.range)),
            ("drop_adj", row.drop_adj),
            ("wind_adj", row.wind_adj),
            ("time", row.time),
        ] {
            if value.is_some_and(|v| !v.is_finite()) {
                return Err(CardServiceError::InvalidRequest(format!(
                    "the stored card's rows[{index}].{field} is not a finite number"
                )));
            }
        }
    }
    Ok(())
}

/// Render the printable PDF dope card for a card request.
///
/// `stored` decides where the numbers come from, and it is the whole point of this surface:
///
/// * `Some(card)` — REPRINT. The rows are the caller's: the stored `card.range_table`
///   response for this same request. Nothing is solved, `bc5d_table_path` is never opened,
///   and the footer's BC, engine version and table version are the stored card's. A saved
///   card therefore reprints identically after an engine bump, after the correction table at
///   the stored path is overwritten in place, and even after that file is deleted.
/// * `None` — SOLVE. `range_table_rows` runs, i.e. literally the rows [`range_table_v1`]
///   would return for this request, and the footer states THIS build's version. Unchanged
///   behaviour for a caller that has no stored rows.
///
/// Either way this prints a [`PDF_CARD_KIND`] card and nothing else: a request carrying a
/// wind card's `wind_speeds`/`wind_angles_deg`, or a stored card of another kind, is refused.
/// Both paths map their rows onto the CLI's Range/Drop/Wind/Lead dope card, plus the Lead
/// column that `CardRequestV1::pdf`'s `target_speed` asks for. The Range column is
/// denominated in the stored/requested `distance_unit`, unlike `trajectory -o pdf`, whose
/// dope card is always yards.
///
/// The header/footer block is always imperial, matching both CLI PDF call sites: whatever the
/// request's velocity/temperature/pressure/altitude/wind/weight dimensions are denominated in,
/// they are converted for display only. The `Solver:` label reports this build (`online` with
/// the `online` feature, otherwise `offline`) and the timestamp is generation time, so neither
/// is caller-settable — and neither is a number a shooter dials.
#[cfg(feature = "pdf")]
pub fn pdf_card_v1(
    req: &CardRequestV1,
    stored: Option<&StoredCardV1>,
) -> Result<PdfCardV1, CardServiceError> {
    use crate::pdf_dope_card::{
        calculate_density_altitude, dope_card_page_count, generate_dope_card_pdf, ladder_bc_label,
        DopeCardConfig, RangeUnit,
    };

    let opts = req.pdf.clone().unwrap_or_default();
    let drag_model = DragModel::from(req.drag_model).to_string();
    // Validate presentation options BEFORE spending a zero solve and two trajectories on a
    // request that cannot be rendered anyway.
    let font_scale = resolve_font_scale(&opts)?;
    // A non-finite crossing speed would print "inf"/"NaN" in every Lead cell rather than
    // failing. (A NEGATIVE speed is accepted, matching the CLI: it reads as the mover
    // crossing the other way and simply flips the sign of the hold.)
    if opts.target_speed.is_some_and(|speed| !speed.is_finite()) {
        return Err(CardServiceError::InvalidRequest(
            "pdf.target_speed must be finite".into(),
        ));
    }

    // A wind card's defining fields cannot be honoured by a range-table PDF. Refuse them
    // instead of returning a document whose Wind column contradicts the screen.
    for (field, present) in [
        ("wind_speeds", !req.wind_speeds.is_empty()),
        ("wind_angles_deg", !req.wind_angles_deg.is_empty()),
    ] {
        if present {
            return Err(CardServiceError::InvalidRequest(format!(
                "card.pdf prints a {PDF_CARD_KIND} card; this request carries {field}, a wind \
                 card's defining field, which a range-table PDF cannot show and would silently \
                 ignore. There is no wind_card or come_ups PDF in this build"
            )));
        }
    }

    let to_print = match stored {
        Some(stored) => {
            // Axes and click graduations only: no BC schedule, so no correction table is
            // opened for a card whose numbers are already decided.
            let r = resolve_axes_only(req)?;
            validate_stored_card(stored, req, &r)?;
            let bc = stored
                .card
                .bc_for_solve
                .unwrap_or(req.ballistic_coefficient);
            RowsToPrint {
                rows: stored_rows_to_print(&stored.card, req, &r, opts.target_speed),
                source: PdfRowSource::StoredRows,
                bc,
                // Only the stored card's own ladder block: a card saved without one reprints
                // its scalar as before, never a ladder re-derived from the request.
                bc_label: stored
                    .card
                    .bc_ladder
                    .as_ref()
                    .map(|ladder| {
                        let bcs: Vec<f64> = ladder.segments.iter().map(|s| s.bc).collect();
                        ladder_bc_label(&drag_model, &bcs, bc, ladder.interior_gap)
                    })
                    .unwrap_or_default(),
                engine_version: stored.engine_version.clone().unwrap_or_default(),
                table_version: stored.bc5d_table_version.clone().unwrap_or_default(),
                elevation_unit_label: stored.card.units.elevation_adjustment.clone(),
                windage_unit_label: stored.card.units.windage_adjustment.clone(),
                // The truncation the card was SAVED with. Nothing is re-derived from the
                // stored row set here — a reprint prints the card it was handed, and that
                // includes what the card already said about itself.
                truncation: stored.card.truncation.map(CardTruncationV1::from),
            }
        }
        None => {
            let (card, lead_adj, bc_for_solve) = range_table_rows(req, opts.target_speed)?;
            if card.rows.is_empty() {
                // `generate_dope_card_pdf` refuses an empty row set, and rightly: an empty
                // dope card is not a document. Name the cause the caller can act on instead.
                return Err(CardServiceError::InvalidRequest(format!(
                    "no card rows in {}..={} — the trajectory does not reach this range domain, \
                     or step is coarser than the samples",
                    req.start, req.end
                )));
            }
            RowsToPrint {
                rows: card
                    .rows
                    .iter()
                    .zip(&lead_adj)
                    .map(|(row, lead)| crate::card::CardRow {
                        range: row.range,
                        drop_linear: row.drop_linear,
                        drop_adj: row.drop_adj,
                        come_up: row.come_up,
                        wind_linear: row.wind_linear,
                        wind_adj: row.wind_adj,
                        velocity: row.velocity,
                        energy: row.energy,
                        time: row.time,
                        lead_adj: *lead,
                        wind_columns: row.wind_columns.clone(),
                    })
                    .collect(),
                source: PdfRowSource::Solve,
                bc: bc_for_solve,
                // The ladder `card.range_table` reports for these very rows.
                bc_label: card
                    .bc_ladder
                    .as_ref()
                    .map(|ladder| {
                        let bcs: Vec<f64> = ladder.segments.iter().map(|s| s.bc).collect();
                        ladder_bc_label(&drag_model, &bcs, bc_for_solve, ladder.interior_gap)
                    })
                    .unwrap_or_default(),
                // No table version is knowable from a path, so none is claimed; the engine
                // version is this build's, which is what produced these rows.
                engine_version: env!("CARGO_PKG_VERSION").to_string(),
                table_version: String::new(),
                // The labels `card.range_table`'s `units` block reports for this request:
                // Drop in the elevation unit, Wind AND Lead in the (possibly different,
                // MBA-1410) windage unit.
                elevation_unit_label: card.units.elevation_adjustment.clone(),
                windage_unit_label: card.units.windage_adjustment.clone(),
                // The truncation of the very rows above, not a second determination of it:
                // `range_table_rows` IS `card.range_table`, so the paper and the screen
                // truncate identically or not at all.
                truncation: card.truncation,
            }
        }
    };

    // Refuse on the row/page count now that the rows are known — before a document is built.
    // The byte cap downstream can only measure a document it already paid for.
    let page_count = dope_card_page_count(to_print.rows.len(), font_scale);
    if to_print.rows.len() > MAX_PDF_ROWS || page_count > MAX_PDF_PAGES {
        return Err(CardServiceError::TooLarge(format!(
            "this card has too many rows to print: {} rows, {page_count} pages (the limits are \
             {MAX_PDF_ROWS} rows and {MAX_PDF_PAGES} pages)",
            to_print.rows.len()
        )));
    }

    // The request's own axes, for the header. Resolved here rather than taken from above
    // because neither branch hands a `Resolved` back — the reprint's is scoped to its arm and
    // the solve's lives inside `range_table_rows`. Resolving twice is safe precisely because
    // `Units::resolve` is a pure function of the request: the header cannot land on axes the
    // rows were not computed in.
    let u = Units::resolve(req);
    // The atmosphere defaults `resolve()` applies, restated for the header so the printed
    // conditions are the ones the solve used rather than blanks.
    let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
    let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
    // inHg <-> hPa via the CLI dope card's own factor (main.rs uses 33.8639 on both PDF
    // call sites), NOT pdf_dope_card::INHG_TO_HPA — matching the shipped header exactly.
    let pressure_inhg = u.pressure_to_inhg(pressure);
    let pressure_hpa = u.pressure_to_hpa(pressure);
    let temperature_f = u.temperature_to_fahrenheit(temperature);
    // NOTE: `CardRequestV1::altitude` defaults to METRES whatever the `units` preset says —
    // the one dimension whose fallback is not the preset's, because it never was (see
    // `CardRequestV1::altitude_unit`). The header reports the altitude the solve actually
    // used, so it converts out of whatever `altitude_unit` settled on.
    let altitude_ft = u.altitude_to_feet(req.altitude);

    let config = DopeCardConfig {
        rifle_name: opts
            .title
            .clone()
            .unwrap_or_else(|| "Dope Card".to_string()),
        location: opts.location.clone().unwrap_or_default(),
        density_altitude_ft: calculate_density_altitude(altitude_ft, pressure_inhg, temperature_f),
        pressure_inhg,
        pressure_hpa,
        temperature_f,
        altitude_ft,
        wind_speed_mph: u.wind_to_mph(req.wind_speed),
        // Absent target speed prints 0 here (there is no lead to state) while the Lead
        // column itself stays em-dashed; an explicit 0.0 prints the same 0 and zeroes.
        target_speed_mph: match opts.target_speed {
            Some(speed) => u.wind_to_mph(speed),
            None => 0.0,
        },
        solver_mode: if cfg!(feature = "online") {
            "online".to_string()
        } else {
            "offline".to_string()
        },
        powder: opts.powder.clone().unwrap_or_default(),
        bullet: opts.bullet.clone().unwrap_or_default(),
        weight_gr: u.mass_to_grains_cli(req.mass),
        // The BC these rows came from: the stored card's own, or this solve's (which is the
        // muzzle-corrected value when a BC5D table applied one). Under a BC ladder the footer
        // prints `bc_label`, the ladder's range, instead (MBA-1601).
        bc: to_print.bc,
        drag_model,
        bc_label: to_print.bc_label.clone(),
        velocity_fps: u.velocity_to_fps_pdf(req.muzzle_velocity),
        font_scale,
        bold_data: opts.bold_data,
        // The card's own axes: Drop in the elevation unit, Wind AND Lead in the (possibly
        // different, MBA-1410) windage unit — from the document that owns the rows.
        elevation_unit_label: to_print.elevation_unit_label.clone(),
        windage_unit_label: to_print.windage_unit_label.clone(),
        // Provenance on the paper, so a printed card and a screen can be reconciled later.
        engine_version: to_print.engine_version.clone(),
        table_version: to_print.table_version.clone(),
        // MBA-1477: and the truncation on the paper too, in the one wording every card
        // surface uses, denominated in the card's own distance unit (which
        // `validate_stored_card` has already forced to agree with the request's).
        truncation_note: to_print
            .truncation
            .map(|t| CardTruncation::from(t).printed_note(u.distance_label()))
            .unwrap_or_default(),
    };

    let range_unit = match u.distance {
        CardDistanceUnit::Yards => RangeUnit::Yards,
        CardDistanceUnit::Meters => RangeUnit::Meters,
    };
    // Read BEFORE the document is built, off the same string the header will draw, so the
    // report describes this card's own title rather than a truncation of it.
    let unprintable_title_chars = crate::pdf_dope_card::unprintable_chars(&config.rifle_name);
    let pdf_bytes = generate_dope_card_pdf(&config, &to_print.rows, range_unit)
        .map_err(|e| CardServiceError::Pdf(e.to_string()))?;

    Ok(PdfCardV1 {
        page_count,
        row_count: to_print.rows.len(),
        source: to_print.source,
        pdf_bytes,
        unprintable_title_chars,
        truncation: to_print.truncation,
    })
}