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
//! The thing you're most likely here for.
//!
//! This module itself acts like [`crate::types`] but for misc game-specific types as there are many.

#![allow(unused_imports, reason = "usage of children modules")]

use std::fmt::{Display, Formatter};
use std::marker::PhantomData;
use std::ops::{ControlFlow, Sub};
use std::time::{Duration, Instant};
use bon::Builder;
use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use derive_more::{Deref, DerefMut, Display, From, Not};
use fxhash::FxHashMap;
use serde::{Deserialize, Deserializer};
use serde::de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor};
use serde_with::{serde_as, DisplayFromStr};
use crate::person::{Ballplayer, JerseyNumber, NamedPerson, PersonId};
use crate::meta::{DayNight, NamedPosition};
use crate::request::RequestURLBuilderExt;
use crate::team::TeamId;
use crate::team::roster::RosterStatus;
use crate::{DayHalf, HomeAway, ResourceUsage, ResultHoldingResourceUsage, TeamSide};
use crate::meta::WindDirectionId;
use crate::request;

mod boxscore; // done
mod changes;
mod content;
mod context_metrics;
mod diff;
mod linescore; // done
mod pace; // done
mod plays; // done
mod timestamps; // done
mod uniforms;
mod win_probability;
mod live_feed; // done

pub use boxscore::*;
pub use changes::*;
pub use content::*;
pub use context_metrics::*;
pub use diff::*;
pub use linescore::*;
pub use pace::*;
pub use plays::*;
pub use timestamps::*;
pub use uniforms::*;
pub use win_probability::*;
pub use live_feed::*;

id!(#[doc = "A [`u32`] representing a baseball game. [Sport](crate::sport)-independent"] GameId { gamePk: u32 });

/// Date & Time of the game. 
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct GameDateTime {
	/// The date and time of the game. Note that the time is typically rounded to the hour and the :07, :05 on the hour is for the first pitch, which is a different timestamp.
	#[serde(rename = "dateTime", deserialize_with = "crate::deserialize_datetime")]
	pub datetime: DateTime<Utc>,
	/// The original planned date of the game
	pub original_date: NaiveDate,
	/// The currently set "date" of the game.
	pub official_date: NaiveDate,
	/// Data regarding the game's paused resumption
	#[serde(flatten, default)]
	pub resumed: Option<GameResumedDateTime>,
	
	/// Day or night
	#[serde(rename = "dayNight")]
	pub sky: DayNight,
	/// The local 12-hour time of the game
	pub time: NaiveTime,
	/// AM or PM; use [`DayHalf::into_24_hour_time`] to convert to 24-hour local time.
	pub ampm: DayHalf,
}

/// Optional resumed data regarding a paused game
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct GameResumedDateTime {
	#[serde(rename = "resumeDateTime", deserialize_with = "crate::deserialize_datetime")]
	pub resumed_datetime: DateTime<Utc>,
	#[serde(rename = "resumedFromDateTime", deserialize_with = "crate::deserialize_datetime")]
	pub resumed_from_datetime: DateTime<Utc>,

	#[serde(rename = "resumeDate", default)]
	pub __resume_date: IgnoredAny,
	#[serde(rename = "resumeFromDate", default)]
	pub __resume_from_date: IgnoredAny,
}

/// General weather conditions, temperature, wind, etc.
#[derive(Debug, Deserialize, PartialEq, Clone, Default)]
#[serde(try_from = "__WeatherConditionsStruct")]
pub struct WeatherConditions {
	pub condition: Option<String>,
	pub temp: Option<uom::si::f64::ThermodynamicTemperature>,
	pub wind: Option<(uom::si::f64::Velocity, WindDirectionId)>,
}

#[derive(Deserialize)]
#[doc(hidden)]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
struct __WeatherConditionsStruct {
	condition: Option<String>,
	temp: Option<String>,
	wind: Option<String>,
}

impl TryFrom<__WeatherConditionsStruct> for WeatherConditions {
	type Error = &'static str;

	fn try_from(value: __WeatherConditionsStruct) -> Result<Self, Self::Error> {
		Ok(Self {
			condition: value.condition,
			temp: value.temp.and_then(|temp| temp.parse::<i32>().ok()).map(|temp| uom::si::f64::ThermodynamicTemperature::new::<uom::si::thermodynamic_temperature::degree_fahrenheit>(temp as f64)),
			wind: if let Some(wind) = value.wind {
				let (speed, direction) = wind.split_once(" mph, ").ok_or("invalid wind format")?;
				let speed = speed.parse::<i32>().map_err(|_| "invalid wind speed")?;
				Some((uom::si::f64::Velocity::new::<uom::si::velocity::mile_per_hour>(speed as f64), WindDirectionId::new(direction)))
			} else { None },
		})
	}
}

/// Misc
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct GameInfo {
	pub attendance: Option<u32>,
	#[serde(deserialize_with = "crate::try_deserialize_datetime", default)]
	pub first_pitch: Option<DateTime<Utc>>,
	/// Measured in minutes,
	#[serde(rename = "gameDurationMinutes")]
	pub game_duration: Option<u32>,
	/// Durationg of the game delay; measured in minutes.
	#[serde(rename = "delayDurationMinutes")]
	pub delay_duration: Option<u32>,
}

/// Review usage for each team and if the game supports challenges.
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct TeamReviewData {
	pub has_challenges: bool,
	#[serde(flatten)]
	pub teams: HomeAway<ResourceUsage>,
}

#[derive(Debug, Deserialize, PartialEq, Eq, Clone, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct TeamChallengeData {
	pub has_challenges: bool,
	#[serde(flatten)]
	pub teams: HomeAway<ResultHoldingResourceUsage>,
}

