Coverage for dao/team_sides.py: 89.83%

86 statements  

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

1"""Which side of the youth pyramid a team is on (SB-1748). 

2 

3MLS NEXT Fest puts the Homegrown Division and the Academy Division in one 

4event, and many clubs field a team on each side under the same name. A 

5tournament message says which side it means (`league`: "Homegrown" or 

6"Academy"); this module decides whether a team found by name is on that side. 

7 

8Pure: no database, no DAO imports. The DAO fetches rows and hands them here, 

9so every rule below is tested without one. 

10 

11`teams.league_id` alone cannot be the test — Homegrown clubs carry Flex there 

12and MLS academies carry NULL — so a team's side is read from where it is 

13registered to play (`team_mappings`), with `teams.league_id` only as a 

14fallback. 

15""" 

16 

17from __future__ import annotations 

18 

19from dataclasses import dataclass 

20from typing import TYPE_CHECKING 

21 

22if TYPE_CHECKING: 

23 from collections.abc import Iterable, Mapping 

24 

25RESOLVED = "resolved" 

26AMBIGUOUS = "ambiguous" 

27WRONG_SIDE = "wrong_side" 

28MISSING = "missing" 

29# The message's league is not one MT has: nothing about the team was looked up. 

30UNKNOWN_LEAGUE = "unknown_league" 

31 

32 

33@dataclass(frozen=True) 

34class Candidate: 

35 """A team a name could refer to, with the sides it plays on. 

36 

37 `sides_at_age` is the part of `sides` read from its registrations at the 

38 message's age group itself; empty when `sides` is the every-age fallback. 

39 """ 

40 

41 team_id: int 

42 sides: frozenset[str] 

43 sides_at_age: frozenset[str] = frozenset() 

44 

45 

46@dataclass(frozen=True) 

47class Resolution: 

48 """What a name resolved to. `team_id` is set only when status is RESOLVED. 

49 

50 `reason` is for the ingest failure row an admin reads, never for a client. 

51 """ 

52 

53 status: str 

54 team_id: int | None = None 

55 reason: str | None = None 

56 

57 

58def top_level_league(league_id: int | None, leagues: Mapping[int, Mapping]) -> str | None: 

59 """The name of the league at the top of `league_id`'s parent chain. 

60 

61 A child league is folded into its parent (Flex → Homegrown). `leagues` 

62 maps id → a row with `name` and `parent_league_id`. None for no league or 

63 one the map does not have. 

64 """ 

65 seen: set[int] = set() 

66 current = league_id 

67 while current is not None and current in leagues and current not in seen: 

68 seen.add(current) 

69 parent = leagues[current].get("parent_league_id") 

70 if parent is None or parent not in leagues: 

71 return leagues[current].get("name") 

72 current = parent 

73 # A parent chain that loops has no top; name where the walk stopped. 

74 return leagues[current].get("name") if current in leagues else None 

75 

76 

77def league_named(hint: str | None, leagues: Mapping[int, Mapping]) -> int | None: 

78 """The id of the league a message's `league` names, or None if MT has none. 

79 

80 Compared whole, without case or padding. Never a pattern and never a 

81 nearest match: "HD" is not Homegrown. 

82 """ 

83 wanted = (hint or "").strip().casefold() 

84 if not wanted: 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 return None 

86 for league_id, row in leagues.items(): 

87 if (row.get("name") or "").strip().casefold() == wanted: 

88 return league_id 

89 return None 

90 

91 

92def _fold(league_ids: Iterable[int | None], leagues: Mapping[int, Mapping]) -> frozenset[str]: 

93 names = (top_level_league(league_id, leagues) for league_id in league_ids) 

94 return frozenset(name for name in names if name) 

95 

96 

97def sides_at_age( 

98 mappings: Iterable[tuple[int | None, int | None]], 

99 age_group_id: int | None, 

100 leagues: Mapping[int, Mapping], 

101) -> frozenset[str]: 

102 """The top-level leagues of a team's divisions at one age group. 

103 

104 Empty when it has no registration there, or the age group is unknown. 

105 """ 

106 if age_group_id is None: 106 ↛ 107line 106 didn't jump to line 107 because the condition on line 106 was never true

