opengolfcoach 0.3.0

Cross-platform library for calculating derived golf shot values
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
// Core modules
mod clubhead_data;
mod shot_classifier;
mod trajectory;
mod trajectory_analysis;
mod unit_conversions;
mod vector;

// Language bindings (WASM, C FFI, etc.)
pub mod bindings;

// Re-export bindings at crate root for compatibility
pub use bindings::{calculate_derived_values, calculate_derived_values_ffi};

// Re-export public Rust API types
pub use clubhead_data::{
    estimate_club_face_path, estimate_clubhead_speed, get_smash_factor, ClubFacePathEstimates,
};
pub use trajectory::{calculate_trajectory, Trajectory, TrajectoryPoint, NATIVE_RATE_HZ};
pub use trajectory_analysis::{
    down_sample_trajectory, get_apex_position, get_carry_distance, get_descent_angle,
    get_hang_time, get_landing_position, get_landing_velocity, get_offline_distance,
    get_peak_height, get_time_to_apex, get_total_distance,
};
pub use vector::Vector3;

use serde::{Deserialize, Serialize};
use shot_classifier::classify_shot;
use std::f64::consts::PI;
use unit_conversions::{
    meters_per_second_to_mph, meters_to_yards, mph_to_meters_per_second, vector_meters_to_yards,
    vector_mph_to_mps, vector_mps_to_mph, vector_yards_to_meters, yards_to_meters,
};

// Only used in tests, but needed for bindings module
#[cfg(test)]
use serde_json::Value;

/// Wrapper carrying both right-handed and left-handed perspectives of a value.
///
/// Hand-dependent outputs (shot names, club path/face) are emitted as
/// `Handed<T>` so consumers can pick the perspective matching the player
/// without re-running the calculation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Handed<T> {
    pub right_handed: T,
    pub left_handed: T,
}

/// Sampled ball trajectory. Emitted under `open_golf_coach.trajectory` when
/// the caller opts in via `trajectory_enabled`. The internal simulation runs
/// at 500 Hz; `sample_rate_hz` is the (effective, post-clamp) rate at which
/// the points were emitted, and the points are linearly interpolated between
/// native integrator steps. Coordinates: +X forward, +Y right, +Z up
/// (left-handed; matches Unreal natively, swizzle for Unity / Three.js).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrajectoryOutput {
    pub sample_rate_hz: f64,
    pub points: Vec<TrajectoryPoint>,
}