/// Tags about a game, such as a perfect game in progress, no-hitter, etc.
#[allow(clippy::struct_excessive_bools, reason = "no")]
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct GameTags {
	pub no_hitter: bool,
	pub perfect_game: bool,

	pub away_team_no_hitter: bool,
	pub away_team_perfect_game: bool,

	pub home_team_no_hitter: bool,
	pub home_team_perfect_game: bool,
}

/// Double-header information.
#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
pub enum DoubleHeaderKind {
	#[serde(rename = "N")]
	/// Not a doubleheader
	Not,

	#[serde(rename = "Y")]
	/// First game in a double-header
	FirstGame,

	#[serde(rename = "S")]
	/// Second game in a double-header.
	SecondGame,
}

impl DoubleHeaderKind {
	#[must_use]
	pub const fn is_double_header(self) -> bool {
		matches!(self, Self::FirstGame | Self::SecondGame)
	}
}

#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq, Deref, DerefMut, From)]
pub struct Inning(usize);

impl Inning {
	/// Starting inning of a game
	#[must_use]
	pub const fn starting() -> Self {
		Self(1)
	}
}

impl Display for Inning {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		crate::write_nth(self.0, f)
	}
}

/// Half of the inning.
#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq, Not)]
pub enum InningHalf {
	#[serde(rename = "Top", alias = "top")]
	Top,
	#[serde(rename = "Bottom", alias = "bottom")]
	Bottom,
}

impl InningHalf {
	/// Starting inning half of a game
	#[must_use]
	pub const fn starting() -> Self {
		Self::Top
	}

	pub(crate) fn deserialize_from_is_top_inning<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
		Ok(match bool::deserialize(deserializer)? {
			true => Self::Top,
			false => Self::Bottom,
		})
	}
}

impl InningHalf {
	/// A unicode character representing an up or down arrow.
	#[must_use]
	pub const fn unicode_char_filled(self) -> char {
		match self {
			Self::Top => 'â–²',
			Self::Bottom => 'â–¼',
		}
	}
	
	/// A hollow character representing the inning half
	#[must_use]
	pub const fn unicode_char_empty(self) -> char {
		match self {
			Self::Top => 'â–³',
			Self::Bottom => 'â–½',
		}
	}

