ballistics-engine 0.50.1

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
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
//! Enhanced atmospheric calculations for ballistics.
//!
//! This module provides Rust-accelerated implementations of atmospheric calculations
//! with full ICAO Standard Atmosphere support for improved accuracy at all altitudes.
//!
//! # Humid air: one model, one lookup (0.50.0)
//!
//! Every solver family flies the same humid air. [`TrajectorySolver`](crate::TrajectorySolver),
//! the kernels (`compute_derivatives`, `try_integrate_trajectory`, `try_solve_trajectory_rust`,
//! `fast_integrate*`) and the lean Monte Carlo all take their per-step air from [`air_at`], over
//! a [`KernelAtmosphere`] that carries the station's relative humidity, so a station's density
//! and its sound speed cannot disagree about the humidity.
//!
//! - **At the station.** [`StationAir::new`] calls [`calculate_atmosphere`]: the CIPM-2007
//!   moist-air density ([`calculate_air_density_cimp`]: the virial compressibility `Z` and the
//!   enhancement factor `f`) and the moist speed of sound ([`moist_speed_of_sound`]). Both use
//!   one water-vapour mole fraction, `x_v = (RH/100) f p_sv / p`, with `p_sv` from the
//!   Wagner-Pruss saturation-pressure equation over liquid water. The sound speed is first order
//!   in `x_v`: `gamma = 1.4 (1 - 0.062 x_v)`, `R = 287.0531 (1 + 0.378 x_v)`,
//!   `c = sqrt(gamma R T)`. At 0 % it is the engine's one dry value, `sqrt(1.4 · 287.0531 · T)`,
//!   340.294 m/s at 15 °C.
//! - **Aloft (0.50.0: one vapour model).** The governing air (the station, or the downrange
//!   [`AtmoSock`] zone that replaces it as the base, each with its own humidity) is well mixed:
//!   its water-vapour mole fraction `x_v` is held at every height, for all three of the lapse,
//!   the density and the sound speed. Temperature and pressure start from the governing air's
//!   own values and follow the ICAO layers' lapse rates in geopotential height, with the
//!   virtual-temperature (moist) hydrostatic exponent: the dry one scaled by the moist-air
//!   molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`, the factor the CIPM-2007 density
//!   applies, so moist air's pressure falls more slowly with height. The density scales the
//!   governing air's by `(T_0 · P) / (P_0 · T)`, and the sound speed is the formula above at the
//!   local temperature and the governing `x_v`. Held aloft, `x_v` exceeds saturation in the colder
//!   air: at every height above a saturated station, and from about 2.2 km above a 15 °C / 50 %
//!   station and 0.4 km above a 35 °C / 90 % one. At +3 km it is 1.35 times saturation over the
//!   first and 2.06 times over the second, and at +10 km 34 and 29 times. Condensation is not
//!   modelled. At 0 % every term is the dry one, bit for bit. Until 0.50.0 the sound speed held the
//!   relative humidity instead (re-deriving `x_v` at the local temperature and pressure) and the
//!   lapse was dry.
//! - **Units.** [`RelativeHumidity`] stores a percent. Every Rust field and function takes a
//!   percent (`AtmosphericConditions::humidity`, `BallisticInputs::humidity_percent`, an
//!   [`AtmoSegment`]'s slot 2); only the SI JSON wire (`relative_humidity`) carries a fraction,
//!   and it converts through [`RelativeHumidity::try_fraction`].
//! - **Default.** An omitted humidity is [`DEFAULT_HUMIDITY_PERCENT`], 50 %, unless another reading
//!   supplies it (a saved profile, the shot day for `--zero-humidity`), with two exceptions: an
//!   `.a7p` file's absent humidity is 0 % (the format's own meaning), and the bridge's `true.*`
//!   commands require `humidity_pct`.
//! - **Validation.** One rule, [`RelativeHumidity::try_percent`] / [`RelativeHumidity::try_fraction`]:
//!   a reading up to [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] (5 points) outside 0-100 % is the
//!   saturated or dry air it measures and flies exactly as 100 % or 0 %; anything farther out,
//!   NaN or infinite is refused. Air that cannot exist (an uncapped `x_v` of 1 or more) is
//!   refused by [`StationAir::new`] and [`AtmoSock::validate`], the same test the
//!   `atmosphere.density_altitude` service applies.
//!
//! Two gas constants appear here, one from each standard, each used the same way on every
//! path: the CIPM-2007 density's `R / M_a = 8.314472 / 0.02896546 = 287.0478` J/(kg·K), inside
//! its own formula, and the US Standard Atmosphere 1976 dry-air constant `R_AIR = 287.0531`,
//! for the hydrostatic lapse (divided by `M_m / M_a` for humid air) and the sound speed.
//!
//! One deliberate exception: the muzzle Miller stability factor
//! ([`crate::stability::compute_stability_coefficient`]) keeps Miller's published dry
//! temperature and pressure correction, so it does not move with humidity.
//!
//! A kernel caller builds its atmosphere the way `TrajectorySolver` does (README.md shows the
//! same code):
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use ballistics_engine::{air_at, KernelAtmosphere, RelativeHumidity, StationAir};
//!
//! // 15 C, 1013.25 hPa, 50 % at sea level: the same air TrajectorySolver flies.
//! let station = StationAir::new(0.0, 15.0, 1013.25, RelativeHumidity::try_percent(50.0)?)?;
//! let atmosphere = KernelAtmosphere::Station(station);
//! // For TrajectoryParams::atmosphere / FastIntegrationParams::atmosphere. The air 300 m up:
//! let aloft = air_at(&atmosphere, None, 0.0, 300.0);
//! println!("{:.3} kg/m3, {:.3} m/s", aloft.density_kg_m3, aloft.speed_of_sound_mps);
//! assert!(aloft.density_kg_m3 < station.density_kg_m3());
//! assert_eq!(air_at(&atmosphere, None, 0.0, 0.0).speed_of_sound_mps, station.speed_of_sound_mps());
//! # Ok(())
//! # }
//! ```

use crate::gravity::Gravity;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;

/// ICAO Standard Atmosphere layer definitions
#[derive(Debug, Clone)]
struct AtmosphereLayer {
    /// Base geopotential height of this layer (m)
    base_altitude: f64,
    /// Base temperature at layer start (K)
    base_temperature: f64,
    /// Base pressure at layer start (Pa)
    base_pressure: f64,
    /// Temperature lapse rate (K/m)
    lapse_rate: f64,
}

/// ICAO Standard Atmosphere constants
// ICAO reference quantities are defined using standard Earth gravity, independently of the
// acceleration chosen for an internal simulation.
const G_ACCEL_MPS2: f64 = crate::constants::G_ACCEL_MPS2;
/// Specific gas constant for dry air, J/(kg·K), the US Standard Atmosphere 1976 value. With
/// [`GAMMA`] it is the engine's one dry-air sound-speed constant: `sqrt(GAMMA * R_AIR * T)`. It
/// also drives the hydrostatic lapse: as is for dry air, divided by the moist-air molar-mass
/// ratio `M_m / M_a` for humid air (the virtual-temperature lapse). The CIPM-2007 density uses
/// its own `R / M_A` (287.0478) inside its own formula; each constant is used the same way on
/// every path.
pub(crate) const R_AIR: f64 = 287.0531;
/// Heat-capacity ratio of dry air.
pub(crate) const GAMMA: f64 = 1.4;
const GEOPOTENTIAL_EARTH_RADIUS_M: f64 = 6_356_766.0;
const MIN_GEOMETRIC_ALTITUDE_M: f64 = -5000.0;
const MAX_GEOMETRIC_ALTITUDE_M: f64 = 84000.0;
const MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = -5000.0;
const MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = 84000.0;

/// CIPM-2007 constants for the moist-air density, [`calculate_air_density_cimp`]. Their ratio
/// `R / M_A` is 287.0478 J/(kg·K), CIPM's dry-air gas constant; the sound speed and the lapse
/// use the US-1976 [`R_AIR`] instead. `M_V / M_A` also sets the moist-air molar-mass ratio
/// (`moist_molar_mass_ratio`) that both the density and the humid lapse aloft apply.
const R: f64 = 8.314472; // Universal gas constant
const M_A: f64 = 28.96546e-3; // Molar mass of dry air (kg/mol)
const M_V: f64 = 18.01528e-3; // Molar mass of water vapor (kg/mol)

/// ICAO Standard Atmosphere layer data up to 84 km
/// Pressures calculated using barometric formula between layers
const ICAO_LAYERS: &[AtmosphereLayer] = &[
    // Troposphere (-5 - 11 km; the sea-level base extrapolates smoothly below 0 m)
    AtmosphereLayer {
        base_altitude: 0.0,
        base_temperature: 288.15, // 15°C
        base_pressure: 101325.0,  // 1013.25 hPa
        lapse_rate: -0.0065,      // -6.5 K/km
    },
    // Tropopause (11 - 20 km)
    AtmosphereLayer {
        base_altitude: 11000.0,
        base_temperature: 216.65, // -56.5°C
        base_pressure: 22632.1,   // 226.32 hPa
        lapse_rate: 0.0,          // Isothermal
    },
    // Stratosphere 1 (20 - 32 km)
    AtmosphereLayer {
        base_altitude: 20000.0,
        base_temperature: 216.65, // -56.5°C
        base_pressure: 5474.89,   // 54.75 hPa
        lapse_rate: 0.001,        // +1 K/km
    },
    // Stratosphere 2 (32 - 47 km)
    AtmosphereLayer {
        base_altitude: 32000.0,
        base_temperature: 228.65, // -44.5°C
        base_pressure: 868.02,    // 8.68 hPa
        lapse_rate: 0.0028,       // +2.8 K/km
    },
    // Stratopause (47 - 51 km)
    AtmosphereLayer {
        base_altitude: 47000.0,
        base_temperature: 270.65, // -2.5°C
        base_pressure: 110.91,    // 1.11 hPa
        lapse_rate: 0.0,          // Isothermal
    },
    // Mesosphere 1 (51 - 71 km)
    AtmosphereLayer {
        base_altitude: 51000.0,
        base_temperature: 270.65, // -2.5°C
        base_pressure: 66.94,     // 0.67 hPa
        lapse_rate: -0.0028,      // -2.8 K/km
    },
    // Mesosphere 2 (71 - 84 km)
    AtmosphereLayer {
        base_altitude: 71000.0,
        base_temperature: 214.65, // -58.5°C
        base_pressure: 3.96,      // 0.04 hPa
        lapse_rate: -0.002,       // -2.0 K/km
    },
];

/// Calculate ICAO Standard Atmosphere conditions at any altitude.
///
/// This function implements the full ICAO Standard Atmosphere model with all
/// atmospheric layers up to 84 km altitude.
///
/// # Arguments
/// * `altitude_m` - Geometric altitude above mean sea level in meters (-5000 to 84000; values
///   outside are clamped). It is converted to geopotential height before layer evaluation.
///
/// # Returns
/// Tuple of (temperature_k, pressure_pa)
pub(crate) fn calculate_icao_standard_atmosphere(altitude_m: f64) -> (f64, f64) {
    let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
    let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
        MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
        MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
    );

    // Find the appropriate atmospheric layer
    let layer = ICAO_LAYERS
        .iter()
        .rev()
        .find(|layer| geopotential_height >= layer.base_altitude)
        .unwrap_or(&ICAO_LAYERS[0]);

    let height_diff = geopotential_height - layer.base_altitude;
    let temperature = layer.base_temperature + layer.lapse_rate * height_diff;

    let pressure = if layer.lapse_rate.abs() < 1e-10 {
        // Isothermal layer
        layer.base_pressure * (-G_ACCEL_MPS2 * height_diff / (R_AIR * layer.base_temperature)).exp()
    } else {
        // Non-isothermal layer
        let temp_ratio = temperature / layer.base_temperature;
        layer.base_pressure * temp_ratio.powf(-G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR))
    };

    (temperature, pressure)
}

/// Convert physical geometric altitude to the geopotential height used by ICAO layer tables.
#[inline]
fn geometric_to_geopotential_height_m(geometric_altitude_m: f64) -> f64 {
    GEOPOTENTIAL_EARTH_RADIUS_M * geometric_altitude_m
        / (GEOPOTENTIAL_EARTH_RADIUS_M + geometric_altitude_m)
}

/// Whether a pressure lies inside the legacy default sentinel's band, within 0.5 hPa of the
/// 1013.25 hPa sea-level standard. [`resolve_station_pressure`] reads an unmarked value there
/// as omitted at any altitude above 1 m.
pub(crate) fn in_legacy_default_pressure_band(pressure_hpa: f64) -> bool {
    const SEA_LEVEL_HPA: f64 = 1013.25;
    (pressure_hpa - SEA_LEVEL_HPA).abs() < 0.5
}

/// Whether a temperature lies inside the legacy default sentinel's band, within 0.1 °C of the
/// 15 °C sea-level standard. [`resolve_station_temperature`] reads an unmarked value there as
/// omitted at any altitude above 1 m.
pub(crate) fn in_legacy_default_temperature_band(temperature_c: f64) -> bool {
    const SEA_LEVEL_TEMP_C: f64 = 15.0;
    (temperature_c - SEA_LEVEL_TEMP_C).abs() < 0.1
}

/// Resolve the station-pressure override for an air-density calculation, by the legacy
/// default-sentinel convention.
///
/// Presence-blind legacy convention: a bare `f64` cannot say whether it was supplied, so a
/// sea-level default at a real altitude is read as omitted. The rule:
/// * A pressure within 0.5 hPa of the 1013.25 hPa sea-level standard at an altitude above 1 m
///   is read as "omitted, standard atmosphere at this altitude": `None`, so
///   [`calculate_atmosphere`] derives the station pressure from altitude (ICAO standard)
///   instead of flying sea-level density there.
/// * Any other value is returned as `Some` and used as the STATION pressure, so altitude is
///   not double-counted.
///
/// The ±0.5 hPa tolerance covers the `29.92 inHg ≈ 1013.21 hPa` conversion, and `>1 m` avoids
/// triggering at sea level. A real reading inside that band (QNH 1031 hPa at 150 m reduces to
/// 1012.86 hPa) is indistinguishable from the default here. A caller that knows presence uses
/// [`resolve_station_conditions_with_presence`], which flies a supplied value as given.
pub fn resolve_station_pressure(pressure_hpa: f64, altitude_m: f64) -> Option<f64> {
    if in_legacy_default_pressure_band(pressure_hpa) && altitude_m.abs() > 1.0 {
        None // pressure left at default + real altitude → derive station pressure from altitude
    } else {
        Some(pressure_hpa) // explicit station pressure is authoritative
    }
}

/// Resolve the temperature override for an air-density calculation, by the legacy
/// default-sentinel convention, mirroring [`resolve_station_pressure`].
///
/// Presence-blind legacy convention: a bare `f64` cannot say whether it was supplied, so a
/// sea-level default at a real altitude is read as omitted.
/// * A temperature within 0.1 °C of the 15 °C sea-level standard at an altitude above 1 m is
///   read as "omitted, standard atmosphere at this altitude": `None`, so
///   [`calculate_atmosphere`] applies the ICAO lapse-rate temperature for that altitude
///   (≈ −6.5 °C/km).
/// * Any other value is returned as `Some` and used as given.
///
/// Without the omitted case, `--altitude` with the default temperature held the air at 15 °C,
/// which under-estimates density by ~2.4% at 1 km up to ~7% at 3 km versus the standard
/// atmosphere (validated against py_ballisticcalc). The 0.1 °C tolerance matches the
/// `59 °F = 15.0 °C` default exactly, and `>1 m` avoids triggering at sea level. A real 15 °C
/// reading at altitude is indistinguishable from the default here; a caller that knows presence
/// uses [`resolve_station_conditions_with_presence`].
pub fn resolve_station_temperature(temperature_c: f64, altitude_m: f64) -> Option<f64> {
    if in_legacy_default_temperature_band(temperature_c) && altitude_m.abs() > 1.0 {
        None // temperature left at default + real altitude → derive ICAO lapse temperature
    } else {
        Some(temperature_c) // explicit temperature is authoritative
    }
}

/// Return the station temperature and pressure that [`calculate_atmosphere`] will use after
/// applying the default-at-altitude resolution rules.
///
/// A thin, byte-identical delegate to
/// [`resolve_station_conditions_with_pressure_mode`] at [`PressureReferenceMode::Absolute`]
/// (MBA-1397) — kept as a separate name/signature so no existing caller needs to change.
///
/// Presence-blind: both values go through the legacy default sentinels
/// ([`resolve_station_temperature`], [`resolve_station_pressure`]). See
/// [`resolve_station_conditions_with_presence`].
pub fn resolve_station_conditions(
    temperature_c: f64,
    pressure_hpa: f64,
    altitude_m: f64,
) -> (f64, f64) {
    resolve_station_conditions_with_pressure_mode(
        temperature_c,
        pressure_hpa,
        altitude_m,
        PressureReferenceMode::Absolute,
    )
}

/// Whether a station-pressure input is already absolute (station) pressure, or a sea-level-
/// corrected altimeter setting (QNH / "barometer" reading) that must be reduced to station
/// pressure at the shooter's altitude before use (MBA-1397).
///
/// Kestrel, AB Mobile, Shooter, JBM, and Hornady 4DOF all let the user declare which one they
/// are entering. Previously this engine only supported [`Absolute`](Self::Absolute) — an
/// entered sea-level-corrected barometer/METAR value at a real altitude was silently treated
/// as station pressure, over-stating air density and under-stating drop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum PressureReferenceMode {
    /// The input is already absolute station pressure — today's meaning, and the default, so
    /// every existing caller that never sets this is byte-identical to pre-MBA-1397 behavior.
    #[default]
    Absolute,
    /// The input is a sea-level-corrected altimeter setting (QNH) and must be reduced to
    /// station pressure at the target altitude via [`reduce_qnh_to_station_pressure`].
    Qnh,
}

/// Reduce a sea-level-corrected altimeter setting (QNH) to the station pressure at
/// `altitude_m` (MBA-1397), using the altimeter-setting relation (MBA-1605):
///
/// `station = QNH * (1 + (L*h/T0) * (P0/QNH)^n)^(1/n)`, with `n = -L*R/g`
///
/// for the ICAO troposphere's lapse rate `L` (-0.0065 K/m), sea-level temperature `T0`
/// (288.15 K) and sea-level pressure `P0` (1013.25 hPa), so `n` = 0.190263. This is what an
/// altimeter setting means: an altimeter set to QNH reads field elevation on the ground, so the
/// station pressure's ISA pressure altitude is the QNH's own pressure altitude plus `h`. Written
/// that way it is the additive form `station = P0 * ((QNH/P0)^n + L*h/T0)^(1/n)`; the
/// algebraically equal form above is the one evaluated, because it returns QNH bit-exactly at
/// `h = 0`.
///
/// This is the altimeter-setting relation on ICAO constants with geopotential height. It has the
/// shape of the NWS/ASOS altimeter-setting algorithm but is not that algorithm, which uses its
/// own rounded constants (`n` = 0.190284 and `k` = 8.4228807e-5, `P0^n * 0.0065/T0` at 288 K),
/// adds the field elevation as entered rather than its geopotential height, and subtracts a
/// 0.3 hPa sensor offset. Even without that offset, NWS/ASOS gives a station pressure about
/// 0.1 hPa lower than this function at 1500 m and 0.3 to 0.45 hPa lower at 4000 to 5000 m (QNH
/// 950 to 1050 hPa).
///
/// Before 0.49.0 this function scaled the standard pressure ratio by QNH,
/// `station = QNH * (1 + L*h/T0)^(1/n)`, and called that the altimeter-setting reduction. It is
/// not: the two agree only at QNH = 1013.25 hPa or at `h = 0`, and the ratio form ran 0.49 hPa
/// low for a QNH of 1030 hPa at 1500 m.
///
/// `h` is GEOPOTENTIAL height, not the geometric altitude the caller supplies — this function
/// converts the one to the other first (`geometric_to_geopotential_height_m`), as ISA requires.
/// Substituting geometric altitude directly into that expression reproduces the reduction only
/// to about 0.04 hPa at 1500 m, which is why the worked values below are not what the bare
/// formula gives.
///
/// Reuses the SAME troposphere layer (`ICAO_LAYERS[0]`) and physical constants
/// (`G_ACCEL_MPS2`, `R_AIR`) that `calculate_icao_standard_atmosphere` (private to this crate)
/// uses for its own non-isothermal-layer pressure formula, rather than re-hardcoding the
/// lapse rate / sea-level temperature / exponent a second time. `altitude_m` is clamped and
/// converted to geopotential height exactly like `calculate_icao_standard_atmosphere`, and
/// `(P0/QNH)^n` is exactly 1 at QNH = 1013.25 hPa. At QNH = 1013.25 hPa the reduction therefore
/// equals the ICAO standard station pressure to rounding, but not bit for bit at every altitude
/// (for example 1012.0492647136854 against 1012.0492647136847 at 10 m; the two agree exactly at
/// 150 m). Callers that must stay bit-identical for an omitted pressure keep the mode they
/// already used for it.
///
/// The reduction is only physically meaningful within the troposphere (the altitude range
/// real shooting takes place in); it is not re-derived per-layer for higher altitudes. No
/// station pressure exists once the QNH's pressure altitude plus `h` reaches `T0/-L`
/// (44,331 m, where the troposphere's lapse rate reaches absolute zero), nor for a non-positive
/// QNH; there this returns NaN, which callers refuse as a non-finite pressure.
pub fn reduce_qnh_to_station_pressure(qnh_hpa: f64, altitude_m: f64) -> f64 {
    let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
    let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
        MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
        MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
    );
    let layer = &ICAO_LAYERS[0]; // troposphere: the only layer the altimeter-setting relation covers
    let height_term = layer.lapse_rate * geopotential_height / layer.base_temperature;
    let exponent = -G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR); // 1/n
    let sea_level_hpa = layer.base_pressure / 100.0;
    let setting_term = (sea_level_hpa / qnh_hpa).powf(exponent.recip()); // (P0/QNH)^n
    qnh_hpa * (1.0 + height_term * setting_term).powf(exponent)
}

/// Mode-aware counterpart of [`resolve_station_pressure`] (MBA-1397). Does NOT change that
/// function's signature or behavior — [`PressureReferenceMode::Absolute`] is a pure
/// passthrough to it — so this is a new function alongside the original, not a replacement.
///
/// [`PressureReferenceMode::Qnh`] reduces `pressure_hpa` (interpreted as a QNH) to station
/// pressure via [`reduce_qnh_to_station_pressure`] and returns it as `Some(..)`
/// UNCONDITIONALLY, bypassing the default-sentinel ambiguity `resolve_station_pressure` must
/// use to infer omission from a bare `f64`. This matters: a QNH the caller explicitly declared
/// should never be silently re-interpreted as an omitted default merely because the REDUCED
/// number happens to land within the sentinel's tolerance of the 1013.25 hPa sea-level
/// constant (a real, reachable case — e.g. a high-pressure day's QNH reducing to ~1013 hPa at
/// a few hundred meters of elevation).
pub fn resolve_station_pressure_with_mode(
    pressure_hpa: f64,
    altitude_m: f64,
    mode: PressureReferenceMode,
) -> Option<f64> {
    match mode {
        PressureReferenceMode::Absolute => resolve_station_pressure(pressure_hpa, altitude_m),
        PressureReferenceMode::Qnh => {
            Some(reduce_qnh_to_station_pressure(pressure_hpa, altitude_m))
        }
    }
}

/// Mode-aware counterpart of [`resolve_station_conditions`] (MBA-1397): identical for
/// [`PressureReferenceMode::Absolute`] (byte-identical delegate — [`resolve_station_conditions`]
/// itself now forwards here), and reduces an explicit QNH pressure to station pressure via
/// [`resolve_station_pressure_with_mode`] for [`PressureReferenceMode::Qnh`] before applying
/// the same standard-atmosphere fallback used when either input is left at its sea-level
/// default.
///
/// Presence-blind: this is [`resolve_station_conditions_with_presence`] with
/// [`StationAtmospherePresence::NEITHER`], bit for bit. The temperature sentinel runs in BOTH
/// arms, so a typed 15 °C at altitude flies the ICAO lapse temperature here even with a
/// declared QNH; only the pressure sentinel is bypassed in the `Qnh` arm. A caller that knows
/// which values were supplied uses [`resolve_station_conditions_with_presence`].
pub fn resolve_station_conditions_with_pressure_mode(
    temperature_c: f64,
    pressure_hpa: f64,
    altitude_m: f64,
    pressure_mode: PressureReferenceMode,
) -> (f64, f64) {
    resolve_station_conditions_with_presence(
        temperature_c,
        pressure_hpa,
        altitude_m,
        pressure_mode,
        StationAtmospherePresence::NEITHER,
    )
}

/// Which of a station temperature / pressure pair the caller actually supplied (0.49.0).
///
/// A field that is not supplied is resolved by the pre-0.49.0 default-sentinel rule
/// ([`resolve_station_temperature`] / [`resolve_station_pressure_with_mode`]): the ICAO
/// standard at |altitude| > 1 m when the value is the sea-level default, the value itself
/// otherwise. That makes [`Self::NEITHER`] exactly the old behaviour of every presence-blind
/// API, which is why it is the `Default`, and makes a supplied field authoritative whatever
/// its value: a typed 15 °C, 59 °F, 1013.25 hPa or 29.92 inHg at altitude flies as typed.
///
/// Pass it to [`resolve_station_conditions_with_presence`], or to one of the
/// `*_with_station_presence` twins of the solver, zero, Monte Carlo, lead, hold-curve and
/// truing entry points.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StationAtmospherePresence {
    /// The station temperature was a reading the caller supplied.
    pub temperature_supplied: bool,
    /// The station pressure (or the QNH it is reduced from) was a reading the caller supplied.
    pub pressure_supplied: bool,
}

impl StationAtmospherePresence {
    /// Neither value was supplied: the pre-0.49.0 default-sentinel rule, bit for bit.
    pub const NEITHER: Self = Self::new(false, false);
    /// Both values were supplied: both fly as given (a declared QNH after its reduction).
    pub const BOTH: Self = Self::new(true, true);

    /// Presence from two flags.
    pub const fn new(temperature_supplied: bool, pressure_supplied: bool) -> Self {
        Self {
            temperature_supplied,
            pressure_supplied,
        }
    }

    /// Presence of a temperature reading and a pressure reading.
    pub const fn from_readings(temperature: StationReading, pressure: StationReading) -> Self {
        Self::new(temperature.supplied, pressure.supplied)
    }
}

/// A station temperature or pressure on a presence-carrying request (0.49.0): the value the
/// engine is handed and whether the caller supplied it.
///
/// On the wire it is a bare JSON number when supplied and ABSENT when omitted. The type's own
/// `Deserialize` rejects a JSON `null`; the truing DTOs (`TruingModelInputsV1`,
/// `WindTruingRequest`) read a `null` field as omitted, as the `card.*` requests do. An omitted
/// reading carries the surface's legacy default (59 °F / 29.92 inHg on
/// the truing DTOs, the metric CLI's 1013.25 hPa expressed in inHg, and so on), so it resolves
/// exactly as that default did before 0.49.0. Use [`Self::omitted`] for that, never a bare
/// `Option`: at |altitude| <= 1 m an omitted value flies as itself, so the default it carries
/// is part of the result.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StationReading {
    /// The value handed to the engine.
    pub value: f64,
    /// Whether the caller supplied it. `false` means the legacy default-sentinel rule decides.
    pub supplied: bool,
}

impl StationReading {
    /// A reading the caller supplied: it flies as given.
    pub const fn supplied(value: f64) -> Self {
        Self {
            value,
            supplied: true,
        }
    }

    /// No reading: `default_value` is the surface's legacy default, resolved by the
    /// pre-0.49.0 rule (ICAO standard at a real altitude when it is the sea-level default).
    pub const fn omitted(default_value: f64) -> Self {
        Self {
            value: default_value,
            supplied: false,
        }
    }

    /// `true` when no reading was supplied. Used as `skip_serializing_if`.
    pub fn is_omitted(&self) -> bool {
        !self.supplied
    }
}

impl serde::Serialize for StationReading {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_f64(self.value)
    }
}

impl<'de> serde::Deserialize<'de> for StationReading {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        <f64 as serde::Deserialize>::deserialize(deserializer).map(Self::supplied)
    }
}

/// Resolve the station temperature and pressure a solve flies, honouring which of them the
/// caller supplied (0.49.0). This is the presence-aware resolver every surface that knows
/// presence goes through.
///
/// For each field:
/// * supplied: returned as given; a pressure declared as QNH ([`PressureReferenceMode::Qnh`])
///   is first reduced to station pressure with [`reduce_qnh_to_station_pressure`];
/// * omitted: resolved exactly as before 0.49.0, through [`resolve_station_temperature`] /
///   [`resolve_station_pressure_with_mode`], then the ICAO standard at `altitude_m` when the
///   value is the sea-level default at a real altitude.
///
/// With [`StationAtmospherePresence::NEITHER`] the result is bit-identical to
/// [`resolve_station_conditions_with_pressure_mode`] (which now delegates here). With
/// [`StationAtmospherePresence::BOTH`] in [`PressureReferenceMode::Absolute`] it returns the
/// pair unchanged.
pub fn resolve_station_conditions_with_presence(
    temperature_c: f64,
    pressure_hpa: f64,
    altitude_m: f64,
    pressure_mode: PressureReferenceMode,
    presence: StationAtmospherePresence,
) -> (f64, f64) {
    let temp_override = if presence.temperature_supplied {
        Some(temperature_c)
    } else {
        resolve_station_temperature(temperature_c, altitude_m)
    };
    let press_override = if presence.pressure_supplied {
        Some(match pressure_mode {
            PressureReferenceMode::Absolute => pressure_hpa,
            PressureReferenceMode::Qnh => reduce_qnh_to_station_pressure(pressure_hpa, altitude_m),
        })
    } else {
        resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode)
    };
    if let (Some(temp_c), Some(pressure_hpa)) = (temp_override, press_override) {
        // Value-neutral fast path: the ICAO evaluation below would be discarded.
        return (temp_c, pressure_hpa);
    }
    let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
    (
        temp_override.unwrap_or(std_temp_k - 273.15),
        press_override.unwrap_or(std_pressure_pa / 100.0),
    )
}

// ---------------------------------------------------------------------------------------
// Station-pressure plausibility
// ---------------------------------------------------------------------------------------

/// The lowest ratio of station pressure to the ICAO standard pressure at the station's
/// altitude that [`station_pressure_plausibility`] treats as weather. See that function for
/// where the band comes from.
pub const STATION_PRESSURE_MIN_PLAUSIBLE_RATIO: f64 = 0.85;
/// The highest ratio of station pressure to the ICAO standard pressure at the station's
/// altitude that [`station_pressure_plausibility`] treats as weather.
pub const STATION_PRESSURE_MAX_PLAUSIBLE_RATIO: f64 = 1.08;

/// How an explicit absolute station pressure compares with the ICAO standard pressure at the
/// altitude it was sent with. Returned by [`station_pressure_plausibility`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StationPressurePlausibility {
    /// The ICAO standard pressure at the altitude, in pascals.
    pub icao_standard_pa: f64,
    /// The station pressure divided by `icao_standard_pa`.
    pub ratio: f64,
    /// Whether `ratio` lies outside [`STATION_PRESSURE_MIN_PLAUSIBLE_RATIO`] to
    /// [`STATION_PRESSURE_MAX_PLAUSIBLE_RATIO`] (both edges inside), or is not finite.
    pub implausible: bool,
}

