mlb-api 1.0.3

Endpoints for MLB's public Statcast API.
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
use std::{fmt::Display, num::NonZeroUsize, ops::{Deref, DerefMut}};

use bon::Builder;
use chrono::{DateTime, Utc};
use derive_more::{Deref, DerefMut, Display};
use serde::{Deserialize, Deserializer, de::IgnoredAny};
use serde_with::{serde_as, DefaultOnNull, DefaultOnError};
use uuid::Uuid;

use crate::{Copyright, Handedness, HomeAway, game::{AtBatCount, Base, BattingOrderIndex, ContactHardness, GameId, Inning, InningHalf}, meta::{EventType, HitTrajectory, NamedPosition, PitchCodeId, PitchType, ReviewReasonId}, person::{NamedPerson, PersonId}, request::RequestURL, stats::raw::{HittingHotColdZones, PitchingHotColdZones, StrikeZoneSection}, team::TeamId};

/// A collection of plays, often a whole game's worth.
#[allow(clippy::struct_field_names, clippy::unsafe_derive_deserialize, reason = "not relevant here")]
#[derive(Debug, Deserialize, PartialEq, Clone, Deref)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct Plays {
    #[serde(default)]
    pub copyright: Copyright,
    
    #[deref]
    #[serde(rename = "allPlays")]
    plays: Vec<Play>,

    /// Unlinked from the `plays` list
    pub current_play: Option<Play>,

    #[serde(rename = "scoringPlays")]
    pub(super) scoring_play_indices: Vec<usize>,

    #[serde(rename = "playsByInning")]
    pub(super) play_indices_by_inning: Vec<InningPlaysIndices>,
}

impl IntoIterator for Plays {
    type Item = Play;
    type IntoIter = <Vec<Play> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.plays.into_iter()
    }
}

impl<'a> IntoIterator for &'a Plays {
    type Item = &'a Play;
    type IntoIter = std::slice::Iter<'a, Play>;

    fn into_iter(self) -> Self::IntoIter {
        self.plays.iter()
    }
}

impl Plays {
    /// Gives a mutable refernece to the underlying plays.
    ///
    /// # Safety
    /// [`Self::scroing_plays`], [`Self::by_inning`] and [`Self::by_inning_halves`] use caches for these plays, if mutated, these caches will be outdated.
    #[must_use]
    pub const unsafe fn plays_mut(&mut self) -> &mut Vec<Play> {
        &mut self.plays
    }

    /// Reduces this type into the underlying [`Vec<Play>`]
    #[must_use]
    pub fn into_plays(self) -> Vec<Play> {
        self.plays
    }

    /// Iterator over a list of scoring plays.
    ///
    /// ## Examples
    /// ```no_run
    /// let plays: Plays = ...;
    ///
    /// for play in plays.scoring_plays() {
    ///     dbg!(play);
    /// }
    /// ```
    pub fn scoring_plays(&self) -> impl Iterator<Item=&Play> {
        self.scoring_play_indices.iter()
            .filter_map(|&idx| self.plays.get(idx))
    }

    /// Iterator of plays by inning
    ///
    /// ## Examples
    /// ```no_run
    /// let plays: Plays = ...;
    ///
    /// for plays in plays.by_inning() {
    ///     for play in plays {
    ///         dbg!(play);
    ///     }
    /// }
    /// ```
    pub fn by_inning(&self) -> impl Iterator<Item=impl Iterator<Item=&Play>> {
        self.play_indices_by_inning.iter()
            .map(|inning| (inning.start..=inning.end)
                .filter_map(|idx| self.plays.get(idx)))
    }

    /// Iterator of plays by inning halves. (top then bottom)
    ///
    /// ## Examples
    /// ```no_run
    /// let plays: Plays = ...;
    ///
    /// for (top, bottom) in plays.by_inning_halves() {
    ///     for play in top {
    ///         dbg!(play);
    ///     }
    ///     for play in bottom {
    ///         dbg!(play);
    ///     }
    /// }
    /// ```
    pub fn by_inning_halves(&self) -> impl Iterator<Item=(impl Iterator<Item=&Play>, impl Iterator<Item=&Play>)> {
        self.play_indices_by_inning.iter()
            .map(|inning| (
                inning.top_indices.iter().filter_map(|&idx| self.plays.get(idx)),
                inning.bottom_indices.iter().filter_map(|&idx| self.plays.get(idx))
            ))
    }
}

#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub(super) struct InningPlaysIndices {
    #[serde(rename = "startIndex")]
    pub(super) start: usize,
    #[serde(rename = "endIndex")]
    pub(super) end: usize,
    #[serde(rename = "top")]
    pub(super) top_indices: Vec<usize>,
    #[serde(rename = "bottom")]
    pub(super) bottom_indices: Vec<usize>,
    #[doc(hidden)]
    #[serde(rename = "hits", default)]
    pub(super) __balls_in_play: IgnoredAny,
}