	/// Three ascii characters representing the inning half
	#[must_use]
	pub const fn three_char(self) -> &'static str {
		match self {
			Self::Top => "Top",
			Self::Bottom => "Bot",
		}
	}

	/// The team that bats in this inning half
	#[must_use]
	pub const fn bats(self) -> TeamSide {
		match self {
			Self::Top => TeamSide::Away,
			Self::Bottom => TeamSide::Home,
		}
	}

	/// The team that pitches in this inning half
	#[must_use]
	pub const fn pitches(self) -> TeamSide {
		match self {
			Self::Top => TeamSide::Home,
			Self::Bottom => TeamSide::Away,
		}
	}
}

/// The balls and strikes in a given at bat. Along with the number of outs (this technically can change during the AB due to pickoffs etc)
#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Display, Default)]
#[display("{balls}-{strikes} ({outs} out)")]
pub struct AtBatCount {
	#[serde(default)]
	pub balls: u8,
	#[serde(default)]
	pub strikes: u8,
	#[serde(default)]
	pub outs: u8,
}

#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
pub struct SituationCount {
	pub balls: u8,
	pub strikes: u8,
	pub outs: u8,
	pub inning: Inning,
	#[serde(rename = "isTopInning", deserialize_with = "InningHalf::deserialize_from_is_top_inning")]
	pub inning_half: InningHalf,
	#[serde(rename = "runnerOn1b")]
	pub runner_on_first: bool,
	#[serde(rename = "runnerOn2b")]
	pub runner_on_second: bool,
	#[serde(rename = "runnerOn3b")]
	pub runner_on_third: bool,
}

/// The classic "R | H | E" and LOB in a scoreboard.
#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
#[serde(from = "__RHEStruct")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct RHE {
	pub runs: usize,
	pub hits: usize,
	pub errors: usize,
	pub left_on_base: usize,
	/// Ex: Home team wins and doesn't need to play Bot 9.
	pub was_inning_half_played: bool,
}

#[doc(hidden)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct __RHEStruct {
	pub runs: Option<usize>,
	#[serde(default)]
    pub hits: usize,
    #[serde(default)]
    pub errors: usize,
    #[serde(default)]
    pub left_on_base: usize,

    // only sometimes present, regardless of whether a game is won
    #[doc(hidden)]
    #[serde(rename = "isWinner", default)]
    pub __is_winner: IgnoredAny,
}

impl From<__RHEStruct> for RHE {
	fn from(__RHEStruct { runs, hits, errors, left_on_base, .. }: __RHEStruct) -> Self {
		Self {
			runs: runs.unwrap_or(0),
			hits,
			errors,
			left_on_base,
			was_inning_half_played: runs.is_some(),
		}
	}
}

/// Unparsed miscellaneous data.
///
/// Some of these values might be handwritten per game so parsing them would prove rather difficult.
/// 
/// ## Examples
/// | Name          | Value     |
/// |---------------|-----------|
/// | First pitch   | 8:10 PM.  |
/// | Weather       | 68 degrees, Roof Closed |
/// | Att           | 44,713.   |
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct LabelledValue {
	pub label: String,
	#[serde(default)]
	pub value: String,
}

#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct SectionedLabelledValues {
	#[serde(rename = "title")]
	pub section: String,
	#[serde(rename = "fieldList")]
	pub values: Vec<LabelledValue>,
}

/// Various flags about the player in the current game
#[allow(clippy::struct_excessive_bools, reason = "not what's happening here")]
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct PlayerGameStatusFlags {
	pub is_current_batter: bool,
	pub is_current_pitcher: bool,
	pub is_on_bench: bool,
	pub is_substitute: bool,
}

#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct Official {
	pub official: NamedPerson,
	pub official_type: OfficialType,
}

#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
pub enum OfficialType {
	#[serde(rename = "Home Plate")]
	HomePlate,
	#[serde(rename = "First Base")]
	FirstBase,
	#[serde(rename = "Second Base")]
	SecondBase,
	#[serde(rename = "Third Base")]
	ThirdBase,
	#[serde(rename = "Left Field")]
	LeftField,
	#[serde(rename = "Right Field")]
	RightField,
}