/// Compare an explicit absolute station pressure, in pascals, with the ICAO standard pressure
/// at `altitude_m`, and say whether the two can describe the same station.
///
/// An explicit absolute pressure is authoritative wherever the engine takes one, so a pressure
/// that belongs to some other altitude is flown as it was sent. The two common cases are a
/// sea-level figure sent at a real elevation: a 101325 Pa placeholder, or a weather report's
/// altimeter setting (QNH) sent as station pressure instead of as a QNH. At Cusco's 3310.128 m
/// a 101325 Pa placeholder is 1.503 times the standard pressure there. The reverse, a true
/// station reading sent with the wrong altitude (omitted, or in the wrong unit), shows up as a
/// ratio far from 1 too. Callers use this to warn; nothing here changes a pressure.
///
/// The band, [`STATION_PRESSURE_MIN_PLAUSIBLE_RATIO`] to
/// [`STATION_PRESSURE_MAX_PLAUSIBLE_RATIO`], is wide enough that recorded weather never leaves
/// it. The WMO's table of weather and climate extremes (as of 31 July 2025) lists these
/// sea-level pressure records:
///
/// - 870 hPa in the eye of Typhoon Tip, 12 October 1979, the lowest (tornadoes excluded);
/// - 1083.8 hPa at Agata, Russia, 31 December 1968, the highest at a station below 750 m;
/// - 1089.1 hPa at Tosontsengel, Mongolia, 30 December 2004, the highest above 750 m.
///
/// Against the 1013.25 hPa standard those are 0.859, 1.070 and 1.075. They are sea-level
/// figures. At a station above sea level the high extreme moves toward standard, because the
/// record highs come from cold air: reduced to sea level through a column denser than the
/// standard one, a station pressure nearer standard becomes the record sea-level figure. Cold
/// air moves the low side the other way. Under a cold column an ordinary sea-level pressure
/// puts a high station further below standard than the sea-level figure is: a 3000 m station
/// under a 243 K column reads 0.948 times the ICAO standard there with 1013.25 hPa at sea
/// level, and 0.917 with 980 hPa. Both stay well above 0.85.
///
/// The band catches gross mismatches, not every placeholder: 101325 Pa stays inside it up to
/// about 645 m, where it is already 8% above standard.
///
/// This is for absolute station pressure only. A QNH is a sea-level figure by declaration, so
/// comparing it with the standard at the station's altitude would say nothing about it.
pub fn station_pressure_plausibility(
    station_pressure_pa: f64,
    altitude_m: f64,
) -> StationPressurePlausibility {
    let (_, icao_standard_pa) = calculate_icao_standard_atmosphere(altitude_m);
    let ratio = station_pressure_pa / icao_standard_pa;
    let implausible = !(STATION_PRESSURE_MIN_PLAUSIBLE_RATIO
        ..=STATION_PRESSURE_MAX_PLAUSIBLE_RATIO)
        .contains(&ratio);
    StationPressurePlausibility {
        icao_standard_pa,
        ratio,
        implausible,
    }
}

// ---------------------------------------------------------------------------------------
// MBA-1366: density altitude as a direct atmosphere input
// ---------------------------------------------------------------------------------------

/// NWS pressure-altitude and FAA-rule constants — the ONE copy.
///
/// Both directions of the density-altitude model now live in this module: the forward
/// [`faa_rule_density_altitude_ft`] (the engine's reported density altitude) and its exact
/// inverse [`resolve_atmosphere_for_density_altitude`] (MBA-1366, the DA entry mode). They
/// used to live apart, with these constants duplicated here because the forward formula sat
/// in `pdf_dope_card` — first in the `ballistics` binary, then (from 0.33.0's Task 10) in
/// this library but behind `#[cfg(feature = "pdf")]`, which this unconditional module could
/// not import across without breaking the `--no-default-features` wasm32 build CI
/// type-checks.
///
/// The fix was to move the formula DOWN rather than import it UP: `atmosphere` is
/// unconditional, so the forward function lives here and
/// `pdf_dope_card::calculate_density_altitude` now delegates to it, bit for bit. That leaves
/// no second copy to drift, and it is what lets the `atmosphere.density_altitude` bridge
/// command exist in every build with the bridge — including wasm32, which has no PDF card.
///
/// `src/main.rs`'s `density_altitude_round_trips_through_the_dope_card_formula*` tests still
/// pin forward and inverse together, now through a single set of constants.
const DA_NWS_SEA_LEVEL_HPA: f64 = 1013.25;
const DA_NWS_PRESSURE_ALT_FT: f64 = 145_366.45;
const DA_NWS_EXPONENT: f64 = 0.190_284;
const DA_NWS_SEA_LEVEL_TEMP_F: f64 = 59.0;
const DA_NWS_LAPSE_F_PER_1000FT: f64 = 3.57;
/// The FAA rule of thumb, "120 ft of density altitude per °C away from standard", expressed
/// per °F because the NWS constants above are Fahrenheit.
const DA_FAA_RULE_FT_PER_DEG_F: f64 = 120.0 * 5.0 / 9.0;
const DA_FT_TO_M: f64 = 0.3048;

/// NWS pressure altitude, feet, from STATION pressure in hPa.
///
/// The published NWS station-pressure equation
/// (<https://www.weather.gov/media/epz/wxcalc/pressureAltitude.pdf>):
///
/// ```text
/// PA_ft = 145366.45 * (1 - (P_hPa / 1013.25)^0.190284)
/// ```
///
/// Station pressure, never an altimeter setting (MBA-643): a QNH already corrects to sea
/// level and would report the pressure altitude of the sea rather than of the firing point.
///
/// It is the troposphere's closed form, with the NWS's rounded constants, and that is all it
/// is anywhere: below -5 km and above 11 km it continues the troposphere's lapse, which the
/// standard atmosphere does not have above 11 km, so there it is no longer the standard
/// atmosphere's altitude of the pressure (standard pressure at 20 km, 5474.89 Pa, reads
/// 18879 m), and it approaches 145366.45 ft (44308 m), where that lapse would reach 0 K, as
/// the pressure falls to 0. [`pressure_altitude_m`] is this formula inside -5 km to 11 km and
/// the standard atmosphere's own altitude outside it.
pub fn nws_pressure_altitude_ft(station_pressure_hpa: f64) -> f64 {
    DA_NWS_PRESSURE_ALT_FT
        * (1.0 - (station_pressure_hpa / DA_NWS_SEA_LEVEL_HPA).powf(DA_NWS_EXPONENT))
}

/// The pressure altitude of a station pressure, m, wherever it lands: the NWS formula
/// ([`nws_pressure_altitude_ft`] in metres, to the bit) inside -5 km to 11 km, where it is the
/// published figure, and outside that band the standard atmosphere's own (geopotential)
/// altitude of the pressure, walking the same ICAO layers [`air_at`] walks: the troposphere's
/// lapse below -5 km, isothermal from 11 km, warming from 20 km and 32 km, isothermal again
/// from 47 km, cooling from 51 km and 71 km, the last layer's lapse continuing above 84 km.
/// Each layer's base pressure is chained from 101325 Pa by the layer formula, so standard
/// pressure at any height reads that height.
///
/// Every pressure above 0 has a finite pressure altitude, below 178.3 km (where the last
/// layer's lapse reaches 0 K). At the band's edges the two differ by the few metres the NWS
/// constants and the ICAO troposphere part by: the NWS formula reads 22615.3 Pa as 11000 m and
/// the standard atmosphere reads it as 11005 m, so the figure steps up by 5 m there as the
/// pressure falls, and at the bottom edge (177725 Pa) it steps down by 2 m as the pressure
/// rises. It never falls as the pressure falls. A NaN pressure gives NaN.
///
/// ```
/// use ballistics_engine::atmosphere::{nws_pressure_altitude_ft, pressure_altitude_m};
///
/// // Inside the band, the NWS formula to the bit.
/// assert_eq!(pressure_altitude_m(850.0).to_bits(), (nws_pressure_altitude_ft(850.0) * 0.3048).to_bits());
/// // Standard pressure at 20 km reads 20 km.
/// assert!((pressure_altitude_m(54.7489) - 20_000.0).abs() < 1.0);
/// // A near vacuum still has an altitude.
/// assert!(pressure_altitude_m(0.01).is_finite());
/// ```
pub fn pressure_altitude_m(station_pressure_hpa: f64) -> f64 {
    let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
    if nws_m.is_nan() || (LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m) {
        return nws_m;
    }
    standard_pressure_altitude_m(station_pressure_hpa * 100.0)
}

/// The standard atmosphere's geopotential altitude, m, of a pressure in pascals: the ICAO layers
/// walked from sea level, each base pressure chained by the layer formula, the troposphere's
/// lapse continued below sea level and the last layer's above 84 km.
fn standard_pressure_altitude_m(pressure_pa: f64) -> f64 {
    let sea_level = &ICAO_LAYERS[0];
    let mut base_pressure = sea_level.base_pressure;
    for (index, layer) in ICAO_LAYERS.iter().enumerate() {
        let (base, base_temperature, lapse) = (
            layer.base_altitude,
            layer.base_temperature,
            layer.lapse_rate,
        );
        let isothermal = lapse.abs() < 1e-10;
        let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
        let top = ICAO_LAYERS
            .get(index + 1)
            .map_or(f64::INFINITY, |next| next.base_altitude);
        let top_pressure = if top.is_infinite() {
            0.0
        } else if isothermal {
            base_pressure * (-(top - base) / scale_height).exp()
        } else {
            base_pressure
                * (1.0 + lapse * (top - base) / base_temperature)
                    .powf(-G_ACCEL_MPS2 / (lapse * R_AIR))
        };
        if pressure_pa >= top_pressure || top.is_infinite() {
            return if isothermal {
                base + scale_height * (base_pressure / pressure_pa).ln()
            } else {
                let temperature = base_temperature
                    * (pressure_pa / base_pressure).powf(-lapse * R_AIR / G_ACCEL_MPS2);
                base + (temperature - base_temperature) / lapse
            };
        }
        base_pressure = top_pressure;
    }
    unreachable!("the last layer has no top")
}

/// Density altitude by the FAA rule of thumb, feet: NWS pressure altitude plus 120 ft for
/// every °C the station is away from ISA temperature at that pressure altitude. **Humidity is
/// not an input.**
///
/// ```text
/// DA_ft = PA_ft + (120 * 5/9) * (T_F - ISA_T_F(PA))      ISA_T_F(PA) = 59 - 3.57 * PA_ft/1000
/// ```
///
/// This is the density altitude the engine has always reported —
/// `pdf_dope_card::calculate_density_altitude` delegates to it — and the one
/// [`resolve_atmosphere_for_density_altitude`], the density-altitude ENTRY mode, inverts
/// exactly.
///
/// It stays humidity-free for compatibility, not out of necessity. Every card printed to date
/// shows this figure, and the entry mode that inverts it has shipped since MBA-1366 taking a
/// temperature but no humidity (the run's humidity is applied separately, afterwards). A
/// humidity-aware forward could be inverted just as well given the run's humidity, the way
/// temperature already is; it would change every printed card and what an entered density
/// altitude resolves to.
///
/// Outside the troposphere this still starts from [`nws_pressure_altitude_ft`], not the
/// layered [`pressure_altitude_m`] reported by the bridge. Both the NWS pressure formula and
/// this temperature correction continue there, preserving the inverse used for density-altitude
/// entry. They do not become the standard atmosphere's pressure or density altitude.
///
/// It is not the National Weather Service's density altitude either, despite the NWS pressure
/// altitude inside it: the NWS calculator uses virtual temperature, so it includes humidity
/// and tracks [`density_matched_altitude_m`] to within a few meters.
///
/// And it is an approximation. The rule is a straight line where the real dependence curves,
/// and 120 ft/°C is slightly steeper than the exact slope at sea level (118.6 ft/°C for an
/// ideal gas, 119.0 for the CIPM density [`density_matched_altitude_m`] uses), so
/// it drifts from the exact figure as the temperature moves away from standard FOR THE
/// PRESSURE ALTITUDE: about +22 m at 30 °C and 1013.25 hPa in completely dry air. See
/// [`density_matched_altitude_m`] for the exact, humidity-inclusive figure, and why the bridge
/// reports both.
pub fn faa_rule_density_altitude_ft(station_pressure_hpa: f64, temperature_f: f64) -> f64 {
    let pressure_alt = nws_pressure_altitude_ft(station_pressure_hpa);

    // ISA temperature at pressure altitude (lapse rate: 3.57°F per 1000 ft)
    let isa_temp_f = DA_NWS_SEA_LEVEL_TEMP_F - (pressure_alt / 1000.0) * DA_NWS_LAPSE_F_PER_1000FT;

    pressure_alt + DA_FAA_RULE_FT_PER_DEG_F * (temperature_f - isa_temp_f)
}

/// ISA troposphere constants for [`density_matched_altitude_m`].
const ISA_SEA_LEVEL_TEMP_K: f64 = 288.15;
const ISA_LAPSE_K_PER_M: f64 = 0.0065;

/// The reference air that [`density_matched_altitude_m`] calls sea level: ICAO standard sea
/// level, perfectly dry, evaluated with the SAME CIPM-2007 model as the air being described.
const DENSITY_MATCH_REFERENCE_TEMP_C: f64 = 15.0;
const DENSITY_MATCH_REFERENCE_PRESSURE_HPA: f64 = 1013.25;

/// The altitude in the ICAO Standard Atmosphere whose standard density equals the ACTUAL
/// density of this air, humidity included — density altitude by its textbook definition.
///
/// ```text
/// ratio = rho_CIPM(T, P, RH) / rho_CIPM(15 C, 1013.25 hPa, 0%)
/// h_m   = (T0 / L) * (1 - ratio^(1/n))      T0 = 288.15 K, L = 0.0065 K/m,
///                                            n  = g0 / (R L) - 1  (= 4.25588)
/// ```
///
/// # Why this exists alongside [`faa_rule_density_altitude_ft`]
///
/// Two different quantities are both called "density altitude" in the field, and reporting
/// them under one name is how an external user came to ask why the engine read 0 m where
/// another tool read 36 m at ICAO standard with 50% humidity (2026-09). The FAA-rule figure
/// is humidity-free for compatibility (see its docs). This one answers the question a shooter
/// usually means — "which ISA altitude has the air density I actually have" — and so it must
/// include humidity: water vapor (18 g/mol) is lighter than dry air (~29 g/mol), so humid air
/// is thinner.
///
/// At 15 °C, 1013.25 hPa and 50% RH this reads 33.1 m where the FAA-rule figure reads 0. But
/// the difference is NOT purely humidity, and callers must not present it that way: the FAA
/// rule also drifts from this exact figure whenever the temperature is not standard for the
/// pressure altitude, so the two disagree by about 22 m at 30 °C in perfectly dry air.
///
/// # Anchoring
///
/// Density comes from [`calculate_atmosphere`] — the one CIPM-2007 path every solver uses —
/// and the ratio is taken against that SAME model's density for ICAO standard dry sea level,
/// not against the textbook 1.225 kg/m³. The model is accurate, but it is not built to
/// reproduce 1.225 exactly (its own anchor test allows ±0.002), and at sea level 0.002 kg/m³
/// is roughly 17 m of altitude. Anchoring to the model makes ICAO standard dry air read
/// exactly 0 and makes the humidity effect the model's own.
///
/// # Scope
///
/// Heights are the standard atmosphere's own (geopotential), with no correction to geometric
/// height — the same plain-height convention as the FAA-rule figure and the DA entry mode.
///
/// Up to 11 km this is the closed-form troposphere above, which covers every shooting condition
/// on Earth; below sea level it continues the troposphere's lapse, as the standard atmosphere
/// does. Air thinner than the standard tropopause's (hot air, or a low station pressure) reads
/// its altitude in the standard atmosphere's upper layers, the ICAO table [`air_at`] walks:
/// isothermal from 11 km, warming from 20 km and 32 km, isothermal again from 47 km, cooling from
/// 51 km and 71 km, the last layer's lapse continuing above 84 km. So the figure is the standard
/// atmosphere's altitude of equal density for any finite positive density: standard air reads
/// its own altitude in every layer, and it falls steadily as the air thins. Up to 11 km the
/// result is the closed form above to the bit.
///
/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
/// refuse what this computes.
pub fn density_matched_altitude_m(
    temperature_c: f64,
    station_pressure_hpa: f64,
    humidity_percent: f64,
) -> f64 {
    let (density, _) = calculate_atmosphere(
        0.0,
        Some(temperature_c),
        Some(station_pressure_hpa),
        humidity_percent,
    );
    let (reference, _) = calculate_atmosphere(
        0.0,
        Some(DENSITY_MATCH_REFERENCE_TEMP_C),
        Some(DENSITY_MATCH_REFERENCE_PRESSURE_HPA),
        0.0,
    );
    let ratio = density / reference;
    let exponent = G_ACCEL_MPS2 / (R_AIR * ISA_LAPSE_K_PER_M) - 1.0;
    let troposphere =
        (ISA_SEA_LEVEL_TEMP_K / ISA_LAPSE_K_PER_M) * (1.0 - ratio.powf(1.0 / exponent));
    // NaN, and every figure up to the tropopause, is the closed form's, to the bit.
    if troposphere.is_nan() || troposphere <= TROPOSPHERE_TOP_M {
        return troposphere;
    }
    standard_altitude_above_tropopause_m(ratio, exponent)
}

/// The standard atmosphere's altitude, m (geopotential), of the density ratio `ratio` (to ICAO
/// sea level) thinner than the tropopause's: the ICAO layers above the troposphere walked up from
/// 11 km, the last one's lapse continuing above 84 km, as [`air_at`] walks them.
/// `troposphere_exponent` is the troposphere's density exponent `g0 / (R L) - 1`, which sets the
/// tropopause's ratio, `(T(11 km) / T0)^n`. Any ratio from 0 up to the tropopause's has a finite
/// altitude: the last layer cools to 0 K, and to no density, at 178.3 km.
fn standard_altitude_above_tropopause_m(ratio: f64, troposphere_exponent: f64) -> f64 {
    let sea_level = &ICAO_LAYERS[0];
    let mut base_ratio =
        (ICAO_LAYERS[1].base_temperature / sea_level.base_temperature).powf(troposphere_exponent);
    for (index, layer) in ICAO_LAYERS.iter().enumerate().skip(1) {
        let (base, base_temperature, lapse) = (
            layer.base_altitude,
            layer.base_temperature,
            layer.lapse_rate,
        );
        // The density ratio within this layer, relative to its base: isothermal, or the power
        // law of a lapse.
        let isothermal = lapse.abs() < 1e-10;
        let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
        let density_exponent = -G_ACCEL_MPS2 / (R_AIR * lapse) - 1.0;
        let top = ICAO_LAYERS
            .get(index + 1)
            .map_or(f64::INFINITY, |next| next.base_altitude);
        let top_ratio = if top.is_infinite() {
            0.0
        } else if isothermal {
            base_ratio * (-(top - base) / scale_height).exp()
        } else {
            base_ratio * (1.0 + lapse * (top - base) / base_temperature).powf(density_exponent)
        };
        if ratio >= top_ratio || top.is_infinite() {
            return if isothermal {
                base + scale_height * (base_ratio / ratio).ln()
            } else {
                let temperature =
                    base_temperature * (ratio / base_ratio).powf(1.0 / density_exponent);
                base + (temperature - base_temperature) / lapse
            };
        }
        base_ratio = top_ratio;
    }
    unreachable!("the last layer has no top")
}

/// Back-solve an ISA-equivalent station altitude/temperature/pressure from a directly-declared
/// density altitude (MBA-1366) — the single-value atmosphere entry mode Shooter, Nosler, AB
/// Analytics, Ballistic AE, and TRASOL all support as an alternative to altitude + pressure +
/// temperature.
///
/// This is the exact algebraic inverse of the FAA-rule density-altitude model this engine
/// already uses to REPORT density altitude ([`faa_rule_density_altitude_ft`], which
/// `pdf_dope_card::calculate_density_altitude` delegates to):
///
/// ```text
/// pressure_alt_ft = 145366.45 * (1 - (station_hpa / 1013.25)^0.190284)
/// isa_temp_f      = 59.0 - pressure_alt_ft / 1000.0 * 3.57
/// density_alt_ft  = pressure_alt_ft + (120*5/9) * (station_temp_f - isa_temp_f)
/// ```
///
/// Solved for `station_hpa` given a target `density_alt_ft` and a station temperature `K = 120
/// * 5/9` is the "120 ft per °C" density-altitude correction rule, expressed in ft per °F):
///
/// ```text
/// pressure_alt_ft = (density_alt_ft - K*(station_temp_f - 59.0)) / (1 + K*3.57/1000.0)
/// station_hpa     = 1013.25 * (1 - pressure_alt_ft/145366.45)^(1/0.190284)
/// ```
///
/// # Temperature precedence (MBA-1366)
/// * `explicit_temperature_c == None`: ISA-at-density-altitude is the default. Algebraically
///   this collapses `pressure_alt_ft` to EXACTLY `density_alt_ft`: the correction term above is
///   zero by construction whenever the station temperature equals the ISA temperature at that
///   pressure altitude, which is self-consistently true when temperature is left at ISA — i.e.
///   omitting an explicit temperature is equivalent to typing `--altitude <density_altitude>`
///   with no `--temperature`/`--pressure` override.
/// * `explicit_temperature_c == Some(t)`: `t` wins outright (returned unchanged as
///   `temperature_c`, never re-derived) and the station pressure is re-solved so the resulting
///   density altitude still reproduces the input exactly. The FAA-rule density altitude is
///   honored either way, but the DENSITY is not: the rule is a straight-line approximation, not
///   a curve of equal density, so the ISA-default case rebuilds different air — at 30 °C and
///   1013.25 hPa, a rebuilt 11.4 °C / 949 hPa, 0.3% denser, with a speed of sound 3% lower. Only
///   the real temperature reproduces the real air.
///
/// # Height convention
/// The FAA-rule formula being inverted ([`faa_rule_density_altitude_ft`]) performs no
/// geopotential correction — it treats its altitude as a plain height (the DOPE card, which
/// delegates to it, leaves its own `_altitude_ft` parameter unused for that reason). Consistent with that, the `altitude_m` this returns is GEOMETRIC altitude
/// — the same convention every other engine altitude input uses (`--altitude`,
/// [`AtmosphericConditions::altitude`](crate::cli_api::AtmosphericConditions::altitude)) —
/// rather than being run through `geometric_to_geopotential_height_m` a second time here; that
/// conversion is `calculate_icao_standard_atmosphere`'s job (both private to this crate — see
/// their doc comments elsewhere in this file), applied once this altitude re-enters the normal
/// altitude-lapse pipeline (this is what "back-solve an ISA-equivalent atmosphere" means —
/// unlike [`get_direct_atmosphere`], which would freeze speed of sound and bypass that pipeline
/// entirely).
///
/// # Interaction with [`PressureReferenceMode`] (QNH)
/// Density altitude supersedes pressure outright — callers must not also run a declared
/// `--pressure`/QNH value through [`resolve_station_pressure_with_mode`] when a density
/// altitude is present; see the CLI/WASM call sites, which emit a note to that effect.
///
/// # Returns
/// `(altitude_m, temperature_c, pressure_hpa)`, meant to be written directly into
/// [`crate::cli_api::AtmosphericConditions`] (and the paired `BallisticInputs` environment
/// fields, so powder-temperature sensitivity and the moist speed of sound both see the real
/// resolved temperature) via the Authoritative
/// (`TrajectorySolver::new_with_resolved_station_atmosphere`) constructor.
pub fn resolve_atmosphere_for_density_altitude(
    density_altitude_m: f64,
    explicit_temperature_c: Option<f64>,
) -> (f64, f64, f64) {
    let density_altitude_ft = density_altitude_m / DA_FT_TO_M;
    const K: f64 = DA_FAA_RULE_FT_PER_DEG_F;

    let (pressure_alt_ft, temperature_c) = match explicit_temperature_c {
        Some(temp_c) => {
            let temp_f = temp_c * 9.0 / 5.0 + 32.0;
            let denom = 1.0 + K * DA_NWS_LAPSE_F_PER_1000FT / 1000.0;
            let pressure_alt_ft =
                (density_altitude_ft - K * (temp_f - DA_NWS_SEA_LEVEL_TEMP_F)) / denom;
            (pressure_alt_ft, temp_c)
        }
        None => {
            // ISA-at-DA default: the correction term vanishes by construction (see doc
            // comment above), so the pressure altitude IS the density altitude exactly.
            let pressure_alt_ft = density_altitude_ft;
            let isa_temp_f =
                DA_NWS_SEA_LEVEL_TEMP_F - pressure_alt_ft / 1000.0 * DA_NWS_LAPSE_F_PER_1000FT;
            let isa_temp_c = (isa_temp_f - 32.0) * 5.0 / 9.0;
            (pressure_alt_ft, isa_temp_c)
        }
    };

    let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
        * (1.0 - pressure_alt_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
    let altitude_m = pressure_alt_ft * DA_FT_TO_M;

    (altitude_m, temperature_c, pressure_hpa)
}

/// The NWS station pressure, hPa, at a pressure altitude in feet, when it is finite and above 0:
/// the inverse of [`nws_pressure_altitude_ft`], as [`resolve_atmosphere_for_density_altitude`]
/// evaluates it. `None` at or above 145366.45 ft, where the formula's lapse reaches 0 K, and
/// where it overflows far below sea level.
fn nws_station_pressure_hpa(pressure_altitude_ft: f64) -> Option<f64> {
    let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
        * (1.0 - pressure_altitude_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
    (pressure_hpa.is_finite() && pressure_hpa > 0.0).then_some(pressure_hpa)
}

/// The station a density altitude gives ([`resolve_atmosphere_for_density_altitude`], bit for
/// bit), or the refusal of a density altitude no air has: the one rule every surface that takes
/// a density altitude applies. A density altitude flies when it is finite and the station the
/// FAA rule's inverse gives for it can exist; nothing narrower. The station is checked as any
/// other is afterwards (its humidity, and air that cannot exist), by [`StationAir::new`].
///
/// ```
/// use ballistics_engine::atmosphere::station_for_density_altitude;
///
/// assert!(station_for_density_altitude(-10_000.0, None).is_ok()); // far below sea level
/// assert!(station_for_density_altitude(40_000.0, None).is_ok()); // far above the troposphere
/// assert!(station_for_density_altitude(50_000.0, None).is_err()); // below 0 K by the rule
/// assert!(station_for_density_altitude(50_000.0, Some(40.0)).is_ok()); // hot air that thin
/// ```
///
/// # Errors
///
/// - `density_altitude_m` not finite: [`AtmosphereErrorReason::NotFinite`] on
///   `density_altitude_m`.
/// - an `explicit_temperature_c` the one temperature rule refuses
///   ([`check_station_temperature_c`]), on `temperature_c`.
/// - no air at it: [`AtmosphereErrorReason::NoAirAtDensityAltitude`] on `density_altitude_m`,
///   whose [`AtmosphereError::altitude_m`] is its pressure altitude by the FAA rule.
pub fn station_for_density_altitude(
    density_altitude_m: f64,
    explicit_temperature_c: Option<f64>,
) -> Result<(f64, f64, f64), AtmosphereError> {
    const FIELD: &str = "density_altitude_m";
    if !density_altitude_m.is_finite() {
        return Err(AtmosphereError::new(
            FIELD,
            density_altitude_m,
            AtmosphereErrorReason::NotFinite,
        ));
    }
    if let Some(temperature_c) = explicit_temperature_c {
        check_station_temperature_c(temperature_c)?;
    }
    let (altitude_m, temperature_c, pressure_hpa) =
        resolve_atmosphere_for_density_altitude(density_altitude_m, explicit_temperature_c);
    let exists = altitude_m.is_finite()
        && pressure_hpa.is_finite()
        && pressure_hpa > 0.0
        && temperature_c.is_finite()
        && temperature_c > ABSOLUTE_ZERO_C;
    if !exists {
        return Err(AtmosphereError {
            altitude_m: Some(altitude_m),
            ..AtmosphereError::new(
                FIELD,
                density_altitude_m,
                AtmosphereErrorReason::NoAirAtDensityAltitude,
            )
        });
    }
    Ok((altitude_m, temperature_c, pressure_hpa))
}

/// Enhanced atmospheric calculation with ICAO Standard Atmosphere.
///
/// # Arguments
/// * `altitude_m` - Altitude in meters
/// * `temp_override_c` - Temperature override in Celsius (None for standard)
/// * `press_override_hpa` - Pressure override in hPa (None for standard)
/// * `humidity_percent` - Humidity percentage (0-100)
///
/// # Returns
/// Tuple of (air_density_kg_m3, speed_of_sound_mps)
///
/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
/// refuse what this computes.
pub fn calculate_atmosphere(
    altitude_m: f64,
    temp_override_c: Option<f64>,
    press_override_hpa: Option<f64>,
    humidity_percent: f64,
) -> (f64, f64) {
    // Get standard atmosphere conditions or use overrides
    let combined_overrides = temp_override_c.zip(press_override_hpa);
    let (temp_k, pressure_pa) = if let Some((temp_c, pressure_hpa)) = combined_overrides {
        // Both overrides provided
        (temp_c + 273.15, pressure_hpa * 100.0)
    } else {
        // Get ICAO standard conditions
        let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);

        let final_temp_k = if let Some(temp_c) = temp_override_c {
            temp_c + 273.15
        } else {
            std_temp_k
        };

        let final_pressure_pa = if let Some(press_hpa) = press_override_hpa {
            press_hpa * 100.0
        } else {
            std_pressure_pa
        };

        (final_temp_k, final_pressure_pa)
    };

    // Humidity clamp shared by the CIPM density and the moist speed of sound: a total-function
    // guard for this unvalidated public function. Validated callers (StationAir::new) pass a
    // RelativeHumidity, already in range, so it never moves their value. A NaN passes through
    // the clamp and gives NaN air (the vapour cap keeps it).
    let humidity_clamped = humidity_percent.clamp(0.0, 100.0);
    let temp_c = temp_k - 273.15;

    // Density: CIPM-2007 is the engine's one humid-air density model. Every solver's station
    // density comes from this call, through StationAir::new; a downrange zone's base density
    // calls calculate_air_density_cimp directly in air_at. There is no second density formula.
    let density = calculate_air_density_cimp(temp_c, pressure_pa / 100.0, humidity_clamped);

    // Speed of sound uses an ideal-gas moist-air mixture approximation, first order in the
    // water-vapor mole fraction. Extracted into `moist_speed_of_sound`, whose formula air_at
    // also evaluates at every step (at the station's x_v, held aloft); its vapor pressure comes
    // from the SAME Wagner-Pruss saturation-pressure equation (`enhanced_saturation_vapor_pressure`)
    // and CIPM enhancement factor that the density above uses. Only the vapor fraction is
    // shared; the acoustic relation remains ideal-gas.
    let speed_of_sound = moist_speed_of_sound(temp_k, pressure_pa, humidity_clamped);

    (density, speed_of_sound)
}

/// Speed of sound using an ideal-gas moist-air mixture approximation, first order in the
/// water-vapor mole fraction.
///
/// The water-vapor mole fraction is derived from the SAME Wagner-Pruss saturation vapor
/// pressure (`enhanced_saturation_vapor_pressure`) and CIPM-2007 enhancement factor used by
/// [`calculate_air_density_cimp`], so a single vapor formula feeds both density and c. Only the
/// vapor fraction is shared with the CIPM path; the acoustic relation itself remains ideal-gas.
/// The mixture applies first-order humidity corrections to the dry-air heat-capacity ratio and
/// gas constant, `gamma = 1.4 (1 - 0.062 x_v)` and `R = 287.0531 (1 + 0.378 x_v)`, then
/// evaluates `sqrt(gamma * R * T)`; at 0 % that is the dry `sqrt(1.4 · 287.0531 · T)`. It is
/// not Cramer's full real-gas polynomial and does not include Cramer's pressure or
/// carbon-dioxide terms.
///
/// It is the station's (and a downrange zone's) sound speed. Aloft, [`air_at`] evaluates the same
/// formula at the local temperature and the station's (or zone's) own `x_v`, held at every
/// height, so at the station's height the two agree to the bit.
///
/// # Arguments
/// * `temp_k` - Temperature in Kelvin
/// * `pressure_pa` - Total (station) pressure in Pa
/// * `humidity_percent` - Relative humidity percentage (0-100)
///
/// # Returns
/// Speed of sound in m/s
///
/// Its gas constant, `287.0531 (1 + 0.378 x_v)`, is first order in `x_v`: it differs from the exact
/// `R_AIR / (M_m / M_a)` the lapse uses by -1.1e-5 at 15 °C / 50 % and -1.3e-3 at 45 °C / 100 %
/// (1013.25 hPa), where the sound speed is 0.24 m/s (0.065 %) below what the lapse's gas constant
/// gives. The gap grows as the pressure falls: 0.50 m/s at 45 °C / 100 % and 700 hPa.
///
/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
/// refuse what this computes.
pub fn moist_speed_of_sound(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
    // The one CIPM vapour mole fraction (`vapor_mole_fraction`, which the density uses too),
    // capped at the physical maximum of 1 by the one NaN-keeping cap. Its pressure floor guards
    // pressure_pa == 0 (a 0 hPa override would otherwise give +Inf -> NaN speed of sound).
    let mole_fraction_vapor = capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
        temp_k,
        pressure_pa,
        humidity_percent,
    ));

    moist_sound_speed_at_mole_fraction(temp_k, mole_fraction_vapor)
}