/// The play(s) within an "At-Bat"
///
/// For individual "plays" and actions, look to [`PlayEvent`]s
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct Play {
    /// See [`PlayDetails`].
    pub result: PlayDetails,
    /// See [`PlayAbout`].
    pub about: PlayAbout,
    /// Active count in the at-bat.
    pub count: AtBatCount,
    /// See [`PlayMatchup`].
    pub matchup: PlayMatchup,
    /// See [`PlayEvent`].
    pub play_events: Vec<PlayEvent>,
    pub runners: Vec<RunnerData>,
    #[serde(rename = "reviewDetails", default, deserialize_with = "deserialize_review_data")]
    pub reviews: Vec<ReviewData>,
    
    /// Timestamp at which the [`Play`] is called complete.
    #[serde(rename = "playEndTime", deserialize_with = "crate::deserialize_datetime")]
    pub play_end_timestamp: DateTime<Utc>,

    #[doc(hidden)]
    #[serde(rename = "pitchIndex", default)]
    pub __pitch_indices: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "actionIndex", default)]
    pub __action_indices: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "runnerIndex", default)]
    pub __runner_indices: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "atBatIndex", default)]
    pub __at_bat_index: IgnoredAny,
}

/// The result of a play, such as a Strikeout, Home Run, etc.
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PlayDetails {
    #[serde(flatten, default)]
    pub completed_play_details: Option<CompletedPlayDetails>,
    
    /// Score as of the end of the play
    pub away_score: usize,
    /// Score as of the end of the play
    pub home_score: usize,

    #[doc(hidden)]
    #[serde(rename = "event", default)]
    pub __event: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "type", default)]
    pub __type: IgnoredAny,
}

/// Information supplied to [`PlayDetails`] when the play is complete
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct CompletedPlayDetails {
    #[serde(rename = "eventType")]
    pub event: EventType,
    /// Shohei Ohtani strikes out swinging.
    pub description: String,
    /// Runs batted in
    pub rbi: usize,
    /// Whether the batter in the play is out
    pub is_out: bool,
}

/// Miscallaneous data regarding a play
#[allow(clippy::struct_excessive_bools, reason = "inapplicable")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PlayAbout {
    /// Ordinal at bat of the game (starts at 0)
    #[serde(rename = "atBatIndex")]
    pub at_bat_idx: usize,

    /// The inning half this play is in
    #[serde(rename = "halfInning")]
    pub inning_half: InningHalf,

    /// The inning this play is in
    pub inning: Inning,

    /// The timestamp that this play begins; includes milliseconds
    #[serde(rename = "startTime", deserialize_with = "crate::deserialize_datetime")]
    pub start_timestamp: DateTime<Utc>,

    /// The timestamp that this play ends at; includes milliseconds
    #[serde(rename = "endTime", deserialize_with = "crate::deserialize_datetime")]
    pub end_timestamp: DateTime<Utc>,

    /// Whether the play is "complete" or not, i.e. opposite of ongoing.
    ///
    /// Once a play is complete it cannot be edited
    pub is_complete: bool,

    /// Whether the play itself is scoring, such as a Home Run.
    ///
    /// Note that [`Play`]s that include [`PlayEvent`]s that score runs that are not part of the [`Play`] (such as stealing home) do not indicate this as true.
    ///
    /// This is the predicate for [`Plays::scoring_plays`]
    pub is_scoring_play: Option<bool>,

    /// Whether the play has a replay review occur. Note that At-Bats can have multiple challenges occur.
    #[serde(default)]
    pub has_review: bool,

    /// Whether the play has counted towards an out so far.
    ///
    /// Note this does not account for pickoffs, caught stealing, etc, it only counts for the current [`PlayEvent`].
    #[serde(default)]
    pub has_out: bool,

    /// Ordinal ranking for +/- WPA effect.
    ///
    /// `1` means largest effect on WPA,
    /// `2` means second most, etc.
    #[serde(default)]
    pub captivating_index: usize,

    #[doc(hidden)]
    #[serde(rename = "isTopInning")]
    pub __is_top_inning: IgnoredAny,
}

/// Hitter & Pitcher matchup information
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PlayMatchup {
    pub batter: NamedPerson,
    pub pitcher: NamedPerson,
    /// Cannot change during the play
    pub bat_side: Handedness,
    /// Cannot change during the play
    pub pitch_hand: Handedness,
    pub post_on_first: Option<NamedPerson>,
    pub post_on_second: Option<NamedPerson>,
    pub post_on_third: Option<NamedPerson>,

    #[doc(hidden)]
    #[serde(rename = "batterHotColdZones", default)]
    pub __batter_hot_cold_zones: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "pitcherHotColdZones", default)]
    pub __pitcher_hot_cold_zones: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "batterHotColdZoneStats", default)]
    pub __batter_hot_cold_zone_stats: IgnoredAny,
    #[doc(hidden)]
    #[serde(rename = "pitcherHotColdZoneStats", default)]
    pub __pitcher_hot_cold_zone_stats: IgnoredAny,
    
    // pub batter_hot_cold_zones: HittingHotColdZones,
    // pub pitcher_hot_cold_zones: PitchingHotColdZones,

    pub splits: ApplicablePlayMatchupSplits,
}

/// Batter, Pitcher, and Men-On-Base splits; unknown type.
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct ApplicablePlayMatchupSplits {
    pub batter: String,
    pub pitcher: String,
    pub men_on_base: String,
}

/// Data regarding a baserunner.
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct RunnerData {
    pub movement: RunnerMovement,
    pub details: RunnerDetails,
    #[serde(default)]
    pub credits: Vec<RunnerCredit>,
}