/// A position in the batting order, 1st, 2nd, 3rd, 4th, etc.
///
/// Note that this number is split in two, the general batting order position is the `major` while if there is a lineup movement then the player would have an increased `minor` since they replace an existing batting order position.
///
/// Example:
/// Alice bats 1st (major = 1, minor = 0)
/// Bob pinch hits and bats 1st for Alice (major = 1, minor = 1)
/// Alice somehow hits again (major = 1, minor = 0)
/// Charlie pinch runs and takes over from then on (major = 1, minor = 2)
///
/// Note: These minors are [`Display`]ed incremented one more than is done internally, so (major = 1, minor = 1) displays as `1st (2)`.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct BattingOrderIndex {
	pub major: usize,
	pub minor: usize,
}

impl<'de> Deserialize<'de> for BattingOrderIndex {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
	    D: Deserializer<'de>
	{
		let v: usize = String::deserialize(deserializer)?.parse().map_err(D::Error::custom)?;
		Ok(Self {
			major: v / 100,
			minor: v % 100,
		})
	}
}

impl Display for BattingOrderIndex {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		crate::write_nth(self.major, f)?;
		if self.minor > 0 {
			write!(f, " ({})", self.minor + 1)?;
		}
		Ok(())
	}
}

/// Decisions of winner & loser (and potentially the save)
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct Decisions {
	pub winner: Option<NamedPerson>,
	pub loser: Option<NamedPerson>,
	pub save: Option<NamedPerson>,
}

/// Game records in stats like exit velocity, hit distance, etc.
///
/// Currently unable to actually get data for these though
#[derive(Debug, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "_debug", serde(deny_unknown_fields))]
pub struct GameStatLeaders {
	#[doc(hidden)]
	#[serde(rename = "hitDistance", default)]
	pub __distance: IgnoredAny,
	#[doc(hidden)]
	#[serde(rename = "hitSpeed", default)]
	pub __exit_velocity: IgnoredAny,
	#[doc(hidden)]
	#[serde(rename = "pitchSpeed", default)]
	pub __velocity: IgnoredAny,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Display)]
pub enum Base {
	#[display("1B")]
	First,
	#[display("2B")]
	Second,
	#[display("3B")]
	Third,
	#[display("HP")]
	Home,
}

impl<'de> Deserialize<'de> for Base {
	#[allow(clippy::too_many_lines, reason = "Visitor impl takes up the bulk, is properly scoped")]
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>
	{
		struct BaseVisitor;

		impl Visitor<'_> for BaseVisitor {
			type Value = Base;

			fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "a string or integer representing the base")
			}

			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
			where
				E: Error,
			{
				Ok(match v {
					"1B" | "1" => Base::First,
					"2B" | "2" => Base::Second,
					"3B" | "3" => Base::Third,
					"score" | "HP" | "4B" | "4" => Base::Home,
					_ => return Err(E::unknown_variant(v, &["1B", "1", "2B" , "2", "3B", "3", "score", "HP", "4B", "4"]))
				})
			}

			fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
			where
				E: Error,
			{
				Ok(match v {
					1 => Base::First,
					2 => Base::Second,
					3 => Base::Third,
					4 => Base::Home,
					_ => return Err(E::unknown_variant("[a number]", &["1", "2", "3", "4"]))
				})
			}
		}

		deserializer.deserialize_any(BaseVisitor)
	}
}

#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone)]
pub enum ContactHardness {
	#[serde(rename = "soft")]
	Soft,
	#[serde(rename = "medium")]
	Medium,
	#[serde(rename = "hard")]
	Hard,
}