/// The moist-air sound speed of [`moist_speed_of_sound`] at a GIVEN water-vapour mole fraction:
/// `sqrt(1.4 (1 - 0.062 x_v) · 287.0531 (1 + 0.378 x_v) · T)`. The station's sound speed
/// evaluates it at the station's own `x_v`, and [`air_at`] at the governing air's `x_v`, held
/// aloft; at `x_v = 0` it is the dry `sqrt(1.4 · 287.0531 · T)` to the bit.
#[inline(always)]
fn moist_sound_speed_at_mole_fraction(temp_k: f64, mole_fraction_vapor: f64) -> f64 {
    // Heat-capacity ratio and gas constant for moist air (mole-fraction coefficients). 0.378 is
    // the dry-air molecular-weight ratio (0.6078 would belong to specific humidity, not mole
    // fraction).
    let gamma_moist = GAMMA * (1.0 - mole_fraction_vapor * 0.062);
    let r_moist = R_AIR * (1.0 + 0.378 * mole_fraction_vapor);

    (gamma_moist * r_moist * temp_k).sqrt()
}

/// The moist-air molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`, where
/// `M_m = (1 - x_v) M_a + x_v M_v` is the molar mass of air holding a water-vapour mole fraction
/// `x_v`. The CIPM-2007 density ([`calculate_air_density_cimp`]) multiplies by it, and the
/// virtual-temperature lapse of [`air_at`] scales the dry hydrostatic exponent by it, so the lapse
/// and the density carry the same humidity term. Exactly 1 at `x_v = 0`.
///
/// The two gas constants still differ a little, dry air included: the lapse's ideal-gas `R_AIR /
/// (M_m / M_a)` and the `Z R / M_m` the CIPM-2007 density implies (its compressibility `Z`, and its
/// `R / M_a = 287.0478` against `R_AIR = 287.0531`) differ by 1.2e-4 to 9.0e-4 from -20 to 45 °C,
/// 700 to 1013.25 hPa and 0 to 100 %.
#[inline(always)]
fn moist_molar_mass_ratio(mole_fraction_vapor: f64) -> f64 {
    1.0 - mole_fraction_vapor * (1.0 - M_V / M_A)
}

/// The water-vapour mole fraction of the GOVERNING air (the station's, or the active
/// [`AtmoSock`] zone's) that [`air_at`] holds at every height: the station sound speed's own
/// `x_v` ([`calculate_atmosphere`]'s kelvin and pascal conversions, then the one
/// [`vapor_mole_fraction`], capped at 1), so the air at the governing air's height is that air
/// to the bit. Exactly 0 at 0 %.
///
/// The one place this `x_v` is formed. It is evaluated once per base air, when a
/// [`StationAir`] or an [`AtmoSock`] is built (see [`GoverningAir`]), and per call only by the
/// legacy `get_local_atmosphere*` wrappers, whose base is a caller's raw tuple.
#[inline(always)]
fn governing_vapor_mole_fraction(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
    capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
        temp_c + 273.15,
        pressure_hpa * 100.0,
        humidity_percent,
    ))
}

/// The water-vapour mole fraction capped at its physical maximum, 1: `x.min(1.0)` for every
/// number, to the bit, but a NaN stays a NaN (`f64::min` would return 1.0 for it, pure steam).
///
/// Every capped `x_v` in the engine goes through it ([`calculate_air_density_cimp`],
/// [`moist_speed_of_sound`], the governing air's `x_v` aloft), so a NaN humidity, or air above
/// water's critical point (647.096 K, where the saturation pressure is undefined), gives NaN
/// air everywhere instead of steam. A cap is reached only by air
/// that cannot exist, which every validated boundary refuses before it gets here.
#[inline(always)]
fn capped_vapor_mole_fraction(mole_fraction_vapor: f64) -> f64 {
    if mole_fraction_vapor > 1.0 {
        1.0
    } else {
        mole_fraction_vapor
    }
}

/// Enhanced air density calculation using CIPM formula with ICAO atmosphere.
///
/// # Arguments
/// * `temp_c` - Temperature in Celsius
/// * `pressure_hpa` - Pressure in hPa
/// * `humidity_percent` - Humidity percentage (0-100)
///
/// # Returns
/// Air density in kg/m³
///
/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
/// refuse what this computes.
pub fn calculate_air_density_cimp(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
    let t_k = temp_c + 273.15;

    // Enhanced saturation vapor pressure calculation
    let p_sv = enhanced_saturation_vapor_pressure(t_k);

    let pressure_pa = pressure_hpa * 100.0;

    // Enhanced enhancement factor with temperature dependence. CIPM constants use Pa.
    let f = enhanced_enhancement_factor(pressure_pa, temp_c);

    // Floor the pressure divisor (mirrors calculate_atmosphere): a 0 hPa pressure would
    // otherwise make x_v = +Inf -> NaN density. No-op for all valid (>0) pressures.
    let p_pa = pressure_pa.max(f64::MIN_POSITIVE);

    // Mole fraction of water vapor, capped at the physical maximum of 1 (a NaN stays NaN). The
    // cap is silent: air whose vapor pressure would exceed its total pressure does not exist,
    // and callers that must refuse it rather than compute pure steam test
    // `water_vapor_mole_fraction_uncapped` first (StationAir::new, AtmoSock::validate and the
    // bridge's `atmosphere.density_altitude`).
    let x_v = capped_vapor_mole_fraction(vapor_mole_fraction(p_sv, f, humidity_percent, p_pa));

    // Enhanced compressibility factor. CIPM virial constants use Pa.
    let z = enhanced_compressibility_factor(p_pa, t_k, x_v);

    // Calculate density with enhanced precision. The last factor is the moist-air molar-mass
    // ratio M_m / M_a, which the virtual-temperature lapse aloft scales by too.
    // Note: parentheses are important here for correct operator precedence
    ((p_pa * M_A) / (z * R * t_k)) * moist_molar_mass_ratio(x_v)
}

/// CIPM-2007 mole fraction of water vapor, `x_v = RH * f * p_sv / p`, UNCAPPED: the one
/// formula [`calculate_air_density_cimp`] uses (it caps the result at 1). A value at or above 1
/// means the stated humidity would need more vapor pressure than the air has total pressure.
pub(crate) fn water_vapor_mole_fraction_uncapped(
    temp_c: f64,
    pressure_hpa: f64,
    humidity_percent: f64,
) -> f64 {
    let t_k = temp_c + 273.15;
    let p_sv = enhanced_saturation_vapor_pressure(t_k);
    let pressure_pa = pressure_hpa * 100.0;
    let f = enhanced_enhancement_factor(pressure_pa, temp_c);
    vapor_mole_fraction(
        p_sv,
        f,
        humidity_percent,
        pressure_pa.max(f64::MIN_POSITIVE),
    )
}

/// [`water_vapor_mole_fraction_uncapped`] in the units the sound speed works in: temperature in
/// kelvin and total pressure in Pa. UNCAPPED; [`moist_speed_of_sound`] caps it at 1.
///
/// The enhancement factor reads `temp_k - 273.15`, which is not always the caller's Celsius
/// value to the last bit, so this is a separate entry rather than a call through the Celsius
/// one. Both reach the same [`vapor_mole_fraction`].
#[inline(always)]
fn moist_air_vapor_mole_fraction(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
    let temp_c = temp_k - 273.15;
    let p_sv_hpa = enhanced_saturation_vapor_pressure(temp_k);
    let f = enhanced_enhancement_factor(pressure_pa, temp_c);
    vapor_mole_fraction(
        p_sv_hpa,
        f,
        humidity_percent,
        pressure_pa.max(f64::MIN_POSITIVE),
    )
}

/// The engine's ONE water-vapour mole fraction, `x_v = (RH/100) * f * p_sv / p`, uncapped.
///
/// The CIPM-2007 density ([`calculate_air_density_cimp`]), the moist speed of sound
/// ([`moist_speed_of_sound`]) and the impossible-air test ([`water_vapor_mole_fraction_uncapped`],
/// behind [`StationAir::new`] and the density-altitude service) all evaluate it here, in this
/// operation order, so they cannot drift apart. `p_sv_hpa` is in hPa and `p_pa` in Pa; the
/// humidity is clamped into `[0, 100]` as a total-function guard for the unvalidated legacy
/// entry points (validated callers pass a [`RelativeHumidity`], already in range), and a NaN
/// humidity, or a NaN `p_sv_hpa` above water's critical point at any humidity above 0, gives a
/// NaN `x_v`, which [`capped_vapor_mole_fraction`] keeps.
///
/// Dry air holds no water vapour at any temperature: at 0 % `x_v` is exactly 0 whatever
/// `p_sv_hpa` is, so dry air above water's critical point (647.096 K, where `p_sv_hpa` is NaN)
/// is dry air, not air that cannot exist. Wherever `p_sv_hpa` is a number (below that point)
/// this is the very value the full formula gives, bit for bit: the same zero, with its sign,
/// and NaN for a NaN temperature or pressure (through `f`).
#[inline(always)]
pub(crate) fn vapor_mole_fraction(p_sv_hpa: f64, f: f64, humidity_percent: f64, p_pa: f64) -> f64 {
    let humidity_percent = humidity_percent.clamp(0.0, 100.0);
    if humidity_percent == 0.0 {
        // The full formula without its positive, finite p_sv factor (and the exact factors 100
        // and 1/100, which move no zero): the same signed zero, or NaN, as ever.
        return humidity_percent * f / p_pa;
    }
    // Vapor pressure with clamping. p_sv is in hPa (enhanced_saturation_vapor_pressure
    // returns hPa — its critical-pressure constant is 220640 hPa), so p_v is in hPa too.
    let p_v = humidity_percent / 100.0 * f * p_sv_hpa;

    // Convert the vapor pressure to Pa BEFORE forming the mole fraction: the divisor below
    // is in Pa. Dividing the hPa p_v by the Pa total made x_v 100x too small, which erased
    // the humidity term and returned essentially dry-air density (e.g. 15 C / 1013.25 hPa /
    // 50% RH gave ~1.2254 instead of the CIPM-2007 moist value ~1.2216 — moist air is
    // LIGHTER than dry air).
    let p_v_pa = p_v * 100.0;
    p_v_pa / p_pa
}

/// Saturation vapor pressure of water, hPa, over LIQUID water at every temperature (the WMO
/// convention for relative humidity, also below 0 °C; there is no ice branch).
///
/// The Wagner-Pruss saturation-pressure equation, the form of the IAPWS supplementary release
/// on the saturation properties of ordinary water substance:
/// `ln(p_sv / p_c) = (T_c / T) (a1 Ï„ + a2 Ï„^1.5 + a3 Ï„^3 + a4 Ï„^3.5 + a5 Ï„^4 + a6 Ï„^7.5)` with
/// `Ï„ = 1 - T / T_c`, `T_c = 647.096 K` and `p_c = 22.064 MPa`. (The industrial IF97
/// formulation's region-4 saturation equation is a different formula.)
#[inline(always)]
fn enhanced_saturation_vapor_pressure(t_k: f64) -> f64 {
    #[cfg(test)]
    air_trace::count_saturation_pressure();

    // Wagner-Pruss coefficients a1..a6.
    const A: [f64; 6] = [
        -7.85951783,
        1.84408259,
        -11.7866497,
        22.6807411,
        -15.9618719,
        1.80122502,
    ];

    // Ensure temperature is positive and reasonable
    let t_k_safe = t_k.max(173.15); // -100°C minimum

    let tau = 1.0 - t_k_safe / 647.096; // Critical temperature of water
    let ln_p_ratio = (647.096 / t_k_safe)
        * (A[0] * tau
            + A[1] * tau.powf(1.5)
            + A[2] * tau.powf(3.0)
            + A[3] * tau.powf(3.5)
            + A[4] * tau.powf(4.0)
            + A[5] * tau.powf(7.5));

    220640.0 * ln_p_ratio.exp() // Critical pressure in hPa (22.064 MPa)
}

/// CIPM-2007 enhancement factor `f = alpha + beta*p + gamma*t^2` (p in Pa, t in Celsius).
#[inline(always)]
fn enhanced_enhancement_factor(p: f64, t: f64) -> f64 {
    const ALPHA: f64 = 1.00062;
    const BETA: f64 = 3.14e-8;
    const GAMMA: f64 = 5.6e-7;

    ALPHA + BETA * p + GAMMA * t * t
}

/// CIPM-2007 compressibility factor `Z` (virial expansion, second order in `p/T`).
#[inline(always)]
fn enhanced_compressibility_factor(p: f64, t_k: f64, x_v: f64) -> f64 {
    // CIPM-2007 molar virial coefficients (p in Pa, t in Celsius).
    const A0: f64 = 1.58123e-6;
    const A1: f64 = -2.9331e-8;
    const A2: f64 = 1.1043e-10;
    const B0: f64 = 5.707e-6;
    const B1: f64 = -2.051e-8;
    const C0: f64 = 1.9898e-4;
    const C1: f64 = -2.376e-6;
    const D: f64 = 1.83e-11;
    const E: f64 = -0.765e-8;

    // Ensure temperature is positive
    let t_k_safe = t_k.max(173.15); // -100°C minimum
    let t = t_k_safe - 273.15;
    let p_t = p / t_k_safe;

    let z_second_order =
        1.0 - p_t * (A0 + A1 * t + A2 * t * t + (B0 + B1 * t) * x_v + (C0 + C1 * t) * x_v * x_v);

    let z_third_order = p_t * p_t * (D + E * x_v * x_v);

    z_second_order + z_third_order
}

/// Convert an `(x, y)` position in the shot-aligned frame to true world altitude.
///
/// The engine rotates gravity by `shooting_angle_rad`, so shot-frame X follows the inclined
/// line of fire and Y is perpendicular to it in the vertical plane. Atmosphere lookup needs the
/// world-vertical projection of that position, added to the station altitude.
#[inline]
pub(crate) fn shot_frame_altitude(
    base_altitude_m: f64,
    downrange_m: f64,
    shot_y_m: f64,
    shooting_angle_rad: f64,
) -> f64 {
    base_altitude_m + downrange_m * shooting_angle_rad.sin() + shot_y_m * shooting_angle_rad.cos()
}

/// Local DRY air: [`get_local_atmosphere_humid`] at 0 % relative humidity.
///
/// Dry by contract, which is why it is deprecated: a flight's air has a humidity, and
/// [`air_at`] over a [`StationAir`] flies it. The replacement is
/// `air_at(&KernelAtmosphere::Station(StationAir::new(base_alt, base_temp_c, base_press_hpa,
/// humidity)?), None, 0.0, altitude_m)`; a caller that holds its own density ratio builds the
/// station with [`StationAir::with_density_ratio`] instead. The density is the same as every other
/// path's (the base ratio scaled by the lapse); the sound speed is the engine's one dry value,
/// `sqrt(1.4 · 287.0531 · T)`, the shared composition at [`RelativeHumidity::DRY`]. Until 0.50.0
/// this function used a second dry constant, `sqrt(401.874 · T)`, 4.2e-7 slower.
///
/// # Arguments
/// * `altitude_m` - Query geometric altitude above mean sea level in meters
/// * `base_alt` - Base geometric altitude above mean sea level in meters
/// * `base_temp_c` - Base temperature in Celsius
/// * `base_press_hpa` - Base pressure in hPa
/// * `base_ratio` - Base density ratio
///
/// # Returns
/// Tuple of (air_density_kg_m3, speed_of_sound_mps)
#[deprecated(
    since = "0.50.0",
    note = "dry air by contract; use air_at(&KernelAtmosphere::Station(StationAir::new(..)?), None, 0.0, altitude_m), or StationAir::with_density_ratio for a caller-held density ratio"
)]
pub fn get_local_atmosphere(
    altitude_m: f64,
    base_alt: f64,
    base_temp_c: f64,
    base_press_hpa: f64,
    base_ratio: f64,
) -> (f64, f64) {
    let air = compose_local_air(
        altitude_m,
        base_alt,
        &GoverningAir::new(
            base_temp_c,
            base_press_hpa,
            base_ratio,
            RelativeHumidity::DRY.percent(),
        ),
        Gravity::EARTH,
    );
    (air.density_kg_m3, air.speed_of_sound_mps)
}

/// The local air, unvalidated: the same composition as [`air_at`], from a caller-held base
/// tuple. The base air's water-vapour mole fraction, from `base_temp_c`, `base_press_hpa` and
/// `humidity_percent`, is held at every height for the virtual-temperature lapse, the density
/// and the moist-air speed of sound at the local temperature.
///
/// A legacy entry point: it clamps an out-of-range humidity instead of refusing it (a NaN
/// propagates to NaN air, never to steam), and it cannot know whether `base_ratio` was built at
/// `humidity_percent`. In-crate code calls [`air_at`] with a [`KernelAtmosphere`] instead.
///
/// # Arguments
/// * `altitude_m` - Query geometric altitude above mean sea level in meters
/// * `base_alt` - Base (station) geometric altitude above mean sea level in meters
/// * `base_temp_c` - Base temperature in Celsius
/// * `base_press_hpa` - Base pressure in hPa
/// * `base_ratio` - Base density ratio (density / 1.225)
/// * `humidity_percent` - Relative humidity percentage (0-100)
///
/// # Returns
/// Tuple of (air_density_kg_m3, moist_speed_of_sound_mps)
pub fn get_local_atmosphere_humid(
    altitude_m: f64,
    base_alt: f64,
    base_temp_c: f64,
    base_press_hpa: f64,
    base_ratio: f64,
    humidity_percent: f64,
) -> (f64, f64) {
    get_local_atmosphere_humid_with_gravity(
        altitude_m,
        base_alt,
        base_temp_c,
        base_press_hpa,
        base_ratio,
        humidity_percent,
        Gravity::EARTH,
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn get_local_atmosphere_humid_with_gravity(
    altitude_m: f64,
    base_alt: f64,
    base_temp_c: f64,
    base_press_hpa: f64,
    base_ratio: f64,
    humidity_percent: f64,
    gravity: Gravity,
) -> (f64, f64) {
    // The same composition `air_at` uses, without its validation: this legacy entry keeps its
    // internal clamp of an out-of-range humidity (a NaN gives NaN air), and can never diverge
    // from `air_at`. Its base is the caller's raw tuple, so it computes the base air's vapour
    // mole fraction on every call, through the same one formula.
    let air = compose_local_air(
        altitude_m,
        base_alt,
        &GoverningAir::new(base_temp_c, base_press_hpa, base_ratio, humidity_percent),
        gravity,
    );
    (air.density_kg_m3, air.speed_of_sound_mps)
}

// =================================================================================================
// The single source of truth for humid air: a validated relative humidity, the station air built
// from it, the kernel atmosphere that carries it, and the one per-step air lookup.
// =================================================================================================

/// The relative humidity, in percent, that an omitted humidity means: 50 %.
///
/// [`RelativeHumidity::DEFAULT`] holds the same value. `AtmosphericConditions::default` means
/// it, and solve v1's omitted `relative_humidity` is the same default in the SI wire's unit,
/// `RelativeHumidity::DEFAULT.fraction()` (exactly 0.5).
pub const DEFAULT_HUMIDITY_PERCENT: f64 = 50.0;

/// How far, in percentage points, a relative-humidity READING may lie outside 0-100 % and
/// still be read as the saturated (100 %) or dry (0 %) air it measures: 5.
///
/// Weather is an input source, never a gate. The humidity a shooter enters is most often a
/// sensor's (a Kestrel, a WEATHERmeter, a phone), and relative-humidity sensors are good to
/// about ±2-3 %: in fog and other condensing air they read above 100 %, where free air is
/// supersaturated by under 1 %, and in very dry air they can read a little below 0 %. Such a
/// reading is sensor error around saturated or dry air, not a different atmosphere, and must
/// not fail a calculation. So [`RelativeHumidity::try_percent`] accepts a percent from -5 to
/// 105 and stores it clamped into 0..=100 (101.7 is exactly 100, -2 exactly 0), and
/// [`RelativeHumidity::try_fraction`] does the same with a fraction from -0.05 to 1.05. Every
/// surface reads humidity through those two constructors, so every surface has this band.
///
/// A value farther out is refused, as before: it is not a reading of real air but a wrong unit
/// (a percent sent as a fraction) or a typo. Air that cannot exist at all (a water-vapour mole
/// fraction of 1 or more) is a separate rule, [`StationAir::new`]'s, and the band does not
/// relax it.
pub const HUMIDITY_SENSOR_TOLERANCE_PERCENT: f64 = 5.0;

/// The percents [`RelativeHumidity::try_percent`] accepts: the sensor band around 0..=100.
const HUMIDITY_PERCENT_BAND: (f64, f64) = (
    -HUMIDITY_SENSOR_TOLERANCE_PERCENT,
    100.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT,
);

/// The fractions [`RelativeHumidity::try_fraction`] accepts: the same band in fraction units,
/// exactly -0.05 and 1.05.
const HUMIDITY_FRACTION_BAND: (f64, f64) = (
    -HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
    1.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
);

/// Absolute zero in degrees Celsius; a station temperature must lie above it.
const ABSOLUTE_ZERO_C: f64 = -273.15;
/// The density ratio `density / 1.225 kg/m³` a station may carry is below this (and above 0).
/// It is `fast_integrate`'s ceiling for a supplied standard-mode ratio.
const MAX_STATION_DENSITY_RATIO: f64 = 2.0;
/// Uniform (direct-mode) air must have a density below this, in kg/m³, and at least 0 (a
/// vacuum): 0.49.0's `compute_derivatives` direct-mode detection, `density < 2`, which took a
/// density of exactly 0 as the way to switch drag off.
const MAX_UNIFORM_DENSITY_KG_M3: f64 = 2.0;
/// Uniform (direct-mode) air must have a speed of sound above this, in m/s. The same bound the
/// kernels' direct-mode detection uses today.
const MIN_UNIFORM_SPEED_OF_SOUND_MPS: f64 = 200.0;

/// A validated relative humidity.
///
/// It stores a PERCENT in `[0, 100]`, and [`Self::fraction`] gives the same humidity in
/// `[0, 1]`. The two constructors name the unit at the call site, and there is deliberately no
/// `From<f64>`, so a bare number is never read in the wrong unit.
///
/// One rule, the sensor band ([`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]): a reading up to 5 points
/// outside the range is the saturated or dry air it measures, stored as exactly 100 or 0, so it
/// flies exactly as that end does. Anything farther out, or not finite, is refused with an
/// [`AtmosphereError`] that reports the value unchanged.
///
/// ```
/// use ballistics_engine::RelativeHumidity;
///
/// let from_percent = RelativeHumidity::try_percent(50.0).unwrap();
/// let from_fraction = RelativeHumidity::try_fraction(0.5).unwrap();
/// assert_eq!(from_percent, from_fraction);
/// assert_eq!(from_percent, RelativeHumidity::DEFAULT);
/// assert_eq!(from_fraction.percent(), 50.0);
/// assert_eq!(from_percent.fraction(), 0.5);
///
/// // A sensor reading in fog, or in very dry air, is that air.
/// assert_eq!(RelativeHumidity::try_percent(101.7).unwrap().percent(), 100.0);
/// assert_eq!(RelativeHumidity::try_percent(-2.0).unwrap(), RelativeHumidity::DRY);
/// assert_eq!(RelativeHumidity::try_fraction(1.03).unwrap().percent(), 100.0);
///
/// assert!(RelativeHumidity::try_percent(150.0).is_err());
/// assert!(RelativeHumidity::try_percent(105.0000001).is_err());
/// // A percent sent where a fraction belongs is refused, not read as 50 %.
/// assert!(RelativeHumidity::try_fraction(50.0).is_err());
/// ```
///
/// A bare `f64` does not convert, because it does not say whether 0.5 means 50 % or 0.5 %
/// (E0277: no `From<f64>`):
///
/// ```compile_fail,E0277
/// use ballistics_engine::RelativeHumidity;
///
/// let humidity: RelativeHumidity = 0.5.into();
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RelativeHumidity(f64);

impl RelativeHumidity {
    /// The default for an omitted humidity: [`DEFAULT_HUMIDITY_PERCENT`], 50 %.
    pub const DEFAULT: Self = Self(DEFAULT_HUMIDITY_PERCENT);

    /// Dry air, 0 %.
    pub const DRY: Self = Self(0.0);

    /// The lowest and the highest fraction [`Self::try_fraction`] accepts, both included: the
    /// sensor band ([`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]) in fraction units, exactly
    /// `(-0.05, 1.05)`.
    ///
    /// For a schema that publishes the bounds the decoder enforces (the MCP server's
    /// `relative_humidity`), so the band it states is derived from the one number rather than
    /// written out again.
    pub const FRACTION_BAND: (f64, f64) = HUMIDITY_FRACTION_BAND;

    /// A relative humidity given in PERCENT.
    ///
    /// Accepts a finite `percent` from -5 to 105, both ends included (the sensor band,
    /// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]). A percent in `0.0..=100.0` is stored unchanged,
    /// one above 100 as exactly 100 and one below 0 (or `-0.0`) as `0.0`. Anything else is
    /// refused, with field `humidity_percent`, the value unchanged, and reason
    /// [`AtmosphereErrorReason::NotFinite`] or
    /// [`AtmosphereErrorReason::HumidityPercentOutOfRange`].
    pub fn try_percent(percent: f64) -> Result<Self, AtmosphereError> {
        sensor_band(
            percent,
            HUMIDITY_PERCENT_BAND,
            100.0,
            "humidity_percent",
            AtmosphereErrorReason::HumidityPercentOutOfRange,
        )
        .map(Self)
    }

    /// A relative humidity given as a FRACTION, the SI wire's `relative_humidity`.
    ///
    /// Accepts a finite `fraction` from -0.05 to 1.05, both ends included (the sensor band in
    /// fraction units), and stores the fraction snapped into `0.0..=1.0` times 100: an
    /// in-range fraction is `fraction * 100.0`, exact at 0, 0.5 and 1 and within one ulp of the
    /// decimal percent elsewhere, one above 1 is exactly 100, one below 0 is 0. Anything else is
    /// refused, with field `relative_humidity`, the value unchanged, and reason
    /// [`AtmosphereErrorReason::NotFinite`] or
    /// [`AtmosphereErrorReason::HumidityFractionOutOfRange`]; so a percent sent by mistake
    /// (`50.0`) is an error rather than 5000 %.
    pub fn try_fraction(fraction: f64) -> Result<Self, AtmosphereError> {
        // The very conversion solve v1 and the density-altitude service apply today, so a
        // caller moving onto this constructor flies the same bits.
        Self::snap_fraction(fraction).map(|fraction| Self(fraction * 100.0))
    }

    /// The fraction [`Self::try_fraction`] accepts, snapped into `0.0..=1.0` in the fraction's
    /// own unit: an in-range fraction comes back with its bits unchanged (`-0.0` as `0.0`),
    /// one above 1 as exactly 1 and one below 0 as 0. For a wire that echoes the fraction it
    /// flies (solve v1's resolved `relative_humidity`); its errors are `try_fraction`'s.
    pub(crate) fn snap_fraction(fraction: f64) -> Result<f64, AtmosphereError> {
        sensor_band(
            fraction,
            HUMIDITY_FRACTION_BAND,
            1.0,
            "relative_humidity",
            AtmosphereErrorReason::HumidityFractionOutOfRange,
        )
    }

    /// Whether `fraction` is a relative humidity in `0.0..=1.0` itself, not merely a sensor
    /// reading the band reads as one: exactly the fractions [`Self::snap_fraction`] leaves
    /// where it found them (`-0.0` included, NaN and the infinities not).
    ///
    /// For a caller that moves a humidity HYPOTHETICALLY rather than reading one, the
    /// perturbation layer's central difference: a perturbed 1.001 is not fog read by a sensor,
    /// and flying it as saturated air would silently halve the derivative at the end.
    pub(crate) fn is_physical_fraction(fraction: f64) -> bool {
        matches!(Self::snap_fraction(fraction), Ok(snapped) if snapped == fraction)
    }

    /// The humidity in percent, `0.0..=100.0`.
    pub const fn percent(self) -> f64 {
        self.0
    }

    /// The humidity as a fraction, `0.0..=1.0` (`percent / 100`).
    ///
    /// A `const fn`, so a wire default can be written as the one default in the wire's unit:
    /// `RelativeHumidity::DEFAULT.fraction()` is exactly `0.5`.
    pub const fn fraction(self) -> f64 {
        self.0 / 100.0
    }
}

/// The one sensor-band rule, in a unit whose saturated air is `saturated` (100 for a percent,
/// 1 for a fraction): a finite `value` inside `band` comes back snapped into
/// `0.0..=saturated` (at or below 0, `-0.0` included, as `+0.0`; above `saturated` as exactly
/// `saturated`; otherwise unchanged); anything else is refused with `field` and the value
/// unchanged.
fn sensor_band(
    value: f64,
    (lowest, highest): (f64, f64),
    saturated: f64,
    field: &'static str,
    out_of_band: AtmosphereErrorReason,
) -> Result<f64, AtmosphereError> {
    let unit = match out_of_band {
        AtmosphereErrorReason::HumidityFractionOutOfRange => HumidityUnit::Fraction,
        _ => HumidityUnit::Percent,
    };
    if !value.is_finite() {
        return Err(
            AtmosphereError::new(field, value, AtmosphereErrorReason::NotFinite).of_humidity(unit),
        );
    }
    if !(lowest..=highest).contains(&value) {
        return Err(AtmosphereError::new(field, value, out_of_band).of_humidity(unit));
    }
    Ok(if value <= 0.0 {
        0.0
    } else if value > saturated {
        saturated
    } else {
        value
    })
}

/// The range of a relative humidity PERCENT as every refusal states it, built from
/// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] so the words cannot drift from the band the
/// constructor enforces: `percent from 0 to 100 (a sensor reading from -5 to 105 is read as 0 or
/// 100)`.
fn humidity_percent_range() -> String {
    format!(
        "percent from 0 to 100 (a sensor reading from {} to {} is read as 0 or 100)",
        HUMIDITY_PERCENT_BAND.0, HUMIDITY_PERCENT_BAND.1
    )
}

/// The range of a relative humidity FRACTION (the SI wire's `relative_humidity`) as every
/// refusal states it, from the same constant: `fraction from 0 to 1 (0.5 = 50 %; a sensor
/// reading from -0.05 to 1.05 is read as 0 or 1)`.
fn humidity_fraction_range() -> String {
    format!(
        "fraction from 0 to 1 (0.5 = 50 %; a sensor reading from {} to {} is read as 0 or 1)",
        HUMIDITY_FRACTION_BAND.0, HUMIDITY_FRACTION_BAND.1
    )
}

/// Parse a relative-humidity PERCENT typed as text (a terminal or CLI flag's value) through the
/// one validator, [`RelativeHumidity::try_percent`].
///
/// The error is the reason alone, for a caller that names the flag and the value itself (clap
/// does): `not a number; relative humidity is a percent from 0 to 100 (a sensor reading from -5
/// to 105 is read as 0 or 100)` for text that is no number, and
/// [`AtmosphereError::explanation`] for a number the band refuses.
///
/// ```
/// use ballistics_engine::atmosphere::parse_humidity_percent_text;
///
/// assert_eq!(parse_humidity_percent_text("101.7").unwrap().percent(), 100.0);
/// assert!(parse_humidity_percent_text("150")
///     .unwrap_err()
///     .starts_with("relative humidity must be a percent from 0 to 100 (a sensor reading"));
/// assert!(parse_humidity_percent_text("wet").unwrap_err().starts_with("not a number; "));
/// ```
pub fn parse_humidity_percent_text(raw: &str) -> Result<RelativeHumidity, String> {
    let value: f64 = raw.trim().parse().map_err(|_| {
        format!(
            "not a number; relative humidity is a {}",
            humidity_percent_range()
        )
    })?;
    RelativeHumidity::try_percent(value).map_err(|error| error.explanation())
}

/// Parse a terminal humidity flag's value (`--humidity 37.5`, `--zero-humidity 80`) through the
/// one validator, [`RelativeHumidity::try_percent`]: a PERCENT, 0 to 100, and a sensor reading
/// up to [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] outside it is the end it reads as (`101.7` gives
/// `100.0`); anything farther out is refused, never clamped. The WASM terminal's hand-written
/// parser calls it for every humidity flag (the native CLI's clap parser goes through
/// [`parse_humidity_percent_text`]); its errors name the flag, for example
/// `"--humidity = 150: relative humidity must be a percent from 0 to 100 (a sensor reading from
/// -5 to 105 is read as 0 or 100)"`.
#[cfg(any(target_arch = "wasm32", test))]
pub(crate) fn parse_humidity_percent_arg(flag: &str, raw: &str) -> Result<f64, String> {
    match raw.trim().parse::<f64>() {
        Ok(value) => RelativeHumidity::try_percent(value)
            .map(RelativeHumidity::percent)
            .map_err(|error| error.at_field(flag.to_string()).to_string()),
        Err(_) => Err(format!(
            "{flag} = {raw}: {}",
            parse_humidity_percent_text(raw).expect_err("text that is no number")
        )),
    }
}

/// Why an atmosphere value was refused. Carried by [`AtmosphereError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AtmosphereErrorReason {
    /// The value is NaN or infinite.
    NotFinite,
    /// A relative humidity percent outside `[0, 100]` by more than the sensor band,
    /// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]: below -5 or above 105. It displays the band it
    /// enforces: "relative humidity must be a percent from 0 to 100 (a sensor reading from -5 to
    /// 105 is read as 0 or 100)".
    HumidityPercentOutOfRange,
    /// A relative humidity fraction outside `[0, 1]` by more than the sensor band: below -0.05
    /// or above 1.05. It displays the band in fraction units: "relative humidity must be a
    /// fraction from 0 to 1 (0.5 = 50 %; a sensor reading from -0.05 to 1.05 is read as 0 or 1)".
    HumidityFractionOutOfRange,
    /// A temperature at or below absolute zero, -273.15 °C.
    AtOrBelowAbsoluteZero,
    /// A pressure at or below zero.
    NonPositivePressure,
    /// Air that cannot exist: the stated humidity needs a water-vapour mole fraction of 1 or
    /// more, that is more vapour pressure than the air's total pressure; or the air is humid
    /// above water's critical point (647.096 K), where no saturation vapour pressure, and so no
    /// relative humidity, is defined; or, dry above that point, it is too hot for the CIPM-2007
    /// density to stay finite and positive; or its pressure is so far beyond any air's (above
    /// about 4e156 Pa) that the density does not either. Dry air at any lower temperature above
    /// absolute zero exists. The same refusal the `atmosphere.density_altitude` service makes.
    ImpossibleAir,
    /// A station density ratio (density / 1.225 kg/m³) outside `(0, 2)`.
    DensityRatioOutOfRange,
    /// A uniform (direct-mode) air density outside `[0, 2)` kg/m³ (0 is a vacuum).
    UniformDensityOutOfRange,
    /// A uniform (direct-mode) speed of sound at or below 200 m/s.
    UniformSpeedOfSoundOutOfRange,
    /// A downrange atmosphere zone whose `until_distance_m` is not above 0.
    NonPositiveZoneThreshold,
    /// Air that cannot exist aloft: from this station (or downrange zone) temperature the
    /// standard lapse takes the air to absolute zero, at an altitude the flight reaches. Every
    /// trajectory kernel refuses the flight at the step that gets there, with this reason on the
    /// temperature ([`AtmosphereError::field`] `temperature_c`, the governing air's temperature);
    /// [`AtmosphereError::altitude_m`] is where the air reaches 0 K. A flight that stays below
    /// that height flies.
    AirAloftBelowAbsoluteZero,
    /// A density altitude no air has by the FAA rule its entry inverts
    /// ([`station_for_density_altitude`]): at its pressure altitude by that rule
    /// ([`AtmosphereError::altitude_m`]) the NWS pressure formula gives no finite pressure above
    /// 0 (at or above 145366.45 ft, 44308 m), or, with no temperature given, the rule's standard
    /// temperature is at or below absolute zero (at or above 145286 ft, 44283 m). On the field
    /// `density_altitude_m`.
    NoAirAtDensityAltitude,
}

impl fmt::Display for AtmosphereErrorReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NotFinite => "must be finite",
            Self::HumidityPercentOutOfRange => {
                return write!(
                    f,
                    "relative humidity must be a {}",
                    humidity_percent_range()
                )
            }
            Self::HumidityFractionOutOfRange => {
                return write!(
                    f,
                    "relative humidity must be a {}",
                    humidity_fraction_range()
                )
            }
            Self::AtOrBelowAbsoluteZero => "temperature must be above absolute zero (-273.15 °C)",
            Self::NonPositivePressure => "pressure must be greater than 0",
            Self::ImpossibleAir => {
                "no such air exists: at this temperature and pressure the humidity needs a \
                 water-vapour mole fraction of 1 or more (more vapour pressure than the total), \
                 or the air is humid above water's critical point, or too hot or too dense to \
                 have a density"
            }
            Self::DensityRatioOutOfRange => {
                "density ratio (density / 1.225 kg/m^3) must be greater than 0 and less than 2"
            }
            Self::UniformDensityOutOfRange => {
                "air density must be at least 0 (a vacuum) and less than 2 kg/m^3"
            }
            Self::UniformSpeedOfSoundOutOfRange => "speed of sound must be greater than 200 m/s",
            Self::NonPositiveZoneThreshold => {
                "an atmosphere zone's until_distance_m must be greater than 0"
            }
            Self::AirAloftBelowAbsoluteZero => "the air aloft would fall below absolute zero",
            Self::NoAirAtDensityAltitude => "no air has this density altitude by the FAA rule",
        })
    }
}