/// Derived values calculated by OpenGolfCoach
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DerivedValues {
    // Spin conversions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backspin_rpm: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub sidespin_rpm: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_spin_rpm: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub spin_axis_degrees: Option<f64>,

    // Trajectory results
    #[serde(skip_serializing_if = "Option::is_none")]
    pub landing_position: Option<Vector3>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub landing_velocity: Option<Vector3>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub carry_distance_meters: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_distance_meters: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub offline_distance_meters: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub descent_angle_degrees: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub hang_time_seconds: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub peak_height_meters: Option<f64>,

    // Clubhead estimates
    #[serde(skip_serializing_if = "Option::is_none")]
    pub club_speed_meters_per_second: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub smash_factor: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub optimal_maximum_distance_meters: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub distance_efficiency_percent: Option<f64>,

    // Hand-dependent values: each carries both right- and left-handed perspectives.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub club_path_degrees: Option<Handed<f64>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub club_face_to_target_degrees: Option<Handed<f64>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub club_face_to_path_degrees: Option<Handed<f64>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub shot_name: Option<Handed<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub shot_rank: Option<Handed<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub shot_color_rgb: Option<Handed<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub us_customary_units: Option<USCustomaryValues>,

    // Environmental conditions used (only if not provided by user)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pressure_pascals: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub elevation_meters: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature_kelvin: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub humidity_percent: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub trajectory: Option<TrajectoryOutput>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USCustomaryValues {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ball_speed_mph: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub club_speed_mph: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub carry_distance_yards: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_distance_yards: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub offline_distance_yards: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub landing_position_yards: Option<Vector3>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub landing_velocity_mph: Option<Vector3>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub peak_height_yards: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub optimal_maximum_distance_yards: Option<f64>,
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct InputUSCustomaryUnits {
    #[serde(default)]
    pub ball_speed_mph: Option<f64>,

    #[serde(default)]
    pub club_speed_mph: Option<f64>,

    #[serde(default)]
    pub carry_distance_yards: Option<f64>,

    #[serde(default)]
    pub total_distance_yards: Option<f64>,

    #[serde(default)]
    pub offline_distance_yards: Option<f64>,

    #[serde(default)]
    pub landing_position_yards: Option<Vector3>,

    #[serde(default)]
    pub landing_velocity_mph: Option<Vector3>,

    #[serde(default)]
    pub peak_height_yards: Option<f64>,
}

impl DerivedValues {
    fn new() -> Self {
        DerivedValues {
            backspin_rpm: None,
            sidespin_rpm: None,
            total_spin_rpm: None,
            spin_axis_degrees: None,
            landing_position: None,
            landing_velocity: None,
            carry_distance_meters: None,
            total_distance_meters: None,
            offline_distance_meters: None,
            descent_angle_degrees: None,
            hang_time_seconds: None,
            peak_height_meters: None,
            club_speed_meters_per_second: None,
            smash_factor: None,
            optimal_maximum_distance_meters: None,
            distance_efficiency_percent: None,
            club_path_degrees: None,
            club_face_to_target_degrees: None,
            club_face_to_path_degrees: None,
            shot_name: None,
            shot_rank: None,
            shot_color_rgb: None,
            us_customary_units: None,
            pressure_pascals: None,
            elevation_meters: None,
            temperature_kelvin: None,
            humidity_percent: None,
            trajectory: None,
        }
    }

    fn populate_us_customary_units(&mut self, ball_speed_mps: Option<f64>) {
        let mut units = self.us_customary_units.clone().unwrap_or_default();

        if units.ball_speed_mph.is_none() {
            if let Some(speed) = ball_speed_mps {
                units.ball_speed_mph = Some(meters_per_second_to_mph(speed));
            }
        }

        if units.club_speed_mph.is_none() {
            if let Some(club_speed) = self.club_speed_meters_per_second {
                units.club_speed_mph = Some(meters_per_second_to_mph(club_speed));
            }
        }

        if units.carry_distance_yards.is_none() {
            if let Some(carry) = self.carry_distance_meters {
                units.carry_distance_yards = Some(meters_to_yards(carry));
            }
        }

        if units.total_distance_yards.is_none() {
            if let Some(total) = self.total_distance_meters {
                units.total_distance_yards = Some(meters_to_yards(total));
            }
        }

        if units.offline_distance_yards.is_none() {
            if let Some(offline) = self.offline_distance_meters {
                units.offline_distance_yards = Some(meters_to_yards(offline));
            }
        }

        if units.landing_position_yards.is_none() {
            if let Some(position) = self.landing_position {
                units.landing_position_yards = Some(vector_meters_to_yards(&position));
            }
        }

        if units.landing_velocity_mph.is_none() {
            if let Some(velocity) = self.landing_velocity {
                units.landing_velocity_mph = Some(vector_mps_to_mph(&velocity));
            }
        }

        if units.peak_height_yards.is_none() {
            if let Some(height) = self.peak_height_meters {
                units.peak_height_yards = Some(meters_to_yards(height));
            }
        }

        if units.optimal_maximum_distance_yards.is_none() {
            if let Some(max_distance) = self.optimal_maximum_distance_meters {
                units.optimal_maximum_distance_yards = Some(meters_to_yards(max_distance));
            }
        }

        if units.has_values() {
            self.us_customary_units = Some(units);
        }
    }
}

impl USCustomaryValues {
    fn has_values(&self) -> bool {
        self.ball_speed_mph.is_some()
            || self.club_speed_mph.is_some()
            || self.carry_distance_yards.is_some()
            || self.total_distance_yards.is_some()
            || self.offline_distance_yards.is_some()
            || self.landing_position_yards.is_some()
            || self.landing_velocity_mph.is_some()
            || self.peak_height_yards.is_some()
    }
}

impl InputUSCustomaryUnits {
    fn has_values(&self) -> bool {
        self.ball_speed_mph.is_some()
            || self.club_speed_mph.is_some()
            || self.carry_distance_yards.is_some()
            || self.total_distance_yards.is_some()
            || self.offline_distance_yards.is_some()
            || self.landing_position_yards.is_some()
            || self.landing_velocity_mph.is_some()
            || self.peak_height_yards.is_some()
    }
}

fn apply_us_unit_inputs(derived: &mut DerivedValues, units: &InputUSCustomaryUnits) {
    if derived.carry_distance_meters.is_none() {
        if let Some(val) = units.carry_distance_yards {
            derived.carry_distance_meters = Some(yards_to_meters(val));
        }
    }
    if derived.total_distance_meters.is_none() {
        if let Some(val) = units.total_distance_yards {
            derived.total_distance_meters = Some(yards_to_meters(val));
        }
    }
    if derived.offline_distance_meters.is_none() {
        if let Some(val) = units.offline_distance_yards {
            derived.offline_distance_meters = Some(yards_to_meters(val));
        }
    }
    if derived.peak_height_meters.is_none() {
        if let Some(val) = units.peak_height_yards {
            derived.peak_height_meters = Some(yards_to_meters(val));
        }
    }
    if derived.landing_position.is_none() {
        if let Some(vec_yds) = units.landing_position_yards {
            derived.landing_position = Some(vector_yards_to_meters(&vec_yds));
        }
    }
    if derived.landing_velocity.is_none() {
        if let Some(vec_mph) = units.landing_velocity_mph {
            derived.landing_velocity = Some(vector_mph_to_mps(&vec_mph));
        }
    }
    if derived.club_speed_meters_per_second.is_none() {
        if let Some(club_mph) = units.club_speed_mph {
            derived.club_speed_meters_per_second = Some(mph_to_meters_per_second(club_mph));
        }
    }
}

/// Input data structure for reading values from JSON.
///
/// Fields are public and `Default::default()` returns an all-`None` instance,
/// so Rust callers can construct an `InputData` directly without going
/// through JSON:
///
/// ```ignore
/// use opengolfcoach::{calculate_derived_values_from_input, InputData};
///
/// let input = InputData {
///     ball_speed_meters_per_second: Some(70.0),
///     vertical_launch_angle_degrees: Some(12.5),
///     trajectory_enabled: Some(true),
///     ..Default::default()
/// };
/// let derived = calculate_derived_values_from_input(&input);
/// ```
#[derive(Debug, Clone, Deserialize, Default)]
pub struct InputData {
    #[serde(default)]
    pub ball_speed_meters_per_second: Option<f64>,

    #[serde(default)]
    pub ball_speed_mph: Option<f64>,

    #[serde(default)]
    pub vertical_launch_angle_degrees: Option<f64>,

    #[serde(default)]
    pub horizontal_launch_angle_degrees: Option<f64>,

    #[serde(default)]
    pub total_spin_rpm: Option<f64>,

    #[serde(default)]
    pub spin_axis_degrees: Option<f64>,

    #[serde(default)]
    pub backspin_rpm: Option<f64>,

    #[serde(default)]
    pub sidespin_rpm: Option<f64>,

    #[serde(default)]
    pub club_speed_meters_per_second: Option<f64>,

    #[serde(default)]
    pub club_speed_mph: Option<f64>,

    #[serde(default, alias = "carry_yards")]
    pub carry_distance_yards: Option<f64>,

    #[serde(default, alias = "total_yards")]
    pub total_distance_yards: Option<f64>,

    #[serde(default, alias = "offline_yards")]
    pub offline_distance_yards: Option<f64>,

    #[serde(default)]
    pub peak_height_yards: Option<f64>,

    #[serde(default)]
    pub landing_position_yards: Option<Vector3>,

    #[serde(default)]
    pub landing_velocity_mph: Option<Vector3>,

    // Derived outputs that may come from external sources
    #[serde(default)]
    pub landing_position: Option<Vector3>,

    #[serde(default)]
    pub landing_velocity: Option<Vector3>,

    #[serde(default)]
    pub carry_distance_meters: Option<f64>,

    #[serde(default)]
    pub total_distance_meters: Option<f64>,

    #[serde(default)]
    pub offline_distance_meters: Option<f64>,

    #[serde(default)]
    pub descent_angle_degrees: Option<f64>,

    #[serde(default)]
    pub hang_time_seconds: Option<f64>,

    #[serde(default)]
    pub peak_height_meters: Option<f64>,

    #[serde(default)]
    pub smash_factor: Option<f64>,

    // Environmental conditions
    #[serde(default)]
    pub pressure_pascals: Option<f64>,

    #[serde(default)]
    pub elevation_meters: Option<f64>,

    #[serde(default)]
    pub temperature_kelvin: Option<f64>,

    #[serde(default)]
    pub humidity_percent: Option<f64>,

    #[serde(default)]
    pub us_customary_units: Option<InputUSCustomaryUnits>,

    /// Opt in to receiving the simulated ball trajectory under
    /// `open_golf_coach.trajectory`. Default `false`.
    #[serde(default)]
    pub trajectory_enabled: Option<bool>,

    /// Down-sample rate for the emitted trajectory, in Hz. Clamped to
    /// `(0, 500]`. If `trajectory_enabled` is `true` and this is `None` or
    /// `<= 0.0`, the native simulation rate (500 Hz) is used.
    #[serde(default)]
    pub trajectory_output_framerate_hz: Option<f64>,
}

/// Calculate all derived values from input data
pub fn calculate_derived_values_from_input(input: &InputData) -> DerivedValues {
    let mut derived = DerivedValues::new();

    macro_rules! copy_if_provided {
        ($field:ident) => {
            if let Some(value) = &input.$field {
                derived.$field = Some(value.clone());
            }
        };
    }

    copy_if_provided!(backspin_rpm);
    copy_if_provided!(sidespin_rpm);
    copy_if_provided!(total_spin_rpm);
    copy_if_provided!(spin_axis_degrees);
    copy_if_provided!(landing_position);
    copy_if_provided!(landing_velocity);
    copy_if_provided!(carry_distance_meters);
    copy_if_provided!(total_distance_meters);
    copy_if_provided!(offline_distance_meters);
    copy_if_provided!(descent_angle_degrees);
    copy_if_provided!(hang_time_seconds);
    copy_if_provided!(peak_height_meters);
    copy_if_provided!(club_speed_meters_per_second);
    copy_if_provided!(smash_factor);

    let root_us_units = InputUSCustomaryUnits {
        ball_speed_mph: input.ball_speed_mph,
        club_speed_mph: input.club_speed_mph,
        carry_distance_yards: input.carry_distance_yards,
        total_distance_yards: input.total_distance_yards,
        offline_distance_yards: input.offline_distance_yards,
        landing_position_yards: input.landing_position_yards,
        landing_velocity_mph: input.landing_velocity_mph,
        peak_height_yards: input.peak_height_yards,
    };
    if root_us_units.has_values() {
        apply_us_unit_inputs(&mut derived, &root_us_units);
    }

    if let Some(us_units) = &input.us_customary_units {
        apply_us_unit_inputs(&mut derived, us_units);
    }

    let mut ball_speed_mps = input.ball_speed_meters_per_second;
    if ball_speed_mps.is_none() {
        if let Some(speed_mph) = input.ball_speed_mph {
            ball_speed_mps = Some(mph_to_meters_per_second(speed_mph));
        }
    }
    if ball_speed_mps.is_none() {
        if let Some(us_units) = &input.us_customary_units {
            if let Some(speed_mph) = us_units.ball_speed_mph {
                ball_speed_mps = Some(mph_to_meters_per_second(speed_mph));
            }
        }
    }

    // Calculate spin components if we have total spin and spin axis, but not if already provided
    if derived.backspin_rpm.is_none() || derived.sidespin_rpm.is_none() {
        if let (Some(total_spin), Some(spin_axis)) = (input.total_spin_rpm, input.spin_axis_degrees)
        {
            let (backspin, sidespin) = calculate_spin_components(total_spin, spin_axis);
            if derived.backspin_rpm.is_none() {
                derived.backspin_rpm = Some(backspin);
            }
            if derived.sidespin_rpm.is_none() {
                derived.sidespin_rpm = Some(sidespin);
            }
        }
    }

    // Calculate total spin and spin axis if we have backspin and sidespin, but not if already provided
    if derived.total_spin_rpm.is_none() || derived.spin_axis_degrees.is_none() {
        if let (Some(backspin), Some(sidespin)) = (input.backspin_rpm, input.sidespin_rpm) {
            let (total_spin, spin_axis) = calculate_total_spin_and_axis(backspin, sidespin);
            if derived.total_spin_rpm.is_none() {
                derived.total_spin_rpm = Some(total_spin);
            }
            if derived.spin_axis_degrees.is_none() {
                derived.spin_axis_degrees = Some(spin_axis);
            }
        }
    }

    // Calculate trajectory-based values
    if let (Some(ball_speed), Some(v_angle)) = (ball_speed_mps, input.vertical_launch_angle_degrees)
    {
        let h_angle = input.horizontal_launch_angle_degrees.unwrap_or(0.0);

        // Use provided or derived spin values
        let backspin = input.backspin_rpm.or(derived.backspin_rpm).unwrap_or(0.0);
        let sidespin = input.sidespin_rpm.or(derived.sidespin_rpm).unwrap_or(0.0);

        // Environmental conditions: use provided values or defaults
        // Defaults from trajectory.rs: ELEVATION_M = 0.0, TEMPERATURE_C = 25.0, RELATIVE_HUMIDITY = 0.50
        const DEFAULT_ELEVATION_M: f64 = 0.0;
        const DEFAULT_TEMPERATURE_K: f64 = 298.15; // 25°C in Kelvin
        const DEFAULT_HUMIDITY_PERCENT: f64 = 50.0;

        let elevation_m = input.elevation_meters.unwrap_or(DEFAULT_ELEVATION_M);
        let temperature_k = input.temperature_kelvin.unwrap_or(DEFAULT_TEMPERATURE_K);
        let humidity_percent = input.humidity_percent.unwrap_or(DEFAULT_HUMIDITY_PERCENT);

        // If user didn't provide these values, we'll add them to derived output later
        let should_output_elevation = input.elevation_meters.is_none();
        let should_output_temperature = input.temperature_kelvin.is_none();
        let should_output_humidity = input.humidity_percent.is_none();
        let should_output_pressure = input.pressure_pascals.is_none();

        // Only calculate trajectory if we need any trajectory-derived values
        // OR the caller explicitly requested the trajectory output.
        let trajectory_requested = matches!(input.trajectory_enabled, Some(true));
        let needs_trajectory = trajectory_requested
            || derived.landing_position.is_none()
            || derived.landing_velocity.is_none()
            || derived.carry_distance_meters.is_none()
            || derived.total_distance_meters.is_none()
            || derived.offline_distance_meters.is_none()
            || derived.descent_angle_degrees.is_none()
            || derived.hang_time_seconds.is_none()
            || derived.peak_height_meters.is_none();

        if needs_trajectory {
            let trajectory = calculate_trajectory(
                ball_speed,
                v_angle,
                h_angle,
                backspin,
                sidespin,
                elevation_m,
                temperature_k,
                humidity_percent,
                input.pressure_pascals,
            );

            if derived.carry_distance_meters.is_none() {
                derived.carry_distance_meters = Some(get_carry_distance(&trajectory));
            }
            if derived.total_distance_meters.is_none() {
                derived.total_distance_meters = Some(get_total_distance(&trajectory));
            }
            if derived.offline_distance_meters.is_none() {
                derived.offline_distance_meters = Some(get_offline_distance(&trajectory));
            }
            if derived.descent_angle_degrees.is_none() {
                derived.descent_angle_degrees = Some(get_descent_angle(&trajectory));
            }
            if derived.hang_time_seconds.is_none() {
                derived.hang_time_seconds = Some(get_hang_time(&trajectory));
            }
            if derived.peak_height_meters.is_none() {
                derived.peak_height_meters = Some(get_peak_height(&trajectory));
            }

            if derived.landing_position.is_none() {
                derived.landing_position = Some(get_landing_position(&trajectory));
            }
            if derived.landing_velocity.is_none() {
                derived.landing_velocity = Some(get_landing_velocity(&trajectory));
            }

            if trajectory_requested {
                // Resolve effective sample rate: requested value clamps into
                // (0, NATIVE_RATE_HZ]; missing or non-positive values fall
                // back to the native simulation rate so we ship full fidelity
                // by default.
                let requested = input.trajectory_output_framerate_hz.unwrap_or(NATIVE_RATE_HZ);
                let effective_rate = if requested.is_finite() && requested > 0.0 {
                    requested.min(NATIVE_RATE_HZ)
                } else {
                    NATIVE_RATE_HZ
                };
                let points = down_sample_trajectory(&trajectory, effective_rate);
                derived.trajectory = Some(TrajectoryOutput {
                    sample_rate_hz: effective_rate,
                    points,
                });
            }
        }

        // Determine clubhead speed: use provided value (metric or converted) if available
        let club_speed = if let Some(measured_speed) = derived.club_speed_meters_per_second {
            measured_speed
        } else {
            // Estimate clubhead speed from ball launch conditions
            // Calculate total spin (use provided or derived values)
            let total_spin = input
                .total_spin_rpm
                .or(derived.total_spin_rpm)
                .unwrap_or_else(|| {
                    // Calculate from backspin/sidespin if available
                    let bs = backspin;
                    let ss = sidespin;
                    (bs.powi(2) + ss.powi(2)).sqrt()
                });

            estimate_clubhead_speed(ball_speed, v_angle, total_spin)
        };

        // Only set club_speed if not provided
        if derived.club_speed_meters_per_second.is_none() {
            derived.club_speed_meters_per_second = Some(club_speed);
        }

        // Calculate smash factor (ball speed / club speed ratio) only if not provided
        if input.smash_factor.is_none() {
            derived.smash_factor = Some(get_smash_factor(ball_speed, club_speed));
        }

        // Calculate distance efficiency (carry distance vs theoretical maximum)
        // Theoretical maximum is 2.4 yards per mph club speed, or 4.91 meters per m/s club speed
        if let Some(carry_meters) = derived.carry_distance_meters {
            let theoretical_max_meters = club_speed * 4.91;
            let efficiency = carry_meters / theoretical_max_meters * 100.0;
            derived.optimal_maximum_distance_meters = Some(theoretical_max_meters);
            derived.distance_efficiency_percent = Some(efficiency.round());
        }

        // Compute hand-dependent values once per perspective. Each is paired
        // into a Handed<T> so consumers can pick the side that matches the
        // player without re-running the calculation.
        let total_spin_for_classification =
            input.total_spin_rpm.or(derived.total_spin_rpm).or_else(|| {
                derived
                    .backspin_rpm
                    .zip(derived.sidespin_rpm)
                    .map(|(bs, ss)| (bs.powi(2) + ss.powi(2)).sqrt())
            });
        let spin_axis_for_classification =
            input.spin_axis_degrees.or(derived.spin_axis_degrees);
        let has_h_angle_input = input.horizontal_launch_angle_degrees.is_some();

        let rh = compute_for_hand(
            ball_speed,
            v_angle,
            h_angle,
            total_spin_for_classification,
            spin_axis_for_classification,
            has_h_angle_input,
            false,
        );
        let lh = compute_for_hand(
            ball_speed,
            v_angle,
            h_angle,
            total_spin_for_classification,
            spin_axis_for_classification,
            has_h_angle_input,
            true,
        );

        if let (Some(r), Some(l)) = (rh.shot_name, lh.shot_name) {
            derived.shot_name = Some(Handed { right_handed: r, left_handed: l });
        }
        if let (Some(r), Some(l)) = (rh.shot_rank, lh.shot_rank) {
            derived.shot_rank = Some(Handed { right_handed: r, left_handed: l });
        }
        if let (Some(r), Some(l)) = (rh.shot_color_rgb, lh.shot_color_rgb) {
            derived.shot_color_rgb = Some(Handed { right_handed: r, left_handed: l });
        }
        if let (Some(r), Some(l)) = (rh.club_path_degrees, lh.club_path_degrees) {
            derived.club_path_degrees = Some(Handed { right_handed: r, left_handed: l });
        }
        if let (Some(r), Some(l)) = (rh.club_face_to_target_degrees, lh.club_face_to_target_degrees) {
            derived.club_face_to_target_degrees =
                Some(Handed { right_handed: r, left_handed: l });
        }
        if let (Some(r), Some(l)) = (rh.club_face_to_path_degrees, lh.club_face_to_path_degrees) {
            derived.club_face_to_path_degrees =
                Some(Handed { right_handed: r, left_handed: l });
        }

        // Add environmental defaults to output if user didn't provide them
        if should_output_elevation {
            derived.elevation_meters = Some(elevation_m);
        }
        if should_output_temperature {
            derived.temperature_kelvin = Some(temperature_k);
        }
        if should_output_humidity {
            derived.humidity_percent = Some(humidity_percent);
        }
        if should_output_pressure {
            // Calculate pressure from elevation if not provided
            // Helper function in trajectory.rs converts elevation to hPa, then convert to Pa
            let pressure_hpa = 1013.25 * (1.0 - (0.0065 * elevation_m) / 288.15).powf(5.255);
            derived.pressure_pascals = Some(pressure_hpa * 100.0);
        }
    }

    derived.populate_us_customary_units(ball_speed_mps);

    derived
}

/// Convert total spin and spin axis to backspin and sidespin components
///
/// # Arguments
/// * `total_spin_rpm` - Total spin rate in RPM
/// * `spin_axis_degrees` - Spin axis angle in degrees (0 = pure backspin, positive = curves right of target line, i.e. slice/fade for a RH golfer)
///
/// # Returns
/// (backspin_rpm, sidespin_rpm)
pub fn calculate_spin_components(total_spin_rpm: f64, spin_axis_degrees: f64) -> (f64, f64) {
    let spin_axis_rad = spin_axis_degrees * PI / 180.0;

    // Backspin is the cosine component
    let backspin = total_spin_rpm * spin_axis_rad.cos();

    // Sidespin is the sine component
    let sidespin = total_spin_rpm * spin_axis_rad.sin();

    (backspin, sidespin)
}

/// Convert backspin and sidespin to total spin and spin axis
///
/// # Arguments
/// * `backspin_rpm` - Backspin rate in RPM
/// * `sidespin_rpm` - Sidespin rate in RPM (positive = right of target line, i.e. slice spin for a RH golfer)
///
/// # Returns
/// (total_spin_rpm, spin_axis_degrees)
pub fn calculate_total_spin_and_axis(backspin_rpm: f64, sidespin_rpm: f64) -> (f64, f64) {
    // Total spin is the magnitude of the vector
    let total_spin = (backspin_rpm.powi(2) + sidespin_rpm.powi(2)).sqrt();

    // Spin axis is the angle of the vector
    let spin_axis_rad = sidespin_rpm.atan2(backspin_rpm);
    let spin_axis_degrees = spin_axis_rad * 180.0 / PI;

    (total_spin, spin_axis_degrees)
}

#[derive(Default)]
struct HandedScalars {
    shot_name: Option<String>,
    shot_rank: Option<String>,
    shot_color_rgb: Option<String>,
    club_path_degrees: Option<f64>,
    club_face_to_target_degrees: Option<f64>,
    club_face_to_path_degrees: Option<f64>,
}

// Compute the hand-dependent values for one perspective. When `mirror` is
// true, the absolute-frame inputs are reflected across the target line
// (negate HLA and spin axis). Both the right-handed classifier and the
// face/path estimator are antisymmetric under that reflection, so feeding
// them mirrored inputs naturally yields outputs already expressed in the
// left-handed player's own swing reference frame — no further adjustment
// is needed.
fn compute_for_hand(
    ball_speed_mps: f64,
    v_angle: f64,
    h_angle: f64,
    total_spin: Option<f64>,
    spin_axis: Option<f64>,
    has_h_angle_input: bool,
    mirror: bool,
) -> HandedScalars {
    let sign = if mirror { -1.0 } else { 1.0 };
    let h = sign * h_angle;
    let sa = spin_axis.map(|v| sign * v);

    let mut out = HandedScalars::default();

    if has_h_angle_input {
        if let Some(spin_axis_value) = sa {
            let est = estimate_club_face_path(ball_speed_mps, h, spin_axis_value);
            out.club_path_degrees = Some(est.club_path_degrees);
            out.club_face_to_target_degrees = Some(est.club_face_to_target_degrees);
            out.club_face_to_path_degrees = Some(est.club_face_to_path_degrees);
        }
    }

    if let (Some(total_spin), Some(spin_axis_value)) = (total_spin, sa) {
        if let Some(c) = classify_shot(ball_speed_mps, v_angle, h, total_spin, spin_axis_value) {
            out.shot_name = Some(c.shot_name);
            out.shot_rank = Some(c.shot_rank);
            out.shot_color_rgb = Some(c.shot_color_rgb);
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use unit_conversions::{mph_to_meters_per_second, yards_to_meters};

    #[test]
    fn test_spin_components() {
        let (backspin, sidespin) = calculate_spin_components(3000.0, 0.0);
        assert!((backspin - 3000.0).abs() < 0.1);
        assert!(sidespin.abs() < 0.1);

        let (backspin, sidespin) = calculate_spin_components(3000.0, 45.0);
        assert!((backspin - 2121.3).abs() < 1.0);
        assert!((sidespin - 2121.3).abs() < 1.0);
    }

    #[test]
    fn test_total_spin_and_axis() {
        let (total, axis) = calculate_total_spin_and_axis(3000.0, 0.0);
        assert!((total - 3000.0).abs() < 0.1);
        assert!(axis.abs() < 0.1);

        let (total, axis) = calculate_total_spin_and_axis(2121.3, 2121.3);
        assert!((total - 3000.0).abs() < 1.0);
        assert!((axis - 45.0).abs() < 0.1);
    }

    #[test]
    fn test_trajectory_calculation() {
        // Test driver shot: 120 mph (~53.6 m/s), 12° launch, 2300 RPM backspin
        let trajectory =
            calculate_trajectory(53.6, 12.0, 0.0, 2300.0, 0.0, 0.0, 298.15, 50.0, None);
        let landing_pos = get_landing_position(&trajectory);
        let _landing_vel = get_landing_velocity(&trajectory);

        // Trajectory should have multiple points
        assert!(
            trajectory.points.len() > 1,
            "Trajectory should have multiple points"
        );

        // Physics model produces realistic carry distances
        let carry = landing_pos.magnitude();
        assert!(
            carry > 100.0 && carry < 300.0,
            "Carry distance {} should be reasonable for driver",
            carry
        );

        // Should be near centerline (Y is left/right)
        assert!(
            landing_pos.y.abs() < 10.0,
            "Offline {} should be minimal with no sidespin",
            landing_pos.y
        );

        // Should have landed (Z is up/down)
        assert!(
            landing_pos.z <= 0.1,
            "Should have landed, z = {}",
            landing_pos.z
        );

        // Forward component should be positive (X is forward)
        assert!(landing_pos.x > 0.0, "Forward distance should be positive");
    }

    #[test]
    fn test_total_distance_includes_roll() {
        let trajectory =
            calculate_trajectory(70.0, 11.0, 0.0, 2200.0, 0.0, 0.0, 298.15, 50.0, None);
        let carry = get_carry_distance(&trajectory);
        let total = get_total_distance(&trajectory);
        assert!(
            total >= carry,
            "Total distance {} should be at least the carry {}",
            total,
            carry
        );
        assert!(
            total - carry < 25.0,
            "Roll {} should stay within realistic bounds",
            total - carry
        );
        assert!(
            total - carry > 1.0,
            "Roll {} should be non-trivial for a driver",
            total - carry
        );
    }


    #[test]
    fn test_trajectory_time() {
        // Test that time increases correctly
        let trajectory =
            calculate_trajectory(53.6, 12.0, 0.0, 2300.0, 0.0, 0.0, 298.15, 50.0, None);

        // First point should be at t=0
        assert_eq!(trajectory.points[0].t, 0.0, "Initial time should be 0");

        // Time should increase monotonically
        for i in 1..trajectory.points.len() {
            assert!(
                trajectory.points[i].t > trajectory.points[i - 1].t,
                "Time should increase monotonically"
            );
        }

        // Last point should have non-zero time (ball took some time to land)
        let final_time = trajectory.points.last().unwrap().t;
        assert!(final_time > 0.0, "Flight time should be positive");
        assert!(
            final_time < 30.0,
            "Flight time should be reasonable (< 30s)"
        );
    }

    #[test]
    fn test_json_output_structure() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": -2.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();

        // Original fields should be preserved
        assert_eq!(output["ball_speed_meters_per_second"], 70.0);
        assert_eq!(output["vertical_launch_angle_degrees"], 12.0);

        // Should have open_golf_coach section
        assert!(output.get("open_golf_coach").is_some());

        // Derived values should be in open_golf_coach
        let derived = &output["open_golf_coach"];
        assert!(derived.get("carry_distance_meters").is_some());
        assert!(derived.get("total_distance_meters").is_some());
        assert!(derived.get("backspin_rpm").is_some());
        assert!(derived.get("sidespin_rpm").is_some());
        assert!(derived.get("hang_time_seconds").is_some());
        assert!(derived.get("peak_height_meters").is_some());
        assert!(derived["club_path_degrees"]["right_handed"].is_f64());
        assert!(derived["club_path_degrees"]["left_handed"].is_f64());
        assert!(derived["club_face_to_target_degrees"]["right_handed"].is_f64());
        assert!(derived["club_face_to_target_degrees"]["left_handed"].is_f64());
        assert!(derived["club_face_to_path_degrees"]["right_handed"].is_f64());
        assert!(derived["club_face_to_path_degrees"]["left_handed"].is_f64());
        assert!(derived["shot_name"]["right_handed"].is_string());
        assert!(derived["shot_name"]["left_handed"].is_string());
        assert!(derived["shot_rank"]["right_handed"].is_string());
        assert!(derived["shot_rank"]["left_handed"].is_string());
        assert!(derived["shot_color_rgb"]["right_handed"].is_string());
        assert!(derived["shot_color_rgb"]["left_handed"].is_string());
        assert!(derived.get("us_customary_units").is_some());

        // Verify hang_time_seconds is reasonable
        let hang_time = derived["hang_time_seconds"].as_f64().unwrap();
        assert!(
            hang_time > 0.0 && hang_time < 30.0,
            "Hang time {} should be reasonable",
            hang_time
        );

        // Verify peak_height_meters is reasonable
        let peak_height = derived["peak_height_meters"].as_f64().unwrap();
        assert!(
            peak_height > 0.0 && peak_height < 100.0,
            "Peak height {} should be reasonable",
            peak_height
        );

        let us_units = &derived["us_customary_units"];
        assert!(us_units.get("ball_speed_mph").is_some());
        assert!(us_units.get("carry_distance_yards").is_some());
        assert!(us_units.get("club_speed_mph").is_some());
    }

    #[test]
    fn test_preserve_provided_derived_values() {
        // Hand-independent values supplied by the caller should round-trip.
        // Hand-dependent values are no longer accepted as inputs.
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": -1.5,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0,
            "open_golf_coach": {
                "carry_distance_meters": 150.0,
                "smash_factor": 1.42
            }
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();

        let derived = &output["open_golf_coach"];
        assert!((derived["carry_distance_meters"].as_f64().unwrap() - 150.0).abs() < 1e-6);
        assert!((derived["smash_factor"].as_f64().unwrap() - 1.42).abs() < 1e-6);
    }

    #[test]
    fn test_us_customary_unit_values() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 53.6,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": 0.0,
            "total_spin_rpm": 2300.0,
            "spin_axis_degrees": 0.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];
        let us_units = &derived["us_customary_units"];

        let ball_speed_mph = us_units["ball_speed_mph"].as_f64().unwrap();
        assert!((ball_speed_mph - 120.0).abs() < 0.5);

        let carry_yards = us_units["carry_distance_yards"].as_f64().unwrap();
        let carry_meters = derived["carry_distance_meters"].as_f64().unwrap();
        assert!((carry_yards - carry_meters * 1.0936133).abs() < 1e-6);

        let club_speed_mph = us_units["club_speed_mph"].as_f64().unwrap();
        let club_speed_mps = derived["club_speed_meters_per_second"].as_f64().unwrap();
        assert!((club_speed_mph - club_speed_mps * 2.23693629).abs() < 1e-6);
    }

    #[test]
    fn test_shot_classification_matches_straight() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": 0.0,
            "total_spin_rpm": 2500.0,
            "spin_axis_degrees": 0.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];

        // A perfectly straight shot mirrors to itself across handedness.
        assert_eq!(derived["shot_name"]["right_handed"], "Straight");
        assert_eq!(derived["shot_name"]["left_handed"], "Straight");
        assert_eq!(derived["shot_rank"]["right_handed"], "B");
        assert_eq!(derived["shot_rank"]["left_handed"], "B");
        assert_eq!(derived["shot_color_rgb"]["right_handed"], "0x7CB342");
        assert_eq!(derived["shot_color_rgb"]["left_handed"], "0x7CB342");
    }

    #[test]
    fn test_handed_mirroring_push_fade() {
        // RH: HLA=+5 (push), spin_axis=+10 (fade) -> "Push Fade".
        // The same physical shot reads as a pull-draw for a LH golfer.
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": 5.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 10.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];

        assert_eq!(derived["shot_name"]["right_handed"], "Push Fade");
        assert_eq!(derived["shot_name"]["left_handed"], "Pull Draw");

        // Club path/face/face-to-path read in the player's own swing frame
        // and should be exact mirrors across handedness.
        let rh_path = derived["club_path_degrees"]["right_handed"]
            .as_f64()
            .unwrap();
        let lh_path = derived["club_path_degrees"]["left_handed"]
            .as_f64()
            .unwrap();
        assert!((rh_path + lh_path).abs() < 1e-9);

        let rh_face = derived["club_face_to_target_degrees"]["right_handed"]
            .as_f64()
            .unwrap();
        let lh_face = derived["club_face_to_target_degrees"]["left_handed"]
            .as_f64()
            .unwrap();
        assert!((rh_face + lh_face).abs() < 1e-9);

        let rh_f2p = derived["club_face_to_path_degrees"]["right_handed"]
            .as_f64()
            .unwrap();
        let lh_f2p = derived["club_face_to_path_degrees"]["left_handed"]
            .as_f64()
            .unwrap();
        assert!((rh_f2p + lh_f2p).abs() < 1e-9);
    }

    #[test]
    fn test_handed_shanks_mirror() {
        // |HLA| > 12 with VLA > 12 hits the shank special-case. The same
        // physical shot is "Right Shank" for RH and "Left Shank" for LH.
        let json_input = r#"{
            "ball_speed_meters_per_second": 60.0,
            "vertical_launch_angle_degrees": 13.0,
            "horizontal_launch_angle_degrees": 13.0,
            "total_spin_rpm": 3000.0,
            "spin_axis_degrees": 0.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];

        assert_eq!(derived["shot_name"]["right_handed"], "Right Shank");
        assert_eq!(derived["shot_name"]["left_handed"], "Left Shank");
    }

    #[test]
    fn test_handed_no_hla_same_classification() {
        // Without an HLA input, both perspectives reduce to identical labels
        // (HLA defaults to 0, which mirrors to itself).
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "total_spin_rpm": 2500.0,
            "spin_axis_degrees": 0.0
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];

        assert_eq!(
            derived["shot_name"]["right_handed"],
            derived["shot_name"]["left_handed"]
        );
        // Without an HLA input we don't compute club path/face for either hand.
        assert!(derived.get("club_path_degrees").is_none());
    }

    #[test]
    fn test_us_customary_input_conversion() {
        let json_input = r#"{
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": 0.0,
            "total_spin_rpm": 2300.0,
            "spin_axis_degrees": 0.0,
            "us_customary_units": {
                "ball_speed_mph": 150.0,
                "carry_distance_yards": 240.0,
                "club_speed_mph": 100.0
            }
        }"#;

        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];

        let expected_carry_meters = yards_to_meters(240.0);
        assert!(
            (derived["carry_distance_meters"].as_f64().unwrap() - expected_carry_meters).abs()
                < 1e-6
        );

        let expected_club_speed = mph_to_meters_per_second(100.0);
        assert!(
            (derived["club_speed_meters_per_second"].as_f64().unwrap() - expected_club_speed).abs()
                < 1e-6
        );

        let us_units = &derived["us_customary_units"];
        assert!((us_units["carry_distance_yards"].as_f64().unwrap() - 240.0).abs() < 1e-6);
        assert!((us_units["ball_speed_mph"].as_f64().unwrap() - 150.0).abs() < 0.1);
    }

    const METERS_TO_YARDS: f64 = 1.093_613_3;

    /// Helper to assert carry is within a percentage of expected
    fn assert_carry_within_pct(actual_yd: f64, expected_yd: f64, pct: f64, label: &str) {
        let margin = expected_yd * pct / 100.0;
        let lo = expected_yd - margin;
        let hi = expected_yd + margin;
        assert!(
            actual_yd > lo && actual_yd < hi,
            "{label} carry {actual_yd:.1} yd outside {pct}% of expected {expected_yd:.0} ({lo:.1}-{hi:.1})",
        );
    }

    #[test]
    fn test_pro_average_driver() {
        // Pro average driver: ~171 mph ball speed, ~10° launch, ~2500 rpm
        let trajectory = calculate_trajectory(
            76.4, 10.0, 0.0, 2500.0, 0.0, 0.0, 298.15, 50.0, None,
        );
        let carry_yd = get_carry_distance(&trajectory) * METERS_TO_YARDS;
        assert_carry_within_pct(carry_yd, 282.0, 3.0, "Pro driver");
    }

    #[test]
    fn test_pro_average_7iron() {
        // Pro average 7-iron: ~123 mph ball speed, ~16° launch, ~7100 rpm
        let trajectory = calculate_trajectory(
            55.0, 16.0, 0.0, 7100.0, 0.0, 0.0, 298.15, 50.0, None,
        );
        let carry_yd = get_carry_distance(&trajectory) * METERS_TO_YARDS;
        assert_carry_within_pct(carry_yd, 176.0, 3.0, "Pro 7-iron");
    }

    #[test]
    fn test_amateur_average_driver() {
        // Amateur average driver: ~143 mph ball speed, ~13° launch, ~2500 rpm
        let trajectory = calculate_trajectory(
            63.9, 13.0, 0.0, 2500.0, 0.0, 0.0, 298.15, 50.0, None,
        );
        let carry_yd = get_carry_distance(&trajectory) * METERS_TO_YARDS;
        assert_carry_within_pct(carry_yd, 223.0, 3.0, "Amateur driver");
    }

    #[test]
    fn test_amateur_average_7iron() {
        // Amateur average 7-iron: ~106 mph ball speed, ~19° launch, ~6600 rpm
        let trajectory = calculate_trajectory(
            47.4, 19.0, 0.0, 6600.0, 0.0, 0.0, 298.15, 50.0, None,
        );
        let carry_yd = get_carry_distance(&trajectory) * METERS_TO_YARDS;
        assert_carry_within_pct(carry_yd, 143.0, 3.0, "Amateur 7-iron");
    }

    #[test]
    fn test_amateur_average_pw() {
        // Amateur average PW: ~88 mph ball speed, ~25° launch, ~8500 rpm
        let trajectory = calculate_trajectory(
            39.3, 25.0, 0.0, 8500.0, 0.0, 0.0, 298.15, 50.0, None,
        );
        let carry_yd = get_carry_distance(&trajectory) * METERS_TO_YARDS;
        assert_carry_within_pct(carry_yd, 108.0, 3.0, "Amateur PW");
    }

    fn baseline_shot_json() -> &'static str {
        r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": -2.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0
        }"#
    }

    #[test]
    fn test_trajectory_omitted_by_default() {
        let result = calculate_derived_values(baseline_shot_json()).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        assert!(
            output["open_golf_coach"].get("trajectory").is_none(),
            "trajectory should not be present when not requested"
        );
    }

    #[test]
    fn test_trajectory_emitted_at_default_rate() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": -2.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0,
            "trajectory_enabled": true
        }"#;
        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let traj = &output["open_golf_coach"]["trajectory"];
        assert!(traj.is_object(), "trajectory should be an object");
        assert_eq!(traj["sample_rate_hz"].as_f64().unwrap(), 500.0);
        let points = traj["points"].as_array().expect("points array");
        assert!(points.len() > 100, "default rate should yield many points");
        let first = &points[0];
        assert!(first["t"].as_f64().unwrap().abs() < 1e-6);
        assert!(first["x"].as_f64().unwrap().abs() < 1e-6);
        assert!(first["z"].as_f64().unwrap().abs() < 1e-6);
        let last = &points[points.len() - 1];
        assert!(
            last["z"].as_f64().unwrap().abs() < 0.5,
            "last point z {} should be near ground",
            last["z"]
        );
    }

    #[test]
    fn test_trajectory_emitted_at_requested_rate() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "horizontal_launch_angle_degrees": -2.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0,
            "trajectory_enabled": true,
            "trajectory_output_framerate_hz": 60.0
        }"#;
        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let derived = &output["open_golf_coach"];
        let traj = &derived["trajectory"];
        assert_eq!(traj["sample_rate_hz"].as_f64().unwrap(), 60.0);
        let points = traj["points"].as_array().expect("points array");
        assert!(points.len() >= 2);

        // First sample at t=0, last at hang time.
        assert!(points[0]["t"].as_f64().unwrap().abs() < 1e-6);
        let hang_time = derived["hang_time_seconds"].as_f64().unwrap();
        let last_t = points[points.len() - 1]["t"].as_f64().unwrap();
        assert!(
            (last_t - hang_time).abs() < 0.05,
            "last sample t={} should be within one frame of hang_time={}",
            last_t,
            hang_time
        );

        // Interior samples should be ~1/60 s apart (skip the final
        // landing-snap point, whose spacing may be shorter).
        let dt = 1.0 / 60.0;
        for win in points.windows(2).take(points.len().saturating_sub(2)) {
            let delta = win[1]["t"].as_f64().unwrap() - win[0]["t"].as_f64().unwrap();
            assert!(
                (delta - dt).abs() < 1e-6,
                "interior frame spacing {} should equal {}",
                delta,
                dt
            );
        }
    }

    #[test]
    fn test_trajectory_clamped_to_native_rate() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0,
            "trajectory_enabled": true,
            "trajectory_output_framerate_hz": 5000.0
        }"#;
        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        let traj = &output["open_golf_coach"]["trajectory"];
        assert_eq!(
            traj["sample_rate_hz"].as_f64().unwrap(),
            500.0,
            "rate above native should clamp to 500"
        );
    }

    #[test]
    fn test_trajectory_disabled_explicitly() {
        let json_input = r#"{
            "ball_speed_meters_per_second": 70.0,
            "vertical_launch_angle_degrees": 12.0,
            "total_spin_rpm": 2800.0,
            "spin_axis_degrees": 15.0,
            "trajectory_enabled": false,
            "trajectory_output_framerate_hz": 60.0
        }"#;
        let result = calculate_derived_values(json_input).unwrap();
        let output: Value = serde_json::from_str(&result).unwrap();
        assert!(
            output["open_golf_coach"].get("trajectory").is_none(),
            "trajectory should be absent when explicitly disabled"
        );
    }

    #[test]
    fn test_trajectory_zero_or_negative_rate_uses_default() {
        for bad_rate in [0.0_f64, -1.0_f64] {
            let json_input = format!(
                r#"{{
                    "ball_speed_meters_per_second": 70.0,
                    "vertical_launch_angle_degrees": 12.0,
                    "total_spin_rpm": 2800.0,
                    "spin_axis_degrees": 15.0,
                    "trajectory_enabled": true,
                    "trajectory_output_framerate_hz": {}
                }}"#,
                bad_rate
            );
            let result = calculate_derived_values(&json_input).unwrap();
            let output: Value = serde_json::from_str(&result).unwrap();
            let traj = &output["open_golf_coach"]["trajectory"];
            assert_eq!(
                traj["sample_rate_hz"].as_f64().unwrap(),
                500.0,
                "non-positive rate {} should fall back to native 500",
                bad_rate
            );
        }
    }

    #[test]
    fn test_typed_rust_api_no_json() {
        // Round-trip end-to-end via the typed Rust path: construct InputData
        // with a struct literal, run the derivation, read TrajectoryOutput
        // back as typed Rust values. No serde_json anywhere in this test.
        let input = InputData {
            ball_speed_meters_per_second: Some(70.0),
            vertical_launch_angle_degrees: Some(12.0),
            horizontal_launch_angle_degrees: Some(-2.0),
            total_spin_rpm: Some(2800.0),
            spin_axis_degrees: Some(15.0),
            trajectory_enabled: Some(true),
            trajectory_output_framerate_hz: Some(60.0),
            ..Default::default()
        };
        let derived = calculate_derived_values_from_input(&input);
        let traj = derived.trajectory.expect("trajectory was requested");
        assert_eq!(traj.sample_rate_hz, 60.0);
        assert!(traj.points.len() >= 2);
        let first = traj.points.first().unwrap();
        assert!(first.t.abs() < 1e-9);
        assert!(first.x.abs() < 1e-9);
        assert!(first.z.abs() < 1e-9);
        let last = traj.points.last().unwrap();
        assert!(
            last.z.abs() < 0.5,
            "landing z={} should be near ground",
            last.z
        );
    }
}