Coverage for mt_tools/matchup.py: 93.89%

202 statements  

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

1"""Matchup: both teams of one match, each inside its own tables (SB-1782). 

2 

3Fest matches pair teams from different conferences, so a match preview's common 

4opponents and head-to-head are mostly empty. The matchup puts the two team 

5dossiers side by side for a Scouting tab, and never compares across them: each 

6side is described in its own conference tables (`team_dossier`), and its badges 

7come from the cross-conference stat boards (`leaderboards`), which are stat 

8boards, not rankings. 

9 

10Two layers, so the rules are testable without a database: 

11 

12- **Gathering** (`get_matchup`) reads the match, one dossier per side, the stat 

13 boards and the two teams' previous meetings through `ToolDeps`. 

14- **Rules** (`stakes_for`, `shares_conference`, `badges_from`, `meetings_from`) 

15 are pure functions over plain values. 

16 

17## Sides 

18 

19Each side is `get_team_dossier(..., for_match_id=match_id)`, so it carries its 

20season age and whether it is playing up. One side's dossier error is that 

21side's `dossier.error`: it never fails the call or blanks the other side. 

22 

23## Badges 

24 

25Per side, the boards of each top-level league the team is registered in at its 

26**season age** (a Flex conference counts as its parent, Homegrown), read once 

27per (league, age) for the call; test leagues are skipped. A badge is a board 

28where the team ranks in the top `BADGE_RANK` and in the top third of the board's 

29`ranked_count` (teams with `MIN_GP` games), so never "8th of 8"; a 0 on a count 

30board (points, goals, unbeaten, pro wins) is no badge. At most `MAX_BADGES` per 

31team, best rank first, then board order. Badges are null when the boards could 

32not be read, [] when the team is on none (or its league has no boards). 

33 

34## Conference and stakes 

35 

36`shares_conference` is whether the dossiers share a table (a division id); null 

37when either dossier failed. `scouting_relevant`: a tournament match, or two teams 

38known not to share a conference. `stakes` is null outside a tournament, "group" 

39in a group stage, "none" for a showcase, consolation, third-place or placement 

40final, and "elimination" for every other knockout round. 

41 

42## Previous meetings 

43 

44Played matches between the two teams at the match's age group, every season, 

45newest first; the score is this match's home team first. Null when the read 

46failed. 

47 

48Badge fact ids are `t<team>:a<age>:board:<league_id>:<key>`, with the season age. 

49""" 

50 

51from collections.abc import Iterable 

52from datetime import UTC, date, datetime 

53from typing import Literal 

54 

55import structlog 

56from pydantic import BaseModel 

57 

58from mt_ai.tools.deps import ToolDeps 

59from mt_ai.tools.schemas import AgeGroupRef, ToolError, Viewer 

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

61from mt_tools.leaderboards import NOT_A_RANKING, Board, LeaderboardsResult, get_leaderboards 

62from mt_tools.motw_candidates import PLAYED_STATUSES 

63from mt_tools.team_dossier import TeamDossierResult, get_team_dossier, visible_mappings 

64 

65logger = structlog.get_logger() 

66 

67BADGE_RANK = 10 

68MAX_BADGES = 3 

69# Boards where 0 is nothing to show: "1st with 0 wins over pro academies" is no badge. 

70# (Fewest goals against is not here: 0 is the best there.) 

71ZERO_IS_NOTHING = frozenset({"pts", "ppg", "gf", "gf_pg", "unbeaten"}) 

72# Boards never shown as a badge (SB-1887): pro academies often field a younger squad 

73# in Flex, so a win over one is no scouting headline. The board itself stays on /leaders. 

74NOT_A_BADGE = frozenset({"pro_wins"}) 

75UNAVAILABLE = "The matchup is unavailable right now." 

76 

77Stakes = Literal["none", "group", "elimination"] 

78 

79NO_STAKES_ROUNDS = frozenset({"showcase", "consolation", "placement_final", "third_place"}) 

80GROUP_ROUNDS = frozenset({"group_stage"}) 

81ELIMINATION_ROUNDS = frozenset( 

82 { 

83 "round_of_32", 

84 "round_of_16", 

85 "quarterfinal", 

86 "semifinal", 

87 "final", 

88 "wildcard", 

89 "silver_semifinal", 

90 "bronze_semifinal", 

91 "silver_final", 

92 "bronze_final", 

93 } 

94) 

95 

96 

97# --- result models ----------------------------------------------------------- 

98 

99 

100class MatchupTournament(BaseModel): 

101 id: int 

102 name: str | None = None 