/// Data regarding the basepath of a runner
#[serde_as]
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct RunnerMovement {
    /// The base the runner begins the play at. `None` if they do not start on-base at the beginning of the play.
    pub origin_base: Option<Base>,

    /// Unsure how it is different from ``origin_base``
    #[serde(rename = "start")]
    pub start_base: Option<Base>,

    /// The latest base the runner is called "safe" at. `None` if the runner was never safe at any base.
    #[serde(rename = "end")]
    pub end_base: Option<Base>,

    /// The base the runner was called out at. `None` if the runner was never called out.
    pub out_base: Option<Base>,

    /// Identical to `out_base.is_some()`
    #[serde_as(deserialize_as = "DefaultOnNull")]
    #[serde(default)]
    pub is_out: bool,
    
    /// Ordinal of out in the game. `None` if the runner was not called out. Otherwise 1, 2, or 3.
    pub out_number: Option<usize>,
}

/// Details about the runner's movement
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct RunnerDetails {
    /// `None` represents completely unforced movement, such as hitting a single with no-one on.
    pub movement_reason: Option<MovementReason>,
    pub runner: NamedPerson,
    pub is_scoring_event: bool,
    #[serde(rename = "rbi")]
    pub is_rbi: bool,
    #[serde(rename = "earned")]
    pub is_earned: bool,

    // Same as [`PlayDetails`].event
    #[doc(hidden)]
    #[serde(rename = "eventType", default)]
    pub __event_tyoe: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "event", default)]
    pub __event_type: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "responsiblePitcher", default)]
    pub __responsible_pitcher: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "teamUnearned", default)]
    pub __team_unearned: IgnoredAny,
    
    #[doc(hidden)]
    #[serde(rename = "playIndex", default)]
    pub __play_index: IgnoredAny,
}

/// Reasons for baserunner movement
#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Display)]
pub enum MovementReason {
    //// Unforced base advancement, such as going first to third on a single.
    #[display("Unforced Base Advancement")]
    #[serde(rename = "r_adv_play")]
    AdvancementUnforced,
    
    /// Forced base advancement, such as moving up one base on a single.
    #[display("Forced Base Advancement")]
    #[serde(rename = "r_adv_force")]
    AdancementForced,

    /// Advancement from a choice in throwing, such as throwing home and allowing this runner to move up a base instead.
    #[display("Advancement from Throw")]
    #[serde(rename = "r_adv_throw")]
    AdvancementThrow,

    /// Runner fails to tag up and is forced out.
    #[display("Doubled Off")]
    #[serde(rename = "r_doubled_off")]
    DoubledOff,

    #[display("Thrown Out")]
    #[serde(rename = "r_thrown_out")]
    ThrownOut,

    #[display("Called Out Returning")]
    #[serde(rename = "r_out_returning")]
    CalledOutReturning,
        
    /// Standard force-out.
    #[display("Forced Out")]
    #[serde(rename = "r_force_out")]
    ForceOut,

    /// Deviation from the basepath, etc.
    #[display("Runner Called Out")]
    #[serde(rename = "r_runner_out")]
    RunnerCalledOut,

    /// A Stolen Base with no throw.
    #[display("Defensive Indifference")]
    #[serde(rename = "r_defensive_indiff")]
    DefensiveIndifference,

    #[display("Rundown")]
    #[serde(rename = "r_rundown")]
    Rundown,

    /// Stretching a single into a double.
    #[display("Out Stretching")]
    #[serde(rename = "r_out_stretching")]
    OutStretching,

    #[display("Stolen Base (2B)")]
    #[serde(rename = "r_stolen_base_2b")]
    StolenBase2B,

    #[display("Stolen Base (3B)")]
    #[serde(rename = "r_stolen_base_3b")]
    StolenBase3B,

    #[display("Stolen Base (HP)")]
    #[serde(rename = "r_stolen_base_home")]
    StolenBaseHome,

    #[display("Caught Stealing (2B)")]
    #[serde(rename = "r_caught_stealing_2b")]
    CaughtStealing2B,

    #[display("Caught Stealing (3B)")]
    #[serde(rename = "r_caught_stealing_3b")]
    CaughtStealing3B,

    #[display("Caught Stealing (HP)")]
    #[serde(rename = "r_caught_stealing_home")]
    CaughtStealingHome,
    
    /// Successful pickoff
    #[display("Pickoff (1B)")]
    #[serde(rename = "r_pickoff_1b")]
    Pickoff1B,
    
    /// Successful pickoff
    #[display("Pickoff (2B)")]
    #[serde(rename = "r_pickoff_2b")]
    Pickoff2B,
    
    /// Successful pickoff
    #[display("Pickoff (3B)")]
    #[serde(rename = "r_pickoff_3b")]
    Pickoff3B,
    
    #[display("Pickoff (Error) (1B)")]
    #[serde(rename = "r_pickoff_error_1b")]
    PickoffError1B,
    
    #[display("Pickoff (Error) (2B)")]
    #[serde(rename = "r_pickoff_error_2b")]
    PickoffError2B,
    
    #[display("Pickoff (Error) (3B)")]
    #[serde(rename = "r_pickoff_error_3b")]
    PickoffError3B,

    #[display("Pickoff (Caught Stealing) (2B)")]
    #[serde(rename = "r_pickoff_caught_stealing_2b")]
    PickoffCaughtStealing2B,
    
    #[display("Pickoff (Caught Stealing) (3B)")]
    #[serde(rename = "r_pickoff_caught_stealing_3b")]
    PickoffCaughtStealing3B,
    
