rlstatsapi 0.1.4

Rocket League Stats API TCP client, parser, and optional Python bindings
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
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::error::RlStatsError;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventEnvelope<T = Value> {
    #[serde(rename = "Event", alias = "event")]
    pub event: String,
    #[serde(rename = "Data", alias = "data")]
    pub data: T,
}

#[derive(Debug, Clone)]
pub enum StatsEvent {
    UpdateState(UpdateStateData),
    BallHit(BallHitData),
    ClockUpdatedSeconds(ClockUpdatedSecondsData),
    CountdownBegin(MatchOnlyData),
    CrossbarHit(CrossbarHitData),
    GoalReplayEnd(MatchOnlyData),
    GoalReplayStart(MatchOnlyData),
    GoalReplayWillEnd(MatchOnlyData),
    GoalScored(GoalScoredData),
    MatchCreated(MatchOnlyData),
    MatchInitialized(MatchOnlyData),
    MatchDestroyed(MatchOnlyData),
    MatchEnded(MatchEndedData),
    MatchPaused(MatchOnlyData),
    MatchUnpaused(MatchOnlyData),
    PodiumStart(MatchOnlyData),
    ReplayCreated(MatchOnlyData),
    RoundStarted(MatchOnlyData),
    StatfeedEvent(StatfeedEventData),
    Unknown(UnknownEvent),
}

#[derive(Debug, Clone)]
pub struct UnknownEvent {
    pub event: String,
    pub data: Value,
}

pub fn stats_event_name(event: &StatsEvent) -> &'static str {
    match event {
        StatsEvent::UpdateState(_) => "UpdateState",
        StatsEvent::BallHit(_) => "BallHit",
        StatsEvent::ClockUpdatedSeconds(_) => "ClockUpdatedSeconds",
        StatsEvent::CountdownBegin(_) => "CountdownBegin",
        StatsEvent::CrossbarHit(_) => "CrossbarHit",
        StatsEvent::GoalReplayEnd(_) => "GoalReplayEnd",
        StatsEvent::GoalReplayStart(_) => "GoalReplayStart",
        StatsEvent::GoalReplayWillEnd(_) => "GoalReplayWillEnd",
        StatsEvent::GoalScored(_) => "GoalScored",
        StatsEvent::MatchCreated(_) => "MatchCreated",
        StatsEvent::MatchInitialized(_) => "MatchInitialized",
        StatsEvent::MatchDestroyed(_) => "MatchDestroyed",
        StatsEvent::MatchEnded(_) => "MatchEnded",
        StatsEvent::MatchPaused(_) => "MatchPaused",
        StatsEvent::MatchUnpaused(_) => "MatchUnpaused",
        StatsEvent::PodiumStart(_) => "PodiumStart",
        StatsEvent::ReplayCreated(_) => "ReplayCreated",
        StatsEvent::RoundStarted(_) => "RoundStarted",
        StatsEvent::StatfeedEvent(_) => "StatfeedEvent",
        StatsEvent::Unknown(_) => "Unknown",
    }
}

