Coverage for mt_tools/leaderboards.py: 97.94%

280 statements  

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

1"""Cross-conference leaderboards: one league and age group, the whole season (SB-1781). 

2 

3A stat board, not a strength ranking. Homegrown conferences only meet at 

4tournaments, so a team's points or goals are earned against its own conference 

5(and its Flex bracket): the boards compare numbers, they do not say who is better. 

6Every response carries that sentence and its denominator. 

7 

8Two layers, so the counting is testable without a database: 

9 

10- **Gathering** (`get_leaderboards`) resolves the league, age group and season and 

11 reads the results through the DAO protocols MT AI uses (`ToolDeps`). 

12- **Counting and ranking** (`tally`, `conference_of`, `rank_rows`, `split_min_gp`, 

13 `build_boards`) are pure functions over plain dicts. 

14 

15## Counted 

16 

17Status completed or forfeit; divisions of a top-level league and its child 

18leagues (Homegrown + Flex); the competitions those leagues hold 

19(`leagues.match_type_id`: League, Flex); the season; the age group. A side counts 

20only if it fielded that age group (`effective_side_age_groups`), so a side that 

21played up into another age group's match counts at its own age. A match with no 

22score is skipped and counted in coverage. Points are W=3, D=1, and a level score 

23is a draw (D) even when a Flex shootout decided it: Flex standings award 

24shootout points, these boards do not, and the board title and note say so. 

25 

26## Boards 

27 

28Total and per game, top `limit` (ties share a rank, 1, 1, 3): points, goals for, 

29goals against (fewest first), goal difference; unbeaten (no loss, by games 

30played); wins over pro academies. **Every board ranks only teams with `MIN_GP` 

31games**, so a team with one game and none conceded can never top fewest goals 

32against. Teams under it are listed once, in the result's `unranked` (top `limit` 

33by games played, with `unranked_count`); each board carries only its own 

34`unranked_count`, and `ranked_count`, the teams it ranks (the "of N"). Wins over 

35pro academies lists only teams that played one: a team that never met a pro 

36academy is absent from that board, not 0. 

37 

38Every row carries games played, the team's club id and logo (null when absent), 

39and the team's Homegrown conference: the conference it played most League games 

40in. A team with only Flex games has none; it is shown with `no_conference`, 

41never dropped. 

42""" 

43 

44from collections import Counter 

45from collections.abc import Callable, Iterable 

46from dataclasses import dataclass, field 

47from datetime import date 

48from fractions import Fraction 

49from typing import Literal, NamedTuple 

50 

51import structlog 

52from pydantic import BaseModel 

53 

54from dao.side_age_groups import effective_side_age_groups 

55from mt_ai.tools.deps import ToolDeps 

56from mt_ai.tools.schemas import AgeGroupRef, SeasonRef, TeamRef, ToolError, Viewer 

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

58 

59logger = structlog.get_logger() 

60 

61MIN_GP = 6 

62DEFAULT_LIMIT = 20 

63MAX_LIMIT = 50 

64 

65COMPETITIONS = ("League", "Flex") 

66COUNTED_STATUSES = frozenset({"completed", "forfeit"}) 

67 

68UNAVAILABLE = "Leaderboards are unavailable right now." 

69NOT_A_RANKING = ( 

70 "Conferences only meet at tournaments, so this compares stats across conferences: a stat board, not a ranking." 

71) 

72SHOOTOUTS = "Level scores count as draws; Flex shootout points are not counted." 

73 

74Variant = Literal["total", "per_game"] 

75Better = Literal["higher", "lower"] 

76 

77 

78# --- result models ----------------------------------------------------------- 

79 

80 

81class LeaderRow(BaseModel): 

82 rank: int | None # null: in `unranked`, under MIN_GP games 

83 team: TeamRef 

84 # The team's club, so a client can show its logo and filter by it without 

85 # loading every team and club. Null when the team has no club or no logo. 

86 club_id: int | None = None 

87 club_logo_url: str | None = None 

88 conference: str | None = None 

89 no_conference: bool = False 

90 gp: int 

91 w: int 

92 d: int 

93 l: int 

94 # Per-game boards: rounded to 2 places, ranked exactly. Null on `unranked` rows. 

95 value: int | float | None = None 

96 # Wins over pro academies only: games played against one. 

97 pro_games: int | None = None 

98 

99 

100class Board(BaseModel): 

101 key: str 

102 title: str 