    #[display("Pickoff (Caught Stealing) (HP)")]
    #[serde(rename = "r_pickoff_caught_stealing_home")]
    PickoffCaughtStealingHome,

    /// General interference
    #[display("Interference")]
    #[serde(rename = "r_interference")]
    Interference,

    #[display("Hit By Ball")]
    #[serde(rename = "r_hbr")]
    HitByBall,
}

impl MovementReason {
    /// If the movement reason is a pickoff
    #[must_use]
    pub const fn is_pickoff(self) -> bool {
        matches!(self, Self::Pickoff1B | Self::Pickoff2B | Self::Pickoff3B | Self::PickoffError1B | Self::PickoffError2B | Self::PickoffError3B | Self::PickoffCaughtStealing2B | Self::PickoffCaughtStealing3B | Self::PickoffCaughtStealingHome)
    }

    /// If the movement reason is a stolen base attempt
    #[must_use]
    pub const fn is_stolen_base_attempt(self) -> bool {
        matches!(self, Self::StolenBase2B | Self::StolenBase3B | Self::StolenBaseHome | Self::CaughtStealing2B | Self::CaughtStealing3B | Self::CaughtStealingHome | Self::PickoffCaughtStealing2B | Self::PickoffCaughtStealing3B | Self::PickoffCaughtStealingHome)
    }

    /// If the movement reason is a stolen base
    #[must_use]
    pub const fn is_stolen_base(self) -> bool {
        matches!(self, Self::StolenBase2B | Self::StolenBase3B | Self::StolenBaseHome)
    }
}

/// Fielder credits to outs
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct RunnerCredit {
    pub player: PersonId,
    pub position: NamedPosition,
    pub credit: CreditKind,
}

/// Statistical credits to fielders; putouts, assists, etc.
#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Display)]
pub enum CreditKind {
    #[display("Putout")]
    #[serde(rename = "f_putout")]
    Putout,
    
    #[display("Assist")]
    #[serde(rename = "f_assist")]
    Assist,
    
    #[display("Outfield Assist")]
    #[serde(rename = "f_assist_of")]
    OutfieldAssist,
    
    /// The fielder just, fielded the ball, no outs or anything.
    #[display("Fielded Ball")]
    #[serde(rename = "f_fielded_ball")]
    FieldedBall,
    
    #[display("Fielding Error")]
    #[serde(rename = "f_fielding_error")]
    FieldingError,
    
    #[display("Throwing Error")]
    #[serde(rename = "f_throwing_error")]
    ThrowingError,
    
    #[display("Deflection")]
    #[serde(rename = "f_deflection")]
    Deflection,

    /// They literally touched it, no deflection, just a tap.
    #[display("Touch")]
    #[serde(rename = "f_touch")]
    Touch,

    #[display("Dropped Ball Error")]
    #[serde(rename = "f_error_dropped_ball")]
    DroppedBallError,

    #[display("Defensive Shift Violation")]
    #[serde(rename = "f_defensive_shift_violation_error")]
    DefensiveShiftViolation,

    #[display("Interference")]
    #[serde(rename = "f_interference")]
    Interference,

    #[display("Catcher's Interference")]
    #[serde(rename = "c_catcher_interf")]
    CatchersInterference,
}

/// # Errors
/// See `D::Error`, likely [`serde_json::Error`]
pub fn deserialize_review_data<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<ReviewData>, D::Error> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
    struct RawReviewData {
        #[serde(flatten)]
        base: ReviewData,
        #[serde(default)]
        additional_reviews: Vec<ReviewData>,
    }

    let RawReviewData { base, mut additional_reviews } = RawReviewData::deserialize(deserializer)?;
    additional_reviews.insert(0, base);
    Ok(additional_reviews)
}

/// Data regarding replay reviews; present on [`Play`], not [`PlayEvent`].
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct ReviewData {
    pub is_overturned: bool,
    #[serde(rename = "inProgress")]
    pub is_in_progress: bool,
    pub review_type: ReviewReasonId,
    /// If `None`, then a crew-chief review.
    #[serde(alias = "challengeTeamId")]
    pub challenging_team: Option<TeamId>,
    /// For ABS challenges
    pub player: Option<NamedPerson>,
}

/// An "indivisible" play, such as pickoff, pitch, stolen base, etc.
#[allow(clippy::large_enum_variant, reason = "not a problemo dw")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all_fields = "camelCase", tag = "type")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub enum PlayEvent {
    #[serde(rename = "action")]
    Action {
        details: ActionPlayDetails,
        #[serde(rename = "actionPlayId")]
        play_id: Option<Uuid>,
        
        #[serde(flatten)]
        common: PlayEventCommon,
    },
    #[serde(rename = "pitch")]
    Pitch {
        details: PitchPlayDetails,
        pitch_data: Option<PitchData>,
        hit_data: Option<HitData>,
        /// Starts at 1
        #[serde(rename = "pitchNumber")]
        pitch_ordinal: usize,
        play_id: Uuid,

        #[serde(flatten)]
        common: PlayEventCommon,
    },
    #[serde(rename = "stepoff")]
    Stepoff {
        details: StepoffPlayDetails,
        play_id: Option<Uuid>,
        
        #[serde(flatten)]
        common: PlayEventCommon,
    },
    #[serde(rename = "no_pitch")]
    NoPitch {
        details: NoPitchPlayDetails,
        play_id: Option<Uuid>,
        /// Starts at 1
        #[serde(rename = "pitchNumber", default)]
        pitch_ordinal: usize,

        #[serde(flatten)]
        common: PlayEventCommon,
    },
    #[serde(rename = "pickoff")]
    Pickoff {
        details: PickoffPlayDetails,
        #[serde(alias = "actionPlayId", default)]
        play_id: Option<Uuid>,

        #[serde(flatten)]
        common: PlayEventCommon,
    }
}

