Skip to main content

sunday_slate/live/
snapshot.rs

1use std::collections::{BTreeMap, HashMap};
2use std::sync::Arc;
3
4use nfl_data::{
5    Game, LiveGame, LiveGamePhase, LiveGameSnapshot, LivePlayerStats, LiveTeamStats,
6    PlayerWeekStats, ProviderOutcome, TeamAbbr, TeamWeekStats,
7};
8use time::OffsetDateTime;
9
10use crate::entries::{Lineup, NflPlayerId, RosterSlot};
11use crate::live::identity::{IdentityMatch, LiveIdentityIndex};
12use crate::live::{Coverage, LiveContestSnapshot, LiveError, LiveSlotStatus, LiveTotal};
13use crate::player_identity::{canonical_team, tank01_team};
14use nfl_data::scoring::{self, WeekStats};
15use nfl_data::slates::SlateId;
16use tank01_data::PollEvent;
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct LiveGameState {
20    pub game: Game,
21    pub tank01_game_id: Option<String>,
22    pub phase: LiveGamePhase,
23    pub period: Option<String>,
24    pub clock: Option<String>,
25    pub home_score: Option<i32>,
26    pub away_score: Option<i32>,
27    pub status_observed: bool,
28    pub players: HashMap<NflPlayerId, PlayerWeekStats>,
29    pub player_section_present: bool,
30    pub player_identity_incomplete: bool,
31    pub player_observed_at: Option<OffsetDateTime>,
32    pub player_stale: bool,
33    pub defenses: HashMap<TeamAbbr, LiveTeamStats>,
34    pub defense_observed_at: HashMap<TeamAbbr, OffsetDateTime>,
35    pub defense_stale: HashMap<TeamAbbr, bool>,
36    pub last_error: Option<LiveError>,
37}
38
39impl LiveGameState {
40    fn new(game: Game, tank01_game_id: Option<String>, now: OffsetDateTime) -> Self {
41        let phase = if game.kickoff_eastern().is_some_and(|kickoff| now < kickoff) {
42            LiveGamePhase::Scheduled
43        } else {
44            LiveGamePhase::Unknown
45        };
46        Self {
47            game,
48            tank01_game_id,
49            phase,
50            period: None,
51            clock: None,
52            home_score: None,
53            away_score: None,
54            status_observed: false,
55            players: HashMap::new(),
56            player_section_present: false,
57            player_identity_incomplete: false,
58            player_observed_at: None,
59            player_stale: false,
60            defenses: HashMap::new(),
61            defense_observed_at: HashMap::new(),
62            defense_stale: HashMap::new(),
63            last_error: None,
64        }
65    }
66
67    pub fn team_is_scheduled(&self, team: &TeamAbbr) -> bool {
68        self.game.home_team == *team || self.game.away_team == *team
69    }
70    pub fn defense_is_stale(&self, team: &TeamAbbr) -> bool {
71        self.defense_stale
72            .iter()
73            .find(|(candidate, _)| **candidate == *team)
74            .map(|(_, stale)| *stale)
75            .unwrap_or(false)
76    }
77
78    pub(crate) fn player_is_stale_at(&self, now: OffsetDateTime) -> bool {
79        self.phase_requires_observation()
80            && (self.player_stale
81                || self
82                    .player_observed_at
83                    .is_none_or(|at| now - at > time::Duration::seconds(60)))
84    }
85
86    pub(crate) fn defense_is_stale_at(&self, team: &TeamAbbr, now: OffsetDateTime) -> bool {
87        self.phase_requires_observation()
88            && (self.defense_is_stale(team)
89                || self
90                    .defense_observed_at
91                    .iter()
92                    .find(|(candidate, _)| **candidate == *team)
93                    .is_none_or(|(_, at)| now - *at > time::Duration::seconds(60)))
94    }
95
96    fn phase_requires_observation(&self) -> bool {
97        self.phase == LiveGamePhase::InProgress
98    }
99}
100
101pub struct SnapshotReducer {
102    contest: SlateId,
103    games: Vec<Game>,
104    identity: Arc<LiveIdentityIndex>,
105    game_states: HashMap<String, LiveGameState>,
106    by_tank01_game_id: HashMap<String, String>,
107    revision: u64,
108    latest_error: Option<LiveError>,
109    identity_outcomes: BTreeMap<String, IdentityMatch>,
110}
111
112impl SnapshotReducer {
113    pub fn new(
114        contest: SlateId,
115        games: Vec<Game>,
116        identity: Arc<LiveIdentityIndex>,
117        now: OffsetDateTime,
118    ) -> Self {
119        let mut game_states = HashMap::with_capacity(games.len());
120        let mut by_tank01_game_id = HashMap::with_capacity(games.len());
121        for game in &games {
122            let tank01_game_id = tank01_game_id(game);
123            if let Some(tank01_game_id) = &tank01_game_id {
124                by_tank01_game_id.insert(tank01_game_id.clone(), game.game_id.clone());
125            }
126            game_states.insert(
127                game.game_id.clone(),
128                LiveGameState::new(game.clone(), tank01_game_id, now),
129            );
130        }
131        Self {
132            contest,
133            games,
134            identity,
135            game_states,
136            by_tank01_game_id,
137            revision: 0,
138            latest_error: None,
139            identity_outcomes: BTreeMap::new(),
140        }
141    }
142
143    pub fn accepts_event(&self, event: &PollEvent) -> bool {
144        match event {
145            PollEvent::BoxScore { game, .. } => {
146                self.game_states.get(&game.game_id).is_some_and(|state| {
147                    state.tank01_game_id.as_deref() == Some(game.tank01_game_id.as_str())
148                })
149            }
150            PollEvent::Scoreboard { .. } | PollEvent::RunFinished { .. } => true,
151        }
152    }
153
154    pub fn apply(&mut self, event: &PollEvent, feed_games: &[LiveGame]) -> LiveContestSnapshot {
155        match event {
156            PollEvent::Scoreboard { response, .. } => self.apply_scoreboard(response, feed_games),
157            PollEvent::BoxScore { game, response, .. } if self.accepts_event(event) => {
158                self.apply_box_score(game, response)
159            }
160            PollEvent::BoxScore { .. } | PollEvent::RunFinished { .. } => {}
161        }
162        self.revision = self.revision.saturating_add(1);
163        self.snapshot()
164    }
165
166    pub fn fail(&mut self, feed_games: &[LiveGame]) {
167        let error = Some(LiveError::Feed);
168        self.latest_error = error;
169        for game in feed_games {
170            let Some(state) = self.game_states.get_mut(&game.game_id) else {
171                continue;
172            };
173            if state.tank01_game_id.as_deref() != Some(game.tank01_game_id.as_str()) {
174                continue;
175            }
176            state.last_error = error;
177            state.player_stale = true;
178            for team in [&state.game.home_team, &state.game.away_team] {
179                state.defense_stale.insert(*team, true);
180            }
181        }
182    }
183
184    pub fn snapshot(&self) -> LiveContestSnapshot {
185        let mut stats = WeekStats::default();
186        let mut games = self.game_states.values().collect::<Vec<_>>();
187        games.sort_by(|a, b| a.game.game_id.cmp(&b.game.game_id));
188        for state in games {
189            stats.players.extend(state.players.clone());
190            stats
191                .defenses
192                .extend(state.defenses.iter().filter_map(|(&team, row)| {
193                    adapt_defense(&state.game, row, team).map(|stats| (team, stats))
194                }));
195        }
196        LiveContestSnapshot {
197            contest: self.contest,
198            games: self.games.clone(),
199            stats,
200            game_states: self.game_states.clone(),
201            identity: self.identity.clone(),
202            identity_outcomes: self.identity_outcomes.clone(),
203            latest_error: self.latest_error,
204            revision: self.revision,
205        }
206    }
207
208    fn apply_scoreboard(
209        &mut self,
210        response: &nfl_data::ProviderResponse<nfl_data::LiveScoreboard>,
211        feed_games: &[LiveGame],
212    ) {
213        match &response.outcome {
214            ProviderOutcome::Value(scoreboard) => {
215                self.latest_error = None;
216                for update in &scoreboard.games {
217                    if !feed_games
218                        .iter()
219                        .any(|game| game.tank01_game_id == update.tank01_game_id)
220                    {
221                        continue;
222                    }
223                    let Some(gsis_id) = self.by_tank01_game_id.get(&update.tank01_game_id).cloned()
224                    else {
225                        continue;
226                    };
227                    let Some(state) = self.game_states.get_mut(&gsis_id) else {
228                        continue;
229                    };
230                    state.last_error = None;
231                    state.phase = update.phase;
232                    state.period = update.period.clone();
233                    state.clock = update.clock.clone();
234                    state.home_score = update.home_score;
235                    state.away_score = update.away_score;
236                    state.status_observed = true;
237                }
238            }
239            ProviderOutcome::Pregame { .. } | ProviderOutcome::Error(_) => {
240                let error = Some(LiveError::Feed);
241                self.latest_error = error;
242                for game in feed_games {
243                    let Some(gsis_id) = self.by_tank01_game_id.get(&game.tank01_game_id).cloned()
244                    else {
245                        continue;
246                    };
247                    let Some(state) = self.game_states.get_mut(&gsis_id) else {
248                        continue;
249                    };
250                    state.last_error = error;
251                    state.player_stale = true;
252                    for team in [&state.game.home_team, &state.game.away_team] {
253                        state.defense_stale.insert(*team, true);
254                    }
255                }
256            }
257        }
258    }
259
260    fn apply_box_score(
261        &mut self,
262        game: &LiveGame,
263        response: &nfl_data::ProviderResponse<LiveGameSnapshot>,
264    ) {
265        let state_id = game.game_id.clone();
266
267        match &response.outcome {
268            ProviderOutcome::Value(snapshot) => {
269                self.latest_error = None;
270                let adapted_players = snapshot.players.as_ref().map(|players| {
271                    let mut adapted = HashMap::new();
272                    let mut identity_incomplete = false;
273                    for player in players {
274                        let identity = self.resolve_player(player);
275                        let Some(gsis_id) = (match identity {
276                            IdentityMatch::Matched(gsis_id) => Some(gsis_id),
277                            other => {
278                                identity_incomplete = true;
279                                self.identity_outcomes
280                                    .insert(live_player_identity_key(player), other);
281                                None
282                            }
283                        }) else {
284                            continue;
285                        };
286                        adapted.insert(
287                            gsis_id.clone(),
288                            adapt_player(
289                                snapshot,
290                                player,
291                                gsis_id.clone(),
292                                self.identity.scheduled_team(&gsis_id),
293                            ),
294                        );
295                    }
296                    (adapted, identity_incomplete)
297                });
298                let adapted_defenses = snapshot
299                    .defenses
300                    .iter()
301                    .flatten()
302                    .filter(|defense| defense.dst_present && defense.team_stats_present);
303
304                let state = self
305                    .game_states
306                    .get_mut(&state_id)
307                    .expect("game state was checked above");
308                state.last_error = None;
309                state.phase = snapshot.phase;
310                state.period = snapshot.period.clone();
311                state.clock = snapshot.clock.clone();
312                state.home_score = snapshot.home_score;
313                state.away_score = snapshot.away_score;
314                state.status_observed = true;
315                if let Some((players, identity_incomplete)) = adapted_players {
316                    state.players = players;
317                    state.player_section_present = true;
318                    state.player_identity_incomplete = identity_incomplete;
319                    state.player_observed_at = Some(snapshot.observed_at);
320                    state.player_stale = false;
321                }
322                for defense in adapted_defenses {
323                    let team = canonical_team(&defense.team);
324                    state.defenses.insert(team, defense.clone());
325                    state.defense_observed_at.insert(team, snapshot.observed_at);
326                    state.defense_stale.insert(team, false);
327                }
328            }
329            ProviderOutcome::Pregame { .. } | ProviderOutcome::Error(_) => {
330                let error = Some(LiveError::Feed);
331                self.latest_error = error;
332                let state = self
333                    .game_states
334                    .get_mut(&state_id)
335                    .expect("game state was checked above");
336                state.last_error = error;
337                state.player_stale = true;
338                for team in [&state.game.home_team, &state.game.away_team] {
339                    state.defense_stale.insert(*team, true);
340                }
341            }
342        }
343    }
344
345    fn resolve_player(&self, player: &LivePlayerStats) -> IdentityMatch {
346        self.identity.resolve(
347            player.espn_id.as_ref(),
348            player.name.as_deref(),
349            player.team.as_ref(),
350            player.position.as_deref(),
351        )
352    }
353}
354
355fn opposing_team<'a>(game: &'a LiveGame, team: Option<&TeamAbbr>) -> &'a TeamAbbr {
356    match team {
357        Some(team) if *team == game.home_team => &game.away_team,
358        _ => &game.home_team,
359    }
360}
361
362fn adapt_player(
363    snapshot: &LiveGameSnapshot,
364    row: &LivePlayerStats,
365    gsis_id: NflPlayerId,
366    known_team: Option<&TeamAbbr>,
367) -> PlayerWeekStats {
368    let team = known_team
369        .or(row.team.as_ref())
370        .unwrap_or(&snapshot.game.home_team);
371    let opponent = row
372        .opponent
373        .as_ref()
374        .unwrap_or_else(|| opposing_team(&snapshot.game, Some(team)));
375    PlayerWeekStats {
376        season_week: snapshot.game.season_week,
377        gsis_id: gsis_id.0,
378        team: canonical_team(team),
379        opponent: Some(canonical_team(opponent)),
380        completions: row.completions,
381        attempts: row.attempts,
382        passing_yards: row.passing_yards,
383        passing_tds: row.passing_tds,
384        passing_interceptions: row.passing_interceptions,
385        rushing_attempts: row.rushing_attempts,
386        rushing_yards: row.rushing_yards,
387        rushing_tds: row.rushing_tds,
388        targets: row.targets,
389        receptions: row.receptions,
390        receiving_yards: row.receiving_yards,
391        receiving_tds: row.receiving_tds,
392        fumbles_lost: row.fumbles_lost,
393        two_point_conversions: row.two_point_conversions,
394        special_teams_tds: row.special_teams_tds,
395        fumble_recovery_tds: row.fumble_recovery_tds,
396    }
397}
398
399fn adapt_defense(game: &Game, row: &LiveTeamStats, team: TeamAbbr) -> Option<TeamWeekStats> {
400    Some(TeamWeekStats {
401        season_week: game.season_week,
402        team,
403        opponent: canonical_team(&row.opponent),
404        game_id: game.game_id.clone(),
405        sacks: row.sacks,
406        interceptions: row.interceptions,
407        fumble_recoveries: row.fumble_recoveries,
408        safeties: row.safeties,
409        touchdowns: row.touchdowns,
410        blocked_kicks: row.blocked_kicks,
411        conversion_returns: row.conversion_returns,
412        points_allowed: row.points_allowed?,
413    })
414}
415
416pub fn tank01_game_id(game: &Game) -> Option<String> {
417    let date = game.kickoff_eastern()?.date();
418    let date = format!(
419        "{:04}{:02}{:02}",
420        date.year(),
421        date.month() as u8,
422        date.day()
423    );
424    Some(format!(
425        "{}_{}@{}",
426        date,
427        tank01_team(game.away_team.as_str()),
428        tank01_team(game.home_team.as_str())
429    ))
430}
431
432/// The game in the Tank01 id space it polls; `None` without a kickoff date.
433pub fn live_game(game: &Game) -> Option<LiveGame> {
434    Some(LiveGame {
435        game_id: game.game_id.clone(),
436        tank01_game_id: tank01_game_id(game)?,
437        season_week: game.season_week,
438        kickoff: game.kickoff,
439        home_team: game.home_team,
440        away_team: game.away_team,
441    })
442}
443
444fn live_player_identity_key(player: &LivePlayerStats) -> String {
445    player
446        .espn_id
447        .as_ref()
448        .map(|id| format!("espn:{}", id.0))
449        .or_else(|| player.name.as_ref().map(|name| format!("name:{name}")))
450        .unwrap_or_else(|| "unknown".to_owned())
451}
452
453#[derive(Debug, Clone, Copy)]
454enum LiveContribution {
455    ScheduledZero,
456    Observed(f64),
457    Partial(f64),
458    Unavailable,
459}
460
461impl LiveContribution {
462    fn points(self) -> Option<f64> {
463        match self {
464            Self::ScheduledZero => Some(0.0),
465            Self::Observed(points) | Self::Partial(points) => Some(points),
466            Self::Unavailable => None,
467        }
468    }
469}
470
471pub fn score_live_slot(
472    lineup: &Lineup,
473    slot: RosterSlot,
474    snapshot: &LiveContestSnapshot,
475    now: OffsetDateTime,
476) -> LiveSlotStatus {
477    let (contribution, state, stale) = match slot {
478        RosterSlot::Def => {
479            let state = snapshot.game_for_team(&lineup.def);
480            (
481                score_live_defense(&lineup.def, state, now),
482                state,
483                state.is_some_and(|state| state.defense_is_stale_at(&lineup.def, now)),
484            )
485        }
486        slot => {
487            let id = lineup
488                .player_slots()
489                .into_iter()
490                .find_map(|(candidate, id)| (candidate == slot).then_some(id));
491            let state = id.and_then(|id| {
492                snapshot
493                    .identity
494                    .scheduled_team(id)
495                    .and_then(|team| snapshot.game_for_team(team))
496            });
497            (
498                id.map_or(LiveContribution::Unavailable, |id| {
499                    score_live_player(id, state, snapshot, now)
500                }),
501                state,
502                state.is_some_and(|state| state.player_is_stale_at(now)),
503            )
504        }
505    };
506    LiveSlotStatus {
507        total: LiveTotal {
508            points: contribution.points(),
509            coverage: match contribution {
510                LiveContribution::Unavailable => Coverage::Unavailable,
511                LiveContribution::Partial(_) => Coverage::Partial,
512                _ => Coverage::Complete,
513            },
514        },
515        phase: state.map(|state| state.phase),
516        period: state.and_then(|state| state.period.clone()),
517        clock: state.and_then(|state| state.clock.clone()),
518        stale,
519    }
520}
521
522pub fn score_live_lineup(
523    lineup: &Lineup,
524    snapshot: &LiveContestSnapshot,
525    now: OffsetDateTime,
526) -> LiveTotal {
527    let mut values = Vec::with_capacity(9);
528    for player_id in lineup.player_ids() {
529        let state = snapshot
530            .identity
531            .scheduled_team(player_id)
532            .and_then(|team| snapshot.game_for_team(team));
533        values.push(score_live_player(player_id, state, snapshot, now));
534    }
535    let defense_state = snapshot.game_for_team(&lineup.def);
536    values.push(score_live_defense(&lineup.def, defense_state, now));
537
538    let unavailable = values.iter().any(|value| {
539        matches!(
540            value,
541            LiveContribution::Unavailable | LiveContribution::Partial(_)
542        )
543    });
544    let observed = values
545        .iter()
546        .filter_map(|value| match value {
547            LiveContribution::Observed(points) | LiveContribution::Partial(points) => Some(*points),
548            LiveContribution::ScheduledZero | LiveContribution::Unavailable => None,
549        })
550        .count();
551    let available = values.iter().filter_map(|value| value.points()).sum();
552    if unavailable && observed == 0 {
553        LiveTotal {
554            points: None,
555            coverage: Coverage::Unavailable,
556        }
557    } else if unavailable {
558        LiveTotal {
559            points: Some(available),
560            coverage: Coverage::Partial,
561        }
562    } else {
563        LiveTotal {
564            points: Some(available),
565            coverage: Coverage::Complete,
566        }
567    }
568}
569
570/// Full mark for one entry's meter: DEF counts and duplicate-game picks each
571/// count their game's minutes (9 slots × 60 regulation minutes).
572pub const LINEUP_REGULATION_MINUTES: f64 = 9.0 * 60.0;
573
574pub fn lineup_minutes_remaining(
575    lineup: &Lineup,
576    snapshot: &LiveContestSnapshot,
577    now: OffsetDateTime,
578) -> f64 {
579    let mut total = 0.0;
580    for player_id in lineup.player_ids() {
581        let state = snapshot
582            .identity
583            .scheduled_team(player_id)
584            .and_then(|team| snapshot.game_for_team(team));
585        total += game_minutes_remaining(state, now);
586    }
587    total += game_minutes_remaining(snapshot.game_for_team(&lineup.def), now);
588    total.clamp(0.0, LINEUP_REGULATION_MINUTES)
589}
590
591fn game_minutes_remaining(state: Option<&LiveGameState>, now: OffsetDateTime) -> f64 {
592    let Some(state) = state else {
593        return 60.0;
594    };
595    match state.phase {
596        // An unknowable phase is a data gap, not a late game: showing no
597        // minutes would false-red every entry.
598        LiveGamePhase::Scheduled | LiveGamePhase::Unknown => 60.0,
599        LiveGamePhase::Final => 0.0,
600        LiveGamePhase::InProgress => {
601            let period = period_number(state.period.as_deref());
602            let clock = clock_seconds(state.clock.as_deref());
603            match (period, clock) {
604                (Some(n), _) if n >= 5 => 0.0,
605                (Some(n), Some(secs)) if (1..=4).contains(&n) => {
606                    60.0 - 15.0 * (n - 1) as f64 - (900.0 - secs as f64) / 60.0
607                }
608                (Some(n), None) if (1..=4).contains(&n) => {
609                    // A mid-quarter provider glitch; the next frame corrects it.
610                    60.0 - 15.0 * (n - 1) as f64
611                }
612                _ => wall_clock_minutes_remaining(state, now),
613            }
614        }
615    }
616}
617
618fn period_number(period: Option<&str>) -> Option<u32> {
619    let digits: String = period?.chars().filter(char::is_ascii_digit).collect();
620    digits.parse().ok()
621}
622
623fn clock_seconds(clock: Option<&str>) -> Option<u32> {
624    let (minutes, seconds) = clock?.split_once(':')?;
625    let minutes: u64 = minutes.trim().parse().ok()?;
626    let seconds: u64 = seconds.trim().parse().ok()?;
627    Some((minutes * 60 + seconds).min(900) as u32)
628}
629
630fn wall_clock_minutes_remaining(state: &LiveGameState, now: OffsetDateTime) -> f64 {
631    let Some(kickoff) = state.game.kickoff_eastern() else {
632        return 60.0;
633    };
634    let elapsed = (now - kickoff).whole_seconds() as f64;
635    let drained = (elapsed / (3.0 * 3600.0)).clamp(0.0, 1.0);
636    60.0 * (1.0 - drained)
637}
638
639fn score_live_player(
640    id: &NflPlayerId,
641    state: Option<&LiveGameState>,
642    snapshot: &LiveContestSnapshot,
643    now: OffsetDateTime,
644) -> LiveContribution {
645    let Some(state) = state else {
646        return LiveContribution::Unavailable;
647    };
648    match state.phase {
649        LiveGamePhase::Scheduled => scheduled_contribution(state, now),
650        LiveGamePhase::InProgress | LiveGamePhase::Final | LiveGamePhase::Unknown => {
651            if let Some(stats) = state.players.get(id) {
652                LiveContribution::Observed(scoring::score_player(stats).total)
653            } else if state.player_section_present
654                && !state.player_identity_incomplete
655                && snapshot.identity.contains_gsis(id)
656            {
657                LiveContribution::Observed(0.0)
658            } else {
659                LiveContribution::Unavailable
660            }
661        }
662    }
663}
664
665fn score_live_defense(
666    team: &TeamAbbr,
667    state: Option<&LiveGameState>,
668    now: OffsetDateTime,
669) -> LiveContribution {
670    let Some(state) = state else {
671        return LiveContribution::Unavailable;
672    };
673    match state.phase {
674        LiveGamePhase::Scheduled => scheduled_contribution(state, now),
675        LiveGamePhase::InProgress | LiveGamePhase::Final | LiveGamePhase::Unknown => state
676            .defenses
677            .get(&canonical_team(team))
678            .map(|stats| {
679                let points = scoring::score_live_defense(stats).total;
680                if stats.points_allowed.is_some() {
681                    LiveContribution::Observed(points)
682                } else {
683                    LiveContribution::Partial(points)
684                }
685            })
686            .unwrap_or(LiveContribution::Unavailable),
687    }
688}
689
690fn scheduled_contribution(state: &LiveGameState, now: OffsetDateTime) -> LiveContribution {
691    if state.status_observed
692        || state
693            .game
694            .kickoff_eastern()
695            .is_some_and(|kickoff| now < kickoff)
696    {
697        LiveContribution::ScheduledZero
698    } else {
699        LiveContribution::Unavailable
700    }
701}
702
703impl LiveContestSnapshot {
704    pub fn game(&self, game_id: &str) -> Option<&LiveGameState> {
705        self.game_states.get(game_id)
706    }
707
708    pub fn scored_games(&self) -> Vec<Game> {
709        self.games
710            .iter()
711            .map(|game| {
712                let mut game = game.clone();
713                if let Some(state) = self.game(&game.game_id) {
714                    game.home_score = state.home_score;
715                    game.away_score = state.away_score;
716                }
717                game
718            })
719            .collect()
720    }
721
722    pub fn game_for_team(&self, team: &TeamAbbr) -> Option<&LiveGameState> {
723        self.game_states
724            .values()
725            .find(|state| state.team_is_scheduled(team))
726    }
727
728    pub fn has_active_game(&self) -> bool {
729        self.game_states
730            .values()
731            .any(|state| state.phase == LiveGamePhase::InProgress)
732    }
733
734    pub fn is_delayed(&self, now: OffsetDateTime) -> bool {
735        self.game_states.values().any(|state| {
736            state.phase_requires_observation()
737                && (state.player_is_stale_at(now)
738                    || state.defense_is_stale_at(&state.game.home_team, now)
739                    || state.defense_is_stale_at(&state.game.away_team, now))
740        })
741    }
742}
743#[cfg(test)]
744mod tests {
745    use std::collections::BTreeMap;
746
747    use nfl_data::{
748        EspnPlayerId, Game, LiveGame, LiveGameSnapshot, LivePlayerStats, LiveProviderError,
749        LiveTeamStats, Player, ProviderOutcome, ProviderResponse, TeamAbbr,
750    };
751    use time::macros::datetime;
752
753    use super::*;
754    use crate::entries::Lineup;
755    use crate::tests::factories;
756
757    fn game() -> Game {
758        let mut game = factories::game("live", 1);
759        game.kickoff = Some(datetime!(2025 - 09 - 07 17:00 UTC));
760        game
761    }
762
763    fn identity() -> Arc<LiveIdentityIndex> {
764        Arc::new(LiveIdentityIndex::from_sources(
765            &[Player {
766                espn_id: Some("e1".into()),
767                position: Some("RB".into()),
768                ..factories::player("p1", "A Runner")
769            }],
770            &[],
771        ))
772    }
773
774    fn player_stats() -> LivePlayerStats {
775        LivePlayerStats {
776            espn_id: Some(EspnPlayerId("e1".into())),
777            name: Some("A Runner".into()),
778            team: Some(TeamAbbr::KC),
779            position: Some("RB".into()),
780            opponent: Some(TeamAbbr::BUF),
781            completions: 0,
782            attempts: 0,
783            passing_tds: 0,
784            passing_interceptions: 0,
785            rushing_attempts: 1,
786            rushing_tds: 0,
787            targets: 0,
788            receptions: 0,
789            receiving_tds: 0,
790            fumbles_lost: 0,
791            two_point_conversions: 0,
792            special_teams_tds: 0,
793            fumble_recovery_tds: 0,
794            passing_yards: 0,
795            rushing_yards: 10,
796            receiving_yards: 0,
797        }
798    }
799
800    fn defense_stats() -> LiveTeamStats {
801        LiveTeamStats {
802            team: TeamAbbr::KC,
803            opponent: TeamAbbr::BUF,
804            sacks: 1,
805            interceptions: 0,
806            fumble_recoveries: 0,
807            safeties: 0,
808            touchdowns: 0,
809            blocked_kicks: 0,
810            conversion_returns: 0,
811            points_allowed: Some(7),
812            dst_present: true,
813            team_stats_present: true,
814        }
815    }
816
817    fn response(
818        outcome: ProviderOutcome<LiveGameSnapshot>,
819        observed_at: time::OffsetDateTime,
820    ) -> ProviderResponse<LiveGameSnapshot> {
821        ProviderResponse {
822            requested_at: observed_at,
823            received_at: observed_at,
824            elapsed_ms: 1,
825            http_status: Some(200),
826            headers: BTreeMap::new(),
827            raw_body: None,
828            outcome,
829        }
830    }
831
832    fn box_event(
833        game: &LiveGame,
834        snapshot: LiveGameSnapshot,
835        observed_at: time::OffsetDateTime,
836    ) -> PollEvent {
837        PollEvent::BoxScore {
838            sequence: 1,
839            game: game.clone(),
840            request: tank01_data::PollRequest {
841                endpoint: "box".into(),
842                query: BTreeMap::new(),
843            },
844            play_by_play: false,
845            changed: true,
846            response: response(ProviderOutcome::Value(snapshot), observed_at),
847        }
848    }
849
850    fn lineup() -> Lineup {
851        let id = crate::entries::NflPlayerId("p1".into());
852        Lineup {
853            qb: id.clone(),
854            rb1: id.clone(),
855            rb2: id.clone(),
856            wr1: id.clone(),
857            wr2: id.clone(),
858            wr3: id.clone(),
859            te: id.clone(),
860            flex: id,
861            def: TeamAbbr::KC,
862        }
863    }
864
865    #[test]
866    fn live_defense_keeps_interception_points_while_points_allowed_is_pending() {
867        let game = game();
868        let live_game = live_game(&game).expect("fixture kickoff");
869        let now = datetime!(2025 - 09 - 07 18:00 UTC);
870        let mut reducer = SnapshotReducer::new(SlateId(1), vec![game], identity(), now);
871
872        for (allowed, points, coverage) in [
873            (Some(7), 10.0, Coverage::Complete),
874            (None, 6.0, Coverage::Partial),
875            (Some(7), 10.0, Coverage::Complete),
876        ] {
877            let live = LiveGameSnapshot {
878                game: live_game.clone(),
879                observed_at: now,
880                phase: LiveGamePhase::InProgress,
881                period: None,
882                clock: None,
883                home_score: Some(7),
884                away_score: Some(7),
885                players: Some(vec![player_stats()]),
886                defenses: Some(vec![LiveTeamStats {
887                    sacks: 0,
888                    interceptions: 3,
889                    points_allowed: allowed,
890                    ..defense_stats()
891                }]),
892            };
893            let snapshot = reducer.apply(
894                &box_event(&live_game, live, now),
895                std::slice::from_ref(&live_game),
896            );
897            let slot = score_live_slot(&lineup(), RosterSlot::Def, &snapshot, now);
898            assert_eq!(
899                slot.total,
900                LiveTotal {
901                    points: Some(points),
902                    coverage
903                }
904            );
905            assert_eq!(
906                score_live_lineup(&lineup(), &snapshot, now).coverage,
907                coverage
908            );
909        }
910    }
911
912    #[test]
913    fn omitted_sections_preserve_last_good_data_and_errors_mark_it_stale() {
914        let game = game();
915        let live_game = live_game(&game).expect("fixture kickoff");
916        let observed_at = datetime!(2025 - 09 - 07 18:00 UTC);
917        let mut reducer = SnapshotReducer::new(SlateId(1), vec![game], identity(), observed_at);
918        let first = LiveGameSnapshot {
919            game: live_game.clone(),
920            observed_at,
921            phase: LiveGamePhase::InProgress,
922            period: Some("1".into()),
923            clock: Some("10:00".into()),
924            home_score: Some(7),
925            away_score: Some(0),
926            players: Some(vec![player_stats()]),
927            defenses: Some(vec![defense_stats()]),
928        };
929
930        let snapshot = reducer.apply(
931            &box_event(&live_game, first, observed_at),
932            std::slice::from_ref(&live_game),
933        );
934        let state = snapshot.game("live").expect("live game");
935        assert_eq!(state.players.len(), 1);
936        assert_eq!(state.defenses.len(), 1);
937
938        let second_at = datetime!(2025 - 09 - 07 18:00:20 UTC);
939        let second = LiveGameSnapshot {
940            game: live_game.clone(),
941            observed_at: second_at,
942            phase: LiveGamePhase::InProgress,
943            period: Some("1".into()),
944            clock: Some("09:40".into()),
945            home_score: Some(7),
946            away_score: Some(3),
947            players: None,
948            defenses: None,
949        };
950        let snapshot = reducer.apply(
951            &box_event(&live_game, second, second_at),
952            std::slice::from_ref(&live_game),
953        );
954        let state = snapshot.game("live").expect("live game");
955        assert_eq!(state.players.len(), 1);
956        assert_eq!(state.defenses.len(), 1);
957        assert_eq!(state.away_score, Some(3));
958        let before_failure =
959            score_live_lineup(&lineup(), &snapshot, second_at + time::Duration::seconds(1));
960
961        let error_at = datetime!(2025 - 09 - 07 18:01 UTC);
962        let error = response(
963            ProviderOutcome::Error(LiveProviderError::Transport {
964                message: "timeout".into(),
965            }),
966            error_at,
967        );
968        let snapshot = reducer.apply(
969            &PollEvent::BoxScore {
970                sequence: 2,
971                game: live_game.clone(),
972                request: tank01_data::PollRequest {
973                    endpoint: "box".into(),
974                    query: BTreeMap::new(),
975                },
976                play_by_play: false,
977                changed: false,
978                response: error,
979            },
980            std::slice::from_ref(&live_game),
981        );
982        let after_failure = score_live_lineup(&lineup(), &snapshot, error_at);
983        assert_eq!(after_failure.points, before_failure.points);
984        assert_eq!(after_failure.coverage, before_failure.coverage);
985        let state = snapshot.game("live").expect("live game");
986        assert_eq!(state.players.len(), 1);
987        assert_eq!(state.defenses.len(), 1);
988        assert!(state.player_stale);
989        assert!(state.last_error.is_some());
990    }
991
992    #[test]
993    fn scheduled_slots_are_zero_but_missing_live_defense_is_unavailable() {
994        let game = game();
995        let live_game = live_game(&game).expect("fixture kickoff");
996        let identity = identity();
997        let scheduled_at = datetime!(2025 - 09 - 07 16:00 UTC);
998        let mut reducer = SnapshotReducer::new(SlateId(1), vec![game], identity, scheduled_at);
999        let scheduled = reducer.snapshot();
1000        let scheduled_total = score_live_lineup(&lineup(), &scheduled, scheduled_at);
1001        assert_eq!(scheduled_total.points, Some(0.0));
1002        assert_eq!(scheduled_total.coverage, Coverage::Complete);
1003
1004        let observed_at = datetime!(2025 - 09 - 07 18:00 UTC);
1005        let live = LiveGameSnapshot {
1006            game: live_game.clone(),
1007            observed_at,
1008            phase: LiveGamePhase::InProgress,
1009            period: Some("1".into()),
1010            clock: Some("10:00".into()),
1011            home_score: Some(7),
1012            away_score: Some(0),
1013            players: Some(vec![player_stats()]),
1014            defenses: Some(Vec::new()),
1015        };
1016        let snapshot = reducer.apply(
1017            &box_event(&live_game, live, observed_at),
1018            std::slice::from_ref(&live_game),
1019        );
1020        let defense = score_live_slot(&lineup(), RosterSlot::Def, &snapshot, observed_at);
1021        assert_eq!(defense.total.coverage, Coverage::Unavailable);
1022        assert_eq!(
1023            score_live_lineup(&lineup(), &snapshot, observed_at).coverage,
1024            Coverage::Partial
1025        );
1026    }
1027    #[test]
1028    fn final_games_are_not_delayed_by_stale_state() {
1029        let game = game();
1030        let reducer = SnapshotReducer::new(
1031            SlateId(1),
1032            vec![game],
1033            identity(),
1034            datetime!(2025 - 09 - 07 18:00 UTC),
1035        );
1036        let mut snapshot = reducer.snapshot();
1037        let state = snapshot.game_states.get_mut("live").expect("live game");
1038        state.phase = LiveGamePhase::Final;
1039        state.last_error = Some(LiveError::Feed);
1040        state.player_stale = true;
1041        state.player_observed_at = Some(datetime!(2025 - 09 - 07 18:00 UTC));
1042        state
1043            .defense_observed_at
1044            .insert(state.game.home_team, datetime!(2025 - 09 - 07 18:00 UTC));
1045        state.defense_stale.insert(state.game.home_team, true);
1046        state.defense_stale.insert(state.game.away_team, true);
1047
1048        assert!(!snapshot.is_delayed(datetime!(2025 - 09 - 07 18:05 UTC)));
1049    }
1050
1051    #[test]
1052    fn missing_live_defense_observation_is_delayed() {
1053        let game = game();
1054        let live_game = live_game(&game).expect("fixture kickoff");
1055        let observed_at = datetime!(2025 - 09 - 07 18:00 UTC);
1056        let mut reducer = SnapshotReducer::new(SlateId(1), vec![game], identity(), observed_at);
1057        let live = LiveGameSnapshot {
1058            game: live_game.clone(),
1059            observed_at,
1060            phase: LiveGamePhase::InProgress,
1061            period: Some("1".into()),
1062            clock: Some("10:00".into()),
1063            home_score: Some(7),
1064            away_score: Some(0),
1065            players: Some(vec![player_stats()]),
1066            defenses: Some(vec![defense_stats()]),
1067        };
1068        let snapshot = reducer.apply(
1069            &box_event(&live_game, live, observed_at),
1070            std::slice::from_ref(&live_game),
1071        );
1072
1073        assert!(snapshot.is_delayed(observed_at + time::Duration::seconds(1)));
1074    }
1075    #[test]
1076    fn due_game_without_status_observation_is_unavailable() {
1077        let game = game();
1078        let now = datetime!(2025 - 09 - 07 18:00 UTC);
1079        let reducer = SnapshotReducer::new(SlateId(1), vec![game], identity(), now);
1080        let total = score_live_lineup(&lineup(), &reducer.snapshot(), now);
1081
1082        assert_eq!(total.points, None);
1083        assert_eq!(total.coverage, Coverage::Unavailable);
1084    }
1085
1086    fn minutes_state(
1087        phase: LiveGamePhase,
1088        period: Option<&str>,
1089        clock: Option<&str>,
1090    ) -> LiveGameState {
1091        LiveGameState {
1092            game: game(),
1093            tank01_game_id: Some("live".into()),
1094            phase,
1095            period: period.map(str::to_string),
1096            clock: clock.map(str::to_string),
1097            home_score: Some(14),
1098            away_score: Some(7),
1099            status_observed: true,
1100            players: HashMap::new(),
1101            player_section_present: false,
1102            player_identity_incomplete: false,
1103            player_observed_at: None,
1104            player_stale: false,
1105            defenses: HashMap::new(),
1106            defense_observed_at: HashMap::new(),
1107            defense_stale: HashMap::new(),
1108            last_error: None,
1109        }
1110    }
1111
1112    #[test]
1113    fn game_minutes_remaining_follows_phase_rules() {
1114        let now = datetime!(2025 - 09 - 07 18:00 UTC);
1115        let minutes = |state: LiveGameState| game_minutes_remaining(Some(&state), now);
1116
1117        assert_eq!(game_minutes_remaining(None, now), 60.0);
1118        assert_eq!(
1119            minutes(minutes_state(LiveGamePhase::Scheduled, None, None)),
1120            60.0
1121        );
1122        assert_eq!(
1123            minutes(minutes_state(
1124                LiveGamePhase::Unknown,
1125                Some("3"),
1126                Some("05:00")
1127            )),
1128            60.0
1129        );
1130        assert_eq!(
1131            minutes(minutes_state(
1132                LiveGamePhase::Final,
1133                Some("4"),
1134                Some("00:00")
1135            )),
1136            0.0
1137        );
1138        assert_eq!(
1139            minutes(minutes_state(
1140                LiveGamePhase::InProgress,
1141                Some("2"),
1142                Some("08:00")
1143            )),
1144            38.0
1145        );
1146        assert_eq!(
1147            minutes(minutes_state(
1148                LiveGamePhase::InProgress,
1149                Some("Q2"),
1150                Some("08:00")
1151            )),
1152            38.0,
1153            "provider decorations around the quarter digit parse"
1154        );
1155        assert_eq!(
1156            minutes(minutes_state(
1157                LiveGamePhase::InProgress,
1158                Some("2"),
1159                Some("00:00")
1160            )),
1161            30.0
1162        );
1163        assert_eq!(
1164            minutes(minutes_state(
1165                LiveGamePhase::InProgress,
1166                Some("1"),
1167                Some("15:00")
1168            )),
1169            60.0
1170        );
1171        assert_eq!(
1172            minutes(minutes_state(
1173                LiveGamePhase::InProgress,
1174                Some("5"),
1175                Some("10:00")
1176            )),
1177            0.0
1178        );
1179        assert_eq!(
1180            minutes(minutes_state(LiveGamePhase::InProgress, Some("3"), None)),
1181            30.0
1182        );
1183        assert_eq!(
1184            minutes(minutes_state(
1185                LiveGamePhase::InProgress,
1186                Some("1"),
1187                Some("99:00")
1188            )),
1189            60.0,
1190            "clock seconds cap at a full quarter"
1191        );
1192
1193        let kickoff = minutes_state(LiveGamePhase::InProgress, None, None);
1194        assert_eq!(
1195            game_minutes_remaining(Some(&kickoff), datetime!(2025 - 09 - 07 18:30 UTC)),
1196            30.0,
1197            "wall-clock fallback halfway through the ~3h window"
1198        );
1199        assert_eq!(
1200            game_minutes_remaining(Some(&kickoff), datetime!(2025 - 09 - 07 16:50 UTC)),
1201            60.0,
1202            "a hit-before-kickoff InProgress state clamps, never overdrains"
1203        );
1204    }
1205
1206    fn minutes_snapshot(
1207        phase: LiveGamePhase,
1208        period: Option<&str>,
1209        clock: Option<&str>,
1210    ) -> LiveContestSnapshot {
1211        let state = minutes_state(phase, period, clock);
1212        LiveContestSnapshot {
1213            contest: SlateId(1),
1214            games: vec![state.game.clone()],
1215            stats: WeekStats::default(),
1216            game_states: HashMap::from([("live".into(), state)]),
1217            identity: Arc::new(LiveIdentityIndex::from_sources(
1218                &[factories::player("p1", "A Runner")],
1219                &[],
1220            )),
1221            identity_outcomes: Default::default(),
1222            latest_error: None,
1223            revision: 1,
1224        }
1225    }
1226
1227    #[test]
1228    fn lineup_minutes_sums_all_nine_slots_and_clamps() {
1229        let now = datetime!(2025 - 09 - 07 18:00 UTC);
1230        let final_snapshot = minutes_snapshot(LiveGamePhase::Final, Some("4"), Some("00:00"));
1231        assert_eq!(
1232            lineup_minutes_remaining(&lineup(), &final_snapshot, now),
1233            0.0
1234        );
1235
1236        let live_snapshot = minutes_snapshot(LiveGamePhase::InProgress, Some("2"), Some("08:00"));
1237        assert_eq!(
1238            lineup_minutes_remaining(&lineup(), &live_snapshot, now),
1239            342.0,
1240            "nine slots x 38 minutes each"
1241        );
1242
1243        let mut identityless = live_snapshot;
1244        identityless.identity = Arc::new(LiveIdentityIndex::empty());
1245        assert_eq!(
1246            lineup_minutes_remaining(&lineup(), &identityless, now),
1247            518.0,
1248            "player gaps hold at a full slot; the def still counts its game's 38"
1249        );
1250
1251        let mut unresolvable = minutes_snapshot(LiveGamePhase::Scheduled, None, None);
1252        unresolvable.game_states.clear();
1253        unresolvable.identity = Arc::new(LiveIdentityIndex::empty());
1254        assert_eq!(
1255            lineup_minutes_remaining(&lineup(), &unresolvable, now),
1256            540.0,
1257            "nine unresolvable slots fill the bar to the full mark"
1258        );
1259    }
1260}