pub(crate) fn deserialize_players_cache<'de, T: DeserializeOwned, D: Deserializer<'de>>(deserializer: D) -> Result<FxHashMap<PersonId, T>, D::Error> {
	struct PlayersCacheVisitor<T2: DeserializeOwned>(PhantomData<T2>);

	impl<'de2, T2: DeserializeOwned> serde::de::Visitor<'de2> for PlayersCacheVisitor<T2> {
		type Value = FxHashMap<PersonId, T2>;

		fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
			formatter.write_str("a map")
		}

		fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
		where
			A: MapAccess<'de2>,
		{
			let mut values = FxHashMap::default();

			while let Some((key, value)) = map.next_entry()? {
				let key: String = key;
				let key = PersonId::new(key.strip_prefix("ID").ok_or_else(|| A::Error::custom("invalid id format"))?.parse::<u32>().map_err(A::Error::custom)?);
				values.insert(key, value);
			}

			Ok(values)
		}
	}

	deserializer.deserialize_map(PlayersCacheVisitor::<T>(PhantomData))
}

/// Meant for active & live games, gives a streamable version of the plays in a game.
///
/// The [`PlayStream`] is meant to be for consistently polling the MLB API for live play-by-play updates.
/// The list of events can be seen on [`PlayStreamEvent`]
///
/// Note that the [`Linescore`] and [`Boxscore`] are not timed to the current state of the game as of the event, to achieve that it is recommended the timecode argument to live feed and iterate through the timecodes on its endpoint; however is much slower, or using diffPatch.
/// 
/// ## Examples
/// ```no_run
/// PlayStream::new(/* game id */).run(|event: PlayStreamEvent, meta: &LiveFeedMetadata, data: &LiveFeedData, linescore: &Linescore, boxscore: &Boxscore| {
///     match event {
///         PlayStreamEvent::Start => println!("Start"),
///         PlayStreamEvent::StartPlay(play) => println!("{} vs. {}", play.matchup.batter.full_name, play.matchup.pitcher.full_name),
///         PlayStreamEvent::PlayEvent(play_event, _play) => {
///             match play_event {
///                 PlayEvent::Action { details, .. } => println!("{}", details.description),
///                 PlayEvent::Pitch { details, common, .. } => println!("{} -> {}", details.call, common.count),
///                 PlayEvent::Stepoff { .. } => println!("Stepoff"),
///                 PlayEvent::NoPitch { .. } => println!("No Pitch"),
///                 PlayEvent::Pickoff { .. } => println!("Pickoff"),
///             }
///         },
///         PlayStreamEvent::PlayEventReviewStart(review, _play_event, _play) => println!("PlayEventReviewStart; {}", review.review_type),
///         PlayStreamEvent::PlayEventReviewEnd(review, _play_event, _play) => println!("PlayEventReviewEnd; {}", review.review_type),
///         PlayStreamEvent::PlayReviewStart(review, _play) => println!("PlayReviewStart; {}", review.review_type),
///         PlayStreamEvent::PlayReviewEnd(review, _play) => println!("PlayReviewEnd; {}", review.review_type),
///         PlayStreamEvent::EndPlay(play) => println!("{}", play.result.completed_play_details.as_ref().expect("Completed play").description),
///         PlayStreamEvent::GameEnd(_, _) => println!("GameEnd"),
///     }
/// }).await?;
/// ```
#[derive(Debug)]
pub struct PlayStream {
	game_id: GameId,

	current_play_idx: usize,
	in_progress_current_play: bool,
	current_play_review_idx: usize,
	in_progress_current_play_review: bool,
	
	current_play_event_idx: usize,
	current_play_event_review_idx: usize,
	in_progress_current_play_event_review: bool,
}

impl PlayStream {
	#[must_use]
	pub fn new(game_id: impl Into<GameId>) -> Self {
		Self {
			game_id: game_id.into(),
			
			current_play_idx: 0,
			in_progress_current_play: false,
			current_play_review_idx: 0,
			in_progress_current_play_review: false,
			
			current_play_event_idx: 0,
			current_play_event_review_idx: 0,
			in_progress_current_play_event_review: false,
		}
	}
}

