Coverage for mt_ai/tools/divisions.py: 95.97%

90 statements  

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

1"""list_divisions — resolve a division by name, for get_standings (SB-1503). 

2 

3"Who's top of the U15 Northeast table?" names a division, not a team, and 

4get_standings by division needs its id and an age group id. This tool lists 

5the divisions a viewer can see, each with the age groups it runs, so the agent 

6can pass `division.id` and `age_groups[].id` straight to get_standings. 

7 

8A division is listed when a team the viewer may see is registered in it 

9(`team_mappings`), through the same team index and the same per-registration 

10visibility as search_teams and get_standings (`tables_of`). So a test league's 

11division never reaches a real viewer, and a division nobody plays in is not 

12listed — it has no table to ask about. 

13 

14Filters are optional and combine: `age_group` ("U15", "u-15", "15") and 

15`league` ("Homegrown", "Flex") match a name exactly, case-insensitively; 

16`query` matches part of a division or league name ("Northeast", "new 

17england"). No match is `not_found` with `alternatives`: what exists with 

18fewer filters, so the agent can recover or ask rather than give up. 

19""" 

20 

21from collections.abc import Callable 

22from itertools import combinations 

23 

24import structlog 

25 

26from mt_ai.tools.deps import ToolDeps 

27from mt_ai.tools.schemas import ( 

28 DivisionAgeGroup, 

29 DivisionsResult, 

30 DivisionSummary, 

31 ErrorKind, 

32 ToolError, 

33 ToolMeta, 

34 Viewer, 

35) 

36from mt_ai.tools.standings import Table, age_number, tables_of 

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

38 

39logger = structlog.get_logger() 

40 

41MAX_DIVISIONS = 50 

42MAX_FILTER_LENGTH = 100 

43MAX_NAMED = 20 # alternatives spelled out in a not_found message 

44 

45# Dropped in this order to find alternatives. A named division that does not 

46# run that age lists the ages it does; a query matching nothing lists what 

47# exists at that age. 

48FILTERS = ("age_group", "league", "query") 

49 

50Registrations = dict[tuple[int, int], tuple[Table, set[int]]] 

51 

52 

53def list_divisions( 

54 deps: ToolDeps, 

55 viewer: Viewer, 

56 age_group: str | None = None, 

57 league: str | None = None, 

58 query: str | None = None, 

59) -> DivisionsResult: 

60 # Blank means "no filter": models often send "" for an optional argument, and an 

61 # error there would cost a round trip for nothing. 

62 age_group, league, query = (v if v is None or v.strip() else None for v in (age_group, league, query)) 

63 filters = {"query": query, "league": league, "age_group": age_group} 

64 

65 def fail(kind: ErrorKind, message: str, **fields) -> DivisionsResult: 

66 return DivisionsResult( 

67 age_group=age_group, league=league, query=query, error=ToolError(kind=kind, message=message), **fields 

68 ) 

69 

70 for name, value in filters.items(): 

71 if value is not None and len(value) > MAX_FILTER_LENGTH: 

72 return fail("invalid_args", f"{name} must be at most {MAX_FILTER_LENGTH} characters.") 

73 

74 try: 

75 registrations = _registrations(load_team_index(deps, viewer)) 

76 except DataUnavailableError as exc: 

77 return fail("unavailable", f"Division data is unavailable right now ({exc}).") 

78 except Exception: 

79 logger.exception("list_divisions failed", age_group=age_group, league=league, query=query) 

80 return fail("unavailable", "Division data is unavailable right now.") 

81 

82 divisions = _matching(registrations, **filters) 

83 if not divisions: 

84 return _not_found(registrations, filters, fail) 

85 return DivisionsResult( 

86 age_group=age_group, 

87 league=league, 

88 query=query, 

89 divisions=divisions[:MAX_DIVISIONS], 

90 meta=ToolMeta(truncated=len(divisions) > MAX_DIVISIONS), 

91 ) 

92 

93 

94def _registrations(index: TeamIndex) -> Registrations: 

95 """(division id, age group id) → the table and the visible teams registered there.""" 

96 out: Registrations = {} 

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

98 for table in tables_of(index, team): 