/// The unit a refused relative humidity was given in, so a refusal that names no range of its
/// own (a NaN) can still state the one the value had to lie in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HumidityUnit {
    Percent,
    Fraction,
}

/// An atmosphere value refused at a boundary: which field, the value given, and why.
///
/// The constructors name their own parameters (`humidity_percent`, `relative_humidity`,
/// `temperature_c`, `pressure_hpa`, ...). A boundary that knows the caller's path, such as a
/// JSON pointer, relabels the error with [`Self::at_field`], or states the whole refusal in its
/// own words with [`Self::refusal_in`]. It displays as `"<field> = <value>: <explanation>"`.
#[derive(Debug, Clone, PartialEq)]
pub struct AtmosphereError {
    field: Cow<'static, str>,
    value: f64,
    reason: AtmosphereErrorReason,
    humidity_unit: Option<HumidityUnit>,
    /// Where air that cannot exist aloft reaches absolute zero, m above mean sea level.
    altitude_m: Option<f64>,
}

impl AtmosphereError {
    /// Find a typed atmosphere refusal through a service's error chain.
    /// Keep the cause until the boundary can name the reading in its own units.
    pub fn in_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Self> {
        let mut current = Some(error);
        while let Some(error) = current {
            if let Some(air) = error.downcast_ref::<Self>() {
                return Some(air);
            }
            current = error.source();
        }
        None
    }

    /// Name a refusal discovered aloft using the same temperature source as the station check.
    pub fn temperature_refusal(&self, field: AirField<'_>, units: AirUnits) -> AirRefusal {
        self.temperature_refusal_from(field, units, StationTemperatureOrigin::Reading)
    }

    /// Like [`Self::temperature_refusal`], retaining a density altitude's derived temperature.
    pub fn temperature_refusal_from(
        &self,
        field: AirField<'_>,
        units: AirUnits,
        origin: StationTemperatureOrigin,
    ) -> AirRefusal {
        let reading = match origin {
            StationTemperatureOrigin::Reading => {
                format!("{} = {}", field.name, units.temperature.text(self.value))
            }
            StationTemperatureOrigin::DensityAltitude => format!(
                "{} gives a station temperature of {}",
                field.name,
                units.temperature.text(self.value)
            ),
        };
        AirRefusal {
            path: field.path.to_string(),
            message: format!("{reading}: {}", self.explanation_in(units.altitude)),
            reason: self.reason,
        }
    }

    fn new(field: &'static str, value: f64, reason: AtmosphereErrorReason) -> Self {
        Self {
            field: Cow::Borrowed(field),
            value,
            reason,
            humidity_unit: None,
            altitude_m: None,
        }
    }

    /// Air that cannot exist aloft: from the governing air's `temperature_c` the standard lapse
    /// reaches absolute zero at `altitude_m` (geometric, above mean sea level), which the flight
    /// reaches.
    fn aloft(temperature_c: f64, altitude_m: f64) -> Self {
        Self {
            altitude_m: Some(altitude_m),
            ..Self::new(
                "temperature_c",
                temperature_c,
                AtmosphereErrorReason::AirAloftBelowAbsoluteZero,
            )
        }
    }

    /// The same error, about a relative humidity given in `unit`.
    fn of_humidity(mut self, unit: HumidityUnit) -> Self {
        self.humidity_unit = Some(unit);
        self
    }

    /// Why the value was refused, in words: the reason's own text, naming the quantity and the
    /// range it must lie in where the reason alone would not. A relative humidity that is not
    /// finite is "relative humidity must be a finite percent from 0 to 100 (a sensor reading
    /// from -5 to 105 is read as 0 or 100)", not a bare "must be finite"; every other refusal is
    /// its [`AtmosphereErrorReason`]'s text.
    ///
    /// For a caller that names the field itself (a flag parser). Any altitude it quotes is in
    /// metres; [`Self::explanation_in`] states it in another unit.
    pub fn explanation(&self) -> String {
        self.explanation_in(AltitudeUnit::Meters)
    }

    /// [`Self::explanation`] with any altitude it quotes (where air that cannot exist aloft
    /// reaches absolute zero) in `altitude_unit`: `"... reaches 0 K at 5049 ft above mean sea
    /// level ..."` in feet.
    pub fn explanation_in(&self, altitude_unit: AltitudeUnit) -> String {
        match (self.reason, self.humidity_unit) {
            (AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Percent)) => format!(
                "relative humidity must be a finite {}",
                humidity_percent_range()
            ),
            (AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Fraction)) => format!(
                "relative humidity must be a finite {}",
                humidity_fraction_range()
            ),
            (reason @ AtmosphereErrorReason::AirAloftBelowAbsoluteZero, _) => {
                match self.altitude_m {
                    Some(altitude_m) => format!(
                        "{reason}: from this temperature the standard lapse reaches 0 K at {} \
                         above mean sea level, which this flight reaches (check the temperature \
                         and its unit)",
                        altitude_unit.text(altitude_m)
                    ),
                    None => reason.to_string(),
                }
            }
            (AtmosphereErrorReason::NoAirAtDensityAltitude, _) => match self.altitude_m {
                Some(pressure_altitude_m) => {
                    let cause =
                        if nws_station_pressure_hpa(pressure_altitude_m / DA_FT_TO_M).is_some() {
                            "the rule's standard temperature is at or below absolute zero"
                        } else {
                            "the NWS pressure formula gives no finite pressure above 0"
                        };
                    format!(
                        "no air has this density altitude: at its pressure altitude by the FAA \
                         rule, {}, {cause} (check the density altitude and its unit)",
                        altitude_unit.text(pressure_altitude_m)
                    )
                }
                None => AtmosphereErrorReason::NoAirAtDensityAltitude.to_string(),
            },
            (reason, _) => reason.to_string(),
        }
    }

    /// For air that cannot exist aloft ([`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]),
    /// the geometric altitude above mean sea level, m, at which the lapse from the refused
    /// temperature reaches absolute zero; `None` for every other refusal.
    pub fn altitude_m(&self) -> Option<f64> {
        self.altitude_m
    }

    /// The refused field's name or path.
    pub fn field(&self) -> &str {
        &self.field
    }

    /// The value that was refused, unchanged.
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Why it was refused.
    pub fn reason(&self) -> AtmosphereErrorReason {
        self.reason
    }

    /// The same error under the caller's own name for the field, for example
    /// `"$.atmosphere.relative_humidity"`.
    pub fn at_field(mut self, field: impl Into<Cow<'static, str>>) -> Self {
        self.field = field.into();
        self
    }
}

impl fmt::Display for AtmosphereError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} = {}: {}",
            self.field,
            echo_number(self.value),
            self.explanation()
        )
    }
}

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

/// The bottom of the band the NWS pressure-altitude formula is read in, m: the bottom of the
/// ICAO table.
pub(crate) const LOWEST_PRESSURE_ALTITUDE_M: f64 = -5_000.0;
/// The top of the standard atmosphere's troposphere, m, and of the band the NWS
/// pressure-altitude formula is read in ([`pressure_altitude_m`]). No reading is refused for a
/// pressure altitude outside the band; it only decides which reading air that cannot exist is
/// blamed on ([`AtmosphereError::refusal_in`]), since a station pressure there is far likelier a
/// unit mistake (hPa sent as pascals is 25 km up) than a humidity.
pub(crate) const TROPOSPHERE_TOP_M: f64 = 11_000.0;

/// The pressure altitude of a station pressure, m ([`pressure_altitude_m`]), when it lies
/// outside the troposphere's band.
pub(crate) fn pressure_altitude_outside_troposphere_m(station_pressure_hpa: f64) -> Option<f64> {
    let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
    (!(LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m))
        .then(|| pressure_altitude_m(station_pressure_hpa))
}

/// °C to K.
const KELVIN_OFFSET: f64 = 273.15;

/// Water's critical temperature, K: above it no saturation vapour pressure (and so no relative
/// humidity) is defined, and only dry air exists.
const WATER_CRITICAL_TEMPERATURE_K: f64 = 647.096;

/// −100 °C. The engine's saturation-vapour-pressure and CIPM compressibility formulas clamp
/// their temperature here: below it the humidity terms are extrapolated (evaluated at this
/// temperature), while the rest of the density is the air's own.
pub(crate) const HUMID_AIR_MODEL_MIN_K: f64 = 173.15;
/// 100 °C. Above the boiling point the saturation-vapour-pressure formula stops describing a
/// stable atmosphere, and above water's critical point (647.096 K) it is not defined at all:
/// there only dry air exists.
pub(crate) const HUMID_AIR_MODEL_MAX_K: f64 = 373.15;

/// Whether a station temperature, K, lies outside [`HUMID_AIR_MODEL_MIN_K`] to
/// [`HUMID_AIR_MODEL_MAX_K`] (both edges inside), where the humid-air terms are extrapolated.
///
/// Not a refusal: no surface refuses a temperature for lying outside this range. It only
/// decides which reading air that cannot exist is blamed on ([`AtmosphereError::refusal_in`]):
/// outside the range the formulas hold for, the temperature is the likelier mistake (°F typed as
/// °C, °C sent as kelvin) than the humidity.
pub(crate) fn outside_humid_air_model_range(temperature_k: f64) -> bool {
    !(HUMID_AIR_MODEL_MIN_K..=HUMID_AIR_MODEL_MAX_K).contains(&temperature_k)
}

/// Where the station pressure a solve flies came from, so air that cannot exist at a station
/// pressure outside the troposphere is blamed on the reading that put it there: the pressure
/// when it was a station reading, the altitude when the pressure was the altitude's.
///
/// Every surface decides it one way, through [`Self::of`] (or [`Self::resolving`], from what a
/// presence-aware resolution was handed), or, for a station a density altitude gave,
/// [`Self::DensityAltitude`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StationPressureOrigin {
    /// A station pressure reading, or a QNH that is itself outside the troposphere (hPa sent as
    /// pascals): the pressure is to blame.
    #[default]
    Reading,
    /// No pressure was given: the station flies the ICAO standard pressure at its altitude, so
    /// the altitude is to blame (feet sent as metres).
    Standard,
    /// A QNH that is itself a plausible sea-level pressure, reduced to the station altitude: the
    /// altitude is to blame.
    Qnh,
    /// A density altitude's station ([`station_for_density_altitude`]): the density altitude is
    /// to blame. A surface names the derived pressure by the density altitude's field,
    /// so the refusal blames [`AirSpelling::pressure`] even if the altitude was overridden.
    DensityAltitude,
}

impl StationPressureOrigin {
    /// The origin of a station pressure from what was given: `given_hpa` is the pressure as
    /// given (a QNH before its reduction), or `None` when none was given and the station flies
    /// the standard pressure at its altitude; `mode` says whether a given pressure is a QNH.
    pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
        match (given_hpa, mode) {
            (None, _) => Self::Standard,
            (Some(qnh_hpa), PressureReferenceMode::Qnh)
                if pressure_altitude_outside_troposphere_m(qnh_hpa).is_none() =>
            {
                Self::Qnh
            }
            (Some(_), _) => Self::Reading,
        }
    }

    /// The origin of the pressure [`resolve_station_conditions_with_presence`] resolves from
    /// these same inputs: a pressure the presence rule replaces with the ICAO standard at the
    /// altitude (an omitted sea-level default at a real altitude) is the standard's; any other
    /// is the given one, a QNH or a reading.
    pub fn resolving(
        pressure_hpa: f64,
        altitude_m: f64,
        mode: PressureReferenceMode,
        presence: StationAtmospherePresence,
    ) -> Self {
        let given = presence.pressure_supplied
            || resolve_station_pressure_with_mode(pressure_hpa, altitude_m, mode).is_some();
        Self::of(given.then_some(pressure_hpa), mode)
    }
}

/// Where the station temperature a solve flies came from, so air that cannot exist, blamed on
/// the temperature, names the reading that carried it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StationTemperatureOrigin {
    /// A temperature reading, or, when none was given, the ICAO standard temperature at the
    /// station altitude (which never leaves the range the humid-air formulas hold for, so no
    /// refusal blames it).
    #[default]
    Reading,
    /// The temperature of a density altitude's station, given no temperature
    /// ([`station_for_density_altitude`]): the density altitude is to blame. A surface that
    /// flies one names the temperature by the density altitude's field.
    DensityAltitude,
}

/// Where a station's pressure and temperature came from, as a surface that resolved the station
/// itself states them to a refusal of its air
/// ([`crate::cli_api::AtmosphericConditions::air_refusal_from`]): the reading to blame, and the
/// QNH as it was given when the pressure was one, so the refusal quotes what was sent, never the
/// station pressure reduced from it as if it had been sent.
///
/// Build one with [`Self::of`] or [`Self::resolving`] (from the pressure as given, a QNH before
/// its reduction) or [`Self::density_altitude`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct StationOrigin {
    /// Where the station pressure came from.
    pub pressure: StationPressureOrigin,
    /// The QNH, hPa, the station pressure was reduced from, when the pressure was given as one;
    /// `None` for a station pressure reading, an omitted pressure and a density altitude's.
    pub qnh_hpa: Option<f64>,
    /// Where the station temperature came from.
    pub temperature: StationTemperatureOrigin,
}

impl StationOrigin {
    /// [`StationPressureOrigin::of`], keeping `given_hpa` as the QNH when `mode` declares it
    /// one. The temperature is a reading.
    pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
        Self {
            pressure: StationPressureOrigin::of(given_hpa, mode),
            qnh_hpa: given_hpa.filter(|_| mode == PressureReferenceMode::Qnh),
            temperature: StationTemperatureOrigin::Reading,
        }
    }

    /// [`StationPressureOrigin::resolving`], keeping `pressure_hpa` as the QNH when `mode`
    /// declares it one (a QNH is always reduced, so always given). The temperature is a reading.
    pub fn resolving(
        pressure_hpa: f64,
        altitude_m: f64,
        mode: PressureReferenceMode,
        presence: StationAtmospherePresence,
    ) -> Self {
        let pressure = StationPressureOrigin::resolving(pressure_hpa, altitude_m, mode, presence);
        Self {
            pressure,
            qnh_hpa: (mode == PressureReferenceMode::Qnh
                && pressure != StationPressureOrigin::Standard)
                .then_some(pressure_hpa),
            temperature: StationTemperatureOrigin::Reading,
        }
    }

    /// A density altitude's station: its pressure (and altitude) are the density altitude's, and
    /// so is its temperature unless one was given (`temperature_given`).
    pub fn density_altitude(temperature_given: bool) -> Self {
        Self {
            pressure: StationPressureOrigin::DensityAltitude,
            qnh_hpa: None,
            temperature: if temperature_given {
                StationTemperatureOrigin::Reading
            } else {
                StationTemperatureOrigin::DensityAltitude
            },
        }
    }
}

/// One station reading as a surface names it: the `name` its messages use and the `path` its
/// machine-readable refusal points at. A CLI uses the flag for both (`--humidity`); a JSON
/// command uses the member's name and its path (`humidity`, `$.humidity`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AirField<'a> {
    /// The reading's name in a message.
    pub name: &'a str,
    /// Where the reading sits in the surface's input: a JSON path, a flag, a file's field.
    pub path: &'a str,
}

impl<'a> AirField<'a> {
    /// A reading whose message name and path are the same text, as a CLI flag's are.
    pub const fn named(name: &'a str) -> Self {
        Self { name, path: name }
    }
}

/// How one surface spells the station air it was given, so a refusal of that air reads in the
/// surface's own words: its field names, the humidity in the unit it was sent in, and the
/// temperature and pressure the solve resolved, in the surface's units with the unit named.
#[derive(Debug, Clone, PartialEq)]
pub struct AirSpelling<'a> {
    /// The relative humidity.
    pub humidity: AirField<'a>,
    /// The station temperature.
    pub temperature: AirField<'a>,
    /// The station pressure.
    pub pressure: AirField<'a>,
    /// The station altitude, or, for a station a density altitude gave, the density altitude
    /// (a density altitude no air has is refused at this field, in `altitude_unit`).
    pub altitude: AirField<'a>,
    /// The humidity as the surface was sent it, in its own unit (a percent, or the SI wire's
    /// fraction).
    pub humidity_sent: f64,
    /// The station temperature the solve flies, with its unit: `"212 °F"`, `"373.15 K"`.
    pub temperature_text: String,
    /// The unit the surface states a temperature in: the unit of `temperature_text`, in which a
    /// refusal of a temperature at or below absolute zero states where absolute zero is, and a
    /// refusal that blames the temperature states the range the humid-air formulas hold for.
    pub temperature_unit: TemperatureUnit,
    /// Where the station temperature came from: a reading, named by `temperature` as the
    /// reading it is (`temperature = 214 °F`), or a density altitude, named by `temperature` as
    /// the reading that gave it (`density_altitude gives a station temperature of ...`).
    pub temperature_origin: StationTemperatureOrigin,
    /// The station pressure the solve flies, with its unit: `"29.92 inHg"`, `"100000 Pa"`.
    pub pressure_text: String,
    /// Where that pressure came from: a reading, the standard pressure at the altitude, a QNH
    /// reduced there, or a density altitude. It decides whether a station pressure outside the
    /// troposphere is the pressure's fault, the altitude's or the density altitude's.
    pub pressure_origin: StationPressureOrigin,
    /// When the pressure was given as a QNH, the QNH as the surface was sent it, with its unit
    /// (`"1013.25 Pa"`, `"5 hPa"`); `None` otherwise. A refusal that names the pressure's field
    /// quotes this, the reading that was sent, and says it was reduced to `pressure_text`, never
    /// the station pressure as if it had been sent.
    pub qnh_text: Option<String>,
    /// The unit the surface states an altitude in: every altitude a refusal quotes (a pressure
    /// altitude, the troposphere's bounds, the station altitude, where air aloft reaches 0 K).
    pub altitude_unit: AltitudeUnit,
}

impl AirSpelling<'_> {
    /// The pressure's field, said to be a QNH, quoting it as it was sent when the surface gave
    /// it: `"--pressure is a QNH of 5 hPa"`, or `"--pressure is a QNH"`.
    fn qnh_named(&self) -> String {
        match &self.qnh_text {
            Some(qnh) => format!("{} is a QNH of {qnh}", self.pressure.name),
            None => format!("{} is a QNH", self.pressure.name),
        }
    }
}

/// The unit a surface states an altitude in, in a refusal of its air: metres (the default, and
/// every SI surface's), or feet (a terminal run with `--units imperial`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AltitudeUnit {
    /// Metres: `1539 m`.
    #[default]
    Meters,
    /// Feet: `5049 ft`.
    Feet,
}

impl AltitudeUnit {
    /// An altitude given in metres, stated in this unit to the nearest whole unit: `"1539 m"`,
    /// `"5049 ft"`; from 10^7 units on, in exponent form to six significant digits
    /// (`"-3.28813e34 m"`), never dozens of digits.
    pub fn text(self, altitude_m: f64) -> String {
        let (value, unit) = match self {
            Self::Meters => (altitude_m, "m"),
            Self::Feet => (altitude_m / 0.3048, "ft"),
        };
        if value.is_finite() && value.abs() >= EXPONENT_FROM {
            format!("{} {unit}", exponent_text(value))
        } else {
            format!("{value:.0} {unit}")
        }
    }

    /// A reading of an altitude given in metres, stated in this unit as a refusal quotes a
    /// reading ([`reading_text`]): `"200000 ft"`, `"44500 m"`, `"NaN ft"`.
    pub fn reading(self, altitude_m: f64) -> String {
        match self {
            Self::Meters => reading_text(altitude_m, "m"),
            Self::Feet => reading_text(altitude_m / 0.3048, "ft"),
        }
    }
}

/// The unit a surface states a temperature in, in a refusal of its air.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TemperatureUnit {
    /// Degrees Celsius: `15 °C`.
    #[default]
    Celsius,
    /// Degrees Fahrenheit: `59 °F`.
    Fahrenheit,
    /// Kelvin, as the SI wire states it: `288.15 K`.
    Kelvin,
}

impl TemperatureUnit {
    /// A temperature given in °C, stated in this unit as a refusal quotes a reading
    /// ([`reading_text`]): `"212 °F"`, `"373.15 K"`.
    pub fn text(self, temperature_c: f64) -> String {
        match self {
            Self::Celsius => reading_text(temperature_c, "°C"),
            Self::Fahrenheit => reading_text(temperature_c * 9.0 / 5.0 + 32.0, "°F"),
            Self::Kelvin => reading_text(temperature_c + KELVIN_OFFSET, "K"),
        }
    }

    /// Absolute zero in this unit: `"-273.15 °C"`, `"-459.67 °F"`, `"0 K"`.
    pub fn absolute_zero_text(self) -> &'static str {
        match self {
            Self::Celsius => "-273.15 °C",
            Self::Fahrenheit => "-459.67 °F",
            Self::Kelvin => "0 K",
        }
    }
}

/// The unit a surface states a pressure in, in a refusal of its air.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PressureUnit {
    /// Hectopascals: `1013.25 hPa`.
    #[default]
    Hectopascals,
    /// Inches of mercury, `inHg × 33.8639 = hPa`: `29.92 inHg`.
    InchesOfMercury,
}

impl PressureUnit {
    /// A pressure given in hPa, stated in this unit as a refusal quotes a reading
    /// ([`reading_text`]): `"29.92 inHg"`, `"1013.25 hPa"`, `"1e160 hPa"`. A pressure that is
    /// not 0 is never stated as 0: one that rounds to 0 at two decimals is written in exponent
    /// form, `"1e-300 hPa"`. (A pressure converts between units by a factor, never an offset,
    /// so a pressure that small is a reading, not rounding left over from a conversion.)
    pub fn text(self, pressure_hpa: f64) -> String {
        let (value, unit) = match self {
            Self::Hectopascals => (pressure_hpa, "hPa"),
            Self::InchesOfMercury => (pressure_hpa / 33.8639, "inHg"),
        };
        let text = reading_text(value, unit);
        if value != 0.0 && value.is_finite() && text == format!("0 {unit}") {
            format!("{} {unit}", exponent_text(value))
        } else {
            text
        }
    }
}

/// The units a surface states its station readings in, in a refusal of its air: the
/// temperature, the pressure and every altitude the refusal quotes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AirUnits {
    /// The temperature's unit.
    pub temperature: TemperatureUnit,
    /// The pressure's unit.
    pub pressure: PressureUnit,
    /// The altitude's unit.
    pub altitude: AltitudeUnit,
}

impl AirUnits {
    /// °C, hPa and metres.
    pub const METRIC: Self = Self {
        temperature: TemperatureUnit::Celsius,
        pressure: PressureUnit::Hectopascals,
        altitude: AltitudeUnit::Meters,
    };
    /// °F, inHg and feet.
    pub const IMPERIAL: Self = Self {
        temperature: TemperatureUnit::Fahrenheit,
        pressure: PressureUnit::InchesOfMercury,
        altitude: AltitudeUnit::Feet,
    };
}

