Coverage for mt_ai/tools/visibility.py: 96.88%

74 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1"""The set of teams a viewer may see, built from cached reads. 

2 

3A team is test content (SB-85/SB-591) when its club or its own league is 

4flagged `is_test`; an age-group registration is test content when its 

5division's league is. Real viewers never see either — a tool that leaked a 

6test team would put CI's fake fixtures into a parent's answer. 

7 

8Everything here comes from `@dao_cache`d DAO reads, so building the index costs 

9Redis lookups, not queries, on a warm cache. 

10""" 

11 

12from dataclasses import dataclass, field 

13from zoneinfo import ZoneInfo, ZoneInfoNotFoundError 

14 

15from mt_ai.tools.deps import ToolDeps 

16from mt_ai.tools.schemas import AgeGroupRef, Registration, TeamCandidate, Viewer 

17 

18DEFAULT_TIMEZONE = "America/New_York" # matches notifications/channel_resolver.py 

19 

20 

21class DataUnavailableError(Exception): 

22 """A read the tool depends on failed or returned something impossible.""" 

23 

24 

25@dataclass(frozen=True) 

26class TeamIndex: 

27 teams: dict[int, dict] = field(default_factory=dict) # visible teams only 

28 clubs: dict[int, dict] = field(default_factory=dict) 

29 leagues: dict[int, dict] = field(default_factory=dict) 

30 test_league_ids: frozenset[int] = frozenset() 

31 test_club_ids: frozenset[int] = frozenset() 

32 include_test: bool = False 

33 

34 def visible_club(self, club_id: int | None) -> dict | None: 

35 """The club, unless it is unknown or test content this viewer may not see.""" 

36 if club_id is None or (club_id in self.test_club_ids and not self.include_test): 

37 return None 

38 return self.clubs.get(club_id) 

39 

40 def club_name(self, team: dict) -> str | None: 

41 club = self.clubs.get(team.get("club_id") or 0) 

42 return club.get("name") if club else None 

43 

44 def league_name(self, team: dict) -> str | None: 

45 league = self.leagues.get(team.get("league_id") or 0) 

46 return league.get("name") if league else team.get("league_name") 

47 

48 def timezone(self, team: dict) -> ZoneInfo: 

49 club = self.clubs.get(team.get("club_id") or 0) 

50 name = (club or {}).get("timezone") or DEFAULT_TIMEZONE 

51 try: 

52 return ZoneInfo(name) 

53 except (ZoneInfoNotFoundError, ValueError): 

54 return ZoneInfo(DEFAULT_TIMEZONE) 

55 

56 def candidates(self, team: dict, age_group_name: str | None = None) -> list[TeamCandidate]: 

57 """One candidate per age group the team plays in (optionally just one age). 

58 

59 Built from the raw `team_mappings` rows, one per (age group, division). 

60 A team in two competitions at one age — League and Flex — is one 

61 candidate with two registrations. `divisions_by_age_group`, a dict keyed 

62 by age group, keeps only one division per age, which made such a team 

63 look like two identical teams (SB-1146). 

64 

65 A team with no visible registrations yields a single age-less 

66 candidate, unless a specific age was asked for — then it yields none. 

67 """ 

68 by_age: dict[int, tuple[AgeGroupRef, list[Registration]]] = {} 

69 for mapping in team.get("team_mappings") or []: 

70 age = mapping.get("age_groups") 

71 if not age: 71 ↛ 72line 71 didn't jump to line 72 because the condition on line 71 was never true

72 continue 

73 if age_group_name and str(age.get("name", "")).casefold() != age_group_name.casefold(): 

74 continue 

75 division = mapping.get("divisions") or {} 

76 if not self.include_test and division.get("league_id") in self.test_league_ids: 

77 continue 

78 ref, registrations = by_age.setdefault(age["id"], (AgeGroupRef(id=age["id"], name=age["name"]), [])) 

79 if division: 

80 registration = Registration(league=_league_of(division), division=division.get("name")) 

81 if registration not in registrations: 81 ↛ 69line 81 didn't jump to line 69 because the condition on line 81 was always true

82 registrations.append(registration) 

83 

84 out = [self._candidate(team, ref, regs) for ref, regs in sorted(by_age.values(), key=_age_order)] 

85 if not out and not age_group_name and not team.get("team_mappings"): 

86 out.append(self._candidate(team, None, [])) 

87 return out 

88 

89 def _candidate(self, team: dict, age: AgeGroupRef | None, registrations: list[Registration]) -> TeamCandidate: 

90 return TeamCandidate( 

91 team_id=team["id"], 

92 name=team["name"], 

93 club_name=self.club_name(team), 

94 league_name=self.league_name(team), 

95 age_group=age, 

96 registrations=sorted(registrations, key=lambda r: (r.league or "", r.division or "")), 

97 ) 

98 

99 

100def _league_of(division: dict) -> str | None: 

101 leagues = division.get("leagues") 

102 return (leagues or {}).get("name") or division.get("league_name") 

103 

104 

105def _age_order(item: tuple[AgeGroupRef, list[Registration]]) -> tuple[int, str]: 

106 """U9 before U13 before U19: numeric where the name has a number.""" 

107 name = item[0].name 

108 digits = "".join(ch for ch in name if ch.isdigit()) 

109 return (int(digits) if digits else 999, name) 

110 

111 

112def load_team_index(deps: ToolDeps, viewer: Viewer) -> TeamIndex: 

113 leagues = deps.leagues.get_all_leagues(include_test=True) 

114 if not leagues: 

115 # get_all_leagues swallows errors and returns []. MT always has leagues, 

116 # so empty means the read failed — and without it test teams can't be 

117 # told apart. Fail closed rather than risk showing them. 

118 raise DataUnavailableError("league list unavailable") 

119 clubs = deps.clubs.get_all_clubs(include_team_counts=False) 

120 

121 test_league_ids = frozenset(lg["id"] for lg in leagues if lg.get("is_test")) 

122 test_club_ids = frozenset(c["id"] for c in clubs if c.get("is_test")) 

123 

124 teams: dict[int, dict] = {} 

125 for team in deps.teams.get_all_teams(): 

126 is_test = team.get("club_id") in test_club_ids or team.get("league_id") in test_league_ids 

127 if is_test and not viewer.include_test: 

128 continue 

129 teams[team["id"]] = team 

130 

131 return TeamIndex( 

132 teams=teams, 

133 clubs={c["id"]: c for c in clubs}, 

134 leagues={lg["id"]: lg for lg in leagues}, 

135 test_league_ids=test_league_ids, 

136 test_club_ids=test_club_ids, 

137 include_test=viewer.include_test, 

138 )