pub fn stats_event_to_value(event: &StatsEvent) -> Result<Value, RlStatsError> {
    let value = match event {
        StatsEvent::UpdateState(data) => {
            json!({"event": "UpdateState", "data": data})
        }
        StatsEvent::BallHit(data) => {
            json!({"event": "BallHit", "data": data})
        }
        StatsEvent::ClockUpdatedSeconds(data) => {
            json!({"event": "ClockUpdatedSeconds", "data": data})
        }
        StatsEvent::CountdownBegin(data) => {
            json!({"event": "CountdownBegin", "data": data})
        }
        StatsEvent::CrossbarHit(data) => {
            json!({"event": "CrossbarHit", "data": data})
        }
        StatsEvent::GoalReplayEnd(data) => {
            json!({"event": "GoalReplayEnd", "data": data})
        }
        StatsEvent::GoalReplayStart(data) => {
            json!({"event": "GoalReplayStart", "data": data})
        }
        StatsEvent::GoalReplayWillEnd(data) => {
            json!({"event": "GoalReplayWillEnd", "data": data})
        }
        StatsEvent::GoalScored(data) => {
            json!({"event": "GoalScored", "data": data})
        }
        StatsEvent::MatchCreated(data) => {
            json!({"event": "MatchCreated", "data": data})
        }
        StatsEvent::MatchInitialized(data) => {
            json!({"event": "MatchInitialized", "data": data})
        }
        StatsEvent::MatchDestroyed(data) => {
            json!({"event": "MatchDestroyed", "data": data})
        }
        StatsEvent::MatchEnded(data) => {
            json!({"event": "MatchEnded", "data": data})
        }
        StatsEvent::MatchPaused(data) => {
            json!({"event": "MatchPaused", "data": data})
        }
        StatsEvent::MatchUnpaused(data) => {
            json!({"event": "MatchUnpaused", "data": data})
        }
        StatsEvent::PodiumStart(data) => {
            json!({"event": "PodiumStart", "data": data})
        }
        StatsEvent::ReplayCreated(data) => {
            json!({"event": "ReplayCreated", "data": data})
        }
        StatsEvent::RoundStarted(data) => {
            json!({"event": "RoundStarted", "data": data})
        }
        StatsEvent::StatfeedEvent(data) => {
            json!({"event": "StatfeedEvent", "data": data})
        }
        StatsEvent::Unknown(data) => json!({
            "event": data.event,
            "data": data.data,
        }),
    };

    Ok(value)
}

pub fn parse_stats_event(input: &str) -> Result<StatsEvent, RlStatsError> {
    let envelope: EventEnvelope<Value> = serde_json::from_str(input)?;
    parse_event_envelope(envelope)
}

pub fn parse_stats_event_value(
    value: Value,
) -> Result<StatsEvent, RlStatsError> {
    let envelope: EventEnvelope<Value> = serde_json::from_value(value)?;
    parse_event_envelope(envelope)
}

fn parse_event_envelope(
    envelope: EventEnvelope<Value>,
) -> Result<StatsEvent, RlStatsError> {
    let data = normalize_event_data(envelope.data)?;

    let event = match envelope.event.as_str() {
        "UpdateState" => StatsEvent::UpdateState(serde_json::from_value(data)?),
        "BallHit" => StatsEvent::BallHit(serde_json::from_value(data)?),
        "ClockUpdatedSeconds" => {
            StatsEvent::ClockUpdatedSeconds(serde_json::from_value(data)?)
        }
        "CountdownBegin" => {
            StatsEvent::CountdownBegin(serde_json::from_value(data)?)
        }
        "CrossbarHit" => StatsEvent::CrossbarHit(serde_json::from_value(data)?),
        "GoalReplayEnd" => {
            StatsEvent::GoalReplayEnd(serde_json::from_value(data)?)
        }
        "GoalReplayStart" => {
            StatsEvent::GoalReplayStart(serde_json::from_value(data)?)
        }
        "GoalReplayWillEnd" => {
            StatsEvent::GoalReplayWillEnd(serde_json::from_value(data)?)
        }
        "GoalScored" => StatsEvent::GoalScored(serde_json::from_value(data)?),
        "MatchCreated" => {
            StatsEvent::MatchCreated(serde_json::from_value(data)?)
        }
        "MatchInitialized" => {
            StatsEvent::MatchInitialized(serde_json::from_value(data)?)
        }
        "MatchDestroyed" => {
            StatsEvent::MatchDestroyed(serde_json::from_value(data)?)
        }
        "MatchEnded" => StatsEvent::MatchEnded(serde_json::from_value(data)?),
        "MatchPaused" => StatsEvent::MatchPaused(serde_json::from_value(data)?),
        "MatchUnpaused" => {
            StatsEvent::MatchUnpaused(serde_json::from_value(data)?)
        }
        "PodiumStart" => StatsEvent::PodiumStart(serde_json::from_value(data)?),
        "ReplayCreated" => {
            StatsEvent::ReplayCreated(serde_json::from_value(data)?)
        }
        "RoundStarted" => {
            StatsEvent::RoundStarted(serde_json::from_value(data)?)
        }
        "StatfeedEvent" => {
            StatsEvent::StatfeedEvent(serde_json::from_value(data)?)
        }
        _ => StatsEvent::Unknown(UnknownEvent {
            event: envelope.event,
            data,
        }),
    };

    Ok(event)
}