/// A reading in a refusal message: rounded to 2 decimals with the trailing zeros dropped (so a
/// temperature converted to °C and back reads `212`, not `212.00000000000003`), then its unit.
/// From a magnitude of 10^7 on it is written in exponent form to six significant digits
/// (`1e160 hPa`), so an absurd reading reads in a few characters, never hundreds of digits.
pub fn reading_text(value: f64, unit: &str) -> String {
    if value.is_finite() && value.abs() >= EXPONENT_FROM {
        return format!("{} {unit}", exponent_text(value));
    }
    let rounded = format!("{value:.2}");
    let trimmed = if rounded.contains('.') {
        rounded.trim_end_matches('0').trim_end_matches('.')
    } else {
        rounded.as_str()
    };
    let trimmed = if trimmed == "-0" { "0" } else { trimmed };
    format!("{trimmed} {unit}")
}

/// The magnitude from which a refusal writes a number in exponent form ([`reading_text`],
/// [`AltitudeUnit::text`], [`echo_number`]): `1e160`, not 161 digits.
const EXPONENT_FROM: f64 = 1e7;

/// `value` in exponent form to six significant digits, trailing zeros dropped: `1e160`,
/// `-3.28813e34`, `1e-300`. For a figure a refusal states that is too large (or, for a
/// pressure, too small) to write out.
fn exponent_text(value: f64) -> String {
    let text = format!("{value:.5e}");
    match text.split_once('e') {
        Some((mantissa, exponent)) if mantissa.contains('.') => format!(
            "{}e{exponent}",
            mantissa.trim_end_matches('0').trim_end_matches('.')
        ),
        _ => text,
    }
}

/// A number a refusal echoes as it was given: exactly, in its shortest form (`106`, `29.92`,
/// `-0.5`), or in exponent form when its magnitude is 10^7 or more, or below 0.001 and not 0
/// (`1e300`, `-1e-300`), so an absurd reading reads in a few characters, never hundreds of
/// digits. The SI wire's echo (`solve_v1::echo_si`) is this.
pub fn echo_number(value: f64) -> String {
    if value == 0.0 || !value.is_finite() || (1e-3..EXPONENT_FROM).contains(&value.abs()) {
        format!("{value}")
    } else {
        format!("{value:e}")
    }
}

/// Station air refused in one surface's own words: the field to blame, as that surface locates
/// it ([`Self::path`]), and the message ([`Self::message`]).
///
/// Every surface states a refusal of the same air one way. Air that cannot exist reads
/// `"<humidity> = <h> at <temperature> and <pressure>: no such air exists: ..."`, naming the
/// three readings that together are impossible; a humidity outside the sensor band reads
/// `"<humidity> = <h>: relative humidity must be a percent from 0 to 100 (...)"`. Built by
/// [`AtmosphereError::refusal_in`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AirRefusal {
    path: String,
    message: String,
    reason: AtmosphereErrorReason,
}

impl AirRefusal {
    /// Why the air was refused.
    pub fn reason(&self) -> AtmosphereErrorReason {
        self.reason
    }

    /// Where the reading to blame sits in the surface's input, as the surface's
    /// [`AirSpelling`] locates it.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The refusal, in the surface's words.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for AirRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

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

impl AtmosphereError {
    /// This refusal of a station's air, stated in a surface's own words.
    ///
    /// `spelling` names the surface's readings and carries their values in its units;
    /// `station_altitude_m`, `station_temperature_c` and `station_pressure_hpa` are the station
    /// the solve resolved. A refusal for any reason but air that cannot exist blames the reading
    /// this error names, in the surface's units (a temperature at or below absolute zero states
    /// absolute zero in [`AirSpelling::temperature_unit`]; a density altitude no air has is the
    /// field [`AirSpelling::altitude`] names, since a surface that flies one names its altitude by
    /// it). Air that cannot exist is blamed by one rule on every surface, so every surface
    /// locates the same air at the same reading:
    ///
    /// 1. the temperature, when the air is humid above water's critical point (647.096 K), or
    ///    the temperature is outside 173.15 K to 373.15 K (-100 °C to 100 °C, where the humid-air
    ///    formulas hold). Such a temperature is refused by no surface on its own (the humidity
    ///    terms are extrapolated there); with air that cannot exist it is the likelier mistake.
    ///    The message names it where it came from ([`AirSpelling::temperature_origin`]): the
    ///    reading (`; temperature = 214 °F is outside -148 °F to 212 °F, ...: check the
    ///    temperature and its unit`), or the density altitude that gave it (`; density_altitude
    ///    gives a station temperature of ...: check the density altitude's unit`);
    /// 2. when the station pressure's pressure altitude is outside the troposphere, the reading
    ///    that put it there ([`AirSpelling::pressure_origin`]): the pressure when it was a
    ///    reading, because a pressure in the wrong unit (hPa sent as pascals) is far likelier
    ///    than a humidity of 50 % in air 25 km up, and the altitude when the pressure was the
    ///    standard pressure there or a plausible QNH reduced there (feet sent as metres), the
    ///    density altitude when a density altitude gave it. The message says which unit to
    ///    check, and quotes a QNH as it was sent ([`AirSpelling::qnh_text`]), with the station
    ///    pressure it was reduced to;
    /// 3. otherwise the humidity.
    ///
    /// A QNH the altimeter-setting relation leaves no station pressure for is quoted as it was
    /// sent too, never as the NaN it reduced to: blamed on the altitude when it is a plausible
    /// sea-level pressure, on the pressure otherwise.
    pub fn refusal_in(
        &self,
        spelling: &AirSpelling<'_>,
        station_altitude_m: f64,
        station_temperature_c: f64,
        station_pressure_hpa: f64,
    ) -> AirRefusal {
        let (path, message) = self.refusal_parts(
            spelling,
            station_altitude_m,
            station_temperature_c,
            station_pressure_hpa,
        );
        AirRefusal {
            path,
            message,
            reason: self.reason,
        }
    }

    fn refusal_parts(
        &self,
        spelling: &AirSpelling<'_>,
        station_altitude_m: f64,
        station_temperature_c: f64,
        station_pressure_hpa: f64,
    ) -> (String, String) {
        let explanation = self.explanation_in(spelling.altitude_unit);
        let altitude = |altitude_m: f64| spelling.altitude_unit.text(altitude_m);
        if self.reason == AtmosphereErrorReason::ImpossibleAir {
            let air = format!(
                "{} = {} at {} and {}: {explanation}",
                spelling.humidity.name,
                echo_number(spelling.humidity_sent),
                spelling.temperature_text,
                spelling.pressure_text
            );
            // In kelvin, as `atmosphere.density_altitude` compares it. A wire `temperature_k`
            // between 136.6 K and 546.3 K loses nothing when 273.15 is subtracted (Sterbenz), so
            // adding it back restores the very float that command compared; farther out no
            // rounding comes near an edge. The two commands decide every edge alike.
            if self.field == "temperature_c"
                || outside_humid_air_model_range(station_temperature_c + KELVIN_OFFSET)
            {
                // Named where it came from, as every other blamed reading is. Humid air above
                // water's critical point, and dry air too hot to have a density, are outside
                // the range too.
                let range = format!(
                    "outside {} to {}, where the humid-air formulas hold",
                    spelling
                        .temperature_unit
                        .text(HUMID_AIR_MODEL_MIN_K - KELVIN_OFFSET),
                    spelling
                        .temperature_unit
                        .text(HUMID_AIR_MODEL_MAX_K - KELVIN_OFFSET)
                );
                let blame = match spelling.temperature_origin {
                    StationTemperatureOrigin::Reading => format!(
                        "{} = {} is {range}: check the temperature and its unit",
                        spelling.temperature.name, spelling.temperature_text
                    ),
                    StationTemperatureOrigin::DensityAltitude => format!(
                        "{} gives a station temperature of {}, {range}: check the density \
                         altitude's unit",
                        spelling.temperature.name, spelling.temperature_text
                    ),
                };
                return (
                    spelling.temperature.path.to_string(),
                    format!("{air}; {blame}"),
                );
            }
            if let Some(altitude_m) = pressure_altitude_outside_troposphere_m(station_pressure_hpa)
            {
                let troposphere = format!(
                    "a pressure altitude of {}, outside the troposphere ({} to {})",
                    altitude(altitude_m),
                    altitude(LOWEST_PRESSURE_ALTITUDE_M),
                    altitude(TROPOSPHERE_TOP_M)
                );
                // A QNH is quoted as it was sent, and said to be reduced, never as if the station
                // pressure reduced from it had been sent.
                let reduced = |unit: &str| {
                    format!(
                        "{air}; {}, and reduced to the station altitude of {} it is a station \
                         pressure of {}, {troposphere}: check the {unit}'s unit",
                        spelling.qnh_named(),
                        altitude(station_altitude_m),
                        spelling.pressure_text
                    )
                };
                return match spelling.pressure_origin {
                    StationPressureOrigin::Reading if spelling.qnh_text.is_some() => {
                        (spelling.pressure.path.to_string(), reduced("pressure"))
                    }
                    StationPressureOrigin::Reading => (
                        spelling.pressure.path.to_string(),
                        format!(
                            "{air}; {} = {} is {troposphere}: check the pressure's unit",
                            spelling.pressure.name, spelling.pressure_text
                        ),
                    ),
                    StationPressureOrigin::Standard => (
                        spelling.altitude.path.to_string(),
                        format!(
                            "{air}; no {} was given, and the standard pressure at the station \
                             altitude of {} is {troposphere}: check the altitude's unit",
                            spelling.pressure.name,
                            altitude(station_altitude_m)
                        ),
                    ),
                    StationPressureOrigin::Qnh => {
                        (spelling.altitude.path.to_string(), reduced("altitude"))
                    }
                    StationPressureOrigin::DensityAltitude => (
                        spelling.pressure.path.to_string(),
                        format!(
                            "{air}; {} gives a station pressure of {}, {troposphere}: check the \
                             density altitude's unit",
                            spelling.pressure.name, spelling.pressure_text
                        ),
                    ),
                };
            }
            return (spelling.humidity.path.to_string(), air);
        }
        // A QNH whose reduction to the station altitude leaves no station pressure (the
        // altimeter-setting relation has none that high) is quoted as it was sent, never as the
        // NaN it reduced to: the altitude's fault when the QNH is itself a plausible sea-level
        // pressure, as on the SI wire, and the pressure's when it is not.
        if self.field == "pressure_hpa"
            && matches!(
                self.reason,
                AtmosphereErrorReason::NotFinite | AtmosphereErrorReason::NonPositivePressure
            )
            && (spelling.pressure_origin == StationPressureOrigin::Qnh
                || spelling.qnh_text.is_some())
        {
            let (path, unit) = if spelling.pressure_origin == StationPressureOrigin::Qnh {
                (spelling.altitude.path, "altitude")
            } else {
                (spelling.pressure.path, "pressure")
            };
            return (
                path.to_string(),
                format!(
                    "{}, and reduced to the station altitude of {} it leaves no station \
                     pressure: the altimeter-setting relation has none that high (check the \
                     {unit}'s unit)",
                    spelling.qnh_named(),
                    altitude(station_altitude_m)
                ),
            );
        }
        // Absolute zero in the surface's own unit, as its reading is.
        let explanation = match self.reason {
            AtmosphereErrorReason::AtOrBelowAbsoluteZero => format!(
                "temperature must be above absolute zero ({})",
                spelling.temperature_unit.absolute_zero_text()
            ),
            _ => explanation,
        };
        let (field, value) = match &*self.field {
            // A temperature or a pressure a density altitude gave is named as that density
            // altitude's, never as if it had been sent as the reading.
            "temperature_c"
                if spelling.temperature_origin == StationTemperatureOrigin::DensityAltitude =>
            {
                return (
                    spelling.temperature.path.to_string(),
                    format!(
                        "{} gives a station temperature of {}: {explanation}",
                        spelling.temperature.name, spelling.temperature_text
                    ),
                );
            }
            "pressure_hpa"
                if spelling.pressure_origin == StationPressureOrigin::DensityAltitude =>
            {
                return (
                    spelling.pressure.path.to_string(),
                    format!(
                        "{} gives a station pressure of {}: {explanation}",
                        spelling.pressure.name, spelling.pressure_text
                    ),
                );
            }
            "temperature_c" => (spelling.temperature, spelling.temperature_text.clone()),
            "pressure_hpa" => (spelling.pressure, spelling.pressure_text.clone()),
            // An altitude is refused only when it is not finite, which needs no unit.
            "altitude_m" => (spelling.altitude, echo_number(self.value)),
            // A density altitude flies as the station's altitude, and a surface that flies one
            // names the altitude by the density altitude's field, in the surface's unit.
            "density_altitude_m" => (
                spelling.altitude,
                spelling.altitude_unit.reading(self.value),
            ),
            _ => (spelling.humidity, echo_number(self.value)),
        };
        (
            field.path.to_string(),
            format!("{} = {value}: {explanation}", field.name),
        )
    }
}

/// The air at the shooter: station altitude, temperature, pressure and relative humidity, with
/// the density and speed of sound they give.
///
/// Every field is private and there is no `Default`, so a station cannot be built without its
/// humidity, and its density and sound speed cannot disagree about that humidity. Build one with
/// [`Self::new`]. [`Self::with_density_ratio`] exists only for legacy 4-tuple callers that hold
/// a density ratio of their own.
///
/// ```
/// use ballistics_engine::{RelativeHumidity, StationAir};
///
/// let station = StationAir::new(0.0, 15.0, 1013.25, RelativeHumidity::DEFAULT).unwrap();
/// assert!(station.density_kg_m3() < 1.225); // moist air is lighter than dry
/// assert!(station.speed_of_sound_mps() > 340.29); // and carries sound faster
///
/// // Air that cannot exist is refused: saturated air at 100 C needs more vapour pressure than
/// // the 1013.25 hPa the air has.
/// let saturated = RelativeHumidity::try_percent(100.0).unwrap();
/// assert!(StationAir::new(0.0, 100.0, 1013.25, saturated).is_err());
/// ```
#[derive(Clone, Copy, PartialEq)]
pub struct StationAir {
    altitude_m: f64,
    temperature_c: f64,
    pressure_hpa: f64,
    humidity: RelativeHumidity,
    density_ratio: f64,
    density_kg_m3: f64,
    speed_of_sound_mps: f64,
    /// The station's water-vapour mole fraction, which [`air_at`] holds at every height:
    /// [`governing_vapor_mole_fraction`] at the fields above, computed once here rather than at
    /// every step of every flight. A cache of the other fields, not state of
    /// its own, so `Debug` leaves it out.
    vapor_mole_fraction: f64,
}

// The derive's output before the vapour mole fraction was held, field for field: it is a cache.
impl fmt::Debug for StationAir {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StationAir")
            .field("altitude_m", &self.altitude_m)
            .field("temperature_c", &self.temperature_c)
            .field("pressure_hpa", &self.pressure_hpa)
            .field("humidity", &self.humidity)
            .field("density_ratio", &self.density_ratio)
            .field("density_kg_m3", &self.density_kg_m3)
            .field("speed_of_sound_mps", &self.speed_of_sound_mps)
            .finish()
    }
}

impl StationAir {
    /// The station air at `altitude_m` (geometric, above mean sea level), `temperature_c`,
    /// absolute station pressure `pressure_hpa` and `humidity`.
    ///
    /// The density and sound speed are [`calculate_atmosphere`]'s at exactly these inputs, so a
    /// station built here matches every solver that resolves its air through that function, to
    /// the bit. The density ratio is `density / 1.225`.
    ///
    /// # Errors
    ///
    /// - `altitude_m`, `temperature_c` or `pressure_hpa` not finite:
    ///   [`AtmosphereErrorReason::NotFinite`].
    /// - `temperature_c <= -273.15`: [`AtmosphereErrorReason::AtOrBelowAbsoluteZero`].
    /// - `pressure_hpa <= 0`: [`AtmosphereErrorReason::NonPositivePressure`].
    /// - Impossible air, refused by exactly the `atmosphere.density_altitude` service's test
    ///   (an uncapped water-vapour mole fraction that is NaN or at least 1):
    ///   [`AtmosphereErrorReason::ImpossibleAir`], on `humidity_percent`, or on
    ///   `temperature_c` for humid air above water's critical point (647.096 K), and for dry air
    ///   there too hot for the CIPM-2007 density to stay positive (about 90,000 K at
    ///   1013.25 hPa); or on `pressure_hpa` for a pressure so far beyond any air's (above about
    ///   4e156 Pa) that the density is not finite and positive.
    ///
    /// Those are the only temperatures refused ([`check_station_temperature_c`] is the rule on
    /// its own): outside 173.15-373.15 K (-100 °C to 100 °C) the humidity terms are extrapolated,
    /// never refused. Below 173.15 K the saturation vapour pressure and the CIPM compressibility
    /// are evaluated at 173.15 K (they clamp their temperature there), and above 373.15 K they
    /// are carried past the range they are fitted to. Dry air holds no vapour at any
    /// temperature, so at 0 % neither term is reached. A station whose lapse takes the air to
    /// absolute zero aloft is accepted here and refused by the flight that reaches that height
    /// ([`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]).
    pub fn new(
        altitude_m: f64,
        temperature_c: f64,
        pressure_hpa: f64,
        humidity: RelativeHumidity,
    ) -> Result<Self, AtmosphereError> {
        check_station_state(altitude_m, temperature_c, pressure_hpa)?;
        refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
        Ok(Self::from_calculate_atmosphere(
            altitude_m,
            temperature_c,
            pressure_hpa,
            humidity,
        ))
    }

    /// A station that keeps a caller-held `density_ratio` (density / 1.225 kg/m³) verbatim.
    ///
    /// For legacy `(altitude, temperature, pressure, ratio)` 4-tuples only, through
    /// [`KernelAtmosphere::from_legacy_params`]: the caller asserts that the ratio was built at
    /// this humidity. Everywhere else use [`Self::new`], which cannot pair a density with the
    /// wrong humidity. The sound speed is the station's own at `humidity`, as in `new`.
    ///
    /// # Errors
    ///
    /// Those of [`Self::new`], plus a `density_ratio` that is not finite or not in `(0, 2)`.
    pub fn with_density_ratio(
        altitude_m: f64,
        temperature_c: f64,
        pressure_hpa: f64,
        density_ratio: f64,
        humidity: RelativeHumidity,
    ) -> Result<Self, AtmosphereError> {
        const FIELD: &str = "density_ratio";
        check_station_state(altitude_m, temperature_c, pressure_hpa)?;
        if !density_ratio.is_finite() {
            return Err(AtmosphereError::new(
                FIELD,
                density_ratio,
                AtmosphereErrorReason::NotFinite,
            ));
        }
        if !(density_ratio > 0.0 && density_ratio < MAX_STATION_DENSITY_RATIO) {
            return Err(AtmosphereError::new(
                FIELD,
                density_ratio,
                AtmosphereErrorReason::DensityRatioOutOfRange,
            ));
        }
        refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
        Ok(Self {
            altitude_m,
            temperature_c,
            pressure_hpa,
            humidity,
            density_ratio,
            density_kg_m3: density_ratio * 1.225,
            // calculate_atmosphere's own sound speed: its K and Pa conversions, then the moist
            // formula.
            speed_of_sound_mps: moist_speed_of_sound(
                temperature_c + 273.15,
                pressure_hpa * 100.0,
                humidity.percent(),
            ),
            vapor_mole_fraction: governing_vapor_mole_fraction(
                temperature_c,
                pressure_hpa,
                humidity.percent(),
            ),
        })
    }

    fn from_calculate_atmosphere(
        altitude_m: f64,
        temperature_c: f64,
        pressure_hpa: f64,
        humidity: RelativeHumidity,
    ) -> Self {
        let (density_kg_m3, speed_of_sound_mps) = calculate_atmosphere(
            altitude_m,
            Some(temperature_c),
            Some(pressure_hpa),
            humidity.percent(),
        );
        Self {
            altitude_m,
            temperature_c,
            pressure_hpa,
            humidity,
            density_ratio: density_kg_m3 / 1.225,
            density_kg_m3,
            speed_of_sound_mps,
            vapor_mole_fraction: governing_vapor_mole_fraction(
                temperature_c,
                pressure_hpa,
                humidity.percent(),
            ),
        }
    }

    /// The station as the governing air of a point no downrange zone covers.
    #[inline(always)]
    fn governing_air(&self) -> GoverningAir {
        GoverningAir {
            temperature_c: self.temperature_c,
            pressure_hpa: self.pressure_hpa,
            density_ratio: self.density_ratio,
            vapor_mole_fraction: self.vapor_mole_fraction,
            #[cfg(test)]
            humidity_percent: self.humidity.percent(),
        }
    }

    /// Station geometric altitude above mean sea level, m. The altitude lapse starts here.
    pub fn altitude_m(&self) -> f64 {
        self.altitude_m
    }

    /// Station temperature, °C.
    pub fn temperature_c(&self) -> f64 {
        self.temperature_c
    }

    /// Absolute station pressure, hPa.
    pub fn pressure_hpa(&self) -> f64 {
        self.pressure_hpa
    }

    /// Station relative humidity.
    pub fn humidity(&self) -> RelativeHumidity {
        self.humidity
    }

    /// Station density over 1.225 kg/m³.
    pub fn density_ratio(&self) -> f64 {
        self.density_ratio
    }

    /// Station air density, kg/m³ (CIPM-2007, humid).
    pub fn density_kg_m3(&self) -> f64 {
        self.density_kg_m3
    }

    /// Station speed of sound, m/s (moist air). The reference for station Mach.
    pub fn speed_of_sound_mps(&self) -> f64 {
        self.speed_of_sound_mps
    }
}

/// The one rule a station temperature, °C, is held to on its own, on every surface: finite and
/// above absolute zero (-273.15 °C). Nothing narrower: outside 173.15-373.15 K (-100 °C to
/// 100 °C) the humidity terms are extrapolated, never refused. [`StationAir::new`] applies it,
/// and then the impossible-air rule, which is the only other reason a temperature is refused (in
/// flight too: [`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]). A surface that checks a
/// reading as it is typed (a CLI flag, converted to °C) applies this same function, so a reading
/// is accepted or refused alike everywhere.
///
/// ```
/// use ballistics_engine::atmosphere::check_station_temperature_c;
///
/// assert!(check_station_temperature_c(250.0).is_ok()); // extrapolated, not refused
/// assert!(check_station_temperature_c(-150.0).is_ok());
/// assert!(check_station_temperature_c(-273.15).is_err()); // absolute zero
/// assert!(check_station_temperature_c(f64::NAN).is_err());
/// ```
///
/// # Errors
///
/// [`AtmosphereErrorReason::NotFinite`] or [`AtmosphereErrorReason::AtOrBelowAbsoluteZero`],
/// on `temperature_c`.
pub fn check_station_temperature_c(temperature_c: f64) -> Result<(), AtmosphereError> {
    if !temperature_c.is_finite() {
        return Err(AtmosphereError::new(
            "temperature_c",
            temperature_c,
            AtmosphereErrorReason::NotFinite,
        ));
    }
    if temperature_c <= ABSOLUTE_ZERO_C {
        return Err(AtmosphereError::new(
            "temperature_c",
            temperature_c,
            AtmosphereErrorReason::AtOrBelowAbsoluteZero,
        ));
    }
    Ok(())
}

/// [`check_station_temperature_c`] for a temperature typed into a flag (`flag`, such as
/// `--temperature`) in °F (`fahrenheit`) or °C, refused in the flag's own words and unit:
/// `"--temperature -500 F is at or below absolute zero (-459.67 F)"`, `"--temperature NaN C is
/// not a finite number"`. The reading is converted to °C exactly as the CLI and the browser
/// terminal fly it, `(F - 32) · 5 / 9`, so the flag refuses precisely the readings the solve
/// would.
///
/// ```
/// use ballistics_engine::atmosphere::check_temperature_flag;
///
/// assert!(check_temperature_flag("--temperature", 482.0, true).is_ok()); // 250 °C
/// assert_eq!(
///     check_temperature_flag("--temperature", -500.0, true).unwrap_err(),
///     "--temperature -500 F is at or below absolute zero (-459.67 F)"
/// );
/// ```
///
/// # Errors
///
/// The refusal, in the flag's words, of a reading [`check_station_temperature_c`] refuses.
pub fn check_temperature_flag(flag: &str, value: f64, fahrenheit: bool) -> Result<(), String> {
    let (celsius, unit, absolute_zero) = if fahrenheit {
        ((value - 32.0) * 5.0 / 9.0, "F", "-459.67 F")
    } else {
        (value, "C", "-273.15 C")
    };
    check_station_temperature_c(celsius).map_err(|error| match error.reason() {
        AtmosphereErrorReason::NotFinite => {
            format!(
                "{flag} {} {unit} is not a finite number",
                echo_number(value)
            )
        }
        _ => format!(
            "{flag} {} {unit} is at or below absolute zero ({absolute_zero})",
            echo_number(value)
        ),
    })
}

/// The one rule a station pressure, hPa, is held to on its own, on every surface: finite and
/// above 0. Nothing narrower: a near vacuum and twice sea level fly. [`StationAir::new`] applies
/// it, and then the impossible-air rule, which is the only other reason a pressure is refused. A
/// surface that checks a reading as it is typed applies this same function
/// ([`check_pressure_flag`]), so a reading is accepted or refused alike everywhere.
///
/// ```
/// use ballistics_engine::atmosphere::check_station_pressure_hpa;
///
/// assert!(check_station_pressure_hpa(0.01).is_ok()); // 1 Pa
/// assert!(check_station_pressure_hpa(2000.0).is_ok());
/// assert!(check_station_pressure_hpa(0.0).is_err());
/// assert!(check_station_pressure_hpa(f64::NAN).is_err());
/// ```
///
/// # Errors
///
/// [`AtmosphereErrorReason::NotFinite`] or [`AtmosphereErrorReason::NonPositivePressure`], on
/// `pressure_hpa`.
pub fn check_station_pressure_hpa(pressure_hpa: f64) -> Result<(), AtmosphereError> {
    if !pressure_hpa.is_finite() {
        return Err(AtmosphereError::new(
            "pressure_hpa",
            pressure_hpa,
            AtmosphereErrorReason::NotFinite,
        ));
    }
    if pressure_hpa <= 0.0 {
        return Err(AtmosphereError::new(
            "pressure_hpa",
            pressure_hpa,
            AtmosphereErrorReason::NonPositivePressure,
        ));
    }
    Ok(())
}

/// [`check_station_pressure_hpa`] for a pressure typed into a flag (`flag`, such as
/// `--pressure`) in inHg (`inhg`) or hPa, refused in the flag's own words and unit:
/// `"--pressure -1 inHg is at or below zero"`, `"--pressure NaN hPa is not a finite number"`.
/// The reading is converted to hPa exactly as the CLI and the browser terminal fly it
/// (`inHg × 33.8639`), so the flag refuses precisely the readings the solve would.
///
/// ```
/// use ballistics_engine::atmosphere::check_pressure_flag;
///
/// assert!(check_pressure_flag("--pressure", 5.0, true).is_ok()); // the stratosphere
/// assert_eq!(
///     check_pressure_flag("--pressure", -1.0, true).unwrap_err(),
///     "--pressure -1 inHg is at or below zero"
/// );
/// ```
///
/// # Errors
///
/// The refusal, in the flag's words, of a reading [`check_station_pressure_hpa`] refuses.
pub fn check_pressure_flag(flag: &str, value: f64, inhg: bool) -> Result<(), String> {
    let (hpa, unit) = if inhg {
        (value * 33.8639, "inHg")
    } else {
        (value, "hPa")
    };
    check_station_pressure_hpa(hpa).map_err(|error| match error.reason() {
        AtmosphereErrorReason::NotFinite => {
            format!(
                "{flag} {} {unit} is not a finite number",
                echo_number(value)
            )
        }
        _ => format!("{flag} {} {unit} is at or below zero", echo_number(value)),
    })
}

/// The one rule a station altitude or a density altitude typed into a flag (`flag`, such as
/// `--altitude`) is held to on its own, in feet (`feet`) or metres: a finite number, refused in
/// the flag's own words and unit otherwise (`"--altitude NaN ft is not a finite number"`). A
/// density altitude is held to the rest of its rule where its station is resolved
/// ([`station_for_density_altitude`]), since that depends on the temperature.
///
/// ```
/// use ballistics_engine::atmosphere::check_altitude_flag;
///
/// assert!(check_altitude_flag("--altitude", 300_000.0, true).is_ok());
/// assert_eq!(
///     check_altitude_flag("--altitude", f64::NAN, true).unwrap_err(),
///     "--altitude NaN ft is not a finite number"
/// );
/// ```
///
/// # Errors
///
/// The refusal of a value that is not a finite number once converted to metres.
pub fn check_altitude_flag(flag: &str, value: f64, feet: bool) -> Result<(), String> {
    let (metres, unit) = if feet {
        (value * DA_FT_TO_M, "ft")
    } else {
        (value, "m")
    };
    if metres.is_finite() {
        Ok(())
    } else {
        Err(format!(
            "{flag} {} {unit} is not a finite number",
            echo_number(value)
        ))
    }
}

fn check_station_state(
    altitude_m: f64,
    temperature_c: f64,
    pressure_hpa: f64,
) -> Result<(), AtmosphereError> {
    if !altitude_m.is_finite() {
        return Err(AtmosphereError::new(
            "altitude_m",
            altitude_m,
            AtmosphereErrorReason::NotFinite,
        ));
    }
    check_station_temperature_c(temperature_c)?;
    check_station_pressure_hpa(pressure_hpa)
}

/// The impossible-air rule every station and zone is held to (and the `atmosphere.density_altitude`
/// service through it): an uncapped vapour mole fraction that is NaN (humid air above water's
/// critical point) or at least 1; and, above that point, where only dry air gets this far, a
/// CIPM-2007 density that is not finite and positive.
fn refuse_impossible_air(
    temperature_c: f64,
    pressure_hpa: f64,
    humidity: RelativeHumidity,
) -> Result<(), AtmosphereError> {
    let x_v = water_vapor_mole_fraction_uncapped(temperature_c, pressure_hpa, humidity.percent());
    if x_v.is_nan() {
        return Err(AtmosphereError::new(
            "temperature_c",
            temperature_c,
            AtmosphereErrorReason::ImpossibleAir,
        ));
    }
    if x_v >= 1.0 {
        return Err(AtmosphereError::new(
            "humidity_percent",
            humidity.percent(),
            AtmosphereErrorReason::ImpossibleAir,
        ));
    }
    // Air the CIPM-2007 density cannot describe is refused. Dry air above water's critical point
    // holds no vapour (its mole fraction is exactly 0) and flies, but its compressibility is a
    // virial fit carried far past its range there, and far enough above it (about 90,000 K at
    // 1013.25 hPa) it gives no positive density at all: refused at its temperature. At any lower
    // temperature only a pressure far beyond any air's (above about 4e156 Pa, where the fit's
    // squared pressure term overflows and the density comes out 0, which a flight would take for
    // a vacuum) does that: refused at its pressure. For every other station the density is
    // finite and positive, and the rule is the two tests above.
    let density = calculate_air_density_cimp(temperature_c, pressure_hpa, humidity.percent());
    if !(density.is_finite() && density > 0.0) {
        let hot = temperature_c + KELVIN_OFFSET > WATER_CRITICAL_TEMPERATURE_K;
        return Err(if hot {
            AtmosphereError::new(
                "temperature_c",
                temperature_c,
                AtmosphereErrorReason::ImpossibleAir,
            )
        } else {
            AtmosphereError::new(
                "pressure_hpa",
                pressure_hpa,
                AtmosphereErrorReason::ImpossibleAir,
            )
        });
    }
    Ok(())
}