103 variant: Variant 

104 better: Better 

105 rows: list[LeaderRow] 

106 # Teams this board would hold but for MIN_GP; listed once, in the result's `unranked`. 

107 unranked_count: int = 0 

108 # Teams the board ranks (MIN_GP games, and on the board at all): the "of N" for a rank. 

109 ranked_count: int = 0 

110 

111 

112class LeaderboardsCoverage(BaseModel): 

113 teams: int 

114 matches: int 

115 conferences: int 

116 min_gp: int = MIN_GP 

117 competitions_present: list[str] 

118 competitions_absent: list[str] 

119 teams_without_conference: int 

120 matches_without_score: int = 0 

121 sides_other_age_group: int = 0 

122 note: str 

123 

124 

125class LeaderboardsResult(BaseModel): 

126 """Boards for one league and age group in one season. 

127 

128 `boards` holds every board, each with `rows` [] when nothing was played (with 

129 `reason`); null with `error` when MT could not check. 

130 """ 

131 

132 league: str 

133 age_group: AgeGroupRef | None = None 

134 season: SeasonRef | None = None 

135 boards: list[Board] | None = None 

136 # Teams under MIN_GP games, most games first, at most `limit` of `unranked_count`. 

137 unranked: list[LeaderRow] | None = None 

138 unranked_count: int = 0 

139 coverage: LeaderboardsCoverage | None = None 

140 reason: str | None = None 

141 error: ToolError | None = None 

142 

143 

144# --- pure counting ------------------------------------------------------------- 

145 

146 

147@dataclass 

148class TeamTally: 

149 team_id: int 

150 name: str 

151 gp: int = 0 

152 w: int = 0 

153 d: int = 0 

154 l: int = 0 

155 gf: int = 0 

156 ga: int = 0 

157 pro_gp: int = 0 

158 pro_w: int = 0 

159 # The team is itself a pro academy: off the "wins over pro academies" board (SB-1819). 

160 is_pro: bool = False 

161 # Homegrown division name → League games played in it. 

162 divisions: Counter = field(default_factory=Counter) 

163 

164 @property 

165 def points(self) -> int: 

166 return 3 * self.w + self.d 

167 

168 @property 

169 def gd(self) -> int: 

170 return self.gf - self.ga 

171 

172 

173@dataclass 

174class Tally: 

175 teams: dict[int, TeamTally] = field(default_factory=dict) 

176 matches: int = 0 

177 by_competition: Counter = field(default_factory=Counter) 

178 without_score: int = 0 

179 sides_other_age_group: int = 0 

180 

181 

182def tally( 

183 matches: Iterable[dict], 

184 age_group_id: int, 

185 *, 

186 home_league_id: int | None = None, 

187 pro_team_ids: frozenset[int] | set[int] = frozenset(), 

188 visible: Callable[[int], bool] | None = None, 

189) -> Tally: 

190 """Each team's season record at `age_group_id` from played League/Flex matches. 

191 

192 `home_league_id` is the league whose League divisions are conferences. 

193 `visible` hides a team's own line (test content); its opponent still counts the game. 

194 """ 

195 out = Tally() 

196 for m in matches: 

197 if m.get("match_status") not in COUNTED_STATUSES or m.get("match_type_name") not in COMPETITIONS: 

198 continue 

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

200 if hs is None or as_ is None: 

201 out.without_score += 1 

202 continue 

203 out.matches += 1 

204 out.by_competition[m["match_type_name"]] += 1 

205 home_age, away_age = effective_side_age_groups(m) 

206 sides = ( 

207 (m.get("home_team_id"), m.get("home_team_name"), home_age, hs, as_, m.get("away_team_id")), 

208 (m.get("away_team_id"), m.get("away_team_name"), away_age, as_, hs, m.get("home_team_id")), 

209 ) 

210 for team_id, name, side_age, gf, ga, opponent in sides: 

211 if team_id is None or (visible is not None and not visible(team_id)): 

212 continue 

213 if side_age != age_group_id: 

214 out.sides_other_age_group += 1 

215 continue 

216 t = out.teams.setdefault( 

217 team_id, TeamTally(team_id=team_id, name=name or str(team_id), is_pro=team_id in pro_team_ids) 

218 ) 

219 t.gp += 1 

220 t.gf += gf 

221 t.ga += ga 

222 # A level score is a draw, whoever won the shootout. 

223 if gf > ga: 