impl Deref for PlayEvent {
    type Target = PlayEventCommon;

    fn deref(&self) -> &Self::Target {
        let (Self::Action { common, .. } | Self::Pitch { common, .. } | Self::Stepoff { common, .. } | Self::NoPitch { common, .. } | Self::Pickoff { common, .. }) = self;
        common
    }
}

impl DerefMut for PlayEvent {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let (Self::Action { common, .. } | Self::Pitch { common, .. } | Self::Stepoff { common, .. } | Self::NoPitch { common, .. } | Self::Pickoff { common, .. }) = self;
        common
    }
}

#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PlayEventCommon {
    /// At the end of the play event
    pub count: AtBatCount,
    #[serde(rename = "startTime", deserialize_with = "crate::deserialize_datetime")]
    pub start_timestamp: DateTime<Utc>,
    #[serde(rename = "endTime", deserialize_with = "crate::deserialize_datetime")]
    pub end_timestamp: DateTime<Utc>,
    pub is_pitch: bool,
    #[serde(rename = "isBaseRunningPlay", default)]
    pub is_baserunning_play: bool,
    /// Pitching Subsitution, Defensive Switches, Pinch Hitting, etc.
    #[serde(default)]
    pub is_substitution: bool,

    /// A player involved in the play.
    pub player: Option<PersonId>,
    /// An umpire involved in the play, ex: Ejection
    pub umpire: Option<PersonId>,
    /// Position (typically a complement of ``player``)
    pub position: Option<NamedPosition>,
    /// Also not always present, check by the [`EventType`]; [`PitchingSubsitution`](EventType::PitchingSubstitution)s don't have it.
    pub replaced_player: Option<PersonId>,
    /// Batting Order Index, typically supplied with a [`DefensiveSwitch`](EventType::DefensiveSwitch) or [`OffensiveSubstitution`](EventType::OffensiveSubstitution)
    #[serde(rename = "battingOrder")]
    pub batting_order_index: Option<BattingOrderIndex>,
    /// Base correlated with play, such as a stolen base
    pub base: Option<Base>,
    #[serde(rename = "reviewDetails", default, deserialize_with = "deserialize_review_data")]
    pub reviews: Vec<ReviewData>,
    pub injury_type: Option<String>,
    
    #[doc(hidden)]
    #[serde(rename = "index", default)]
    pub __index: IgnoredAny,
}

#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct ActionPlayDetails {
    #[serde(rename = "eventType")]
    pub event: EventType,
    /// Shohei Ohtani strikes out swinging.
    pub description: String,

    /// Score as of the end of the play
    pub away_score: usize,
    /// Score as of the end of the play
    pub home_score: usize,

    /// Whether the batter in the play is out
    pub is_out: bool,
    pub is_scoring_play: bool,
    #[serde(default)]
    pub has_review: bool,

    #[serde(rename = "disengagementNum", default)]
    pub disengagements: Option<NonZeroUsize>,
    
    #[doc(hidden)]
    #[serde(rename = "event", default)]
    pub __event: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "type", default)]
    pub __type: IgnoredAny,

    // redundant
    #[doc(hidden)]
    #[serde(rename = "violation", default)]
    pub __violation: IgnoredAny,
}

#[allow(clippy::struct_excessive_bools, reason = "inapplicable")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PitchPlayDetails {
    pub is_in_play: bool,
    pub is_strike: bool,
    pub is_ball: bool,
    pub is_out: bool,
    #[serde(default)]
    pub has_review: bool,
    #[serde(default)]
    pub runner_going: bool,
    #[serde(rename = "disengagementNum", default)]
    pub disengagements: Option<NonZeroUsize>,
    
    #[serde(rename = "type", deserialize_with = "crate::meta::fallback_pitch_type_deserializer", default = "crate::meta::unknown_pitch_type")]
    pub pitch_type: PitchType,

    pub call: PitchCodeId,

    #[doc(hidden)]
    #[serde(rename = "ballColor", default)]
    pub __ball_color: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "trailColor", default)]
    pub __trail_color: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "description", default)]
    pub __description: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "code", default)]
    pub __code: IgnoredAny,

    // redundant
    #[doc(hidden)]
    #[serde(rename = "violation", default)]
    pub __violation: IgnoredAny,
}

#[allow(clippy::struct_excessive_bools, reason = "inapplicable")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct StepoffPlayDetails {
    pub description: String,
    /// Typically "PSO" - "Pitcher Step Off"
    pub code: PitchCodeId,
    pub is_out: bool,
    #[serde(default)]
    pub has_review: bool,
    /// Catcher-called mound disengagement.
    pub from_catcher: bool,
    #[serde(rename = "disengagementNum", default)]
    pub disengagements: Option<NonZeroUsize>,

    // redundant
    #[doc(hidden)]
    #[serde(rename = "violation", default)]
    pub __violation: IgnoredAny,
}

