Coverage for mt_ai/tools/standings.py: 97.60%

117 statements  

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

1"""get_standings — one table, with the coverage that says how to read it (SB-1496). 

2 

3The table is `MatchDAO.get_standings`, the same computation (and cache) as 

4`/api/table`, so MT AI and the Table tab cannot disagree. This module only 

5decides *which* table, and that is the hard part: a standings table is one 

6age group in one division, and a team can sit in several. 

7 

8Which table, given a team: 

9 

10- Its registrations (`team_mappings`) the viewer may see, narrowed by 

11 `age_group_id` and `division_id` when given. Exactly one → that one. 

12- Several, for `League`, `qualifying` or `all` → the team's **home** division: 

13 the one in a top-level league (`leagues.parent_league_id` null). A Flex 

14 bracket sits in Flex, a child of Homegrown (SB-1039), so a team in League 

15 and Flex at one age has exactly one home division. The combined qualifying 

16 table is keyed by that home division — its teams, their League and Flex 

17 results (docs/03-architecture/standings.md). 

18- Anything else — several home divisions (several ages, no age given), or a 

19 named competition other than League with several registrations — is 

20 `ambiguous`, with every option listed. The tool does not guess; the agent 

21 picks an option or asks, and calls again with its ids. 

22 

23Given a division instead, `age_group_id` is required: divisions span ages, and 

24a table across ages would merge one team row's U15 and U16 results. 

25 

26The season defaults as `/api/table` does: the current season, else the most 

27recent one. No qualification cutoff is reported — MT holds no "top N 

28qualify" data, and the tool does not invent one. 

29""" 

30 

31from dataclasses import dataclass 

32 

33import structlog 

34 

35from dao.match_dao import STANDINGS_ALL, STANDINGS_QUALIFYING 

36from mt_ai.tools.deps import ToolDeps 

37from mt_ai.tools.schemas import ( 

38 AgeGroupRef, 

39 DivisionRef, 

40 ErrorKind, 

41 SeasonRef, 

42 StandingsCoverage, 

43 StandingsOption, 

44 StandingsResult, 

45 StandingsRow, 

46 TeamRef, 

47 ToolError, 

48 ToolMeta, 

49 Viewer, 

50) 

51from mt_ai.tools.visibility import DataUnavailableError, TeamIndex, load_team_index 

52 

53logger = structlog.get_logger() 

54 

55LEAGUE = "League" 

56COMBINED = frozenset({STANDINGS_QUALIFYING, STANDINGS_ALL}) 

57 

58 

59class _NotFoundError(Exception): 

60 """An id the viewer cannot see, or that does not exist. The message is for the agent.""" 

61 

62 

63@dataclass(frozen=True) 

64class Table: 

65 age_group: AgeGroupRef 

66 division: DivisionRef 

67 home: bool # the division is in a top-level league (not a Flex bracket) 

68 

69 def option(self) -> StandingsOption: 

70 return StandingsOption(age_group=self.age_group, division=self.division) 

71 

72 

73def get_standings( 

74 deps: ToolDeps, 

75 viewer: Viewer, 

76 team_id: int | None = None, 

77 age_group_id: int | None = None, 

78 division_id: int | None = None, 

79 competition: str = LEAGUE, 

80 season_id: int | None = None, 

81) -> StandingsResult: 

82 competition = _competition(competition) 

83 

84 def result(**fields) -> StandingsResult: 

85 return StandingsResult(team_id=team_id, competition=competition, **fields) 

86 

87 def fail(kind: ErrorKind, message: str, **fields) -> StandingsResult: 

88 return result(error=ToolError(kind=kind, message=message), **fields) 

89 

90 if not competition: 

91 return fail("invalid_args", "competition must be a competition name, 'qualifying' or 'all'.") 

92 if team_id is None and division_id is None: 

93 return fail("invalid_args", "Give a team_id, or a division_id with its age_group_id.") 

94 if team_id is None and age_group_id is None: 

95 return fail("invalid_args", "A division_id needs an age_group_id: divisions span age groups.") 

96 

97 try: 

98 index = load_team_index(deps, viewer) 

99 if team_id is not None: 

100 team = index.teams.get(team_id) 

101 if team is None: 

102 return fail("not_found", f"No team with id {team_id}.") 

103 every = tables_of(index, team) 

104 tables = [ 

105 t 

106 for t in every 

107 if (age_group_id is None or t.age_group.id == age_group_id) 

108 and (division_id is None or t.division.id == division_id) 

109 ] 

110 if not tables: 

111 return fail( 

112 "not_found", 

113 f"{team['name']} plays in no table matching those ids; options lists the ones it does.", 

114 options=[t.option() for t in every], 

115 ) 

116 table = _pick(tables, competition) 

117 if table is None: 

118 return fail( 

119 "ambiguous", 

120 f"{team['name']} plays in {len(tables)} tables; pick one from options.", 

121 options=[t.option() for t in tables], 

122 ) 

123 else: 

124 table = _division_table(index, division_id, age_group_id) 

125 

126 season = _season(deps, season_id) 

127 data = deps.matches.get_standings( 

128 season_id=season.id, 

129 age_group_id=table.age_group.id, 

130 division_id=table.division.id, 

131 match_type=competition, 

132 include_test=viewer.include_test, 

133 raise_on_error=True, 

134 ) 

135 rows = _rows(data["standings"], index, team_id) 

136 coverage = StandingsCoverage.model_validate(data["coverage"]) 

137 except _NotFoundError as exc: 

138 return fail("not_found", str(exc)) 

139 except DataUnavailableError as exc: 