224 t.w += 1 

225 elif gf == ga: 

226 t.d += 1 

227 else: 

228 t.l += 1 

229 if opponent in pro_team_ids: 

230 t.pro_gp += 1 

231 t.pro_w += int(gf > ga) 

232 if m["match_type_name"] == "League" and home_league_id is not None and m.get("league_id") == home_league_id: 

233 division = m.get("division_name") 

234 if division: 234 ↛ 210line 234 didn't jump to line 210 because the condition on line 234 was always true

235 t.divisions[division] += 1 

236 return out 

237 

238 

239def conference_of(team: TeamTally) -> str | None: 

240 """The Homegrown division the team played most League games in; ties alphabetical.""" 

241 if not team.divisions: 

242 return None 

243 return sorted(team.divisions.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] 

244 

245 

246Value = int | Fraction 

247 

248 

249def rank_rows[T](items: Iterable[T], value: Callable[[T], Value], *, higher: bool = True) -> list[tuple[int, T]]: 

250 """Competition ranking (1, 1, 3): equal values share a rank, the next skips. 

251 

252 Values compare exactly, so per-game values are Fractions: 2/3 and 4/6 tie. 

253 Order within a tie is the input order. 

254 """ 

255 ordered = sorted(items, key=lambda i: -value(i) if higher else value(i)) 

256 out: list[tuple[int, T]] = [] 

257 previous: Value | None = None 

258 rank = 0 

259 for position, item in enumerate(ordered, start=1): 

260 v = value(item) 

261 if previous is None or v != previous: 

262 rank, previous = position, v 

263 out.append((rank, item)) 

264 return out 

265 

266 

267def split_min_gp(teams: Iterable[TeamTally], min_gp: int = MIN_GP) -> tuple[list[TeamTally], list[TeamTally]]: 

268 """(ranked, too few games): every board ranks only teams with `min_gp` games.""" 

269 teams = list(teams) 

270 return [t for t in teams if t.gp >= min_gp], [t for t in teams if t.gp < min_gp] 

271 

272 

273@dataclass(frozen=True) 

274class BoardSpec: 

275 key: str 

276 title: str 

277 variant: Variant 

278 better: Better 

279 value: Callable[[TeamTally], Value] 

280 

281 

282BOARDS: tuple[BoardSpec, ...] = ( 

283 BoardSpec("pts", "Points (W=3, D=1; shootouts count as draws)", "total", "higher", lambda t: t.points), 

284 BoardSpec("ppg", "Points per match", "per_game", "higher", lambda t: Fraction(t.points, t.gp)), 

285 BoardSpec("gf", "Goals for", "total", "higher", lambda t: t.gf), 

286 BoardSpec("gf_pg", "Goals for per match", "per_game", "higher", lambda t: Fraction(t.gf, t.gp)), 

287 BoardSpec("ga", "Goals against (fewest)", "total", "lower", lambda t: t.ga), 

288 BoardSpec("ga_pg", "Goals against per match (fewest)", "per_game", "lower", lambda t: Fraction(t.ga, t.gp)), 

289 BoardSpec("gd", "Goal difference", "total", "higher", lambda t: t.gd), 

290 BoardSpec("gd_pg", "Goal difference per match", "per_game", "higher", lambda t: Fraction(t.gd, t.gp)), 

291) 

292BOARD_KEYS = (*(b.key for b in BOARDS), "unbeaten", "pro_wins") 

293 

294 

295class TeamClub(NamedTuple): 

296 club_id: int | None 

297 logo_url: str | None 

298 

299 

300def _row( 

301 team: TeamTally, 

302 rank: int | None, 

303 value: Value | None, 

304 refs: dict[int, TeamRef], 

305 clubs: dict[int, TeamClub], 

306 **extra, 

307) -> LeaderRow: 

308 conference = conference_of(team) 

309 club = clubs.get(team.team_id) 

310 return LeaderRow( 

311 rank=rank, 

312 team=refs.get(team.team_id) or TeamRef(id=team.team_id, name=team.name), 

313 club_id=club.club_id if club else None, 

314 club_logo_url=club.logo_url if club else None, 

315 conference=conference, 

316 no_conference=conference is None, 

317 gp=team.gp, 

318 w=team.w, 

319 d=team.d, 

320 l=team.l, 

321 value=round(float(value), 2) if isinstance(value, Fraction) else value, 

322 **extra, 

323 ) 

324 