103 

104 

105class MatchupMatch(BaseModel): 

106 id: int 

107 date: date 

108 age_group: AgeGroupRef # the bracket: a side playing up is younger 

109 tournament: MatchupTournament | None = None 

110 tournament_round: str | None = None 

111 stakes: Stakes | None = None # null: not a tournament match, or an unknown round 

112 

113 

114class Badge(BaseModel): 

115 """A stat board the team is near the top of. A stat board, not a ranking.""" 

116 

117 board: str # the board key, e.g. "gf_pg" 

118 title: str 

119 league_id: int 

120 league: str 

121 age_group: str # the team's season age, not the bracket 

122 rank: int 

123 of: int # teams the board ranks (MIN_GP games) 

124 value: int | float | None = None 

125 fact_id: str 

126 text: str 

127 

128 

129class MatchupSide(BaseModel): 

130 dossier: TeamDossierResult 

131 # Null: the boards could not be read. []: on no board's top BADGE_RANK. 

132 badges: list[Badge] | None = None 

133 badges_note: str | None = None # the boards' coverage note, verbatim 

134 

135 

136class Meeting(BaseModel): 

137 match_id: int 

138 date: date 

139 season: str | None = None 

140 score: str # this match's home team first 

141 competition: str | None = None 

142 

143 

144class MatchupResult(BaseModel): 

145 """Both sides of one match, each in its own tables. 

146 

147 `home` and `away` are null only with `error`, when the match itself could not 

148 be read; a side whose dossier failed carries its own `dossier.error`. 

149 """ 

150 

151 match: MatchupMatch | None = None 

152 shares_conference: bool | None = None 

153 scouting_relevant: bool = False 

154 home: MatchupSide | None = None 

155 away: MatchupSide | None = None 

156 previous_meetings: list[Meeting] | None = None 

157 error: ToolError | None = None 

158 

159 

160# --- pure rules ---------------------------------------------------------------- 

161 

162 

163def stakes_for(tournament_id: int | None, round_name: str | None) -> Stakes | None: 

164 if tournament_id is None or not round_name: 

165 return None 

166 if round_name in GROUP_ROUNDS: 

167 return "group" 

168 if round_name in NO_STAKES_ROUNDS: 

169 return "none" 

170 if round_name in ELIMINATION_ROUNDS: 

171 return "elimination" 

172 return None 

173 

174 

175def shares_conference(home: TeamDossierResult, away: TeamDossierResult) -> bool | None: 

176 """Whether the two teams share a table; null when either dossier could not be built.""" 

177 if home.error or away.error or home.conferences is None or away.conferences is None: 

178 return None 

179 return bool({c.division.id for c in home.conferences} & {c.division.id for c in away.conferences}) 

180 

181 

182def _ordinal(n: int) -> str: 

183 suffix = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") 

184 return f"{n}{suffix}" 

185 

186 

187def _value_text(board: Board, value) -> str: 

188 if value is None: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 return "" 

190 if board.variant == "per_game": 

191 return f" ({value:.2f})" 

192 return f" ({value})" 

193 

194 

195def badge_cutoff(ranked_count: int) -> int: 

196 """The worst rank that is a badge: the top BADGE_RANK, and never below the top third.""" 