/// The air at one point of a flight, from [`air_at`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LocalAir {
    /// Local air density, kg/m³.
    pub density_kg_m3: f64,
    /// Local speed of sound, m/s.
    pub speed_of_sound_mps: f64,
    /// Local temperature, K. For [`KernelAtmosphere::Uniform`] it is the dry-air temperature
    /// that gives the caller's sound speed, `c² / (1.4 · 287.0531)`.
    pub temperature_k: f64,
    /// Local pressure, Pa. `0.0` for [`KernelAtmosphere::Uniform`], which does not model it.
    pub pressure_pa: f64,
}

/// The atmosphere a trajectory kernel flies.
///
/// [`Self::Station`] carries station air, humidity included, and the air varies with altitude
/// and downrange zones through [`air_at`]. [`Self::Uniform`] is direct mode: one density and
/// sound speed at every point.
///
/// Neither variant can hold unvalidated air. [`StationAir`] has private fields, and `Uniform`
/// can only be built by [`Self::uniform`] or [`Self::from_legacy_params`] outside this crate.
/// Match it with `..`:
///
/// ```
/// use ballistics_engine::KernelAtmosphere;
///
/// let atmosphere = KernelAtmosphere::uniform(1.1, 330.0).unwrap();
/// match atmosphere {
///     KernelAtmosphere::Uniform { density_kg_m3, speed_of_sound_mps, .. } => {
///         assert_eq!((density_kg_m3, speed_of_sound_mps), (1.1, 330.0));
///     }
///     KernelAtmosphere::Station(_) => unreachable!(),
/// }
/// ```
///
/// ```compile_fail,E0639
/// use ballistics_engine::KernelAtmosphere;
///
/// // Bypassing `uniform`'s validation does not compile (E0639: the variant is
/// // `#[non_exhaustive]`).
/// let atmosphere = KernelAtmosphere::Uniform { density_kg_m3: -1.0, speed_of_sound_mps: 0.0 };
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KernelAtmosphere {
    /// Station-referenced air, humidity included.
    Station(StationAir),
    /// Direct mode: the caller's density and speed of sound, unchanged at every point.
    #[non_exhaustive]
    Uniform {
        /// Air density, kg/m³, in `[0, 2)`; exactly 0 is a vacuum, with no drag at all.
        density_kg_m3: f64,
        /// Speed of sound, m/s, above 200.
        speed_of_sound_mps: f64,
    },
}

impl KernelAtmosphere {
    /// Direct-mode air: one density and speed of sound at every point.
    ///
    /// A density of exactly 0 is a vacuum: the flight feels gravity and nothing else, exactly as
    /// 0.49.0's `compute_derivatives` flew the `(0, c, 0, 0)` tuple. `-0.0`
    /// is the same vacuum and is stored as `0.0`.
    ///
    /// ```
    /// use ballistics_engine::KernelAtmosphere;
    ///
    /// assert!(KernelAtmosphere::uniform(0.0, 340.29).is_ok()); // a vacuum
    /// assert!(KernelAtmosphere::uniform(-1.0, 340.29).is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// A `density_kg_m3` that is not finite or not in `[0, 2)`, or a `speed_of_sound_mps` that
    /// is not finite or not above 200. The upper density and lower sound-speed bounds are the
    /// ones 0.49.0's `compute_derivatives` used to recognise direct mode; its other kernels
    /// differed (`fast_integrate` required a density above 0).
    pub fn uniform(density_kg_m3: f64, speed_of_sound_mps: f64) -> Result<Self, AtmosphereError> {
        if !density_kg_m3.is_finite() {
            return Err(AtmosphereError::new(
                "density_kg_m3",
                density_kg_m3,
                AtmosphereErrorReason::NotFinite,
            ));
        }
        if !(0.0..MAX_UNIFORM_DENSITY_KG_M3).contains(&density_kg_m3) {
            return Err(AtmosphereError::new(
                "density_kg_m3",
                density_kg_m3,
                AtmosphereErrorReason::UniformDensityOutOfRange,
            ));
        }
        // -0.0 is the same vacuum as 0.0; adding 0.0 stores it as +0.0 and moves no other value.
        let density_kg_m3 = density_kg_m3 + 0.0;
        if !speed_of_sound_mps.is_finite() {
            return Err(AtmosphereError::new(
                "speed_of_sound_mps",
                speed_of_sound_mps,
                AtmosphereErrorReason::NotFinite,
            ));
        }
        if speed_of_sound_mps <= MIN_UNIFORM_SPEED_OF_SOUND_MPS {
            return Err(AtmosphereError::new(
                "speed_of_sound_mps",
                speed_of_sound_mps,
                AtmosphereErrorReason::UniformSpeedOfSoundOutOfRange,
            ));
        }
        Ok(Self::Uniform {
            density_kg_m3,
            speed_of_sound_mps,
        })
    }

    /// The one-line migration from the legacy kernel 4-tuple, at the humidity the caller states.
    ///
    /// - `(density, speed_of_sound, 0.0, 0.0)`, the direct-mode sentinel, becomes
    ///   [`Self::uniform`] (which validates it; `humidity` is unused, the caller's sound speed
    ///   already being given).
    /// - `(altitude_m, temperature_c, pressure_hpa, density_ratio)`, standard mode, becomes a
    ///   [`StationAir::with_density_ratio`] at `humidity`. A finite ratio `<= 0` means "not
    ///   supplied" and becomes `1.0` (MBA-1157); a ratio at or above 2 is refused.
    ///
    /// # Errors
    ///
    /// Those of [`Self::uniform`] or [`StationAir::with_density_ratio`].
    pub fn from_legacy_params(
        params: (f64, f64, f64, f64),
        humidity: RelativeHumidity,
    ) -> Result<Self, AtmosphereError> {
        let (first, second, third, fourth) = params;
        if third == 0.0 && fourth == 0.0 {
            return Self::uniform(first, second);
        }
        let density_ratio = if fourth.is_finite() && fourth <= 0.0 {
            1.0
        } else {
            fourth
        };
        StationAir::with_density_ratio(first, second, third, density_ratio, humidity)
            .map(Self::Station)
    }

    /// The altitude a kernel measures a point's height from: the station's own altitude, as
    /// `TrajectorySolver` does, so a caller's inputs cannot fly a different station; or
    /// `uniform_fallback` for uniform air, which does not vary with altitude.
    pub(crate) fn reference_altitude_m(&self, uniform_fallback: f64) -> f64 {
        match self {
            Self::Station(station) => station.altitude_m,
            Self::Uniform { .. } => uniform_fallback,
        }
    }
}

/// The governing (base) air a point of a flight lapses from: the station's, or the active
/// downrange [`AtmoSock`] zone's. Everything in it is fixed for the whole flight, its
/// water-vapour mole fraction and density ratio included, so it is computed once, when the
/// station ([`StationAir`]) or the zones ([`AtmoSock::new`]) are built, and the per-step lookup
/// only reads it (recomputing the vapour mole fraction, and a zone's CIPM density, at every
/// step made `fast_integrate`, the lean Monte Carlo and `TrajectorySolver`'s RK4 and RK45
/// 4-10 % slower than 0.49.0, for no change in any bit).
#[derive(Debug, Clone, Copy)]
struct GoverningAir {
    /// Base temperature, °C.
    temperature_c: f64,
    /// Base absolute pressure, hPa.
    pressure_hpa: f64,
    /// Base density over 1.225 kg/m³.
    density_ratio: f64,
    /// [`governing_vapor_mole_fraction`] at the base temperature, pressure and humidity: the
    /// `x_v` held at every height.
    vapor_mole_fraction: f64,
    /// The relative humidity, percent, that `vapor_mole_fraction` came from, for the test-only
    /// [`air_trace`]; the composition itself reads only the mole fraction.
    #[cfg(test)]
    humidity_percent: f64,
}

impl GoverningAir {
    /// Base air at `temperature_c`, `pressure_hpa` and `humidity_percent` (raw: clamped into
    /// 0-100 by the one vapour formula, a NaN kept), with the caller's `density_ratio`. Its
    /// vapour mole fraction goes through [`governing_vapor_mole_fraction`], the one place that
    /// formula lives.
    #[inline]
    fn new(
        temperature_c: f64,
        pressure_hpa: f64,
        density_ratio: f64,
        humidity_percent: f64,
    ) -> Self {
        Self {
            temperature_c,
            pressure_hpa,
            density_ratio,
            vapor_mole_fraction: governing_vapor_mole_fraction(
                temperature_c,
                pressure_hpa,
                humidity_percent,
            ),
            #[cfg(test)]
            humidity_percent,
        }
    }

    /// A downrange zone's air: its own temperature, pressure and humidity, with the CIPM-2007
    /// density ratio at that humidity. Unvalidated, like the zone (see [`AtmoSock::validate`]).
    fn zone(&(temperature_c, pressure_hpa, humidity_percent, _): &AtmoSegment) -> Self {
        Self::new(
            temperature_c,
            pressure_hpa,
            calculate_air_density_cimp(temperature_c, pressure_hpa, humidity_percent) / 1.225,
            humidity_percent,
        )
    }
}

/// The air at one point of a flight: the ONE per-step air computation.
///
/// `downrange_m` selects a zone of `zones`; `altitude_m` is the point's geometric altitude above
/// mean sea level (the world-vertical altitude, not the shot-frame y).
///
/// - [`KernelAtmosphere::Uniform`] returns the caller's density and sound speed unchanged at
///   every point, and ignores `zones`.
/// - [`KernelAtmosphere::Station`] picks a base: the zone that covers `downrange_m` when
///   `zones` holds any (its temperature, pressure and humidity, with a CIPM density ratio at
///   that humidity), otherwise the station itself. An empty zone set means the station. The
///   lapse always starts at the station altitude. The base air is well mixed: its water-vapour
///   mole fraction `x_v` (from its own temperature, pressure and humidity) is held at every
///   height, for all three steps:
///   1. temperature and pressure follow the ICAO layers in geopotential height, with the
///      virtual-temperature hydrostatic exponent: the dry one times the moist-air molar-mass
///      ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`;
///   2. density is the base ratio scaled by `(T_base · P) / (P_base · T)`, the base
///      composition;
///   3. the speed of sound is [`moist_speed_of_sound`]'s formula at the local temperature and
///      the base `x_v`.
///
///   The temperature and pressure of steps 1 and 2 are returned too. At the base air's own
///   height this is that air exactly (the sound speed is [`StationAir::speed_of_sound_mps`] to
///   the bit); at 0 % every step is the dry one, `sqrt(1.4 · 287.0531 · T)` for the sound
///   speed.
///
///   Held aloft, `x_v` exceeds saturation in the colder air: at every height above a saturated
///   station, and from about 2.2 km above a 15 °C / 50 % station and 0.4 km above a 35 °C / 90 %
///   one. At +3 km it is 1.35 times saturation over the first and 2.06 times over the second, and
///   at +10 km 34 and 29 times. Condensation is not modelled.
///
///   The base `x_v`, and a zone's density ratio, are fixed for the flight, so they are computed
///   once, when the station ([`StationAir::new`]) or the zones ([`AtmoSock::new`]) are built.
///   This lookup evaluates no saturation pressure; build the station and the zones once per
///   flight, not per step.
///
/// `zones` must already have passed [`AtmoSock::validate`], as every validated kernel entry
/// checks them once ([`crate::trajectory_integration::try_integrate_trajectory`],
/// `TrajectorySolver`, `fast_integrate*`). This per-step lookup does not: an unvalidated zone
/// humidity outside 0-100 is clamped into it, and a NaN one gives NaN air, never steam.
///
/// Where the lapse from the base temperature reaches absolute zero (183 km above 15 °C at sea
/// level, 1.54 km above a 10 K station) there is no air: from that height the result is not
/// finite. Every trajectory kernel refuses a flight that reaches it, at the step that gets
/// there, as [`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`] on the temperature.
pub fn air_at(
    atmosphere: &KernelAtmosphere,
    zones: Option<&AtmoSock>,
    downrange_m: f64,
    altitude_m: f64,
) -> LocalAir {
    air_at_with_gravity(atmosphere, zones, downrange_m, altitude_m, Gravity::EARTH)
}

/// [`air_at`] in a run's uniform gravity, which sets the hydrostatic lapse.
pub(crate) fn air_at_with_gravity(
    atmosphere: &KernelAtmosphere,
    zones: Option<&AtmoSock>,
    downrange_m: f64,
    altitude_m: f64,
    gravity: Gravity,
) -> LocalAir {
    match atmosphere {
        KernelAtmosphere::Uniform {
            density_kg_m3,
            speed_of_sound_mps,
        } => LocalAir {
            density_kg_m3: *density_kg_m3,
            speed_of_sound_mps: *speed_of_sound_mps,
            temperature_k: speed_of_sound_mps * speed_of_sound_mps / (GAMMA * R_AIR),
            pressure_pa: 0.0,
        },
        KernelAtmosphere::Station(station) => {
            #[cfg(test)]
            let saturation_pressures_before = air_trace::saturation_pressures();
            // The zone that covers this point, else the station: either way air computed when
            // it was built, so this step evaluates no vapour formula. An empty sock covers
            // nothing.
            let base = match zones.and_then(|sock| sock.governing_air_for_range(downrange_m)) {
                Some(zone) => *zone,
                None => station.governing_air(),
            };
            let air = compose_local_air(altitude_m, station.altitude_m, &base, gravity);
            #[cfg(test)]
            air_trace::attribute_lookup_saturation_pressures(saturation_pressures_before);
            air
        }
    }
}

/// The geometric altitudes above mean sea level, m, between which the lapse from `base_temp_k`
/// at `base_alt_m` keeps the air above absolute zero: `(floor, ceiling)`, with
/// `-inf` / `+inf` where it never gets there.
///
/// The temperature [`air_at`] flies is piecewise linear in geopotential height, the base
/// temperature carried through the ICAO lapse rates exactly as [`integrate_local_atmosphere_layers`]
/// walks them (the last layer's lapse continuing above 84.852 km, the troposphere's below 0 m),
/// so each edge is where one layer's line reaches 0 K. Every realistic station has a ceiling too:
/// 15 °C at sea level reaches 0 K about 183 km up.
fn absolute_zero_altitudes_m(base_temp_k: f64, base_alt_m: f64) -> (f64, f64) {
    let base = geometric_to_geopotential_height_m(base_alt_m);
    let to_geometric = |geopotential_m: f64| {
        if geopotential_m >= GEOPOTENTIAL_EARTH_RADIUS_M {
            f64::INFINITY
        } else {
            GEOPOTENTIAL_EARTH_RADIUS_M * geopotential_m
                / (GEOPOTENTIAL_EARTH_RADIUS_M - geopotential_m)
        }
    };

    // Up: at an exact boundary, ascent starts in the higher layer.
    let mut ceiling = f64::INFINITY;
    let (mut height, mut temperature) = (base, base_temp_k);
    let mut index = ICAO_LAYERS
        .iter()
        .rposition(|layer| height >= layer.base_altitude)
        .unwrap_or(0);
    loop {
        let lapse = ICAO_LAYERS[index].lapse_rate;
        let end = ICAO_LAYERS
            .get(index + 1)
            .map_or(f64::INFINITY, |next| next.base_altitude);
        if lapse < 0.0 {
            let zero = height + temperature / -lapse;
            if zero <= end {
                ceiling = to_geometric(zero);
                break;
            }
        }
        if end.is_infinite() {
            break;
        }
        temperature += lapse * (end - height);
        height = end;
        index += 1;
    }

    // Down: at an exact boundary, descent starts in the lower layer. The troposphere's lapse
    // warms the air below its base, so only a warming layer above it (the stratosphere's) can
    // take a cold enough base to 0 K on the way down.
    let mut floor = f64::NEG_INFINITY;
    let (mut height, mut temperature) = (base, base_temp_k);
    let mut index = ICAO_LAYERS
        .iter()
        .rposition(|layer| height > layer.base_altitude)
        .unwrap_or(0);
    loop {
        let lapse = ICAO_LAYERS[index].lapse_rate;
        let end = if index == 0 {
            f64::NEG_INFINITY
        } else {
            ICAO_LAYERS[index].base_altitude
        };
        if lapse > 0.0 {
            let zero = height - temperature / lapse;
            if zero >= end {
                floor = to_geometric(zero);
                break;
            }
        }
        if index == 0 {
            break;
        }
        temperature -= lapse * (height - end);
        height = end;
        index -= 1;
    }
    (floor, ceiling)
}

/// The refusal of a flight that went where its air cannot exist: the step that started at
/// `downrange_m` and `altitude_m` (the last state a kernel accepted, geometric altitude above
/// mean sea level) failed to a non-finite state, and the air within `reach_m` of where it started
/// (the farthest any stage of that step could lie from it) falls to absolute zero, where
/// [`air_at`] has no air at all.
///
/// The governing air is the zone that covers the step (at its start, or as far downrange as it
/// could reach) or the station. `None` when that air stays above 0 K within the step's reach,
/// so a step that failed for any other reason keeps its own error, and for uniform air, which
/// does not lapse. Kernels call this only once a step has failed, so a flight that stays below
/// the height its air reaches 0 K flies exactly as it did.
pub(crate) fn air_aloft_refusal(
    atmosphere: &KernelAtmosphere,
    zones: Option<&AtmoSock>,
    downrange_m: f64,
    altitude_m: f64,
    reach_m: f64,
) -> Option<AtmosphereError> {
    let KernelAtmosphere::Station(station) = atmosphere else {
        return None;
    };
    if !(downrange_m.is_finite() && altitude_m.is_finite() && reach_m.is_finite()) {
        return None;
    }
    let reach_m = reach_m.abs();
    [downrange_m, downrange_m + reach_m]
        .into_iter()
        .find_map(|downrange_m| {
            let temperature_c = zones
                .and_then(|sock| sock.governing_air_for_range(downrange_m))
                .map_or(station.temperature_c, |zone| zone.temperature_c);
            let (floor, ceiling) =
                absolute_zero_altitudes_m(temperature_c + KELVIN_OFFSET, station.altitude_m);
            if altitude_m + reach_m >= ceiling {
                Some(AtmosphereError::aloft(temperature_c, ceiling))
            } else if altitude_m - reach_m <= floor {
                Some(AtmosphereError::aloft(temperature_c, floor))
            } else {
                None
            }
        })
}

/// The composition behind [`air_at`] and the legacy `get_local_atmosphere*` wrappers,
/// unvalidated. The only place the aloft vapour model lives.
///
/// The governing (base) air is well mixed: its water-vapour mole fraction `x_v`, from its own
/// temperature, pressure and humidity, is held at every height, for all three of
/// - the lapse: the ICAO lapse rates with the virtual-temperature hydrostatic exponent, the dry
///   one scaled by the moist-air molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`;
/// - the density: the base ratio scaled by `(T_0 · P) / (P_0 · T)`, the base composition;
/// - the sound speed: [`moist_sound_speed_at_mole_fraction`] at the local temperature and that
///   same `x_v`.
///
/// `base` carries that `x_v`, computed once per base air (see [`GoverningAir`]), so the
/// composition evaluates no saturation pressure. At 0 % `x_v` is 0 and every term is the dry
/// one to the bit.
#[inline]
fn compose_local_air(
    altitude_m: f64,
    base_alt: f64,
    base: &GoverningAir,
    gravity: Gravity,
) -> LocalAir {
    let (temperature_k, pressure_pa, density_kg_m3) = local_temp_pressure_density_with_gravity(
        altitude_m,
        base_alt,
        base.temperature_c,
        base.pressure_hpa,
        base.density_ratio,
        base.vapor_mole_fraction,
        gravity,
    );
    let air = LocalAir {
        density_kg_m3,
        speed_of_sound_mps: moist_sound_speed_at_mole_fraction(
            temperature_k,
            base.vapor_mole_fraction,
        ),
        temperature_k,
        pressure_pa,
    };
    #[cfg(test)]
    air_trace::record(air_trace::AirTraceEntry {
        altitude_m,
        base_alt_m: base_alt,
        base_temp_c: base.temperature_c,
        base_press_hpa: base.pressure_hpa,
        base_ratio: base.density_ratio,
        humidity_percent: base.humidity_percent,
        gravity_mps2: gravity.magnitude(),
        air,
        lookup_saturation_pressures: None,
        consumed: None,
        consumptions: 0,
    });
    air
}

/// Test-only record of every per-step air composition, for the humidity class tests: which base
/// (station or zone) a path composed from, the base humidity whose water-vapour mole fraction it
/// held at every height for the lapse, the density and the sound speed, and the air it got.
/// Compiled out of every non-test build.
#[cfg(test)]
pub(crate) mod air_trace {
    use super::LocalAir;
    use std::cell::{Cell, RefCell};

    /// One call of the composition behind [`super::air_at`]: its inputs and its result.
    #[derive(Debug, Clone, Copy)]
    pub(crate) struct AirTraceEntry {
        /// The point's geometric altitude, m.
        pub altitude_m: f64,
        /// Where the lapse started, m.
        pub base_alt_m: f64,
        /// The base temperature, °C: the station's, or the active zone's.
        pub base_temp_c: f64,
        /// The base pressure, hPa.
        pub base_press_hpa: f64,
        /// The base density ratio (density / 1.225).
        pub base_ratio: f64,
        /// The base relative humidity, percent: the one whose vapour mole fraction the
        /// composition held aloft for the lapse, the density and the sound speed.
        pub humidity_percent: f64,
        /// The gravity the lapse used, m/s².
        pub gravity_mps2: f64,
        /// What the composition returned.
        pub air: LocalAir,
        /// How many Wagner-Pruss saturation pressures the per-step lookup ([`super::air_at`])
        /// evaluated for this point, from choosing its base to returning its air: every
        /// humid-air formula (a vapour mole fraction, a CIPM density) goes through one. `None`
        /// for a composition made outside that lookup (the legacy `get_local_atmosphere*`
        /// wrappers, which compose from a caller's raw base once per call).
        pub lookup_saturation_pressures: Option<u64>,
        /// What the drag computation that followed took from this air ([`record_consumed`]):
        /// the last one, if any did.
        pub consumed: Option<ConsumedAir>,
        /// How many drag computations took this air: 1 for every per-step lookup.
        pub consumptions: u32,
    }

    /// What a per-step drag computation (`TrajectorySolver::calculate_acceleration`,
    /// `compute_derivatives`, the `fast_integrate` substep) took from the air it had just
    /// composed: the density its drag force used, and the airspeed and Mach its drag
    /// coefficient was looked up at. The trace's composition records what `air_at` gave; this
    /// records what the kernel flew, so a kernel that calls `air_at` and then flies something
    /// else cannot pass the class tests.
    #[derive(Debug, Clone, Copy)]
    pub(crate) struct ConsumedAir {
        /// The air density in the drag force, kg/m³.
        pub density_kg_m3: f64,
        /// The airspeed the Mach divides, m/s.
        pub airspeed_mps: f64,
        /// The Mach the drag coefficient was looked up at.
        pub mach: f64,
    }

    thread_local! {
        static TRACE: RefCell<Option<Vec<AirTraceEntry>>> = const { RefCell::new(None) };
        static SATURATION_PRESSURES: Cell<u64> = const { Cell::new(0) };
    }

    /// Count one Wagner-Pruss saturation-pressure evaluation on this thread.
    #[inline(always)]
    pub(super) fn count_saturation_pressure() {
        SATURATION_PRESSURES.with(|count| count.set(count.get() + 1));
    }

    /// The Wagner-Pruss saturation pressures evaluated on this thread so far, traced or not.
    pub(crate) fn saturation_pressures() -> u64 {
        SATURATION_PRESSURES.with(Cell::get)
    }

    /// Credit the per-step lookup that started when the count stood at `before` with what it
    /// evaluated, on the composition it just recorded (the trace's last entry), if tracing.
    pub(super) fn attribute_lookup_saturation_pressures(before: u64) {
        let evaluated = saturation_pressures() - before;
        TRACE.with(|trace| {
            if let Some(last) = trace
                .borrow_mut()
                .as_mut()
                .and_then(|entries| entries.last_mut())
            {
                last.lookup_saturation_pressures = Some(evaluated);
            }
        });
    }

    /// Credit the composition this thread just recorded (the trace's last entry) with a drag
    /// computation that took `density_kg_m3` and looked its drag coefficient up at `mach` for
    /// `airspeed_mps`, if tracing. Called at each per-step drag site, from the values it flies.
    pub(crate) fn record_consumed(density_kg_m3: f64, airspeed_mps: f64, mach: f64) {
        TRACE.with(|trace| {
            if let Some(last) = trace
                .borrow_mut()
                .as_mut()
                .and_then(|entries| entries.last_mut())
            {
                last.consumed = Some(ConsumedAir {
                    density_kg_m3,
                    airspeed_mps,
                    mach,
                });
                last.consumptions += 1;
            }
        });
    }

    pub(super) fn record(entry: AirTraceEntry) {
        TRACE.with(|trace| {
            if let Some(entries) = trace.borrow_mut().as_mut() {
                entries.push(entry);
            }
        });
    }

    /// Restores the trace that was active before [`traced`], even if the traced code panics.
    struct Restore(Option<Vec<AirTraceEntry>>);

    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = self.0.take();
            TRACE.with(|trace| *trace.borrow_mut() = previous);
        }
    }

    /// Run `run` and return its result with every air composition it made on this thread, in
    /// call order.
    pub(crate) fn traced<R>(run: impl FnOnce() -> R) -> (R, Vec<AirTraceEntry>) {
        let restore = Restore(TRACE.with(|trace| trace.borrow_mut().replace(Vec::new())));
        let result = run();
        let entries = TRACE
            .with(|trace| trace.borrow_mut().take())
            .unwrap_or_default();
        drop(restore);
        (result, entries)
    }
}

/// The lapse and density of [`compose_local_air`] in Earth gravity, for the tests, for DRY base
/// air (`x_v = 0`, the dry hydrostatic lapse). Returns
/// `(local_temp_k, local_pressure_pa, density_kg_m3)`.
#[cfg(test)]
fn local_temp_pressure_density(
    altitude_m: f64,
    base_alt: f64,
    base_temp_c: f64,
    base_press_hpa: f64,
    base_ratio: f64,
) -> (f64, f64, f64) {
    local_temp_pressure_density_with_gravity(
        altitude_m,
        base_alt,
        base_temp_c,
        base_press_hpa,
        base_ratio,
        0.0,
        Gravity::EARTH,
    )
}

/// The lapse and density of [`compose_local_air`]: temperature and pressure through the ICAO
/// layers from the base, with the virtual-temperature hydrostatic exponent for base air holding
/// the water-vapour mole fraction `vapor_mole_fraction` (its moist gas constant
/// `R_AIR / (M_m / M_a)`, exactly `R_AIR` at 0), and the density from the base ratio. Returns
/// `(local_temp_k, local_pressure_pa, density_kg_m3)`.
fn local_temp_pressure_density_with_gravity(
    altitude_m: f64,
    base_alt: f64,
    base_temp_c: f64,
    base_press_hpa: f64,
    base_ratio: f64,
    vapor_mole_fraction: f64,
    gravity: Gravity,
) -> (f64, f64, f64) {
    let base_temp_k = base_temp_c + 273.15;

    // A non-finite endpoint would make the boundary walk fail to advance. The
    // previous single-column formula also produced non-finite outputs here.
    if !altitude_m.is_finite() || !base_alt.is_finite() {
        return (f64::NAN, f64::NAN, f64::NAN);
    }

    // The virtual-temperature lapse: R_m T = R_AIR T_v with T_v = T / (M_m / M_a). At x_v = 0
    // the ratio is exactly 1 and this is R_AIR to the bit.
    let gas_constant = R_AIR / moist_molar_mass_ratio(vapor_mole_fraction);
    let base_geopotential_m = geometric_to_geopotential_height_m(base_alt);
    let target_geopotential_m = geometric_to_geopotential_height_m(altitude_m);
    let (temp_k, pressure_hpa) = integrate_local_atmosphere_layers(
        base_geopotential_m,
        target_geopotential_m,
        base_temp_k,
        base_press_hpa,
        gas_constant,
        gravity,
    );

    // Enhanced density calculation
    let density_ratio = base_ratio * (base_temp_k * pressure_hpa) / (base_press_hpa * temp_k);
    let density = density_ratio * 1.225;

    (temp_k, pressure_hpa * 100.0, density)
}

/// Carry arbitrary station temperature and pressure through each crossed ICAO
/// layer in geopotential-height coordinates. The layer table supplies lapse rates and boundaries
/// only; station deviations from the standard atmosphere remain anchored at the converted base.
/// `gas_constant` (J/(kg·K)) sets the hydrostatic exponent: [`R_AIR`] for dry air, the moist
/// `R_AIR / (M_m / M_a)` for humid air (the virtual-temperature lapse).
fn integrate_local_atmosphere_layers(
    base_geopotential_m: f64,
    target_geopotential_m: f64,
    mut temp_k: f64,
    mut pressure_hpa: f64,
    gas_constant: f64,
    gravity: Gravity,
) -> (f64, f64) {
    let mut current_alt = base_geopotential_m;

    if target_geopotential_m > current_alt {
        while current_alt < target_geopotential_m {
            // At an exact boundary, ascent starts in the higher layer.
            let layer_index = ICAO_LAYERS
                .iter()
                .rposition(|layer| current_alt >= layer.base_altitude)
                .unwrap_or(0);
            let segment_end = ICAO_LAYERS
                .get(layer_index + 1)
                .map_or(target_geopotential_m, |next| {
                    target_geopotential_m.min(next.base_altitude)
                });
            (temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
                temp_k,
                pressure_hpa,
                segment_end - current_alt,
                ICAO_LAYERS[layer_index].lapse_rate,
                gas_constant,
                gravity,
            );
            current_alt = segment_end;
        }
    } else {
        while current_alt > target_geopotential_m {
            // At an exact boundary, descent starts in the lower layer. The
            // strict comparison is what makes a cross-layer round trip reversible.
            let layer_index = ICAO_LAYERS
                .iter()
                .rposition(|layer| current_alt > layer.base_altitude)
                .unwrap_or(0);
            let segment_end = if layer_index == 0 {
                target_geopotential_m
            } else {
                target_geopotential_m.max(ICAO_LAYERS[layer_index].base_altitude)
            };
            (temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
                temp_k,
                pressure_hpa,
                segment_end - current_alt,
                ICAO_LAYERS[layer_index].lapse_rate,
                gas_constant,
                gravity,
            );
            current_alt = segment_end;
        }
    }

    (temp_k, pressure_hpa)
}