325 

326def _by_name(teams: Iterable[TeamTally]) -> list[TeamTally]: 

327 return sorted(teams, key=lambda t: (t.name.casefold(), t.team_id)) 

328 

329 

330def _ranked(teams: list[TeamTally], spec_value, higher: bool, limit: int, refs, clubs) -> list[LeaderRow]: 

331 return [ 

332 _row(t, rank, spec_value(t), refs, clubs) 

333 for rank, t in rank_rows(_by_name(teams), spec_value, higher=higher) 

334 if rank <= limit 

335 ] 

336 

337 

338def build_boards( 

339 teams: Iterable[TeamTally], 

340 *, 

341 limit: int = DEFAULT_LIMIT, 

342 min_gp: int = MIN_GP, 

343 refs: dict[int, TeamRef] | None = None, 

344 clubs: dict[int, TeamClub] | None = None, 

345) -> list[Board]: 

346 """Every board from the teams' tallies. Top `limit` by rank, so a tie at the cut stays.""" 

347 refs = refs or {} 

348 clubs = clubs or {} 

349 played = [t for t in teams if t.gp > 0] 

350 ranked, too_few = split_min_gp(played, min_gp) 

351 enough = {t.team_id for t in ranked} 

352 boards: list[Board] = [] 

353 for spec in BOARDS: 

354 boards.append( 

355 Board( 

356 key=spec.key, 

357 title=spec.title, 

358 variant=spec.variant, 

359 better=spec.better, 

360 rows=_ranked(ranked, spec.value, spec.better == "higher", limit, refs, clubs), 

361 unranked_count=len(too_few), 

362 ranked_count=len(ranked), 

363 ) 

364 ) 

365 

366 unbeaten = [t for t in played if t.l == 0] 

367 boards.append( 

368 Board( 

369 key="unbeaten", 

370 title=f"Unbeaten (no losses, {min_gp}+ matches; by matches played)", 

371 variant="total", 

372 better="higher", 

373 rows=_ranked([t for t in unbeaten if t.team_id in enough], lambda t: t.gp, True, limit, refs, clubs), 

374 unranked_count=sum(1 for t in unbeaten if t.team_id not in enough), 

375 ranked_count=sum(1 for t in unbeaten if t.team_id in enough), 

376 ) 

377 ) 

378 

379 # Non-pro teams that met a pro academy. A pro academy beating another pro 

380 # academy is not the upset this board exists to show (SB-1819). 

381 vs_pro = [t for t in played if t.pro_gp > 0 and not t.is_pro] 

382 boards.append( 

383 Board( 

384 key="pro_wins", 

385 title="Wins over pro academies", 

386 variant="total", 

387 better="higher", 

388 rows=[ 

389 _row(t, rank, t.pro_w, refs, clubs, pro_games=t.pro_gp) 

390 for rank, t in rank_rows(_by_name(t for t in vs_pro if t.team_id in enough), lambda t: t.pro_w) 

391 if rank <= limit 

392 ], 

393 unranked_count=sum(1 for t in vs_pro if t.team_id not in enough), 

394 ranked_count=sum(1 for t in vs_pro if t.team_id in enough), 

395 ) 

396 ) 

397 return boards 

398 

399 

400def unranked_rows( 

401 teams: Iterable[TeamTally], 

402 *, 

403 limit: int = DEFAULT_LIMIT, 

404 min_gp: int = MIN_GP, 

405 refs: dict[int, TeamRef] | None = None, 

406 clubs: dict[int, TeamClub] | None = None, 

407) -> tuple[list[LeaderRow], int]: 

408 """(the first `limit` teams under `min_gp`, most games first; how many there are). 

409 

410 Listed once for every board rather than per board: early in a season that is 

411 most teams, ten times over. 

412 """ 

413 refs = refs or {} 

414 clubs = clubs or {} 

415 _, too_few = split_min_gp((t for t in teams if t.gp > 0), min_gp) 

416 ordered = sorted(too_few, key=lambda t: (-t.gp, t.name.casefold(), t.team_id)) 

417 return [_row(t, None, None, refs, clubs) for t in ordered[:limit]], len(too_few) 

418 

419 

420def coverage_note( 

421 teams: int, conferences: int, without_conference: int, absent: list[str], age_group: str, min_gp: int = MIN_GP 

422) -> str: 

423 """The denominator and the caveat, in words (root CLAUDE.md: aggregates state it).""" 