#[allow(clippy::struct_excessive_bools, reason = "inapplicable")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct NoPitchPlayDetails {
    #[serde(default)]
    pub is_in_play: bool,
    #[serde(default)]
    pub is_strike: bool,
    #[serde(default)]
    pub is_ball: bool,
    pub is_out: bool,
    #[serde(default)]
    pub has_review: bool,
    #[serde(default)]
    pub runner_going: bool,

    #[serde(default = "crate::meta::unknown_pitch_code")]
    pub call: PitchCodeId,

    #[serde(rename = "disengagementNum", default)]
    pub disengagements: Option<NonZeroUsize>,
    
    #[doc(hidden)]
    #[serde(rename = "description", default)]
    pub __description: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "code", default)]
    pub __code: IgnoredAny,

    // redundant
    #[doc(hidden)]
    #[serde(rename = "violation", default)]
    pub __violation: IgnoredAny,
}

#[allow(clippy::struct_excessive_bools, reason = "inapplicable")]
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PickoffPlayDetails {
    pub description: String,
    /// Typically "1" - "Pickoff Attempt 1B", "2" - "Pickoff Attempt 2B", "3" - "Pickoff Attempt 3B"
    pub code: PitchCodeId,
    pub is_out: bool,
    #[serde(default)]
    pub has_review: bool,
    /// Catcher-called pickoff.
    pub from_catcher: bool,

    #[serde(rename = "disengagementNum", default)]
    pub disengagements: Option<NonZeroUsize>,

    // redundant
    #[doc(hidden)]
    #[serde(rename = "violation", default)]
    pub __violation: IgnoredAny,
}

/// Statistical data regarding a pitch.
///
/// Some acronyms are an existing spec, best to keep with that.
#[allow(non_snake_case, reason = "spec")]
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct PitchData {
    /// Velocity measured at release, measured in mph
    pub release_speed: f64,
    /// Velocity measured crossing home plate, measured in mph
    pub plate_speed: f64,
    
    /// Height above home plate for the bottom of the hitter's strike zone
    ///
    /// Measured in feet.
    pub sz_bot: f64,
    /// Height above home plate for the top of the hitter's strike zone
    ///
    /// Measured in feet.
    pub sz_top: f64,
    /// Width of the strike zone
    ///
    /// Measured in inches.
    pub sz_wid: f64,
    /// Depth of the strike zone
    ///
    /// Measured in inches.
    pub sz_dep: f64,
    
    /// Acceleration of the pitch near release, horizontal movement axis,
    /// catchers perspective (positive means RHP sweep)
    /// 
    /// Measured in feet/s^2.
    pub aX: f64,
    /// Acceleration of the pitch near release, depth axis,
    /// catchers perspective (positive means deceleration)
    /// 
    /// Measured in feet/s^2.
    pub aY: f64,
    /// Acceleration of the pitch near release, vertical movement axis,
    /// catchers perspective (positive means literal carry)
    ///
    /// Measured in feet/s^2.
    pub aZ: f64,
    
    /// Might be broken, use ``horizontal_movement`` instead
    ///
    /// Horizontal movement of the pitch between the release point and home plate,
    /// catchers perspective (positive means RHP sweep)
    /// as compared to a theoretical pitch thrown at with the same velocity vector
    /// and no spin-induced movement.
    /// This parameter is measured at y=40 feet regardless of the y0 value.
    /// 
    /// Measured in inches.
    ///
    /// Does not account for seam-shifted wake!
    pub pfxX: f64,
    /// Might be broken, use ``vertical_drop`` instead
    ///
    /// Vertical movement of the pitch between the release point and home plate,
    /// catchers perspective (positive means literal rise),
    /// as compared to a theoretical pitch thrown at with the same velocity vector
    /// and no spin-induced movement.
    /// This parameter is measured at y=40 feet regardless of the y0 value.
    /// 
    /// Measured in inches.
    ///
    /// Does not account for seam-shifted wake!
    pub pfxZ: f64,

    /// Horizontal coordinate of the pitch as it crosses home plate, 0 is the middle of the plate.
    /// Catchers perspective, positive means arm-side for a RHP, negative means glove-side for a RHP.
    /// 
    /// Measured in feet.
    pub pX: f64,
    /// Vertical coordinate of the pitch as it crosses home plate, 0 is the plate itself
    /// 
    /// Measured in feet.
    pub pZ: f64,

    /// Horizontal component of velocity out of the hand, catchers perspective, positive means RHP glove-side.
    ///
    /// Measured in feet per second.
    pub vX0: f64,
    /// Depth component of velocity out of the hand, catchers perspective, positive means the ball isn't going into centerfield.
    ///
    /// Measured in feet per second.
    pub vY0: f64,
    /// Vertical component of velocity out of the hand, measured in feet per second.
    ///
    /// Measured in feet per second.
    pub vZ0: f64,

    /// X coordinate of pitch at release
    ///
    /// Measured in feet
    pub x0: f64,
    /// Y coordinate of pitch at release, typically as close to 50 as possible.
    ///
    /// Measured in feet
    pub y0: f64,
    /// Z coordinate of pitch at release
    ///
    /// Measured in feet
    pub z0: f64,

    /// No clue.
    pub x: f64,
    /// No clue.
    pub y: f64,

    /// No clue. Does not match theta angle of induced break vector. Consistently 36.0. Strange.
    pub break_angle: f64,
    /// No clue. Does not match length of induced break vector.
    pub break_length: f64,

    /// Standard metric, amount of vertical movement induced.
    ///
    /// Measured in inches
    pub induced_vertical_movement: f64,
    /// Standard metric, amount of vertical movement the pitch has (including gravity).
    ///
    /// Measured in inches
    pub vertical_drop: f64,
    /// Standard metric, amount of horizontal movement the pitch has.
    ///
    /// Measured in inches
    pub horizontal_movement: f64,
    /// No clue. Thought to be the amount of depth-based movement (acceleration), but it's consistently 24.0. Strange.
    pub depth_break: f64,
    
    /// RPMs out of the hand
    pub spin_rate: f64,

    /// Measured in degrees.
    ///
    /// 0 means complete topspin.
    /// 180 means complete backspin.
    /// 90 means complete sidespin (RHP sweeper).
    /// 270 means complete sidespin (elite RHP changeup).
    /// 
    /// ~225 is your average RHP fastball.
    pub spin_axis: f64,

    pub zone: StrikeZoneSection,

    /// AI model confidence about pitch type designation.
    ///
    /// Sometimes greater than 1.0
    pub type_confidence: f64,

    /// Time from out of the hand to crossing the plate.
    ///
    /// Measured in seconds
    pub time_to_plate: f64,

    /// Extension
    ///
    /// Measured in feet
    pub extension: f64,
}