/// One layer of the hydrostatic lapse, at the gas constant `gas_constant` (see
/// [`integrate_local_atmosphere_layers`]).
#[inline]
fn integrate_local_atmosphere_segment(
    base_temp_k: f64,
    base_pressure_hpa: f64,
    height_diff: f64,
    lapse_rate: f64,
    gas_constant: f64,
    gravity: Gravity,
) -> (f64, f64) {
    let temp_k = base_temp_k + lapse_rate * height_diff;
    let pressure_hpa = if lapse_rate.abs() < 1e-10 {
        base_pressure_hpa
            * (-gravity.magnitude() * height_diff / (gas_constant * base_temp_k)).exp()
    } else {
        let temp_ratio = temp_k / base_temp_k;
        base_pressure_hpa * temp_ratio.powf(-gravity.magnitude() / (lapse_rate * gas_constant))
    };

    (temp_k, pressure_hpa)
}

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

    #[test]
    fn uniform_gravity_controls_hydrostatic_pressure_without_moving_the_station_anchor() {
        for magnitude in [0.0, 1.62, 9.80665, 20.0] {
            let gravity = Gravity::new(magnitude).unwrap();
            let (temperature, pressure) =
                integrate_local_atmosphere_segment(280.0, 900.0, 100.0, 0.0, R_AIR, gravity);
            assert_eq!(temperature, 280.0);
            assert!(
                (pressure / 900.0 - (-magnitude * 100.0 / (R_AIR * 280.0)).exp()).abs() < 1e-14
            );
            let station = local_temp_pressure_density_with_gravity(
                300.0, 300.0, 20.0, 900.0, 0.9, 0.0, gravity,
            );
            assert_eq!(
                station,
                local_temp_pressure_density(300.0, 300.0, 20.0, 900.0, 0.9)
            );
        }
        // Exercise both the lapse and isothermal branches while crossing layer boundaries.
        let (_, pressure, _) = local_temp_pressure_density_with_gravity(
            25_000.0,
            0.0,
            20.0,
            900.0,
            0.9,
            0.0,
            Gravity::new(0.0).unwrap(),
        );
        assert_eq!(pressure, 90_000.0);
    }
}

/// Determine local lapse rate based on altitude and atmospheric layer.
#[cfg(test)]
#[inline(always)]
fn determine_local_lapse_rate(altitude_m: f64) -> f64 {
    // Find the current atmospheric layer to get appropriate lapse rate
    let layer = ICAO_LAYERS
        .iter()
        .rev()
        .find(|layer| altitude_m >= layer.base_altitude)
        .unwrap_or(&ICAO_LAYERS[0]);

    layer.lapse_rate
}

/// Direct atmosphere calculation for simple cases.
///
/// # Arguments
/// * `density` - Pre-computed air density
/// * `speed_of_sound` - Pre-computed speed of sound
///
/// # Returns
/// Tuple of (air_density, speed_of_sound) - just passes through the values
#[inline(always)]
pub fn get_direct_atmosphere(density: f64, speed_of_sound: f64) -> (f64, f64) {
    (density, speed_of_sound)
}

/// Legacy function name for backwards compatibility: [`calculate_air_density_cimp`].
///
/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
/// refuse what this computes.
pub fn calculate_air_density_cipm(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
    calculate_air_density_cimp(temp_c, pressure_hpa, humidity_percent)
}

/// A single downrange-referenced atmosphere zone:
/// `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`.
///
/// The T/P/H are the STATION-REFERENCED conditions (defined at the shooter base altitude) that
/// apply from the previous segment's threshold out to `until_distance_m`. This mirrors
/// [`crate::wind::WindSegment`]'s `(speed, angle, until_distance)` shape so the two segmented
/// models compose the same way (wind by X, atmosphere by X, altitude lapse by Y).
pub type AtmoSegment = (f64, f64, f64, f64);

/// Downrange-segmented atmosphere handler (MBA-1137), the density analogue of
/// [`crate::wind::WindSock`].
///
/// Holds a set of station-referenced atmosphere zones ordered by their `until_distance_m`
/// threshold and answers a stateless downrange lookup ([`AtmoSock::atmo_for_range`]).
///
/// The zone T/P/H are the base (shooter-altitude) conditions for that stretch of range; the
/// solver swaps them into the same local-atmosphere altitude-lapse pipeline that a single-station
/// solve uses, so the downrange (X) zone and the vertical (Y) altitude lapse compose orthogonally
/// without double-counting (the zone sets the base tuple, the lapse multiplies on top of it).
#[derive(Clone)]
pub struct AtmoSock {
    /// Zones sorted ascending by `until_distance_m` (segment slot 3).
    segments: Vec<AtmoSegment>,
    /// Each zone's governing air (its density ratio and water-vapour mole fraction), in
    /// `segments`' order, computed once in [`Self::new`] rather than at every step. A cache of
    /// `segments`, so `Debug` leaves it out.
    governing: Vec<GoverningAir>,
}

// The derive's output before the zones' governing air was held: it is a cache of the zones.
impl fmt::Debug for AtmoSock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AtmoSock")
            .field("segments", &self.segments)
            .finish()
    }
}

impl AtmoSock {
    /// Create a new `AtmoSock` from station-referenced atmosphere zones.
    ///
    /// Each segment is `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`. Segments are
    /// sorted by `until_distance_m`, with NaN thresholds ordered last. Each zone's density ratio
    /// and water-vapour mole fraction, fixed for any flight, are computed here once.
    pub fn new(mut segments: Vec<AtmoSegment>) -> Self {
        segments.sort_by(|a, b| match (a.3.is_nan(), b.3.is_nan()) {
            (true, true) => Ordering::Equal,
            (true, false) => Ordering::Greater,
            (false, true) => Ordering::Less,
            (false, false) => a.3.partial_cmp(&b.3).unwrap(),
        });
        let governing = segments.iter().map(GoverningAir::zone).collect();
        AtmoSock {
            segments,
            governing,
        }
    }

    /// True when this sock carries no zones. [`air_at`] treats an empty sock as no sock: the
    /// station's own air.
    pub fn is_empty(&self) -> bool {
        self.segments.is_empty()
    }

    /// Check every zone the way [`StationAir::new`] checks a station, plus its threshold.
    ///
    /// A zone needs a finite temperature above -273.15 °C, a finite pressure above 0, a
    /// relative humidity that [`RelativeHumidity::try_percent`] accepts (finite, 0 to 100, or a
    /// sensor reading within [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] of it, which the zone flies
    /// as the end it reads as), air that can exist (the same impossible-air test), and an
    /// `until_distance_m` above 0 (`+inf` is allowed, `NaN` is not). An empty sock is valid: it
    /// means the station.
    ///
    /// [`AtmoSock::new`] stays infallible; the checked kernel entries
    /// (`try_integrate_trajectory`, `fast_integrate*`) call this before integrating.
    ///
    /// # Errors
    ///
    /// The first bad zone's [`AtmosphereError`], its field named
    /// `atmo_sock.zones[i].<field>` with `i` the zone's index in threshold order (the order
    /// [`AtmoSock::new`] sorted them into).
    pub fn validate(&self) -> Result<(), AtmosphereError> {
        for (index, &(temperature_c, pressure_hpa, humidity_percent, until_m)) in
            self.segments.iter().enumerate()
        {
            let at = |error: AtmosphereError| {
                let field = format!("atmo_sock.zones[{index}].{}", error.field());
                error.at_field(field)
            };
            check_station_state(0.0, temperature_c, pressure_hpa).map_err(at)?;
            let humidity = RelativeHumidity::try_percent(humidity_percent).map_err(at)?;
            refuse_impossible_air(temperature_c, pressure_hpa, humidity).map_err(at)?;
            if until_m.is_nan() || until_m <= 0.0 {
                return Err(at(AtmosphereError::new(
                    "until_distance_m",
                    until_m,
                    AtmosphereErrorReason::NonPositiveZoneThreshold,
                )));
            }
        }
        Ok(())
    }

    /// Stateless downrange lookup of the active zone's `(temp_c, pressure_hpa, humidity_percent)`.
    ///
    /// Selection matches [`crate::wind::WindSock::vector_for_range_stateless`]: the first segment
    /// whose `until_distance_m` STRICTLY exceeds `downrange_m` wins (thresholds are upper-exclusive).
    /// Unlike wind — which returns zero past the last threshold — the LAST zone is used for any
    /// distance at or beyond the final threshold (there is no "zero atmosphere"). An empty sock
    /// returns the sea-level ISA reference at the engine's default humidity,
    /// `(15 C, 1013.25 hPa, DEFAULT_HUMIDITY_PERCENT)`; [`air_at`] never asks it, treating an
    /// empty sock as the station.
    ///
    /// This is stateless and safe for numerical integration (the same X may be queried repeatedly
    /// or out of order across RK substeps).
    pub fn atmo_for_range(&self, downrange_m: f64) -> (f64, f64, f64) {
        match self.zone_index(downrange_m) {
            Some(index) => {
                let (temp_c, pressure_hpa, humidity_percent, _) = self.segments[index];
                (temp_c, pressure_hpa, humidity_percent)
            }
            // Sea-level ISA at the one default humidity.
            None => (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT),
        }
    }

    /// The governing air of the zone [`Self::atmo_for_range`] selects at `downrange_m`, as
    /// [`Self::new`] computed it; `None` for an empty sock, which [`air_at`] reads as the
    /// station.
    #[inline]
    fn governing_air_for_range(&self, downrange_m: f64) -> Option<&GoverningAir> {
        self.zone_index(downrange_m)
            .map(|index| &self.governing[index])
    }

    /// The one zone selection behind [`Self::atmo_for_range`] and the per-step lookup: the first
    /// zone whose `until_distance_m` STRICTLY exceeds `downrange_m`, the last zone at or beyond
    /// the final threshold (there is no zeroing), and the first (nearest) zone for a NaN
    /// distance, which cannot be ordered. `None` for an empty sock.
    #[inline]
    fn zone_index(&self, downrange_m: f64) -> Option<usize> {
        let last = self.segments.len().checked_sub(1)?;
        if downrange_m.is_nan() {
            return Some(0);
        }
        Some(
            self.segments
                .iter()
                .position(|segment| downrange_m < segment.3)
                .unwrap_or(last),
        )
    }
}

#[cfg(test)]
mod humidity_model_tests;

#[cfg(test)]
mod aloft_vapour_tests;

#[cfg(test)]
mod nan_humidity_tests;

#[cfg(test)]
mod held_vapour_tests;