107 return frozenset() 

108 return _fold((league for age, league in mappings if league is not None and age == age_group_id), leagues) 

109 

110 

111def team_sides( 

112 mappings: Iterable[tuple[int | None, int | None]], 

113 team_league_id: int | None, 

114 age_group_id: int | None, 

115 leagues: Mapping[int, Mapping], 

116) -> frozenset[str]: 

117 """The top-level leagues a team plays in at an age group. 

118 

119 `mappings` is the team's registrations as `(age_group_id, league_id)`, 

120 the league being that of the mapped division. 

121 

122 At `age_group_id`, the answer is the leagues of its divisions at that age. 

123 A team with none there falls back to its registrations at every age plus 

124 `teams.league_id`. Empty when nothing says which side it is on. 

125 """ 

126 rows = [(age, league) for age, league in mappings if league is not None] 

127 at_age = sides_at_age(rows, age_group_id, leagues) 

128 if at_age: 

129 return at_age 

130 return _fold([*(league for _, league in rows), team_league_id], leagues) 

131 

132 

133def classify(candidates: Iterable[Candidate], hint: str | None) -> Resolution: 

134 """Pick the candidate on the hinted side, or say why none can be picked. 

135 

136 With a hint, only candidates whose sides include it count: one is the 

137 answer, several are ambiguous, none means the name exists only on the 

138 other side. With no hint there is nothing to tell candidates apart, so one 

139 candidate is the answer and several are ambiguous. Never a guess. 

140 

141 A candidate registered on the hinted side *and* another at the message's 

142 age group does not count as on that side: the registrations cannot say 

143 which of the two it is, and taking it is how an Academy fixture lands on a 

144 Homegrown team. A candidate cleanly on the hinted side beats it; with 

145 none, the name is ambiguous and the reason names the team. 

146 """ 

147 unique: dict[int, Candidate] = {} 

148 for candidate in candidates: 

149 unique.setdefault(candidate.team_id, candidate) 

150 found = list(unique.values()) 

151 if not found: 

152 return Resolution(MISSING) 

153 

154 wanted = (hint or "").strip() 

155 if not wanted: 

156 if len(found) == 1: 156 ↛ 158line 156 didn't jump to line 158 because the condition on line 156 was always true

157 return Resolution(RESOLVED, team_id=found[0].team_id) 

158 return Resolution(AMBIGUOUS, reason=_ambiguous(found)) 

159 

160 def includes(sides: frozenset[str]) -> bool: 

161 return wanted.casefold() in {side.casefold() for side in sides} 

162 

163 on_side = [c for c in found if includes(c.sides)] 

164 both = [c for c in on_side if includes(c.sides_at_age) and len(c.sides_at_age) > 1] 

165 clean = [c for c in on_side if c not in both] 

166 if len(clean) == 1: 

167 return Resolution(RESOLVED, team_id=clean[0].team_id) 

168 if clean: 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true

169 return Resolution(AMBIGUOUS, reason=_ambiguous(clean)) 

170 if both: 

171 return Resolution(AMBIGUOUS, reason=_on_both_sides(both)) 

172 

173 elsewhere = sorted({side for c in found for side in c.sides}) 

174 if not elsewhere: 174 ↛ 175line 174 didn't jump to line 175 because the condition on line 174 was never true

175 return Resolution(WRONG_SIDE, reason="wrong side: team has no league or division registration") 

176 return Resolution(WRONG_SIDE, reason=f"wrong side: exists as {', '.join(elsewhere)}") 

177 

178 

179def _ambiguous(candidates: Iterable[Candidate]) -> str: 

180 ids = ", ".join(str(team_id) for team_id in sorted(c.team_id for c in candidates)) 

181 return f"ambiguous: team ids {ids}" 

182 

183 

184def _on_both_sides(candidates: Iterable[Candidate]) -> str: 

185 parts = [] 

186 for candidate in sorted(candidates, key=lambda c: c.team_id): 

187 *rest, last = sorted(candidate.sides_at_age) 

188 sides = f"{', '.join(rest)} and {last}" 

189 parts.append(f"team {candidate.team_id} is registered as both {sides} at this age group") 

190 return f"ambiguous: {'; '.join(parts)}"