424 text = f"{teams} {'team' if teams == 1 else 'teams'} from {conferences} conference{'' if conferences == 1 else 's'}" 

425 if without_conference: 

426 text += f", plus {without_conference} with no Homegrown conference" 

427 text += f". {NOT_A_RANKING} Teams with fewer than {min_gp} matches are listed, not ranked. {SHOOTOUTS}" 

428 for competition in absent: 

429 text += f" No {competition} results at {age_group}." 

430 return text 

431 

432 

433# --- gathering ----------------------------------------------------------------- 

434 

435 

436class _InvalidArgsError(Exception): 

437 pass 

438 

439 

440def _day(value) -> date | None: 

441 try: 

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

443 except ValueError: 

444 return None 

445 

446 

447def _season(deps: ToolDeps, season: str | None, today: date) -> SeasonRef: 

448 if season is None: 

449 current = deps.seasons.get_current_season() 

450 if current: 

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

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

453 # empty means the read failed. 

454 seasons = deps.seasons.get_all_seasons() 

455 if not seasons: 455 ↛ 456line 455 didn't jump to line 456 because the condition on line 455 was never true

456 raise DataUnavailableError("season list unavailable") 

457 if season is None: 

458 # get_current_season also swallows errors, so None may be a failed read. 

459 # The newest row can be a season that has not started: only the season 

460 # whose dates contain today stands in for the current one. 

461 spanning = next( 

462 ( 

463 s 

464 for s in seasons 

465 if (start := _day(s.get("start_date"))) and (end := _day(s.get("end_date"))) and start <= today <= end 

466 ), 

467 None, 

468 ) 

469 if spanning is None: 

470 raise DataUnavailableError("no current season") 

471 return SeasonRef(id=spanning["id"], name=spanning["name"]) 

472 found = next((s for s in seasons if str(s.get("name")) == season.strip()), None) 

473 if found is None: 

474 raise _InvalidArgsError(f"No season named {season!r}. Seasons look like {seasons[0]['name']}.") 

475 return SeasonRef(id=found["id"], name=found["name"]) 

476 

477 

478def _leagues(index: TeamIndex, name: str) -> tuple[dict, list[int], list[int]]: 

479 """(the named league, the league ids it covers, the match type ids they hold). 

480 

481 Only a top-level league: a child (Flex) has no conferences of its own, so its 

482 boards would flag every team as having none. The league ids are the league 

483 and its children; the match types are what those leagues declare 

484 (`leagues.match_type_id`: League for Homegrown, Flex for Flex). 

485 """ 

486 visible = [lg for lg in index.leagues.values() if index.include_test or not lg.get("is_test")] 

487 top = [lg for lg in visible if lg.get("parent_league_id") is None] 

488 league = next((lg for lg in top if str(lg.get("name", "")).casefold() == name.strip().casefold()), None) 

489 if league is None: 

490 raise _InvalidArgsError(f"league must be one of {', '.join(sorted(str(lg.get('name')) for lg in top))}.") 

491 covered = [league, *(lg for lg in visible if lg.get("parent_league_id") == league["id"])] 

492 match_type_ids = sorted({lg["match_type_id"] for lg in covered if lg.get("match_type_id") is not None}) 

493 if not match_type_ids: 

494 raise DataUnavailableError(f"league {league.get('name')!r} declares no match type") 

495 return league, [lg["id"] for lg in covered], match_type_ids 

496 

497 

498def _age_group(index: TeamIndex, name: str) -> AgeGroupRef: 

499 """An age group MT has a visible registration at, by name.""" 

500 ages: dict[str, AgeGroupRef] = {} 

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

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

503 age = mapping.get("age_groups") or {} 

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

505 if not age.get("name") or (not index.include_test and division.get("league_id") in index.test_league_ids): 505 ↛ 506line 505 didn't jump to line 506 because the condition on line 505 was never true

506 continue 

507 ages.setdefault(str(age["name"]).casefold(), AgeGroupRef(id=age["id"], name=age["name"])) 

508 found = ages.get(name.strip().casefold()) 

509 if found is None: 

510 raise _InvalidArgsError(f"age_group must be one of {', '.join(sorted(a.name for a in ages.values()))}.") 

511 return found 

512 

513 

514def _pro_team_ids(index: TeamIndex) -> frozenset[int]: 