#[cfg(test)]
mod temperature_rule_tests;

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

    #[test]
    fn inclined_shot_frame_position_maps_to_world_altitude() {
        let base_altitude = 100.0;
        let downrange = 1_000.0;
        let shot_y = 10.0;
        let angle = std::f64::consts::FRAC_PI_6;
        let expected = base_altitude + downrange * angle.sin() + shot_y * angle.cos();

        let actual = shot_frame_altitude(base_altitude, downrange, shot_y, angle);
        assert!(
            (actual - expected).abs() < 1e-12,
            "30-degree shot at x=1000/y=10 should be at {expected} m, got {actual} m"
        );
        assert_eq!(
            shot_frame_altitude(base_altitude, downrange, shot_y, 0.0),
            base_altitude + shot_y,
            "flat-fire altitude must remain byte-identical"
        );
        let downhill = shot_frame_altitude(base_altitude, downrange, shot_y, -angle);
        let expected_downhill = base_altitude - downrange * angle.sin() + shot_y * angle.cos();
        assert!((downhill - expected_downhill).abs() < 1e-12);
    }

    // ---- MBA-1136: CIPM-2007 as the single canonical humid-air density ----

    /// Gate 1: dry sea-level (15 C, 1013.25 hPa, 0% RH) must stay at the ISA reference — density
    /// 1.225 +- 0.002 kg/m^3 and speed of sound 340.3 +- 0.6 m/s. CIPM-2007 at 0% RH reduces to
    /// dry-air ideal gas to within rounding, so this is essentially unchanged from the pre-CIPM
    /// baseline (baseline was 1.225012 / 340.294; now 1.225521 / 340.294 — the tiny density bump
    /// is CIPM compressibility + exact molar mass, the speed of sound is bit-identical).
    #[test]
    fn test_mba1136_dry_sea_level_reference() {
        let (density, sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
        assert!(
            (density - 1.225).abs() < 0.002,
            "dry sea-level density {density} not within 1.225 +- 0.002"
        );
        assert!(
            (sos - 340.3).abs() < 0.6,
            "dry sea-level speed of sound {sos} not within 340.3 +- 0.6"
        );
    }

    /// Gate 2: humid air (15 C, 1013.25 hPa, 50% RH) is the CIPM-2007 value (~1.2211 +- 0.002),
    /// STRICTLY lighter than dry air at the same T/P, with a speed of sound slightly ABOVE dry.
    #[test]
    fn test_mba1136_humid_lighter_than_dry() {
        let (dry_rho, dry_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
        let (moist_rho, moist_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);

        assert!(
            (moist_rho - 1.2211).abs() < 0.002,
            "50% RH density {moist_rho} not within CIPM 1.2211 +- 0.002"
        );
        assert!(
            moist_rho < dry_rho,
            "moist air ({moist_rho}) must be lighter than dry ({dry_rho})"
        );
        assert!(
            moist_sos > dry_sos,
            "moist speed of sound ({moist_sos}) must exceed dry ({dry_sos})"
        );
    }

    /// Gate 3: density is monotone-decreasing in humidity (100% RH < 50% RH < 0% RH).
    #[test]
    fn test_mba1136_density_monotone_in_humidity() {
        let (rho_0, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
        let (rho_50, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);
        let (rho_100, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 100.0);
        assert!(
            rho_100 < rho_50 && rho_50 < rho_0,
            "humidity monotonicity violated: 100%={rho_100}, 50%={rho_50}, 0%={rho_0}"
        );
    }

    /// rank 28: `calculate_atmosphere`'s density is exactly `calculate_air_density_cimp` — there
    /// is a single canonical humid-air density path (no separate Arden-Buck ideal-gas density).
    #[test]
    fn test_mba1136_atmosphere_density_is_cipm() {
        for (t, p, h) in [
            (15.0, 1013.25, 0.0),
            (15.0, 1013.25, 50.0),
            (30.0, 1000.0, 80.0),
            (-10.0, 1020.0, 20.0),
        ] {
            let (density, _) = calculate_atmosphere(0.0, Some(t), Some(p), h);
            let cipm = calculate_air_density_cimp(t, p, h);
            assert_eq!(
                density, cipm,
                "calculate_atmosphere density must equal CIPM at {t}C/{p}hPa/{h}%"
            );
        }
    }

    /// rank 9: the extracted `moist_speed_of_sound` is exactly what `calculate_atmosphere`
    /// returns (behavior-identical extraction), across dry and humid conditions.
    #[test]
    fn test_mba1136_moist_speed_of_sound_extraction() {
        for (t, p, h) in [
            (15.0, 1013.25, 0.0),
            (15.0, 1013.25, 50.0),
            (25.0, 900.0, 100.0),
        ] {
            let (_, sos) = calculate_atmosphere(0.0, Some(t), Some(p), h);
            let extracted = moist_speed_of_sound(t + 273.15, p * 100.0, h);
            assert_eq!(
                sos, extracted,
                "extracted moist_speed_of_sound must match calculate_atmosphere at {t}C/{p}hPa/{h}%"
            );
        }
    }

    /// rank 9: local-atmosphere reference values (base: 500 m, 10 C, 950 hPa, ratio 1.05).
    /// The 1500 m values include the geometric-to-geopotential height conversion.
    ///
    /// Re-baselined in 0.50.0: the dry sound speed is the engine's one dry
    /// constant, sqrt(1.4 * 287.0531 * T), the moist formula at 0 % RH, instead of a second
    /// sqrt(401.874 * T). That moves c by +4.23e-7 relative (+1.43e-4 m/s here); the density and
    /// the tolerance are unchanged.
    #[test]
    #[allow(deprecated)] // the dry legacy lookup is what is under test
    fn test_mba1136_get_local_atmosphere_reference() {
        let (d0, c0) = get_local_atmosphere(500.0, 500.0, 10.0, 950.0, 1.05);
        assert!(
            (d0 - 1.286250000000).abs() < 1e-9,
            "local density@500m drifted: {d0}"
        );
        assert!(
            (c0 - 337.328800091246).abs() < 1e-9,
            "local sos@500m drifted: {c0}"
        );
        let (d1, c1) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
        assert!(
            (d1 - 1.165238292559).abs() < 1e-9,
            "local density@1500m drifted: {d1}"
        );
        assert!(
            (c1 - 333.435687667240).abs() < 1e-9,
            "local sos@1500m drifted: {c1}"
        );
    }

    #[test]
    #[allow(deprecated)] // the dry legacy lookup is what is under test
    fn fractional_station_altitude_is_not_quantized() {
        let station_altitude_m = 500.25;
        let station_temp_c = 10.0;
        let station_pressure_hpa = 950.0;
        let station_density_ratio = 1.05;

        let (density, speed_of_sound) = get_local_atmosphere(
            station_altitude_m,
            station_altitude_m,
            station_temp_c,
            station_pressure_hpa,
            station_density_ratio,
        );

        let expected_density = station_density_ratio * 1.225;
        // The engine's one dry constant (0.50.0; was a second one, 401.874).
        let expected_speed_of_sound = (GAMMA * R_AIR * (station_temp_c + 273.15)).sqrt();
        assert!((density - expected_density).abs() < 1e-12);
        assert!((speed_of_sound - expected_speed_of_sound).abs() < 1e-12);
    }

    /// rank 9: `get_local_atmosphere_humid` returns the SAME density as `get_local_atmosphere`,
    /// and at 0% RH its speed of sound IS the dry value, to the bit: since 0.50.0 there is one
    /// dry constant (the old 401.874 differed from gamma*R by 4.2e-7, which this test used to
    /// absorb with a 1e-3 tolerance). At real humidity the speed of sound exceeds the dry value.
    #[test]
    #[allow(deprecated)] // the dry legacy lookup is what is under test
    fn test_mba1136_get_local_atmosphere_humid() {
        let (d_dry, c_dry) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
        let (d_h0, c_h0) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 0.0);
        assert_eq!(d_dry, d_h0, "humid variant must not change density");
        assert_eq!(
            c_h0.to_bits(),
            c_dry.to_bits(),
            "0% RH humid sos {c_h0} must be the dry sos {c_dry}"
        );
        let (_, c_h80) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 80.0);
        assert!(c_h80 > c_dry, "humid sos {c_h80} should exceed dry {c_dry}");
    }

    #[test]
    fn test_icao_standard_atmosphere() {
        // Test sea level
        let (temp, press) = calculate_icao_standard_atmosphere(0.0);
        assert!((temp - 288.15).abs() < 0.01);
        assert!((press - 101325.0).abs() < 1.0);

        // The table's 11 km tropopause base is geopotential height; convert it back to the
        // geometric altitude accepted by the public atmosphere contract.
        let geometric_tropopause_m =
            GEOPOTENTIAL_EARTH_RADIUS_M * 11000.0 / (GEOPOTENTIAL_EARTH_RADIUS_M - 11000.0);
        let (temp_11km, press_11km) = calculate_icao_standard_atmosphere(geometric_tropopause_m);
        assert!((temp_11km - 216.65).abs() < 0.01);
        assert!((press_11km - 22632.1).abs() < 1.0);

        // Test stratosphere
        let (temp_25km, _) = calculate_icao_standard_atmosphere(25000.0);
        assert!(temp_25km > 216.65); // Temperature increases in stratosphere
    }

    #[test]
    fn standard_atmosphere_extends_below_sea_level() {
        let altitude_m = -430.0;
        let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);

        assert!((temp_k - 290.945_189_079_054).abs() < 1e-9);
        assert!((pressure_pa - 106_598.763_552_437).abs() < 0.1);

        let (station_temp_c, station_pressure_hpa) =
            resolve_station_conditions(15.0, 1013.25, altitude_m);
        assert!((station_temp_c - 17.795_189_079_054).abs() < 1e-9);
        assert!((station_pressure_hpa - 1_065.987_635_524).abs() < 1e-6);

        let (sea_density, _) = calculate_atmosphere(0.0, None, None, 0.0);
        let (below_sea_density, _) = calculate_atmosphere(altitude_m, None, None, 0.0);
        assert!((below_sea_density - 1.276_908_642_79).abs() < 1e-6);
        assert!(below_sea_density > sea_density * 1.04);

        assert_eq!(
            calculate_icao_standard_atmosphere(-6000.0),
            calculate_icao_standard_atmosphere(MIN_GEOMETRIC_ALTITUDE_M)
        );
    }

    #[test]
    fn standard_atmosphere_converts_geometric_to_geopotential_height() {
        let cases: [(f64, f64, f64); 3] = [
            (10_000.0, 223.252_092_647_979, 26_499.901_600_244),
            (30_000.0, 226.509_083_611_330, 1_197.032_108_466),
            (84_000.0, 190.841_043_736_102, 0.531_525_514_935),
        ];
        for (geometric_m, expected_temp_k, expected_pressure_pa) in cases {
            let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(geometric_m);
            let pressure_tolerance = expected_pressure_pa.max(1.0_f64) * 1e-6;

            assert!((temp_k - expected_temp_k).abs() < 1e-9);
            assert!((pressure_pa - expected_pressure_pa).abs() < pressure_tolerance);
        }
    }

    #[test]
    #[allow(deprecated)] // the dry legacy lookup is one of the paths under test
    fn local_atmosphere_walks_icao_layers_continuously() {
        for altitude_m in [
            10999.0, 11000.0, 11001.0, 11050.0, 19999.0, 20000.0, 20001.0, 25000.0,
        ] {
            let (local_temp_k, local_pressure_pa, _) =
                local_temp_pressure_density(altitude_m, 0.0, 15.0, 1013.25, 1.0);
            let (standard_temp_k, standard_pressure_pa) =
                calculate_icao_standard_atmosphere(altitude_m);

            assert!(
                (local_temp_k - standard_temp_k).abs() < 1e-9,
                "local temperature diverged from ICAO at {altitude_m} m: local={local_temp_k}, standard={standard_temp_k}"
            );
            assert!(
                ((local_pressure_pa - standard_pressure_pa) / standard_pressure_pa).abs() < 5e-5,
                "local pressure diverged from ICAO at {altitude_m} m: local={local_pressure_pa}, standard={standard_pressure_pa}"
            );
        }

        let (density_below, sound_below) = get_local_atmosphere(10999.0, 0.0, 15.0, 1013.25, 1.0);
        let (density_above, sound_above) = get_local_atmosphere(11001.0, 0.0, 15.0, 1013.25, 1.0);
        assert!(
            (density_below - density_above).abs() < 0.001,
            "density jumped across 11 km: below={density_below}, above={density_above}"
        );
        assert!(
            (sound_below - sound_above).abs() < 0.1,
            "speed of sound jumped across 11 km: below={sound_below}, above={sound_above}"
        );
    }

    #[test]
    fn local_atmosphere_preserves_nonstandard_station_offset_and_round_trips() {
        let base_alt = 7500.0;
        let base_temp_c = 5.0;
        let base_pressure_hpa = 410.0;
        let base_ratio = 0.72;

        let (high_temp_k, high_pressure_pa, high_density) = local_temp_pressure_density(
            25000.0,
            base_alt,
            base_temp_c,
            base_pressure_hpa,
            base_ratio,
        );
        assert!((high_temp_k - 260.244_615_053_376).abs() < 1e-9);
        assert!((high_pressure_pa / 100.0 - 40.964_358_485_456).abs() < 1e-9);
        assert!((high_density - 0.094_186_400_274).abs() < 1e-9);

        let (back_temp_k, back_pressure_pa, back_density) = local_temp_pressure_density(
            base_alt,
            25000.0,
            high_temp_k - 273.15,
            high_pressure_pa / 100.0,
            high_density / 1.225,
        );
        assert!((back_temp_k - (base_temp_c + 273.15)).abs() < 1e-9);
        assert!((back_pressure_pa / 100.0 - base_pressure_hpa).abs() < 1e-8);
        assert!((back_density - base_ratio * 1.225).abs() < 1e-9);
    }

    #[test]
    fn test_enhanced_atmosphere_sea_level() {
        let (density, speed) = calculate_atmosphere(0.0, None, None, 0.0);
        assert!((density - 1.225).abs() < 0.01);
        assert!((speed - 340.0).abs() < 1.0);
    }

    /// The band's edges are inside it, in both directions. At sea level the ICAO standard is
    /// exactly 101325 Pa, and 1.08 and 0.85 times it are exact in binary, so the division
    /// lands on the constants themselves rather than next to them.
    #[test]
    fn station_pressure_plausibility_band_edges_are_inside_the_band() {
        let at_sea_level = |pa| station_pressure_plausibility(pa, 0.0);
        assert_eq!(at_sea_level(101_325.0).icao_standard_pa, 101_325.0);

        let high_edge = at_sea_level(109_431.0);
        assert_eq!(high_edge.ratio, STATION_PRESSURE_MAX_PLAUSIBLE_RATIO);
        assert!(!high_edge.implausible, "{high_edge:?}");
        assert!(at_sea_level(109_432.0).implausible);

        let low_edge = at_sea_level(86_126.25);
        assert_eq!(low_edge.ratio, STATION_PRESSURE_MIN_PLAUSIBLE_RATIO);
        assert!(!low_edge.implausible, "{low_edge:?}");
        assert!(at_sea_level(86_126.0).implausible);

        // Away from sea level the edges hold to a part in a billion either side.
        for altitude_m in [-400.0, 1500.0, 3310.128] {
            let (_, icao_pa) = calculate_icao_standard_atmosphere(altitude_m);
            for (ratio, implausible) in [
                (STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 - 1e-9), false),
                (STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 + 1e-9), true),
                (STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 + 1e-9), false),
                (STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 - 1e-9), true),
            ] {
                let p = station_pressure_plausibility(ratio * icao_pa, altitude_m);
                assert_eq!(p.icao_standard_pa, icao_pa);
                assert_eq!(
                    p.implausible, implausible,
                    "{altitude_m} m, ratio {ratio}: {p:?}"
                );
            }
        }

        assert!(station_pressure_plausibility(f64::NAN, 0.0).implausible);
    }

    /// The record sea-level pressures the band is justified by stay inside it, and the reported
    /// placeholder at Cusco does not.
    #[test]
    fn station_pressure_plausibility_passes_record_weather_and_flags_a_placeholder() {
        for record_hpa in [870.0, 1083.8, 1089.1] {
            let p = station_pressure_plausibility(record_hpa * 100.0, 0.0);
            assert!(!p.implausible, "{record_hpa} hPa: {p:?}");
        }

        let placeholder = station_pressure_plausibility(101_325.0, 3310.128);
        assert!(placeholder.implausible, "{placeholder:?}");
        assert!((placeholder.ratio - 1.503).abs() < 5e-4, "{placeholder:?}");
        // A real Cusco station reading is close to standard.
        assert!(!station_pressure_plausibility(68_830.0, 3310.128).implausible);
        // The same reading at an omitted (0 m) altitude is far below standard.
        assert!(station_pressure_plausibility(68_830.0, 0.0).implausible);
        // 101325 Pa leaves the band between 640 m and 650 m.
        assert!(!station_pressure_plausibility(101_325.0, 640.0).implausible);
        assert!(station_pressure_plausibility(101_325.0, 650.0).implausible);
    }

    #[test]
    fn test_resolve_station_pressure_contract() {
        // Default sea-level pressure + real altitude => derive from altitude (None).
        assert_eq!(resolve_station_pressure(1013.25, 2000.0), None);
        // 29.92 inHg ≈ 1013.21 hPa is also treated as the default (within tolerance).
        assert_eq!(resolve_station_pressure(1013.21, 2000.0), None);
        // An explicit, non-default station pressure is authoritative (Some, used directly).
        assert_eq!(resolve_station_pressure(850.0, 2000.0), Some(850.0));
        // At/near sea level the default is used directly (no derivation needed).
        assert_eq!(resolve_station_pressure(1013.25, 0.0), Some(1013.25));
    }

    #[test]
    fn qnh_reduction_matches_hand_computed_value_at_nonzero_altitude() {
        // Hand-computed (Python, double precision) from the altimeter-setting relation.
        // NOTE the geopotential step — 1500 m geometric is 1499.646 m geopotential, and it is
        // the geopotential height that enters the formula:
        //   h_geo   = 6356766*1500/(6356766+1500)                    = 1499.6461... m
        //   n       = 1/5.255875601466713                            = 0.19026325503612...
        //   station = 1030.0 * (1 - (0.0065*h_geo/288.15)*(1013.25/1030.0)^n)^(1/n)
        //           = 860.0681114332783 hPa
        // The ratio form this replaced, 1030.0 * (1 - 0.0065*h_geo/288.15)^5.2558756, gave
        // 859.5753123926447 hPa: 0.49 hPa low, because it scales the standard pressure ratio
        // by QNH instead of adding the station height to the QNH's pressure altitude.
        let reduced = reduce_qnh_to_station_pressure(1030.0, 1500.0);
        assert!(
            (reduced - 860.068_111_433_278_3).abs() < 1e-9,
            "reduced={reduced}"
        );
        // The reduction must strictly lower the pressure versus the raw QNH input.
        assert!(reduced < 1030.0);
    }

    #[test]
    fn qnh_reduction_is_identity_at_sea_level() {
        // At h=0 the geopotential height is 0, so the ratio is exactly 1.0 and QNH passes
        // through unchanged (bit-exact: 1.0f64.powf(x) == 1.0).
        assert_eq!(reduce_qnh_to_station_pressure(1030.0, 0.0), 1030.0);
        assert_eq!(reduce_qnh_to_station_pressure(950.5, 0.0), 950.5);
    }

    #[test]
    fn qnh_sea_level_standard_matches_icao_standard_atmosphere_at_every_altitude() {
        // A QNH of exactly 1013.25 hPa (the sea-level standard) must reduce to precisely the
        // ICAO standard station pressure at any altitude -- this is what keeps the omitted-
        // pressure default byte-identical whether the caller declares Absolute or Qnh.
        for altitude_m in [0.0, 500.0, 2000.0, 4500.0] {
            let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
            let reduced = reduce_qnh_to_station_pressure(1013.25, altitude_m);
            assert!(
                (reduced - std_pressure_pa / 100.0).abs() < 1e-9,
                "altitude={altitude_m} reduced={reduced} std={}",
                std_pressure_pa / 100.0
            );
        }
    }

    /// The doc comment's comparison with the NWS/ASOS altimeter-setting algorithm, checked:
    /// with that algorithm's constants (n = 0.190284, k = 8.4228807e-5, the field elevation as
    /// entered) and without its 0.3 hPa sensor offset, its station pressure is about 0.1 hPa
    /// below this function's at 1500 m and 0.3 to 0.45 hPa below at 4000 to 5000 m, over QNH
    /// 950 to 1050 hPa.
    #[test]
    fn qnh_reduction_differs_from_nws_asos_by_the_documented_amounts() {
        let nws_station_hpa = |qnh_hpa: f64, elevation_m: f64| {
            (qnh_hpa.powf(0.190284) - 8.4228807e-5 * elevation_m).powf(1.0 / 0.190284)
        };
        for (altitude_m, low, high) in [
            (1500.0, 0.09, 0.11),
            (4000.0, 0.3, 0.45),
            (5000.0, 0.3, 0.45),
        ] {
            for qnh_hpa in [950.0, 980.0, 1013.25, 1030.0, 1050.0] {
                let gap = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m)
                    - nws_station_hpa(qnh_hpa, altitude_m);
                assert!(
                    (low..=high).contains(&gap),
                    "QNH {qnh_hpa} at {altitude_m} m: this function is {gap} hPa above NWS/ASOS"
                );
            }
        }
    }

    #[test]
    fn qnh_reduction_adds_the_station_height_to_the_qnhs_pressure_altitude() {
        // What an altimeter setting means: an altimeter set to QNH reads field elevation on
        // the ground, so the station pressure's ISA pressure altitude is the QNH's own pressure
        // altitude plus the station's (geopotential) height. The troposphere's pressure
        // altitude is H(p) = (T0/-L) * (1 - (p/P0)^n), n = -L*R/g.
        let layer = &ICAO_LAYERS[0];
        let n = -layer.lapse_rate * R_AIR / G_ACCEL_MPS2;
        let p0_hpa = layer.base_pressure / 100.0;
        let pressure_altitude_m = |pressure_hpa: f64| {
            layer.base_temperature / -layer.lapse_rate * (1.0 - (pressure_hpa / p0_hpa).powf(n))
        };
        // The unit-test pin, Cusco (SPZO), La Paz (SLLP), low and high settings, a standard
        // setting, and a station below sea level.
        for (qnh_hpa, altitude_m) in [
            (1030.0, 1500.0),
            (1033.0, 3310.0),
            (1038.0, 4061.0),
            (1000.0, 2000.0),
            (980.0, 1500.0),
            (1040.0, 4500.0),
            (1013.25, 3000.0),
            (1030.0, -400.0),
        ] {
            let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
            let added_m = pressure_altitude_m(station_hpa) - pressure_altitude_m(qnh_hpa);
            let height_m = geometric_to_geopotential_height_m(altitude_m);
            assert!(
                (added_m - height_m).abs() < 1e-6,
                "QNH {qnh_hpa} hPa at {altitude_m} m: station {station_hpa} hPa adds \
                 {added_m} m of pressure altitude, expected {height_m} m"
            );
        }
    }

    #[test]
    fn qnh_reduction_is_nan_where_no_station_pressure_exists() {
        // A station pressure exists only while the QNH's pressure altitude plus the station
        // height stays below T0/-L (44,331 m, where the troposphere's lapse rate reaches
        // absolute zero). Past that the result is NaN, which every caller's finite-pressure
        // check refuses, rather than a near-vacuum number that would be flown as real air.
        assert!(reduce_qnh_to_station_pressure(500.0, 40_000.0).is_nan());
        assert!(reduce_qnh_to_station_pressure(-1030.0, 1500.0).is_nan());
        // Everywhere real shooting happens the reduction is finite and positive, lowers the
        // pressure above sea level and raises it below.
        for qnh_step in 0..=24 {
            let qnh_hpa = 850.0 + 10.0 * f64::from(qnh_step);
            for altitude_step in 0..=20 {
                let altitude_m = -1000.0 + 500.0 * f64::from(altitude_step);
                let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
                assert!(
                    station_hpa.is_finite() && station_hpa > 0.0,
                    "QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
                );
                assert_eq!(
                    station_hpa.partial_cmp(&qnh_hpa),
                    0.0.partial_cmp(&altitude_m),
                    "QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
                );
            }
        }
    }

    #[test]
    fn resolve_station_pressure_with_mode_absolute_matches_resolve_station_pressure() {
        // PressureReferenceMode::Absolute must be byte-identical to resolve_station_pressure
        // for every case that function's own contract test exercises.
        for (pressure_hpa, altitude_m) in [
            (1013.25, 2000.0),
            (1013.21, 2000.0),
            (850.0, 2000.0),
            (1013.25, 0.0),
        ] {
            assert_eq!(
                resolve_station_pressure_with_mode(
                    pressure_hpa,
                    altitude_m,
                    PressureReferenceMode::Absolute
                ),
                resolve_station_pressure(pressure_hpa, altitude_m)
            );
        }
    }

    #[test]
    fn resolve_station_pressure_with_mode_qnh_bypasses_the_default_sentinel() {
        // Constructed so the REDUCED value coincidentally lands within the absolute-mode
        // sentinel's +/-0.5 hPa tolerance of 1013.25 hPa at a real (>1 m) altitude -- exactly
        // the case that would silently discard an explicit reading under the old,
        // mode-blind resolve_station_pressure.
        let qnh = 1030.0;
        let altitude_m = 138.078_300_203_223_02;
        let reduced = reduce_qnh_to_station_pressure(qnh, altitude_m);
        assert!(
            (reduced - 1013.25).abs() < 0.5,
            "test fixture must land inside the sentinel band; reduced={reduced}"
        );

        // Qnh mode must still return Some(reduced) -- never None -- regardless of the
        // coincidence, and must equal the reduction, not a derived-from-altitude value.
        assert_eq!(
            resolve_station_pressure_with_mode(qnh, altitude_m, PressureReferenceMode::Qnh),
            Some(reduced)
        );

        // Sanity: the OLD absolute-mode function, given that same reduced number directly,
        // WOULD have discarded it (returned None, deriving ICAO-standard pressure instead) --
        // demonstrating why Qnh mode must never be routed back through the plain sentinel
        // check on its output.
        assert_eq!(resolve_station_pressure(reduced, altitude_m), None);
        let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
        assert!(
            (std_pressure_pa / 100.0 - reduced).abs() > 10.0,
            "fixture must show the sentinel misfire actually changes the answer materially"
        );
    }

    #[test]
    fn resolve_station_conditions_with_pressure_mode_absolute_matches_resolve_station_conditions() {
        for (temp_c, pressure_hpa, altitude_m) in [
            (15.0, 1013.25, 2000.0),
            (-5.0, 850.0, 2000.0),
            (15.0, 1013.25, 0.0),
        ] {
            assert_eq!(
                resolve_station_conditions_with_pressure_mode(
                    temp_c,
                    pressure_hpa,
                    altitude_m,
                    PressureReferenceMode::Absolute
                ),
                resolve_station_conditions(temp_c, pressure_hpa, altitude_m)
            );
        }
    }

    #[test]
    fn resolve_station_conditions_with_pressure_mode_qnh_reduces_pressure_only() {
        // -5.0 C is not the sea-level default sentinel (15.0 C), so it stays authoritative --
        // isolating that only the pressure resolution differs between the two modes.
        let (temp_c, pressure_hpa) = resolve_station_conditions_with_pressure_mode(
            -5.0,
            1030.0,
            1500.0,
            PressureReferenceMode::Qnh,
        );
        // Temperature resolution is untouched by pressure mode: an explicit, non-default
        // temperature stays authoritative exactly as resolve_station_conditions would give.
        assert_eq!(temp_c, -5.0);
        assert!((pressure_hpa - 860.068_111_433_278_3).abs() < 1e-9);
    }

    #[test]
    fn test_altitude_affects_density_with_default_pressure() {
        // Regression: with the default pressure, altitude MUST lower density (previously the
        // air-density path ignored altitude whenever pressure was the sea-level default).
        let press = resolve_station_pressure(1013.25, 0.0);
        let (rho_sea, _) = calculate_atmosphere(0.0, Some(15.0), press, 50.0);
        let press_alt = resolve_station_pressure(1013.25, 2000.0);
        let (rho_2km, _) = calculate_atmosphere(2000.0, Some(15.0), press_alt, 50.0);
        assert!(
            rho_2km < rho_sea * 0.9,
            "density at 2000 m ({rho_2km}) should be well below sea level ({rho_sea})"
        );

        // But an explicit station pressure stays authoritative (no altitude double-count):
        // density with an explicit pressure is independent of the altitude field.
        let p = resolve_station_pressure(900.0, 2000.0);
        let (rho_a, _) = calculate_atmosphere(2000.0, Some(15.0), p, 50.0);
        let (rho_b, _) = calculate_atmosphere(0.0, Some(15.0), p, 50.0);
        assert!(
            (rho_a - rho_b).abs() < 1e-9,
            "explicit pressure must ignore altitude"
        );
    }

    #[test]
    fn test_resolve_station_temperature_contract() {
        // Default 15 C + real altitude => derive ICAO lapse temperature (None).
        assert_eq!(resolve_station_temperature(15.0, 2000.0), None);
        // An explicit, non-default temperature is authoritative (Some, used directly).
        assert_eq!(resolve_station_temperature(-5.0, 2000.0), Some(-5.0));
        assert_eq!(resolve_station_temperature(30.0, 2000.0), Some(30.0));
        // At/near sea level the default is used directly (no derivation needed).
        assert_eq!(resolve_station_temperature(15.0, 0.0), Some(15.0));
    }

    #[test]
    fn test_altitude_only_default_matches_full_icao_standard() {
        // Regression: resolving BOTH temperature and pressure for an altitude-only query (defaults
        // left in place) must equal the fully-standard atmosphere at that altitude — i.e. altitude
        // now drives temperature (ICAO lapse) AND pressure, not just pressure. Validated against
        // py_ballisticcalc to ~0.04%. Previously the air held 15 C, leaving density ~7% too thin
        // (warm) at 3 km.
        for alt in [1000.0, 2000.0, 2500.0, 3000.0] {
            let t = resolve_station_temperature(15.0, alt);
            let p = resolve_station_pressure(1013.25, alt);
            let (rho_resolved, _) = calculate_atmosphere(alt, t, p, 0.0);
            let (rho_std, _) = calculate_atmosphere(alt, None, None, 0.0);
            assert!(
                (rho_resolved - rho_std).abs() < 1e-9,
                "alt {alt}: altitude-only default density {rho_resolved} should equal the full \
                 ICAO standard {rho_std}"
            );
            // And it must be denser than the old temperature-held-at-15C behavior (colder = denser).
            let (rho_warm, _) = calculate_atmosphere(alt, Some(15.0), p, 0.0);
            assert!(
                rho_resolved > rho_warm,
                "alt {alt}: lapse-temperature density {rho_resolved} should exceed 15 C-held {rho_warm}"
            );
        }
    }

    #[test]
    fn test_enhanced_atmosphere_with_humidity() {
        let (density_dry, speed_dry) = calculate_atmosphere(0.0, None, None, 0.0);
        let (density_humid, speed_humid) = calculate_atmosphere(0.0, None, None, 80.0);

        // Humid air should be less dense
        assert!(density_humid < density_dry);
        // Humid air should have slightly higher speed of sound
        assert!(speed_humid > speed_dry);
    }

    #[test]
    fn test_enhanced_atmosphere_stratosphere() {
        // Test in stratosphere where temperature increases
        let (density_20km, speed_20km) = calculate_atmosphere(20000.0, None, None, 0.0);
        let (density_30km, speed_30km) = calculate_atmosphere(30000.0, None, None, 0.0);

        // Density should decrease with altitude
        assert!(density_30km < density_20km);
        // Speed of sound should increase due to temperature increase
        assert!(speed_30km > speed_20km);
    }

    #[test]
    fn test_enhanced_cimp_density() {
        let density = calculate_air_density_cimp(15.0, 1013.25, 0.0);
        assert!((density - 1.225).abs() < 0.01);

        // Test with humidity
        let density_humid = calculate_air_density_cimp(15.0, 1013.25, 50.0);
        assert!(density_humid < density);
    }

    #[test]
    fn test_cipm_moist_air_matches_python_reference() {
        // Regression for the hPa/Pa mole-fraction slip: p_v (hPa) was divided by the total
        // pressure in Pa, making x_v 100x too small and erasing the humidity effect entirely.
        // Reference values computed with the validated Python implementation
        // (ballistics.physics.atmosphere_icao.calculate_air_density_cipm_icao), same cases as
        // the Flask suite's tests/test_atmosphere.py::TestCalculateAirDensityCIPM. Tolerance
        // 0.1% (matches that suite's Rust-vs-Python assertion).
        let cases = [
            (15.0, 1013.25, 50.0, 1.221125867723075),
            (30.0, 1000.0, 80.0, 1.1344071877123691),
            (-10.0, 1020.0, 20.0, 1.3500610713710515),
        ];
        for (temp_c, pressure_hpa, humidity_pct, expected) in cases {
            let density = calculate_air_density_cipm(temp_c, pressure_hpa, humidity_pct);
            let rel_err = ((density - expected) / expected).abs();
            assert!(
                rel_err < 1e-3,
                "CIPM density at {temp_c} C / {pressure_hpa} hPa / {humidity_pct}% RH: \
                 got {density}, expected {expected} (rel err {rel_err:.2e} >= 1e-3)"
            );
        }

        // Moist air must be materially lighter than dry air at the same temp/pressure
        // (the broken version returned a difference of only ~4e-5 kg/m^3).
        let dry = calculate_air_density_cipm(15.0, 1013.25, 0.0);
        let moist = calculate_air_density_cipm(15.0, 1013.25, 50.0);
        assert!(
            dry - moist > 3e-3,
            "humidity effect too small: dry {dry} vs 50% RH {moist}"
        );
    }

    #[test]
    fn test_variable_lapse_rates() {
        // Test that lapse rates change appropriately with altitude
        let lapse_tropo = determine_local_lapse_rate(5000.0);
        let lapse_strato = determine_local_lapse_rate(25000.0);

        assert!((lapse_tropo - (-0.0065)).abs() < 0.0001);
        assert!(lapse_strato > 0.0); // Positive lapse rate in stratosphere
    }

    // ---- MBA-1137: AtmoSock stateless downrange lookup (mirrors the WindSock tests) ----

    #[test]
    fn test_atmo_sock_empty_falls_back_to_isa() {
        let sock = AtmoSock::new(vec![]);
        assert!(sock.is_empty());
        // Empty sock returns the sea-level ISA reference regardless of distance, at the engine's
        // one default humidity (50 %, not a 0 % of its own). air_at never asks: to it an empty
        // sock is the station.
        assert_eq!(
            sock.atmo_for_range(0.0),
            (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
        );
        assert_eq!(
            sock.atmo_for_range(500.0),
            (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
        );
    }

    #[test]
    fn test_atmo_sock_single_segment_holds_beyond_last() {
        // One zone until 100 m; it must apply BOTH before and beyond the threshold (unlike wind,
        // which zeroes past the last segment — atmosphere holds the last zone).
        let sock = AtmoSock::new(vec![(25.0, 1000.0, 30.0, 100.0)]);
        assert_eq!(sock.atmo_for_range(50.0), (25.0, 1000.0, 30.0));
        assert_eq!(sock.atmo_for_range(100.0), (25.0, 1000.0, 30.0)); // beyond last -> hold
        assert_eq!(sock.atmo_for_range(5000.0), (25.0, 1000.0, 30.0));
    }

    #[test]
    fn test_atmo_sock_boundary_is_upper_exclusive() {
        // A zone's until_distance_m is exclusive: a query exactly at the boundary rolls to the
        // next zone (mirrors WindSock::test_wind_sock_boundary_is_upper_exclusive).
        let sock = AtmoSock::new(vec![
            (30.0, 1010.0, 80.0, 100.0), // hot/humid near zone
            (-5.0, 900.0, 10.0, 200.0),  // cold/thin far zone
        ]);
        // Just below 100 m -> first zone.
        assert_eq!(sock.atmo_for_range(99.999), (30.0, 1010.0, 80.0));
        // Exactly 100 m -> second zone.
        assert_eq!(sock.atmo_for_range(100.0), (-5.0, 900.0, 10.0));
        // Beyond the last boundary -> hold the last zone (NOT zeroed).
        assert_eq!(sock.atmo_for_range(200.0), (-5.0, 900.0, 10.0));
        assert_eq!(sock.atmo_for_range(1e6), (-5.0, 900.0, 10.0));
    }

    #[test]
    fn test_atmo_sock_sorts_unordered_segments() {
        // Segments supplied out of order are sorted by until_distance so the lookup is monotone.
        let sock = AtmoSock::new(vec![
            (-5.0, 900.0, 10.0, 200.0),
            (30.0, 1010.0, 80.0, 100.0),
        ]);
        assert_eq!(sock.atmo_for_range(50.0), (30.0, 1010.0, 80.0));
        assert_eq!(sock.atmo_for_range(150.0), (-5.0, 900.0, 10.0));
    }

    #[test]
    fn test_atmo_sock_orders_nan_thresholds_last() {
        let positive_nan = f64::from_bits(0x7ff8_0000_0000_0001);
        let negative_nan = f64::from_bits(0xfff8_0000_0000_0002);
        let sock = AtmoSock::new(vec![
            (97.0, 997.0, 97.0, positive_nan),
            (30.0, 1030.0, 30.0, 300.0),
            (98.0, 998.0, 98.0, negative_nan),
            (10.0, 1010.0, 10.0, 100.0),
            (99.0, 999.0, 99.0, f64::NAN),
            (20.0, 1020.0, 20.0, 200.0),
        ]);

        let thresholds: Vec<_> = sock.segments.iter().map(|segment| segment.3).collect();
        assert_eq!(&thresholds[..3], &[100.0, 200.0, 300.0]);
        assert!(thresholds[3..].iter().all(|threshold| threshold.is_nan()));
        assert_eq!(sock.atmo_for_range(f64::NAN), (10.0, 1010.0, 10.0));
        assert_eq!(sock.atmo_for_range(350.0), (99.0, 999.0, 99.0));
    }

    #[test]
    fn test_atmo_sock_nan_uses_first_zone() {
        let sock = AtmoSock::new(vec![
            (30.0, 1010.0, 80.0, 100.0),
            (-5.0, 900.0, 10.0, 200.0),
        ]);
        // NaN can't be ordered; deterministically use the nearest (first) zone rather than panic.
        assert_eq!(sock.atmo_for_range(f64::NAN), (30.0, 1010.0, 80.0));
    }

    // ---- MBA-1366: density altitude as a direct atmosphere input ----

    /// With no explicit temperature, the resolved altitude must equal the input density
    /// altitude EXACTLY (this is the algebraic identity documented on
    /// `resolve_atmosphere_for_density_altitude`: the correction term vanishes when station
    /// temperature is left at ISA).
    #[test]
    fn density_altitude_default_temp_pressure_alt_equals_density_alt() {
        for da_ft in [0.0_f64, 1000.0, 3000.0, 7500.0, -500.0] {
            let da_m = da_ft * DA_FT_TO_M;
            let (altitude_m, temp_c, pressure_hpa) =
                resolve_atmosphere_for_density_altitude(da_m, None);
            assert!(
                (altitude_m - da_m).abs() < 1e-6,
                "da_ft={da_ft}: altitude_m {altitude_m} should equal da_m {da_m}"
            );
            // Sanity: pressure must be a plausible station pressure (strictly decreasing with DA).
            assert!(pressure_hpa > 0.0 && pressure_hpa < 1100.0);
            assert!(temp_c.is_finite());
        }
        // At DA=0 the result must be exactly the sea-level ISA reference.
        let (alt0, temp0, press0) = resolve_atmosphere_for_density_altitude(0.0, None);
        assert!(alt0.abs() < 1e-9);
        assert!((temp0 - 15.0).abs() < 1e-6);
        assert!((press0 - 1013.25).abs() < 1e-6);
    }

    /// Higher density altitude at the ISA default must yield a lower station pressure (thinner
    /// air), matching the physical meaning of density altitude.
    #[test]
    fn density_altitude_pressure_decreases_monotonically() {
        let (_, _, p0) = resolve_atmosphere_for_density_altitude(0.0, None);
        let (_, _, p1) = resolve_atmosphere_for_density_altitude(1000.0, None);
        let (_, _, p2) = resolve_atmosphere_for_density_altitude(3000.0, None);
        assert!(p1 < p0);
        assert!(p2 < p1);
    }

    /// An explicit temperature must be honored EXACTLY (never re-derived), while the implied
    /// pressure altitude (and therefore the resolved altitude/pressure) differs from the
    /// ISA-default case -- proving density is still honored (a different pressure/altitude
    /// combination that reproduces the SAME density altitude at the warmer/colder temperature).
    #[test]
    fn density_altitude_explicit_temperature_overrides_isa_default_but_honors_density() {
        let da_m = 1000.0 * DA_FT_TO_M;
        let (default_alt_m, default_temp_c, default_pressure_hpa) =
            resolve_atmosphere_for_density_altitude(da_m, None);

        // A HOTTER-than-ISA explicit station temperature at the same density altitude implies a
        // LOWER pressure altitude: hot (less dense) air already accounts for some of the
        // "thinness" that defines the density altitude, so less physical elevation is needed to
        // reach the rest of it (equivalently: the correction term subtracts from DA before the
        // pressure inversion, since a warmer station reads MORE dense-feeling per unit of actual
        // elevation than ISA does).
        let hot_temp_c = default_temp_c + 20.0;
        let (hot_alt_m, hot_temp_out, hot_pressure_hpa) =
            resolve_atmosphere_for_density_altitude(da_m, Some(hot_temp_c));
        assert_eq!(
            hot_temp_out, hot_temp_c,
            "explicit temperature must be honored exactly"
        );
        assert!(
            hot_alt_m < default_alt_m,
            "hotter station temp at same DA should imply a lower pressure altitude: \
             hot={hot_alt_m} default={default_alt_m}"
        );
        assert!(hot_pressure_hpa > default_pressure_hpa);

        // A COLDER-than-ISA explicit temperature implies a HIGHER pressure altitude.
        let cold_temp_c = default_temp_c - 20.0;
        let (cold_alt_m, cold_temp_out, cold_pressure_hpa) =
            resolve_atmosphere_for_density_altitude(da_m, Some(cold_temp_c));
        assert_eq!(cold_temp_out, cold_temp_c);
        assert!(cold_alt_m > default_alt_m);
        assert!(cold_pressure_hpa < default_pressure_hpa);
    }

    /// Round trip using ONLY this crate's own math (the forward NWS pressure-altitude formula,
    /// re-derived independently in the test rather than reusing the production function) -- an
    /// implementation-independent algebraic sanity check. The REAL cross-crate round trip
    /// against the production `pdf_dope_card::calculate_density_altitude` forward function
    /// lives in `src/main.rs` (that function is CLI-binary-only and unreachable from this
    /// library crate).
    #[test]
    fn density_altitude_round_trips_through_hand_derived_forward_formula() {
        fn forward_density_altitude_ft(pressure_hpa: f64, temp_c: f64) -> f64 {
            let pressure_alt_ft = 145_366.45 * (1.0 - (pressure_hpa / 1013.25).powf(0.190_284));
            let isa_temp_f = 59.0 - (pressure_alt_ft / 1000.0) * 3.57;
            let temp_f = temp_c * 9.0 / 5.0 + 32.0;
            pressure_alt_ft + (120.0 * 5.0 / 9.0) * (temp_f - isa_temp_f)
        }

        for da_ft in [0.0_f64, 500.0, 2500.0, 6000.0] {
            let da_m = da_ft * DA_FT_TO_M;
            // Default (ISA-at-DA) branch.
            let (_, temp_c, pressure_hpa) = resolve_atmosphere_for_density_altitude(da_m, None);
            let round_tripped_ft = forward_density_altitude_ft(pressure_hpa, temp_c);
            assert!(
                (round_tripped_ft - da_ft).abs() < 1e-6,
                "da_ft={da_ft}: round-tripped {round_tripped_ft} (temp_c={temp_c}, pressure_hpa={pressure_hpa})"
            );

            // Explicit-temperature branch.
            let explicit_temp_c = 25.0;
            let (_, temp_out, pressure_hpa_explicit) =
                resolve_atmosphere_for_density_altitude(da_m, Some(explicit_temp_c));
            assert_eq!(temp_out, explicit_temp_c);
            let round_tripped_explicit_ft =
                forward_density_altitude_ft(pressure_hpa_explicit, temp_out);
            assert!(
                (round_tripped_explicit_ft - da_ft).abs() < 1e-6,
                "da_ft={da_ft} (explicit {explicit_temp_c}C): round-tripped {round_tripped_explicit_ft}"
            );
        }
    }
}

/// Station-presence resolution (0.49.0): a supplied station reading is never read as omitted.
#[cfg(test)]
mod station_presence_tests {
    use super::*;

    /// The body of `resolve_station_conditions_with_pressure_mode` exactly as it stood at
    /// ab4eb0c, before presence existed. It calls only the primitives this change leaves
    /// alone, so comparing against it cannot pass by comparing the new code with itself.
    fn legacy_resolve_ab4eb0c(
        temperature_c: f64,
        pressure_hpa: f64,
        altitude_m: f64,
        pressure_mode: PressureReferenceMode,
    ) -> (f64, f64) {
        let temp_override = resolve_station_temperature(temperature_c, altitude_m);
        let press_override =
            resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode);
        let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
        let temp_c = temp_override.unwrap_or(std_temp_k - 273.15);
        let pressure_hpa = press_override.unwrap_or(std_pressure_pa / 100.0);
        (temp_c, pressure_hpa)
    }

    const TEMPERATURES_C: [f64; 10] = [
        -40.0, 14.89, 14.9, 14.95, 15.0, 15.05, 15.0999, 15.1, 15.2, 30.0,
    ];
    const PRESSURES_HPA: [f64; 11] = [
        1012.7,
        1012.75,
        1012.8562053925472,
        1013.0,
        1013.2079,
        1013.25,
        1013.5,
        1013.75,
        1014.0,
        850.0,
        1031.0,
    ];
    const ALTITUDES_M: [f64; 13] = [
        -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 1.0000001, 3.0, 10.0, 150.0, 1500.0, 1524.0, 5000.0,
    ];
    const MODES: [PressureReferenceMode; 2] =
        [PressureReferenceMode::Absolute, PressureReferenceMode::Qnh];

    fn assert_bits(actual: (f64, f64), expected: (f64, f64), context: &str) {
        assert_eq!(
            actual.0.to_bits(),
            expected.0.to_bits(),
            "temperature {context}: {actual:?} vs {expected:?}"
        );
        assert_eq!(
            actual.1.to_bits(),
            expected.1.to_bits(),
            "pressure {context}: {actual:?} vs {expected:?}"
        );
    }

    #[test]
    fn neither_is_bit_identical_to_ab4eb0c() {
        for t in TEMPERATURES_C {
            for p in PRESSURES_HPA {
                for alt in ALTITUDES_M {
                    for mode in MODES {
                        let expected = legacy_resolve_ab4eb0c(t, p, alt, mode);
                        let context = format!("({t}, {p}, {alt}, {mode:?})");
                        assert_bits(
                            resolve_station_conditions_with_presence(
                                t,
                                p,
                                alt,
                                mode,
                                StationAtmospherePresence::NEITHER,
                            ),
                            expected,
                            &context,
                        );
                        assert_bits(
                            resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
                            expected,
                            &context,
                        );
                    }
                }
            }
        }

        // Six points captured at ab4eb0c, so a change to a shared primitive cannot pass
        // unseen through the verbatim copy above.
        let pinned = [
            (
                (15.05, 1013.0, 150.0, PressureReferenceMode::Absolute),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x402c0ccfd0c49b20),
                    f64::from_bits(0x408f1ae13f434f1f),
                ),
            ),
            (
                (15.0, 1013.25, 1500.0, PressureReferenceMode::Absolute),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x4015025af8d136c0),
                    f64::from_bits(0x408a6cc6358cefbd),
                ),
            ),
            (
                (15.0, 1013.25, 10.0, PressureReferenceMode::Qnh),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x402ddeb85559de00),
                    f64::from_bits(0x408fa064e4e5f101),
                ),
            ),
            (
                (15.0, 1013.2079, 1524.0, PressureReferenceMode::Qnh),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x401462aff47e8bc0),
                    f64::from_bits(0x408a58982cf0204f),
                ),
            ),
            (
                (
                    14.95,
                    1012.8562053925472,
                    1.0000001,
                    PressureReferenceMode::Absolute,
                ),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x402dfcac08345a20),
                    f64::from_bits(0x408fa909fb979713),
                ),
            ),
            (
                (15.0, 1013.25, 3.0, PressureReferenceMode::Absolute),
                // captured at ab4eb0c
                (
                    f64::from_bits(0x402df60418e281e0),
                    f64::from_bits(0x408fa71e04fe2409),
                ),
            ),
        ];
        for ((t, p, alt, mode), expected) in pinned {
            let context = format!("pinned ({t}, {p}, {alt}, {mode:?})");
            assert_bits(
                resolve_station_conditions_with_presence(
                    t,
                    p,
                    alt,
                    mode,
                    StationAtmospherePresence::NEITHER,
                ),
                expected,
                &context,
            );
            assert_bits(
                resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
                expected,
                &context,
            );
        }
    }

    #[test]
    fn both_returns_the_supplied_pair() {
        for t in TEMPERATURES_C {
            for p in PRESSURES_HPA {
                for alt in ALTITUDES_M {
                    let context = format!("({t}, {p}, {alt})");
                    assert_bits(
                        resolve_station_conditions_with_presence(
                            t,
                            p,
                            alt,
                            PressureReferenceMode::Absolute,
                            StationAtmospherePresence::BOTH,
                        ),
                        (t, p),
                        &context,
                    );
                    assert_bits(
                        resolve_station_conditions_with_presence(
                            t,
                            p,
                            alt,
                            PressureReferenceMode::Qnh,
                            StationAtmospherePresence::BOTH,
                        ),
                        (t, reduce_qnh_to_station_pressure(p, alt)),
                        &context,
                    );
                }
            }
        }
        // The headline repro: QNH 1031 hPa at 150 m reduces into the band and still flies.
        let (_, p) = resolve_station_conditions_with_presence(
            20.0,
            1031.0,
            150.0,
            PressureReferenceMode::Qnh,
            StationAtmospherePresence::BOTH,
        );
        assert_eq!(p.to_bits(), 1012.8562053925472_f64.to_bits(), "{p:?}");
    }

    #[test]
    fn presence_is_per_field() {
        let (icao_t_k, icao_p_pa) = calculate_icao_standard_atmosphere(1500.0);
        let temperature_only = resolve_station_conditions_with_presence(
            15.0,
            1013.25,
            1500.0,
            PressureReferenceMode::Absolute,
            StationAtmospherePresence::new(true, false),
        );
        assert_bits(temperature_only, (15.0, icao_p_pa / 100.0), "(true, false)");
        let pressure_only = resolve_station_conditions_with_presence(
            15.0,
            1013.0,
            1500.0,
            PressureReferenceMode::Absolute,
            StationAtmospherePresence::new(false, true),
        );
        assert_bits(pressure_only, (icao_t_k - 273.15, 1013.0), "(false, true)");
    }

    #[test]
    fn presence_constructors_agree() {
        assert_eq!(
            StationAtmospherePresence::default(),
            StationAtmospherePresence::NEITHER
        );
        assert_eq!(
            StationAtmospherePresence::NEITHER,
            StationAtmospherePresence::new(false, false)
        );
        assert_eq!(
            StationAtmospherePresence::BOTH,
            StationAtmospherePresence::new(true, true)
        );
        assert_eq!(
            StationAtmospherePresence::from_readings(
                StationReading::supplied(15.0),
                StationReading::omitted(1013.25)
            ),
            StationAtmospherePresence::new(true, false)
        );
        assert_eq!(
            StationAtmospherePresence::from_readings(
                StationReading::omitted(59.0),
                StationReading::supplied(29.92)
            ),
            StationAtmospherePresence::new(false, true)
        );
        assert!(StationReading::omitted(29.92).is_omitted());
        assert!(!StationReading::supplied(29.92).is_omitted());
        assert_eq!(
            StationReading::omitted(29.92).value.to_bits(),
            29.92_f64.to_bits()
        );
    }

    #[derive(Debug, serde::Serialize, serde::Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Probe {
        #[serde(
            default = "probe_default",
            skip_serializing_if = "StationReading::is_omitted"
        )]
        pressure_inhg: StationReading,
    }

    fn probe_default() -> StationReading {
        StationReading::omitted(29.92)
    }

    #[test]
    fn station_reading_serde() {
        let absent: Probe = serde_json::from_str("{}").unwrap();
        assert!(!absent.pressure_inhg.supplied);
        assert_eq!(absent.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());

        let present: Probe = serde_json::from_str(r#"{"pressure_inhg": 29.92}"#).unwrap();
        assert!(present.pressure_inhg.supplied);
        assert_eq!(present.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());

        assert_eq!(serde_json::to_string(&absent).unwrap(), "{}");
        assert_eq!(
            serde_json::to_string(&present).unwrap(),
            r#"{"pressure_inhg":29.92}"#
        );

        assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": null}"#).is_err());
        assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": "29.92"}"#).is_err());
    }
}