197 return min(BADGE_RANK, ranked_count // 3) 

198 

199 

200def badge_label(rank: int, age_name: str, league: str, title: str, of: int) -> str: 

201 """'2nd in U15 Homegrown goals for per game, of 134 teams': the title's case, but its first letter.""" 

202 teams = "team" if of == 1 else "teams" 

203 return f"{_ordinal(rank)} in {age_name} {league} {title[:1].lower()}{title[1:]}, of {of} {teams}" 

204 

205 

206def badges_from( 

207 team_id: int, team_name: str, age: AgeGroupRef, league_id: int, league: str, boards: Iterable[Board] 

208) -> list[Badge]: 

209 """Every board of one league where the team is in the top third and the top BADGE_RANK, in board order.""" 

210 out: list[Badge] = [] 

211 for board in boards: 

212 if board.key in NOT_A_BADGE: 

213 continue 

214 row = next((r for r in board.rows if r.team.id == team_id and r.rank is not None), None) 

215 if row is None or row.rank > badge_cutoff(board.ranked_count): 

216 continue 

217 if board.key in ZERO_IS_NOTHING and not row.value: 

218 continue 

219 label = badge_label(row.rank, age.name, league, board.title, board.ranked_count) 

220 out.append( 

221 Badge( 

222 board=board.key, 

223 title=board.title, 

224 league_id=league_id, 

225 league=league, 

226 age_group=age.name, 

227 rank=row.rank, 

228 of=board.ranked_count, 

229 value=row.value, 

230 fact_id=f"t{team_id}:a{age.id}:board:{league_id}:{board.key}", 

231 text=f"{team_name}: {label}{_value_text(board, row.value)}. {NOT_A_RANKING}", 

232 ) 

233 ) 

234 return out 

235 

236 

237def best_badges(badges: list[Badge]) -> list[Badge]: 

238 """At most MAX_BADGES, best rank first; `badges` arrive in board order, which breaks ties.""" 

239 return sorted(badges, key=lambda b: b.rank)[:MAX_BADGES] 

240 

241 

242def meetings_from(rows: Iterable[dict], match: dict) -> list[Meeting]: 

243 """The two teams' played meetings at the match's age group, newest first, this match excluded.""" 

244 home, away = match["home_team_id"], match["away_team_id"] 

245 out: list[Meeting] = [] 

246 for m in rows: 

247 if m.get("id") == match["id"] or {m.get("home_team_id"), m.get("away_team_id")} != {home, away}: 

248 continue 

249 if m.get("age_group_id") != match.get("age_group_id") or m.get("match_status") not in PLAYED_STATUSES: 

250 continue 

251 hs, as_ = m.get("home_score"), m.get("away_score") 

252 if hs is None or as_ is None: 252 ↛ 253line 252 didn't jump to line 253 because the condition on line 252 was never true

253 continue 

254 ours, theirs = (hs, as_) if m["home_team_id"] == home else (as_, hs) 

255 out.append( 

256 Meeting( 

257 match_id=m["id"], 

258 date=_date(m["match_date"]), 

259 season=m.get("season_name"), 

260 score=f"{ours}-{theirs}", 

261 competition=m.get("match_type_name"), 

262 ) 

263 ) 

264 return sorted(out, key=lambda x: (x.date, x.match_id), reverse=True) 

265 

266 

267# --- gathering ----------------------------------------------------------------- 

268 

269 

270class _InvalidArgsError(Exception): 

271 pass 

272 

273 

274def _date(value) -> date: 

275 return value if isinstance(value, date) else date.fromisoformat(str(value)[:10]) 

276 

277 

278def _is_test(index: TeamIndex, league: dict) -> bool: 

279 return bool(league.get("is_test")) or league.get("id") in index.test_league_ids 

280 

281 

282def top_leagues(index: TeamIndex, team_id: int, dossier: TeamDossierResult) -> list[tuple[int, str]]: 

283 """(id, name) of the top-level leagues of the team's tables (Flex counts as Homegrown). 

284 

285 Test leagues are skipped for every viewer: the stat boards never count them. 

286 """ 

287 team = index.teams.get(team_id) 

288 if team is None or not dossier.conferences or dossier.age_group is None: 288 ↛ 289line 288 didn't jump to line 289 because the condition on line 288 was never true

289 return [] 

290 divisions = {c.division.id for c in dossier.conferences} 

291 out: list[tuple[int, str]] = [] 

292 for m in visible_mappings(team, index): 

293 division = m.get("divisions") or {} 

294 if m["age_groups"]["id"] != dossier.age_group.id or division.get("id") not in divisions: 

295 continue 

296 league = index.leagues.get(division.get("league_id") or 0) 

297 if league and not _is_test(index, league) and league.get("parent_league_id") is not None: 

298 league = index.leagues.get(league["parent_league_id"]) 

299 if not league or _is_test(index, league) or not league.get("name"): 

300 continue 

301 entry = (league["id"], str(league["name"])) 

302 if entry not in out: 

303 out.append(entry) 

304 return out 

305 

306 

307def _side( 

308 deps: ToolDeps, 

309 team_id: int, 

310 dossier: TeamDossierResult, 

311 index: TeamIndex | None, 

312 boards: dict[tuple[str, str], LeaderboardsResult], 

313) -> MatchupSide: 

314 if dossier.error or dossier.team is None or dossier.age_group is None or index is None: 

315 return MatchupSide(dossier=dossier) 

316 age = dossier.age_group # the season age: the dossier's, never the bracket 

317 found: list[Badge] = [] 

318 notes: list[str] = [] 

319 for league_id, league in top_leagues(index, team_id, dossier): 

320 key = (league, age.name) 

321 if key not in boards: 

322 boards[key] = get_leaderboards( 

323 deps, league, age.name, dossier.season.name if dossier.season else None, limit=BADGE_RANK 

324 ) 

325 result = boards[key] 

326 if result.error and result.error.kind == "invalid_args": 

327 # No boards for this league or age (not a top-level league, an age it 

328 # has no registrations at): nothing to rank in, not a failed read. 

329 continue 

330 if result.error or result.boards is None: 

331 logger.warning("matchup_badges_unavailable", team_id=team_id, league=league, age_group=age.name) 

332 return MatchupSide(dossier=dossier) 

333 found.extend(badges_from(team_id, dossier.team.name, age, league_id, league, result.boards)) 

334 if result.coverage and result.coverage.note not in notes: 334 ↛ 319line 334 didn't jump to line 319 because the condition on line 334 was always true

335 notes.append(result.coverage.note) 

336 return MatchupSide(dossier=dossier, badges=best_badges(found), badges_note=" ".join(notes) or None) 

337 

338 

339def get_matchup(deps: ToolDeps, match_id: int, *, viewer: Viewer, now: datetime | None = None) -> MatchupResult: 

340 """Both teams of `match_id` (this season) in their own tables, with badges and past meetings.""" 

341 

342 def fail(kind: Literal["unavailable", "invalid_args"], message: str) -> MatchupResult: 

343 return MatchupResult(error=ToolError(kind=kind, message=message)) 

344 

345 current = now or datetime.now(UTC) 

346 try: 

347 season = deps.seasons.get_current_season() 

348 if not season: 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true

349 raise DataUnavailableError("no current season") 

350 match = deps.matches.get_match_by_id(match_id, include_test=viewer.include_test, raise_on_error=True) 

351 if not match: 

352 raise _InvalidArgsError(f"No match with id {match_id}.") 

353 if match.get("season_id") != season["id"]: 

354 raise _InvalidArgsError(f"Match {match_id} is not in the current season.") 

355 header = MatchupMatch( 

356 id=match["id"], 

357 date=_date(match["match_date"]), 

358 age_group=AgeGroupRef(id=match["age_group_id"], name=str(match.get("age_group_name") or "")), 

359 tournament=MatchupTournament(id=match["tournament_id"], name=match.get("tournament_name")) 

360 if match.get("tournament_id") is not None 

361 else None, 

362 tournament_round=match.get("tournament_round"), 

363 stakes=stakes_for(match.get("tournament_id"), match.get("tournament_round")), 

364 ) 

365 except _InvalidArgsError as exc: 

366 return fail("invalid_args", str(exc)) 

367 except DataUnavailableError as exc: 

368 logger.warning("matchup_unavailable", error=str(exc)) 

369 return fail("unavailable", UNAVAILABLE) 

370 except Exception: 

371 logger.exception("get_matchup failed", match_id=match_id) 

372 return fail("unavailable", UNAVAILABLE) 

373 

374 home_id, away_id = match["home_team_id"], match["away_team_id"] 

375 home_dossier, away_dossier = ( 

376 get_team_dossier(deps, team_id, None, for_match_id=match_id, viewer=viewer, now=current) 

377 for team_id in (home_id, away_id) 

378 ) 

379 

380 # Badges and meetings degrade on their own: neither blanks the dossiers. 

381 index: TeamIndex | None = None 

382 try: 

383 index = load_team_index(deps, viewer) 

384 except Exception: 

385 logger.warning("matchup_index_unavailable", match_id=match_id, exc_info=True) 

386 boards: dict[tuple[str, str], LeaderboardsResult] = {} 

387 home = _side(deps, home_id, home_dossier, index, boards) 

388 away = _side(deps, away_id, away_dossier, index, boards) 

389 

390 meetings: list[Meeting] | None 

391 try: 

392 rows = deps.matches.get_all_matches(team_id=home_id, include_test=viewer.include_test, raise_on_error=True) 

393 meetings = meetings_from(rows, match) 

394 except Exception: 

395 logger.warning("matchup_meetings_unavailable", match_id=match_id, exc_info=True) 

396 meetings = None 

397 

398 shared = shares_conference(home_dossier, away_dossier) 

399 logger.info( 

400 "matchup_built", 

401 match_id=match_id, 

402 shares_conference=shared, 

403 tournament=header.tournament is not None, 

404 home_error=bool(home_dossier.error), 

405 away_error=bool(away_dossier.error), 

406 boards_read=len(boards), 

407 meetings=None if meetings is None else len(meetings), 

408 ) 

409 return MatchupResult( 

410 match=header, 

411 shares_conference=shared, 

412 scouting_relevant=header.tournament is not None or shared is False, 

413 home=home, 

414 away=away, 

415 previous_meetings=meetings, 

416 )