515 return frozenset( 

516 team_id 

517 for team_id, team in index.teams.items() 

518 if (index.clubs.get(team.get("club_id") or 0) or {}).get("pro_academy") 

519 ) 

520 

521 

522def _team_club(index: TeamIndex, team_id: int) -> TeamClub: 

523 club_id = index.teams[team_id].get("club_id") 

524 club = index.clubs.get(club_id) if club_id is not None else None 

525 return TeamClub(club_id, (club or {}).get("logo_url") or None) 

526 

527 

528def get_leaderboards( 

529 deps: ToolDeps, 

530 league: str = "Homegrown", 

531 age_group: str = "U15", 

532 season: str | None = None, 

533 *, 

534 limit: int = DEFAULT_LIMIT, 

535 today: date | None = None, 

536) -> LeaderboardsResult: 

537 """Cross-conference boards for `league` (with its Flex) at `age_group`, public data only. 

538 

539 `season` is a season name ("2026-2027"); default the current season. 

540 """ 

541 

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

543 return LeaderboardsResult(league=league, error=ToolError(kind=kind, message=message)) 

544 

545 if not 1 <= limit <= MAX_LIMIT: 

546 return fail("invalid_args", f"limit must be between 1 and {MAX_LIMIT}.") 

547 

548 viewer = Viewer(include_test=False) 

549 try: 

550 season_ref = _season(deps, season, today or date.today()) 

551 index = load_team_index(deps, viewer) 

552 league_row, league_ids, match_type_ids = _leagues(index, league) 

553 age = _age_group(index, age_group) 

554 matches = deps.matches.get_season_results( 

555 season_id=season_ref.id, 

556 age_group_id=age.id, 

557 league_ids=league_ids, 

558 match_type_ids=match_type_ids, 

559 statuses=tuple(sorted(COUNTED_STATUSES)), 

560 include_test=False, 

561 ) 

562 except _InvalidArgsError as exc: 

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

564 except DataUnavailableError as exc: 

565 logger.warning("leaderboards_unavailable", error=str(exc)) 

566 return fail("unavailable", UNAVAILABLE) 

567 except Exception: 

568 logger.exception("get_leaderboards failed") 

569 return fail("unavailable", UNAVAILABLE) 

570 

571 counted = tally( 

572 matches, 

573 age.id, 

574 home_league_id=league_row["id"], 

575 pro_team_ids=_pro_team_ids(index), 

576 visible=lambda team_id: team_id in index.teams, 

577 ) 

578 refs = { 

579 team_id: TeamRef(id=team_id, name=t.name, club_name=index.club_name(index.teams[team_id])) 

580 for team_id, t in counted.teams.items() 

581 } 

582 clubs = {team_id: _team_club(index, team_id) for team_id in counted.teams} 

583 teams = [t for t in counted.teams.values() if t.gp > 0] 

584 conferences = {conference_of(t) for t in teams} - {None} 

585 without = sum(1 for t in teams if conference_of(t) is None) 

586 present = [c for c in COMPETITIONS if counted.by_competition[c]] 

587 absent = [c for c in COMPETITIONS if not counted.by_competition[c]] 

588 coverage = LeaderboardsCoverage( 

589 teams=len(teams), 

590 matches=counted.matches, 

591 conferences=len(conferences), 

592 competitions_present=present, 

593 competitions_absent=absent, 

594 teams_without_conference=without, 

595 matches_without_score=counted.without_score, 

596 sides_other_age_group=counted.sides_other_age_group, 

597 note=coverage_note(len(teams), len(conferences), without, absent, age.name), 

598 ) 

599 logger.info( 

600 "leaderboards_built", 

601 league=league_row.get("name"), 

602 age_group=age.name, 

603 season=season_ref.name, 

604 teams=coverage.teams, 

605 matches=coverage.matches, 

606 teams_without_conference=without, 

607 competitions_absent=absent, 

608 ) 

609 unranked, unranked_count = unranked_rows(teams, limit=limit, refs=refs, clubs=clubs) 

610 return LeaderboardsResult( 

611 league=str(league_row.get("name")), 

612 age_group=age, 

613 season=season_ref, 

614 boards=build_boards(teams, limit=limit, refs=refs, clubs=clubs), 

615 unranked=unranked, 

616 unranked_count=unranked_count, 

617 coverage=coverage, 

618 reason=None 

619 if teams 

620 else f"No League or Flex results at {age.name} {league_row.get('name')} in {season_ref.name} yet.", 

621 )