/// An event in a game, such as the game starting, ending, a [`Play`] (At-Bat) starting, or a [`PlayEvent`] occuring, or a challenge on a play or play event.
#[derive(Debug, PartialEq, Clone)]
pub enum PlayStreamEvent<'a> {
	/// Sent at the beginning of a stream
	Start,
	
	StartPlay(&'a Play),
	PlayReviewStart(&'a ReviewData, &'a Play),
	PlayReviewEnd(&'a ReviewData, &'a Play),
	EndPlay(&'a Play),
	
	PlayEvent(&'a PlayEvent, &'a Play),
	PlayEventReviewStart(&'a ReviewData, &'a PlayEvent, &'a Play),
	PlayEventReviewEnd(&'a ReviewData, &'a PlayEvent, &'a Play),
	
	GameEnd(&'a Decisions, &'a GameStatLeaders),
}

impl PlayStream {
	/// Runs through plays until the game is over.
	///
	/// # Errors
	/// See [`request::Error`]
	pub async fn run<F: AsyncFnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData, &Linescore, &Boxscore) -> Result<ControlFlow<()>, request::Error>>(self, f: F) -> Result<(), request::Error> {
		self.run_with_custom_error::<request::Error, F>(f).await
	}

	/// Evaluation for the current play
	async fn run_current_play<E, F: AsyncFnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData, &Linescore, &Boxscore) -> Result<ControlFlow<()>, E>>(&self, mut f: F, current_play: &Play, meta: &LiveFeedMetadata, data: &LiveFeedData, linescore: &Linescore, boxscore: &Boxscore) -> Result<ControlFlow<()>, E> {
		macro_rules! flow_try {
			($($t:tt)*) => {
				match ($($t)*).await? {
					ControlFlow::Continue(()) => {},
					ControlFlow::Break(()) => return Ok(ControlFlow::Break(())),
				}
			};
		}
		
		if !self.in_progress_current_play {
			flow_try!(f(PlayStreamEvent::StartPlay(current_play), meta, data, linescore, boxscore));
		}
		let mut play_events = current_play.play_events.iter().skip(self.current_play_event_idx);
		if let Some(current_play_event) = play_events.next() {
			flow_try!(f(PlayStreamEvent::PlayEvent(current_play_event, current_play), meta, data, linescore, boxscore));
			let mut reviews = current_play_event.reviews.iter().skip(self.current_play_event_review_idx);
			if let Some(current_review) = reviews.next() {
				if !self.in_progress_current_play_event_review {
					flow_try!(f(PlayStreamEvent::PlayEventReviewStart(current_review, current_play_event, current_play), meta, data, linescore, boxscore));
				}
				if !current_review.is_in_progress {
					flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(current_review, current_play_event, current_play), meta, data, linescore, boxscore));
				}
			}
			for review in reviews {
				flow_try!(f(PlayStreamEvent::PlayEventReviewStart(review, current_play_event, current_play), meta, data, linescore, boxscore));
				if !review.is_in_progress {
					flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(review, current_play_event, current_play), meta, data, linescore, boxscore));
				}
			}
		}
		for play_event in play_events {
			flow_try!(f(PlayStreamEvent::PlayEvent(play_event, current_play), meta, data, linescore, boxscore));
			for review in &play_event.reviews {
				flow_try!(f(PlayStreamEvent::PlayEventReviewStart(review, play_event, current_play), meta, data, linescore, boxscore));
				if !review.is_in_progress {
					flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(review, play_event, current_play), meta, data, linescore, boxscore));
				}
			}
		}
		let mut reviews = current_play.reviews.iter().skip(self.current_play_review_idx);
		if let Some(current_review) = reviews.next() {
			if !self.in_progress_current_play_review {
				flow_try!(f(PlayStreamEvent::PlayReviewStart(current_review, current_play), meta, data, linescore, boxscore));
			}
			if !current_review.is_in_progress {
				flow_try!(f(PlayStreamEvent::PlayReviewEnd(current_review, current_play), meta, data, linescore, boxscore));
			}
		}
		
		for review in reviews {
			flow_try!(f(PlayStreamEvent::PlayReviewStart(review, current_play), meta, data, linescore, boxscore));
			if !review.is_in_progress {
				flow_try!(f(PlayStreamEvent::PlayReviewEnd(review, current_play), meta, data, linescore, boxscore));
			}
		}
		if current_play.about.is_complete {
			flow_try!(f(PlayStreamEvent::EndPlay(current_play), meta, data, linescore, boxscore));
		}
		
		Ok(ControlFlow::Continue(()))
	}

	/// Evaluation for remaining plays
	async fn run_next_plays<E, F: AsyncFnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData, &Linescore, &Boxscore) -> Result<ControlFlow<()>, E>>(&self, mut f: F, plays: impl Iterator<Item=&Play>, meta: &LiveFeedMetadata, data: &LiveFeedData, linescore: &Linescore, boxscore: &Boxscore) -> Result<ControlFlow<()>, E> {
		macro_rules! flow_try {
			($($t:tt)*) => {
				match ($($t)*).await? {
					ControlFlow::Continue(()) => {},
					ControlFlow::Break(()) => return Ok(ControlFlow::Break(())),
				}
			};
		}
		
		for play in plays {
			flow_try!(f(PlayStreamEvent::StartPlay(play), meta, data, linescore, boxscore));
			for play_event in &play.play_events {
				flow_try!(f(PlayStreamEvent::PlayEvent(play_event, play), meta, data, linescore, boxscore));
				for review in &play_event.reviews {
					flow_try!(f(PlayStreamEvent::PlayEventReviewStart(review, play_event, play), meta, data, linescore, boxscore));
					if !review.is_in_progress {
						flow_try!(f(PlayStreamEvent::PlayEventReviewEnd(review, play_event, play), meta, data, linescore, boxscore));
					}
				}
			}
			for review in &play.reviews {
				flow_try!(f(PlayStreamEvent::PlayReviewStart(review, play), meta, data, linescore, boxscore));
				if !review.is_in_progress {
					flow_try!(f(PlayStreamEvent::PlayReviewEnd(review, play), meta, data, linescore, boxscore));
				}
			}
			if play.about.is_complete {
				flow_try!(f(PlayStreamEvent::EndPlay(play), meta, data, linescore, boxscore));
			}
		}

		Ok(ControlFlow::Continue(()))
	}

	fn update_indices(&mut self, plays: &[Play]) {
		let latest_play = plays.last();

		self.in_progress_current_play = latest_play.is_some_and(|play| !play.about.is_complete);
		self.current_play_idx = if self.in_progress_current_play { plays.len() - 1 } else { plays.len() };

		let current_play = plays.get(self.current_play_idx);
		let current_play_event = current_play.and_then(|play| play.play_events.last());
		let current_play_review = current_play.and_then(|play| play.reviews.last());
		let current_play_event_review = current_play_event.and_then(|play_event| play_event.reviews.last());
		
		self.in_progress_current_play_review = current_play_review.is_some_and(|review| review.is_in_progress);
		self.current_play_review_idx = current_play.map_or(0, |play| if self.in_progress_current_play_review { play.reviews.len() - 1 } else { play.reviews.len() });

		self.current_play_event_idx = current_play.map_or(0, |play| play.play_events.len());

		self.in_progress_current_play_event_review = current_play_event_review.is_some_and(|review| review.is_in_progress);
		self.current_play_event_review_idx = current_play_event.map_or(0, |play_event| if self.in_progress_current_play_event_review { play_event.reviews.len() - 1 } else { play_event.reviews.len() });
	}

	/// Variant of the ``run`` function that allows for custom error types.
	///
	/// # Errors
	/// See [`request::Error`]
	pub async fn run_with_custom_error<E: From<request::Error>, F: AsyncFnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData, &Linescore, &Boxscore) -> Result<ControlFlow<()>, E>>(self, f: F) -> Result<(), E> {
		let feed = LiveFeedRequest::builder().id(self.game_id).build_and_get().await?;
		Self::with_presupplied_feed(feed, f).await
	}

	/// Variant of the ``run`` function that begins with a pre-supplied [`LiveFeedResponse`], useful if preprocessing was done before the play stream.
	///
	/// # Errors
	/// See [`request::Error`]
	pub async fn with_presupplied_feed<E: From<request::Error>, F: AsyncFnMut(PlayStreamEvent, &LiveFeedMetadata, &LiveFeedData, &Linescore, &Boxscore) -> Result<ControlFlow<()>, E>>(mut feed: LiveFeedResponse, mut f: F) -> Result<(), E> {
		macro_rules! flow_try {
			($($t:tt)*) => {
				match ($($t)*).await? {
					ControlFlow::Continue(()) => {},
					ControlFlow::Break(()) => return Ok(()),
				}
			};
		}

		let mut this = Self::new(feed.id);
		flow_try!(f(PlayStreamEvent::Start, &feed.meta, &feed.data, &feed.live.linescore, &feed.live.boxscore));
		
		loop {
		    let since_last_request = Instant::now();
		    
			let LiveFeedResponse { meta, data, live, .. } = &feed;
			let LiveFeedLiveData { linescore, boxscore, decisions, leaders, plays } = live;
			let mut plays = plays.iter().skip(this.current_play_idx);

			if let Some(current_play) = plays.next() {
				flow_try!(this.run_current_play(&mut f, current_play, meta, data, linescore, boxscore));
			}
			
			flow_try!(this.run_next_plays(&mut f, plays, meta, data, linescore, boxscore));
			
			if data.status.abstract_game_code.is_finished() && let Some(decisions) = decisions {
				let _ = f(PlayStreamEvent::GameEnd(decisions, leaders), meta, data, linescore, boxscore).await?;
				return Ok(())
			}

			this.update_indices(&live.plays);

			let total_sleep_time = Duration::from_secs(meta.recommended_poll_rate as _);
			drop(feed);
			tokio::time::sleep(total_sleep_time.saturating_sub(since_last_request.elapsed())).await;
		    feed = LiveFeedRequest::builder().id(this.game_id).build_and_get().await?;
		}
	}
}
	