impl<'de> Deserialize<'de> for PitchData {
    #[allow(clippy::too_many_lines, reason = "deserialization is hard")]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>
    {
        #[must_use]
        const fn default_strike_zone_width() -> f64 {
            17.0
        }

        #[must_use]
        const fn default_strike_zone_depth() -> f64 {
            17.0
        }

        #[must_use]
        const fn default_nan() -> f64 {
            f64::NAN
        }

        #[must_use]
        const fn default_strike_zone_section() -> StrikeZoneSection {
            StrikeZoneSection::MiddleMiddle
        }
        
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        #[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
        struct Raw {
            #[serde(default = "default_nan")]
            start_speed: f64,
            #[serde(default = "default_nan")]
            end_speed: f64,
            #[serde(default = "default_nan")]
            strike_zone_top: f64,
            #[serde(default = "default_nan")]
            strike_zone_bottom: f64,
            #[serde(default = "default_strike_zone_width")]
            strike_zone_width: f64,
            #[serde(default = "default_strike_zone_depth")]
            strike_zone_depth: f64,
            coordinates: RawCoordinates,
            breaks: RawBreaks,
            #[serde(default = "default_strike_zone_section")]
            zone: StrikeZoneSection,
            #[serde(default = "default_nan")]
            type_confidence: f64,
            #[serde(default = "default_nan")]
            plate_time: f64,
            #[serde(default = "default_nan")]
            extension: f64,
        }

        #[allow(non_snake_case, reason = "spec")]
        #[derive(Deserialize)]
        #[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
        struct RawCoordinates {
            #[serde(default = "default_nan")]
            aX: f64,
            #[serde(default = "default_nan")]
            aY: f64,
            #[serde(default = "default_nan")]
            aZ: f64,
            #[serde(default = "default_nan")]
            pfxX: f64,
            #[serde(default = "default_nan")]
            pfxZ: f64,
            #[serde(default = "default_nan")]
            pX: f64,
            #[serde(default = "default_nan")]
            pZ: f64,
            #[serde(default = "default_nan")]
            vX0: f64,
            #[serde(default = "default_nan")]
            vY0: f64,
            #[serde(default = "default_nan")]
            vZ0: f64,
            #[serde(default = "default_nan")]
            x: f64,
            #[serde(default = "default_nan")]
            y: f64,
            #[serde(default = "default_nan")]
            x0: f64,
            #[serde(default = "default_nan")]
            y0: f64,
            #[serde(default = "default_nan")]
            z0: f64,
        }

        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        #[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
        struct RawBreaks {
            #[serde(default = "default_nan")]
            break_angle: f64,
            #[serde(default = "default_nan")]
            break_length: f64,
            #[serde(default = "default_nan")]
            break_y: f64,
            #[serde(default = "default_nan")]
            break_vertical: f64,
            #[serde(default = "default_nan")]
            break_vertical_induced: f64,
            #[serde(default = "default_nan")]
            break_horizontal: f64,
            #[serde(default = "default_nan")]
            spin_rate: f64,
            #[serde(default = "default_nan")]
            spin_direction: f64,
        }

        let Raw {
            start_speed,
            end_speed,
            strike_zone_top,
            strike_zone_bottom,
            strike_zone_width,
            strike_zone_depth,
            coordinates: RawCoordinates {
                pfxX,
                pfxZ,
                aX,
                aY,
                aZ,
                pX,
                pZ,
                vX0,
                vY0,
                vZ0,
                x,
                y,
                x0,
                y0,
                z0,
            },
            breaks: RawBreaks {
                break_angle,
                break_length,
                break_y,
                break_vertical,
                break_vertical_induced,
                break_horizontal,
                spin_rate,
                spin_direction,
            },
            zone,
            type_confidence,
            plate_time,
            extension,
        } =  Raw::deserialize(deserializer)?;

        Ok(Self {
            release_speed: start_speed,
            plate_speed: end_speed,
            sz_bot: strike_zone_bottom,
            sz_top: strike_zone_top,
            sz_wid: strike_zone_width,
            sz_dep: strike_zone_depth,
            aX,
            aY,
            aZ,
            pfxX,
            pfxZ,
            pX,
            pZ,
            vX0,
            vY0,
            vZ0,
            x0,
            y0,
            z0,
            horizontal_movement: break_horizontal,
            x,
            y,
            break_angle,
            break_length,
            induced_vertical_movement: break_vertical_induced,
            vertical_drop: break_vertical,
            depth_break: break_y,
            spin_rate,
            spin_axis: spin_direction,
            zone,
            type_confidence,
            time_to_plate: plate_time,
            extension,
        })
    }
}

