Skip to main content

sunday_slate/live/
identity.rs

1use std::collections::{BTreeSet, HashMap};
2
3use nfl_data::{
4    EspnPlayerId, NflData, NflDataError, Player, SeasonWeek, TeamAbbr, WeeklyRosterEntry,
5};
6
7use crate::entries::NflPlayerId;
8use crate::player_identity::{canonical_team, normalize_name};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum IdentityMatch {
12    Matched(NflPlayerId),
13    Unresolved,
14    Ambiguous,
15}
16
17#[derive(Debug, Clone)]
18pub struct IdentityRecord {
19    pub gsis_id: NflPlayerId,
20    pub name: String,
21    pub team: Option<TeamAbbr>,
22    pub position: Option<String>,
23}
24
25#[derive(Debug, Clone, Default)]
26pub struct LiveIdentityIndex {
27    by_espn: HashMap<String, BTreeSet<NflPlayerId>>,
28    by_name: HashMap<(String, String, String), BTreeSet<NflPlayerId>>,
29    by_gsis: HashMap<NflPlayerId, IdentityRecord>,
30}
31
32impl LiveIdentityIndex {
33    pub fn empty() -> Self {
34        Self::default()
35    }
36
37    pub fn from_sources(players: &[Player], rosters: &[WeeklyRosterEntry]) -> Self {
38        let mut facts = HashMap::<NflPlayerId, IdentityFacts>::new();
39        for player in players {
40            let gsis_id = NflPlayerId(player.gsis_id.clone());
41            let facts = facts.entry(gsis_id).or_default();
42            facts.add_name(&player.full_name);
43            facts.add_espn(player.espn_id.as_deref());
44            facts.add_global_team(player.latest_team.as_ref());
45            facts.add_global_position(player.position.as_deref());
46        }
47        for roster in rosters {
48            let Some(gsis) = roster.gsis_id.as_deref().filter(|id| !id.is_empty()) else {
49                continue;
50            };
51            let facts = facts.entry(NflPlayerId(gsis.to_owned())).or_default();
52            facts.add_name(&roster.full_name);
53            facts.add_espn(roster.espn_id.as_deref());
54            facts.weekly = true;
55            facts
56                .weekly_teams
57                .insert(canonical_team(&roster.team).as_str().to_owned());
58            if let Some(position) = roster.position.as_deref() {
59                facts.weekly_positions.insert(normalize_position(position));
60            }
61        }
62
63        let mut index = Self::default();
64        for (gsis_id, facts) in facts {
65            let (team, position) = if facts.weekly {
66                (
67                    unique_team(&facts.weekly_teams),
68                    unique_string(&facts.weekly_positions),
69                )
70            } else {
71                (
72                    unique_team(&facts.global_teams),
73                    unique_string(&facts.global_positions),
74                )
75            };
76            let record = IdentityRecord {
77                gsis_id: gsis_id.clone(),
78                name: facts.names.values().next().cloned().unwrap_or_default(),
79                team: team.and_then(|team| team.parse().ok()),
80                position,
81            };
82            index.by_gsis.insert(gsis_id.clone(), record);
83            for espn_id in facts.espn_ids {
84                index
85                    .by_espn
86                    .entry(espn_id)
87                    .or_default()
88                    .insert(gsis_id.clone());
89            }
90            if let (Some(team), Some(position)) = (
91                index
92                    .by_gsis
93                    .get(&gsis_id)
94                    .and_then(|record| record.team.as_ref()),
95                index
96                    .by_gsis
97                    .get(&gsis_id)
98                    .and_then(|record| record.position.as_deref()),
99            ) {
100                for name in facts.names.keys() {
101                    index
102                        .by_name
103                        .entry((
104                            name.clone(),
105                            team.as_str().to_owned(),
106                            normalize_position(position),
107                        ))
108                        .or_default()
109                        .insert(gsis_id.clone());
110                }
111            }
112        }
113        index
114    }
115
116    pub async fn build(
117        nfl: &NflData,
118        season_week: SeasonWeek,
119        teams: &[TeamAbbr],
120    ) -> Result<Self, NflDataError> {
121        let players = nfl.players().await?;
122        let mut rosters = Vec::new();
123        let mut seen = BTreeSet::new();
124        for team in teams {
125            if !seen.insert(team.as_str().to_owned()) {
126                continue;
127            }
128            rosters.extend(nfl.weekly_roster(season_week, team).await?);
129        }
130        Ok(Self::from_sources(&players, &rosters))
131    }
132
133    pub fn resolve(
134        &self,
135        espn_id: Option<&EspnPlayerId>,
136        name: Option<&str>,
137        team: Option<&TeamAbbr>,
138        position: Option<&str>,
139    ) -> IdentityMatch {
140        if let Some(espn_id) = espn_id
141            && let Some(candidates) = self.by_espn.get(&espn_id.0)
142        {
143            return match candidates.iter().next() {
144                Some(gsis) if candidates.len() == 1 => IdentityMatch::Matched(gsis.clone()),
145                Some(_) => IdentityMatch::Ambiguous,
146                None => IdentityMatch::Unresolved,
147            };
148        }
149
150        let (Some(name), Some(team), Some(position)) = (name, team, position) else {
151            return IdentityMatch::Unresolved;
152        };
153        let key = (
154            normalize_name(name),
155            team.as_str().to_owned(),
156            normalize_position(position),
157        );
158        match self.by_name.get(&key) {
159            Some(candidates) if candidates.len() == 1 => {
160                IdentityMatch::Matched(candidates.iter().next().expect("one candidate").clone())
161            }
162            Some(candidates) if !candidates.is_empty() => IdentityMatch::Ambiguous,
163            _ => IdentityMatch::Unresolved,
164        }
165    }
166
167    pub fn record(&self, gsis_id: &NflPlayerId) -> Option<&IdentityRecord> {
168        self.by_gsis.get(gsis_id)
169    }
170
171    pub fn contains_gsis(&self, gsis_id: &NflPlayerId) -> bool {
172        self.by_gsis.contains_key(gsis_id)
173    }
174
175    pub fn scheduled_team(&self, gsis_id: &NflPlayerId) -> Option<&TeamAbbr> {
176        self.record(gsis_id).and_then(|record| record.team.as_ref())
177    }
178
179    pub fn position(&self, gsis_id: &NflPlayerId) -> Option<&str> {
180        self.record(gsis_id)
181            .and_then(|record| record.position.as_deref())
182    }
183}
184
185#[derive(Default)]
186struct IdentityFacts {
187    names: std::collections::BTreeMap<String, String>,
188    espn_ids: BTreeSet<String>,
189    global_teams: BTreeSet<String>,
190    global_positions: BTreeSet<String>,
191    weekly: bool,
192    weekly_teams: BTreeSet<String>,
193    weekly_positions: BTreeSet<String>,
194}
195
196impl IdentityFacts {
197    fn add_name(&mut self, name: &str) {
198        let normalized = normalize_name(name);
199        if !normalized.is_empty() {
200            self.names
201                .entry(normalized)
202                .or_insert_with(|| name.to_owned());
203        }
204    }
205
206    fn add_espn(&mut self, espn_id: Option<&str>) {
207        if let Some(espn_id) = espn_id.filter(|id| !id.is_empty()) {
208            self.espn_ids.insert(espn_id.to_owned());
209        }
210    }
211
212    fn add_global_team(&mut self, team: Option<&TeamAbbr>) {
213        if let Some(team) = team {
214            self.global_teams
215                .insert(canonical_team(team).as_str().to_owned());
216        }
217    }
218
219    fn add_global_position(&mut self, position: Option<&str>) {
220        if let Some(position) = position {
221            self.global_positions.insert(normalize_position(position));
222        }
223    }
224}
225
226fn unique_team(values: &BTreeSet<String>) -> Option<String> {
227    (values.len() == 1).then(|| values.iter().next().expect("one team").clone())
228}
229
230fn unique_string(values: &BTreeSet<String>) -> Option<String> {
231    (values.len() == 1).then(|| values.iter().next().expect("one value").clone())
232}
233
234fn normalize_position(position: &str) -> String {
235    position.trim().to_ascii_uppercase()
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use nfl_data::{Season, TeamAbbr, Week};
242    fn player(gsis: &str, espn: Option<&str>, name: &str, team: &str, position: &str) -> Player {
243        Player {
244            gsis_id: gsis.into(),
245            espn_id: espn.map(str::to_owned),
246            full_name: name.into(),
247            first_name: None,
248            last_name: None,
249            position: Some(position.into()),
250            latest_team: Some(team.parse().unwrap()),
251            headshot_url: None,
252        }
253    }
254
255    fn roster(
256        gsis: &str,
257        espn: Option<&str>,
258        name: &str,
259        team: &str,
260        position: &str,
261    ) -> WeeklyRosterEntry {
262        WeeklyRosterEntry {
263            season_week: SeasonWeek::new(Season(2025), Week(1)).unwrap(),
264            team: team.parse().unwrap(),
265            gsis_id: Some(gsis.into()),
266            espn_id: espn.map(str::to_owned),
267            full_name: name.into(),
268            last_name: None,
269            position: Some(position.into()),
270        }
271    }
272
273    #[test]
274    fn exact_espn_id_wins_and_conflicts_stay_ambiguous() {
275        let index = LiveIdentityIndex::from_sources(
276            &[player("a", Some("e1"), "A Player", "BUF", "RB")],
277            &[],
278        );
279        assert_eq!(
280            index.resolve(
281                Some(&EspnPlayerId("e1".into())),
282                Some("wrong"),
283                Some(&TeamAbbr::BUF),
284                Some("RB"),
285            ),
286            IdentityMatch::Matched(NflPlayerId("a".into()))
287        );
288
289        let conflict = LiveIdentityIndex::from_sources(
290            &[
291                player("a", Some("e1"), "A Player", "BUF", "RB"),
292                player("b", Some("e1"), "A Player", "BUF", "RB"),
293            ],
294            &[],
295        );
296        assert_eq!(
297            conflict.resolve(
298                Some(&EspnPlayerId("e1".into())),
299                Some("A Player"),
300                Some(&TeamAbbr::BUF),
301                Some("RB"),
302            ),
303            IdentityMatch::Ambiguous
304        );
305    }
306
307    #[test]
308    fn fallback_requires_name_team_and_position() {
309        let index =
310            LiveIdentityIndex::from_sources(&[], &[roster("a", None, "A Player", "LAR", "RB")]);
311        assert_eq!(
312            index.resolve(None, Some("A Player"), Some(&TeamAbbr::LA), Some("RB"),),
313            IdentityMatch::Matched(NflPlayerId("a".into()))
314        );
315        assert_eq!(
316            index.resolve(None, Some("A Player"), Some(&TeamAbbr::LA), None,),
317            IdentityMatch::Unresolved
318        );
319    }
320    #[test]
321    fn weekly_attributes_override_global_attributes_and_keep_both_names() {
322        let index = LiveIdentityIndex::from_sources(
323            &[player("a", None, "Global Name", "BUF", "RB")],
324            &[roster("a", None, "Weekly Name", "KC", "WR")],
325        );
326        assert_eq!(
327            index.scheduled_team(&NflPlayerId("a".into())),
328            Some(&TeamAbbr::KC)
329        );
330        assert_eq!(index.position(&NflPlayerId("a".into())), Some("WR"));
331        assert_eq!(
332            index.resolve(None, Some("Global Name"), Some(&TeamAbbr::KC), Some("WR"),),
333            IdentityMatch::Matched(NflPlayerId("a".into()))
334        );
335        assert_eq!(
336            index.resolve(None, Some("Weekly Name"), Some(&TeamAbbr::KC), Some("WR"),),
337            IdentityMatch::Matched(NflPlayerId("a".into()))
338        );
339        assert_eq!(
340            index.resolve(None, Some("Global Name"), Some(&TeamAbbr::BUF), Some("RB"),),
341            IdentityMatch::Unresolved
342        );
343    }
344
345    #[test]
346    fn duplicate_weekly_records_do_not_create_ambiguity() {
347        let rows = vec![
348            roster("a", None, "A Player", "KC", "RB"),
349            roster("a", None, "A Player", "KC", "RB"),
350        ];
351        let index = LiveIdentityIndex::from_sources(&[], &rows);
352        assert_eq!(
353            index.resolve(None, Some("A Player"), Some(&TeamAbbr::KC), Some("RB"),),
354            IdentityMatch::Matched(NflPlayerId("a".into()))
355        );
356    }
357
358    #[test]
359    fn conflicting_weekly_attributes_are_order_independent_and_unusable() {
360        let first = vec![
361            roster("a", None, "A Player", "KC", "RB"),
362            roster("a", None, "A Player", "BUF", "WR"),
363        ];
364        let second = first.iter().rev().cloned().collect::<Vec<_>>();
365        for rows in [first, second] {
366            let index = LiveIdentityIndex::from_sources(&[], &rows);
367            assert_eq!(index.scheduled_team(&NflPlayerId("a".into())), None);
368            assert_eq!(index.position(&NflPlayerId("a".into())), None);
369            assert_eq!(
370                index.resolve(None, Some("A Player"), Some(&TeamAbbr::KC), Some("RB"),),
371                IdentityMatch::Unresolved
372            );
373        }
374
375        let conflicting_positions = vec![
376            roster("b", None, "B Player", "KC", "RB"),
377            roster("b", None, "B Player", "KC", "WR"),
378        ];
379        let index = LiveIdentityIndex::from_sources(&[], &conflicting_positions);
380        assert_eq!(
381            index.scheduled_team(&NflPlayerId("b".into())),
382            Some(&TeamAbbr::KC)
383        );
384        assert_eq!(index.position(&NflPlayerId("b".into())), None);
385    }
386
387    #[test]
388    fn conflicting_exact_ids_stay_ambiguous_in_either_input_order() {
389        let players = vec![
390            player("a", Some("e1"), "A Player", "BUF", "RB"),
391            player("b", Some("e1"), "B Player", "KC", "RB"),
392        ];
393        for source in [players.clone(), players.into_iter().rev().collect()] {
394            let index = LiveIdentityIndex::from_sources(&source, &[]);
395            assert_eq!(
396                index.resolve(Some(&EspnPlayerId("e1".into())), None, None, None),
397                IdentityMatch::Ambiguous
398            );
399        }
400    }
401
402    /// A middle-of-season trade means one week's index must never answer for
403    /// another week: the same player resolves to the team he was on then.
404    #[tokio::test]
405    async fn season_week_build_scopes_identity_to_its_own_week() {
406        let nfl = NflData::in_memory().await.expect("in-memory handle");
407        let thielen = |team: &str, week: u8| WeeklyRosterEntry {
408            season_week: SeasonWeek::new(Season(2025), Week(week)).expect("valid fixture week"),
409            team: team.parse().unwrap(),
410            gsis_id: Some("00-0030035".into()),
411            espn_id: None,
412            full_name: "Adam Thielen".into(),
413            last_name: Some("Thielen".into()),
414            position: Some("WR".into()),
415        };
416        nfl.seed_weekly_roster_for_test(&[thielen("MIN", 13), thielen("PIT", 14)])
417            .await
418            .expect("seed weekly roster");
419
420        let gsis = NflPlayerId("00-0030035".into());
421        let teams = [TeamAbbr::MIN, TeamAbbr::PIT];
422        let earlier = LiveIdentityIndex::build(
423            &nfl,
424            SeasonWeek::new(Season(2025), Week(13)).expect("valid fixture week"),
425            &teams,
426        )
427        .await
428        .expect("build week 13");
429        let later = LiveIdentityIndex::build(
430            &nfl,
431            SeasonWeek::new(Season(2025), Week(14)).expect("valid fixture week"),
432            &teams,
433        )
434        .await
435        .expect("build week 14");
436
437        assert_eq!(earlier.scheduled_team(&gsis), Some(&TeamAbbr::MIN));
438        assert_eq!(later.scheduled_team(&gsis), Some(&TeamAbbr::PIT));
439    }
440}