fn normalize_event_data(data: Value) -> Result<Value, RlStatsError> {
    match data {
        Value::String(raw) => {
            let parsed = serde_json::from_str::<Value>(&raw)?;
            Ok(parsed)
        }
        other => Ok(other),
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MatchOnlyData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Vector3 {
    #[serde(rename = "X", default)]
    pub x: f64,
    #[serde(rename = "Y", default)]
    pub y: f64,
    #[serde(rename = "Z", default)]
    pub z: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PlayerRef {
    #[serde(rename = "Name", default)]
    pub name: String,
    #[serde(rename = "Shortcut", default)]
    pub shortcut: i64,
    #[serde(rename = "TeamNum", default)]
    pub team_num: i64,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LastTouch {
    #[serde(rename = "Player", default)]
    pub player: PlayerRef,
    #[serde(rename = "Speed", default)]
    pub speed: f64,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BallHitBall {
    #[serde(rename = "PreHitSpeed", default)]
    pub pre_hit_speed: f64,
    #[serde(rename = "PostHitSpeed", default)]
    pub post_hit_speed: f64,
    #[serde(rename = "Location")]
    pub location: Vector3,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BallHitData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "Players", default)]
    pub players: Vec<PlayerRef>,
    #[serde(rename = "Ball", default)]
    pub ball: BallHitBall,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ClockUpdatedSecondsData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "TimeSeconds", default)]
    pub time_seconds: i64,
    #[serde(rename = "bOvertime", default)]
    pub b_overtime: bool,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CrossbarHitData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "BallLocation")]
    pub ball_location: Vector3,
    #[serde(rename = "BallSpeed", default)]
    pub ball_speed: f64,
    #[serde(rename = "ImpactForce", default)]
    pub impact_force: f64,
    #[serde(rename = "BallLastTouch", default)]
    pub ball_last_touch: LastTouch,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GoalScoredData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "GoalSpeed", default)]
    pub goal_speed: f64,
    #[serde(rename = "GoalTime", default)]
    pub goal_time: f64,
    #[serde(rename = "ImpactLocation")]
    pub impact_location: Vector3,
    #[serde(rename = "Scorer", default)]
    pub scorer: PlayerRef,
    #[serde(rename = "Assister", default)]
    pub assister: Option<PlayerRef>,
    #[serde(rename = "BallLastTouch", default)]
    pub ball_last_touch: LastTouch,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MatchEndedData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "WinnerTeamNum", default)]
    pub winner_team_num: i64,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StatfeedEventData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "EventName", default)]
    pub event_name: String,
    #[serde(rename = "Type", default)]
    pub type_label: String,
    #[serde(rename = "MainTarget", default)]
    pub main_target: PlayerRef,
    #[serde(rename = "SecondaryTarget", default)]
    pub secondary_target: Option<PlayerRef>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TeamState {
    #[serde(rename = "Name", default)]
    pub name: Option<String>,
    #[serde(rename = "TeamNum", default)]
    pub team_num: Option<i64>,
    #[serde(rename = "Score", default)]
    pub score: Option<i64>,
    #[serde(rename = "ColorPrimary", default)]
    pub color_primary: Option<String>,
    #[serde(rename = "ColorSecondary", default)]
    pub color_secondary: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BallState {
    #[serde(rename = "Speed", default)]
    pub speed: Option<f64>,
    #[serde(rename = "TeamNum", default)]
    pub team_num: Option<i64>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateStateGame {
    #[serde(rename = "Teams", default)]
    pub teams: Vec<TeamState>,
    #[serde(rename = "TimeSeconds", default)]
    pub time_seconds: Option<i64>,
    #[serde(rename = "bOvertime", default)]
    pub b_overtime: Option<bool>,
    #[serde(rename = "Frame", default)]
    pub frame: Option<i64>,
    #[serde(rename = "Elapsed", default)]
    pub elapsed: Option<f64>,
    #[serde(rename = "Ball", default)]
    pub ball: Option<BallState>,
    #[serde(rename = "bReplay", default)]
    pub b_replay: Option<bool>,
    #[serde(rename = "bHasWinner", default)]
    pub b_has_winner: Option<bool>,
    #[serde(rename = "Winner", default)]
    pub winner: Option<String>,
    #[serde(rename = "Arena", default)]
    pub arena: Option<String>,
    #[serde(rename = "bHasTarget", default)]
    pub b_has_target: Option<bool>,
    #[serde(rename = "Target", default)]
    pub target: Option<PlayerRef>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateStatePlayer {
    #[serde(rename = "Name", default)]
    pub name: Option<String>,
    #[serde(rename = "PrimaryId", default)]
    pub primary_id: Option<String>,
    #[serde(rename = "Shortcut", default)]
    pub shortcut: Option<i64>,
    #[serde(rename = "TeamNum", default)]
    pub team_num: Option<i64>,
    #[serde(rename = "Score", default)]
    pub score: Option<i64>,
    #[serde(rename = "Goals", default)]
    pub goals: Option<i64>,
    #[serde(rename = "Shots", default)]
    pub shots: Option<i64>,
    #[serde(rename = "Assists", default)]
    pub assists: Option<i64>,
    #[serde(rename = "Saves", default)]
    pub saves: Option<i64>,
    #[serde(rename = "Touches", default)]
    pub touches: Option<i64>,
    #[serde(rename = "CarTouches", default)]
    pub car_touches: Option<i64>,
    #[serde(rename = "Demos", default)]
    pub demos: Option<i64>,
    #[serde(rename = "bHasCar", default)]
    pub b_has_car: Option<bool>,
    #[serde(rename = "Speed", default)]
    pub speed: Option<f64>,
    #[serde(rename = "Boost", default)]
    pub boost: Option<i64>,
    #[serde(rename = "bBoosting", default)]
    pub b_boosting: Option<bool>,
    #[serde(rename = "bOnGround", default)]
    pub b_on_ground: Option<bool>,
    #[serde(rename = "bOnWall", default)]
    pub b_on_wall: Option<bool>,
    #[serde(rename = "bPowersliding", default)]
    pub b_powersliding: Option<bool>,
    #[serde(rename = "bDemolished", default)]
    pub b_demolished: Option<bool>,
    #[serde(rename = "bSupersonic", default)]
    pub b_supersonic: Option<bool>,
    #[serde(rename = "Attacker", default)]
    pub attacker: Option<PlayerRef>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

impl UpdateStatePlayer {
    pub fn effective_speed(&self) -> Option<f64> {
        self.speed
            .or_else(|| {
                first_numeric_f64(
                    &self.extra,
                    &[
                        "speed",
                        "Speed",
                        "CarSpeed",
                        "carSpeed",
                        "car_speed",
                        "Velocity",
                        "velocity",
                        "Car.Speed",
                        "car.speed",
                    ],
                )
            })
            .or_else(|| {
                first_nested_numeric_f64(
                    &self.extra,
                    &[
                        "Car", "car", "CarData", "carData", "car_data",
                        "Vehicle", "vehicle",
                    ],
                    &[
                        "Speed",
                        "speed",
                        "CarSpeed",
                        "carSpeed",
                        "car_speed",
                        "Velocity",
                        "velocity",
                    ],
                )
            })
    }

    pub fn effective_boost(&self) -> Option<i64> {
        self.boost
            .or_else(|| {
                first_numeric_i64(
                    &self.extra,
                    &[
                        "boost",
                        "Boost",
                        "BoostAmount",
                        "boostAmount",
                        "boost_amount",
                        "Car.Boost",
                        "car.boost",
                    ],
                )
            })
            .or_else(|| {
                first_nested_numeric_i64(
                    &self.extra,
                    &[
                        "Car", "car", "CarData", "carData", "car_data",
                        "Vehicle", "vehicle",
                    ],
                    &[
                        "Boost",
                        "boost",
                        "BoostAmount",
                        "boostAmount",
                        "boost_amount",
                    ],
                )
            })
    }

    pub fn effective_boosting(&self) -> Option<bool> {
        self.b_boosting
            .or_else(|| {
                first_bool(
                    &self.extra,
                    &["bBoosting", "boosting", "isBoosting"],
                )
            })
            .or_else(|| {
                first_nested_bool(
                    &self.extra,
                    &[
                        "Car", "car", "CarData", "carData", "car_data",
                        "Vehicle", "vehicle",
                    ],
                    &["bBoosting", "boosting", "isBoosting"],
                )
            })
    }

    pub fn effective_supersonic(&self) -> Option<bool> {
        self.b_supersonic
            .or_else(|| {
                first_bool(
                    &self.extra,
                    &["bSupersonic", "supersonic", "isSupersonic"],
                )
            })
            .or_else(|| {
                first_nested_bool(
                    &self.extra,
                    &[
                        "Car", "car", "CarData", "carData", "car_data",
                        "Vehicle", "vehicle",
                    ],
                    &["bSupersonic", "supersonic", "isSupersonic"],
                )
            })
    }
}

fn first_numeric_f64(
    map: &HashMap<String, Value>,
    keys: &[&str],
) -> Option<f64> {
    keys.iter()
        .find_map(|key| map.get(*key).and_then(value_as_f64))
}

fn first_numeric_i64(
    map: &HashMap<String, Value>,
    keys: &[&str],
) -> Option<i64> {
    keys.iter()
        .find_map(|key| map.get(*key).and_then(value_as_i64))
}

fn first_nested_numeric_f64(
    map: &HashMap<String, Value>,
    container_keys: &[&str],
    value_keys: &[&str],
) -> Option<f64> {
    container_keys.iter().find_map(|container_key| {
        let Value::Object(object) = map.get(*container_key)? else {
            return None;
        };

        value_keys
            .iter()
            .find_map(|value_key| object.get(*value_key).and_then(value_as_f64))
    })
}

fn first_nested_numeric_i64(
    map: &HashMap<String, Value>,
    container_keys: &[&str],
    value_keys: &[&str],
) -> Option<i64> {
    container_keys.iter().find_map(|container_key| {
        let Value::Object(object) = map.get(*container_key)? else {
            return None;
        };

        value_keys
            .iter()
            .find_map(|value_key| object.get(*value_key).and_then(value_as_i64))
    })
}

fn first_bool(map: &HashMap<String, Value>, keys: &[&str]) -> Option<bool> {
    keys.iter()
        .find_map(|key| map.get(*key).and_then(value_as_bool))
}

fn first_nested_bool(
    map: &HashMap<String, Value>,
    container_keys: &[&str],
    value_keys: &[&str],
) -> Option<bool> {
    container_keys.iter().find_map(|container_key| {
        let Value::Object(object) = map.get(*container_key)? else {
            return None;
        };

        value_keys.iter().find_map(|value_key| {
            object.get(*value_key).and_then(value_as_bool)
        })
    })
}

fn value_as_f64(value: &Value) -> Option<f64> {
    match value {
        Value::Number(number) => number
            .as_f64()
            .or_else(|| number.as_i64().map(|v| v as f64)),
        Value::String(text) => text.parse::<f64>().ok(),
        _ => None,
    }
}

fn value_as_i64(value: &Value) -> Option<i64> {
    match value {
        Value::Number(number) => number
            .as_i64()
            .or_else(|| number.as_f64().map(|v| v.trunc() as i64)),
        Value::String(text) => text
            .parse::<i64>()
            .ok()
            .or_else(|| text.parse::<f64>().ok().map(|v| v.trunc() as i64)),
        _ => None,
    }
}

fn value_as_bool(value: &Value) -> Option<bool> {
    match value {
        Value::Bool(boolean) => Some(*boolean),
        Value::Number(number) => number.as_i64().map(|v| v != 0),
        Value::String(text) => {
            let normalized = text.trim().to_ascii_lowercase();
            match normalized.as_str() {
                "true" | "1" | "yes" | "y" | "on" => Some(true),
                "false" | "0" | "no" | "n" | "off" => Some(false),
                _ => None,
            }
        }
        _ => None,
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateStateData {
    #[serde(rename = "MatchGuid", default)]
    pub match_guid: Option<String>,
    #[serde(rename = "Players", default)]
    pub players: Vec<UpdateStatePlayer>,
    #[serde(rename = "Game", default)]
    pub game: UpdateStateGame,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}