140 return fail("unavailable", f"Standings are unavailable right now ({exc}).") 

141 except Exception: 

142 logger.exception("get_standings failed", team_id=team_id, division_id=division_id) 

143 return fail("unavailable", "Standings are unavailable right now.") 

144 

145 return result( 

146 season=season, 

147 age_group=table.age_group, 

148 division=table.division, 

149 rows=rows, 

150 coverage=coverage, 

151 meta=ToolMeta(coverage=_caption(coverage)), 

152 ) 

153 

154 

155def _competition(value: str | None) -> str: 

156 """'qualifying' and 'all' in any case; a competition name as given.""" 

157 value = (value or "").strip() 

158 return value.casefold() if value.casefold() in COMBINED else value 

159 

160 

161def tables_of(index: TeamIndex, team: dict) -> list[Table]: 

162 """Every (age group, division) the team is registered in that this viewer may see.""" 

163 out: list[Table] = [] 

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

165 age, division = mapping.get("age_groups"), mapping.get("divisions") 

166 if not age or not division or division.get("id") is None: 

167 continue 

168 league_id = division.get("league_id") 

169 if not index.include_test and league_id in index.test_league_ids: 

170 continue 

171 league = index.leagues.get(league_id or 0) or {} 

172 table = Table( 

173 age_group=AgeGroupRef(id=age["id"], name=age["name"]), 

174 division=DivisionRef( 

175 id=division["id"], 

176 name=division["name"], 

177 league=league.get("name") or (division.get("leagues") or {}).get("name"), 

178 ), 

179 home=league.get("parent_league_id") is None, 

180 ) 

181 if table not in out: 181 ↛ 164line 181 didn't jump to line 164 because the condition on line 181 was always true

182 out.append(table) 

183 return sorted(out, key=lambda t: (age_number(t.age_group.name), not t.home, t.division.name)) 

184 

185 

186def _pick(tables: list[Table], competition: str) -> Table | None: 

187 if len(tables) == 1: 

188 return tables[0] 

189 if competition == LEAGUE or competition in COMBINED: 

190 home = [t for t in tables if t.home] 

191 if len(home) == 1: 

192 return home[0] 

193 return None 

194 

195 

196def _division_table(index: TeamIndex, division_id: int, age_group_id: int) -> Table: 

197 """The division at that age, if any team the viewer can see is registered there.""" 

198 for team in index.teams.values(): 

199 for table in tables_of(index, team): 

200 if table.division.id == division_id and table.age_group.id == age_group_id: 

201 return table 

202 raise _NotFoundError(f"No division with id {division_id} at age group id {age_group_id}.") 

203 

204 

205def _season(deps: ToolDeps, season_id: int | None) -> SeasonRef: 

206 if season_id is None: 

207 current = deps.seasons.get_current_season() 

208 if current: 

209 return SeasonRef(id=current["id"], name=current["name"]) 

210 # get_all_seasons swallows errors and returns []. MT always has seasons, so 

211 # empty means the read failed. It is newest first, as /api/table relies on. 

212 seasons = deps.seasons.get_all_seasons() 

213 if not seasons: 

214 raise DataUnavailableError("season list unavailable") 

215 if season_id is None: 

216 return SeasonRef(id=seasons[0]["id"], name=seasons[0]["name"]) 

217 season = next((s for s in seasons if s.get("id") == season_id), None) 

218 if season is None: 

219 raise _NotFoundError(f"No season with id {season_id}.") 

220 return SeasonRef(id=season["id"], name=season["name"]) 

221 

222 

223def _rows(standings: list[dict], index: TeamIndex, team_id: int | None) -> list[StandingsRow]: 

224 rows = [] 

225 for position, row in enumerate(standings, start=1): 

226 if row.get("team_id") is None: 226 ↛ 228line 226 didn't jump to line 228 because the condition on line 226 was never true

227 # Positions still count it: dropping a row must not move the others. 

228 logger.warning("Skipping standings row without a team id", team=row.get("team")) 

229 continue 

230 club = index.visible_club(row.get("club_id")) 

231 rows.append( 

232 StandingsRow( 

233 position=position, 

234 team=TeamRef(id=row["team_id"], name=row.get("team") or "", club_name=(club or {}).get("name")), 

235 played=row["played"], 

236 wins=row["wins"], 

237 draws=row["draws"], 

238 losses=row["losses"], 

239 shootout_wins=row.get("shootout_wins", 0), 

240 shootout_losses=row.get("shootout_losses", 0), 

241 goals_for=row["goals_for"], 

242 goals_against=row["goals_against"], 

243 goal_difference=row["goal_difference"], 

244 points=row["points"], 

245 points_per_match=row.get("points_per_match"), 

246 gd_per_match=row.get("gd_per_match"), 

247 gf_per_match=row.get("gf_per_match"), 

248 ga_per_match=row.get("ga_per_match"), 

249 form=row.get("form") or [], 

250 position_change=row.get("position_change") or 0, 

251 is_requested_team=team_id is not None and row["team_id"] == team_id, 

252 ) 

253 ) 

254 return rows 

255 

256 

257def _caption(coverage: StandingsCoverage) -> str: 

258 """The table's denominator in one line (root CLAUDE.md: aggregates state it).""" 

259 text = f"{coverage.matches_counted} played of {coverage.fixtures} scheduled" 

260 if coverage.matches_vs_outside_table: 

261 text += f"; {coverage.matches_vs_outside_table} against {coverage.teams_outside_table} teams outside this table" 

262 return text 

263 

264 

265def age_number(name: str) -> int: 

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

267 return int(digits) if digits else 999