/// Data regarding batted-balls
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(from = "__HitDataStruct")]
pub struct HitData {
    /// sometimes just takes a second to be present
    pub hit_trajectory: Option<HitTrajectory>,
    /// sometimes just takes a second to be present
    pub contact_hardness: Option<ContactHardness>,
    pub statcast: Option<StatcastHitData>,
}

#[serde_as]
#[doc(hidden)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
struct __HitDataStruct {
    #[serde_as(deserialize_as = "DefaultOnError")]
    #[serde(rename = "trajectory", default)]
    hit_trajectory: Option<HitTrajectory>,
    #[serde(rename = "hardness", default)]
    contact_hardness: Option<ContactHardness>,

    #[serde(flatten, default)]
    statcast: Option<StatcastHitData>,

    #[doc(hidden)]
    #[serde(rename = "location", default)]
    __location: IgnoredAny,

    #[doc(hidden)]
    #[serde(rename = "coordinates")]
    __coordinates: IgnoredAny,
}

impl From<__HitDataStruct> for HitData {
    fn from(__HitDataStruct { hit_trajectory, contact_hardness, statcast, .. }: __HitDataStruct) -> Self {
        Self {
            hit_trajectory: hit_trajectory.or_else(|| statcast.as_ref().map(|statcast| statcast.launch_angle).map(HitTrajectory::from_launch_angle)),
            contact_hardness,
            statcast,
        }
    }
}

/// Statcast data regarding batted balls, only sometimes present.
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct StatcastHitData {
    /// Speed of the ball as it leaves the bat
    ///
    /// Measured in mph
    #[serde(rename = "launchSpeed")]
    pub exit_velocity: f64,
    /// Vertical Angle in degrees at which the ball leaves the bat.
    ///
    /// Measured in degrees
    pub launch_angle: f64,

    /// Distance the ball travels before being caught or rolling.
    ///
    /// Measured in feet
    #[serde(rename = "totalDistance")]
    pub distance: f64,
}

#[derive(Builder)]
#[builder(derive(Into))]
pub struct PlayByPlayRequest {
    #[builder(into)]
    id: GameId,
}

impl<S: play_by_play_request_builder::State + play_by_play_request_builder::IsComplete> crate::request::RequestURLBuilderExt for PlayByPlayRequestBuilder<S> {
    type Built = PlayByPlayRequest;
}

impl Display for PlayByPlayRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "http://statsapi.mlb.com/api/v1/game/{}/playByPlay", self.id)
    }
}

impl RequestURL for PlayByPlayRequest {
    type Response = Plays;
}

#[cfg(test)]
mod tests {
    use crate::TEST_YEAR;
    use crate::game::PlayByPlayRequest;
    use crate::meta::GameType;
    use crate::request::RequestURLBuilderExt;
    use crate::schedule::ScheduleRequest;
    use crate::season::{Season, SeasonsRequest};
    use crate::sport::SportId;

    #[tokio::test]
    async fn ws_gm7_2025_pbp() {
        let _ = PlayByPlayRequest::builder().id(813_024).build_and_get().await.unwrap();
    }

    #[tokio::test]
    async fn postseason_pbp() {
        let [season]: [Season; 1] = SeasonsRequest::builder().season(TEST_YEAR).sport_id(SportId::MLB).build_and_get().await.unwrap().seasons.try_into().unwrap();
		let postseason = season.postseason.expect("Expected the MLB to have a postseason");
		let games = ScheduleRequest::<()>::builder().date_range(postseason).sport_id(SportId::MLB).build_and_get().await.unwrap();
		let games = games.dates.into_iter().flat_map(|date| date.games).filter(|game| game.game_type.is_postseason()).map(|game| game.game_id).collect::<Vec<_>>();
		let mut has_errors = false;
		for game in games {
			if let Err(e) = PlayByPlayRequest::builder().id(game).build_and_get().await {
			    dbg!(e);
			    has_errors = true;
			}
		}
		assert!(!has_errors, "Has errors.");
    }

    #[cfg_attr(not(feature = "_heavy_tests"), ignore)]
    #[tokio::test]
    async fn regular_season_pbp() {
        let [season]: [Season; 1] = SeasonsRequest::builder().season(TEST_YEAR).sport_id(SportId::MLB).build_and_get().await.unwrap().seasons.try_into().unwrap();
        let regular_season = season.regular_season;
        let games = ScheduleRequest::<()>::builder().date_range(regular_season).sport_id(SportId::MLB).build_and_get().await.unwrap();
        let games = games.dates.into_iter().flat_map(|date| date.games).filter(|game| game.game_type == GameType::RegularSeason).collect::<Vec<_>>();
        let mut has_errors = false;
        for game in games {
            if let Err(e) = PlayByPlayRequest::builder().id(game.game_id).build_and_get().await {
                dbg!(e);
                has_errors = true;
            }
        }
        assert!(!has_errors, "Has errors.");
    }
}