99 _, teams = out.setdefault((table.division.id, table.age_group.id), (table, set())) 

100 teams.add(team["id"]) 

101 return out 

102 

103 

104def _matching( 

105 registrations: Registrations, query: str | None, league: str | None, age_group: str | None 

106) -> list[DivisionSummary]: 

107 by_division: dict[int, DivisionSummary] = {} 

108 for table, teams in registrations.values(): 

109 division = table.division 

110 if age_group and _age_key(table.age_group.name) != _age_key(age_group): 

111 continue 

112 if league and _normalize(division.league or "") != _normalize(league): 

113 continue 

114 if query and not _mentions(table, _normalize(query)): 

115 continue 

116 summary = by_division.setdefault(division.id, DivisionSummary(division=division)) 

117 summary.age_groups.append(DivisionAgeGroup(id=table.age_group.id, name=table.age_group.name, teams=len(teams))) 

118 

119 for summary in by_division.values(): 

120 summary.age_groups.sort(key=lambda a: (age_number(a.name), a.name)) 

121 return sorted( 

122 by_division.values(), 

123 key=lambda s: (_normalize(s.division.league or ""), _normalize(s.division.name), s.division.id), 

124 ) 

125 

126 

127def _not_found( 

128 registrations: Registrations, filters: dict[str, str | None], fail: Callable[..., DivisionsResult] 

129) -> DivisionsResult: 

130 """not_found, with what exists once the fewest filters are dropped.""" 

131 given = [name for name in FILTERS if filters[name] is not None] 

132 wanted = _describe(filters) 

133 if not given: 133 ↛ 134line 133 didn't jump to line 134 because the condition on line 133 was never true

134 return fail("not_found", "MT has no divisions with registered teams.") 

135 

136 for size in range(1, len(given) + 1): 136 ↛ 150line 136 didn't jump to line 150 because the loop on line 136 didn't complete

137 for dropped in combinations(given, size): 137 ↛ 136line 137 didn't jump to line 136 because the loop on line 137 didn't complete

138 relaxed = {name: None if name in dropped else value for name, value in filters.items()} 

139 alternatives = _matching(registrations, **relaxed) 

140 if alternatives: 

141 names = ", ".join(_label(s) for s in alternatives[:MAX_NAMED]) 

142 more = f" and {len(alternatives) - MAX_NAMED} more" if len(alternatives) > MAX_NAMED else "" 

143 scope = _describe(relaxed) or "in MT" 

144 return fail( 

145 "not_found", 

146 f"No division {wanted}. Divisions {scope}: {names}{more}.", 

147 alternatives=alternatives[:MAX_DIVISIONS], 

148 meta=ToolMeta(truncated=len(alternatives) > MAX_DIVISIONS), 

149 ) 

150 return fail("not_found", f"No division {wanted}.") # unreachable while MT has any division 

151 

152 

153def _describe(filters: dict[str, str | None]) -> str: 

154 parts = [] 

155 if filters["query"] is not None: 

156 parts.append(f"matching '{filters['query'].strip()}'") 

157 if filters["league"] is not None: 

158 parts.append(f"in league {filters['league'].strip()}") 

159 if filters["age_group"] is not None: 

160 parts.append(f"at {filters['age_group'].strip()}") 

161 return " ".join(parts) 

162 

163 

164def _label(summary: DivisionSummary) -> str: 

165 league = f" ({summary.division.league})" if summary.division.league else "" 

166 ages = "/".join(a.name for a in summary.age_groups) 

167 return f"{summary.division.name}{league} {ages}" 

168 

169 

170def _mentions(table: Table, wanted: str) -> bool: 

171 name, league = _normalize(table.division.name), _normalize(table.division.league or "") 

172 return any(wanted in text for text in (name, league, f"{league} {name}", f"{name} {league}")) 

173 

174 

175def _normalize(text: str) -> str: 

176 return " ".join(text.casefold().split()) 

177 

178 

179def _age_key(name: str) -> str: 

180 """'U15', 'u15', 'U-15', 'u 15' and '15' are one age group.""" 

181 key = "".join(ch for ch in name.casefold() if ch.isalnum()) 

182 return f"u{key}" if key.isdigit() else key