#[cfg(test)]
mod tests {
    use std::ops::ControlFlow;
    use crate::{cache::RequestableEntrypoint, game::{PlayEvent, PlayStream, PlayStreamEvent}};

	#[tokio::test]
	async fn test_play_stream() {
		Box::pin(PlayStream::new(822_834).run(async |event, _meta, _data, _linescore, _boxscore| {
			match event {
				PlayStreamEvent::Start => println!("GameStart"),
				PlayStreamEvent::StartPlay(play) => println!("PlayStart; {} vs. {}", play.matchup.batter.full_name, play.matchup.pitcher.full_name),
				PlayStreamEvent::PlayEvent(play_event, _play) => {
					print!("PlayEvent; ");
					match play_event {
						PlayEvent::Action { details, .. } => println!("{}", details.description),
						PlayEvent::Pitch { details, common, .. } => println!("{} -> {}", details.call, common.count),
						PlayEvent::Stepoff { .. } => println!("Stepoff"),
						PlayEvent::NoPitch { .. } => println!("No Pitch"),
						PlayEvent::Pickoff { .. } => println!("Pickoff"),
					}
				},
				PlayStreamEvent::PlayEventReviewStart(review, _, _) => println!("PlayEventReviewStart; {}", review.review_type),
				PlayStreamEvent::PlayEventReviewEnd(review, _, _) => println!("PlayEventReviewEnd; {}", review.review_type),
				PlayStreamEvent::PlayReviewStart(review, _) => println!("PlayReviewStart; {}", review.review_type),
				PlayStreamEvent::PlayReviewEnd(review, _) => println!("PlayReviewEnd; {}", review.review_type),
				PlayStreamEvent::EndPlay(play) => println!("PlayEnd; {}", play.result.completed_play_details.as_ref().expect("Completed play").description),
				PlayStreamEvent::GameEnd(_, _) => println!("GameEnd"),
			}
			Ok(ControlFlow::Continue(()))
		})).await.unwrap();
	}
}