Coverage for mt_tools/power_rating_read.py: 97.54%

351 statements  

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

1"""The MT Power Rating as served: one stored run, read for people (SB-1808). 

2 

3`GET /api/rankings`, `GET /api/rankings/teams/{id}`, the mt-mcp tools 

4`get_power_rating` / `get_power_rating_team` and `mt rankings` all call the two 

5gathering functions here, so the web, the CLI and MT AI can never disagree. The 

6engine (`mt_tools.power_rating`) computed the numbers and the nightly job stored 

7them; nothing here rates anything. 

8 

9Two layers, so the reading is testable without a database: 

10 

11- **Gathering** (`get_power_rating`, `get_power_rating_team`) resolves the league, 

12 age group and season the way the leaderboards do, then reads the latest run 

13 through `ToolDeps.power_rating`. 

14- **Building** (`build_rankings`, `build_team`, `coverage_note`, `weekly_history`, 

15 `biggest_movers`) are pure functions over the stored rows. 

16 

17## Views (design "Publication") 

18 

19- **national**: only when the run is national. Ranked teams by national rank, 

20 tiers on; a ranked team outside the main island has no rank and is marked 

21 `comparable_nationally: false`. 

22- **conference**: ranked teams grouped by conference, each by its conference 

23 rank. No tiers. The view of every non-national run, whatever was asked for: 

24 a national request on such a run gets this view, with `publication.reason`. 

25 

26## Absent is never zero 

27 

28- `rank_change_7d` / `rating_change_7d` are null when there is no run 7 days 

29 before the latest one, or the team was not in it. Movement is measured 

30 against the run users saw a week before the latest run was computed, so it is 

31 fixed for a run, and the payload can be cached by run id. 

32- Teams under `MIN_MATCHES` are `unranked`, with the `needed` count, never placed. 

33- No run yet is an answer (`teams: []` and a `reason`), not an error. 

34""" 

35 

36from collections.abc import Iterable, Mapping 

37from datetime import UTC, date, datetime, timedelta 

38from typing import Any, Literal, NamedTuple 

39 

40import structlog 

41from pydantic import BaseModel 

42 

43from mt_ai.tools.deps import ToolDeps 

44from mt_ai.tools.schemas import ToolError, Viewer 

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

46from mt_tools.leaderboards import _age_group, _InvalidArgsError, _leagues, _season 

47from mt_tools.power_rating import MIN_MATCHES, TIERS 

48 

49logger = structlog.get_logger() 

50 

51MOVEMENT_DAYS = 7 

52MOVERS = 3 

53UNAVAILABLE = "The Power Rating is unavailable right now." 

54CONFERENCES_MEET = "Conferences meet only at Flex and national events." 

55 

56View = Literal["national", "conference"] 

57VIEWS: tuple[View, ...] = ("national", "conference") 

58 

59 

60# --- result models ----------------------------------------------------------- 

61 

62 

63class RunRef(BaseModel): 

64 id: int 

65 computed_at: datetime 

66 through_date: date | None = None # the latest rated match; null when nothing was rated 

67 matches_counted: int 

68 params_version: str 

69 

70 

71class MovementRef(BaseModel): 

72 """The run movement is measured from: the one users saw 7 days before `run`.""" 

73 

74 run_id: int 

75 computed_at: datetime 

76 

77 

78class PublicationState(BaseModel): 

79 national: bool 

80 reason: str | None = None # why there is no national list; null when there is 

81 

82 

83class TierRef(BaseModel): 

84 key: str 

85 label: str 

86 min: int 

87 

88 

89class RankingsCoverage(BaseModel): 

90 teams_in_pool: int # teams with at least one rated match in the run 

91 ranked: int 

92 unranked_count: int 

93 matches_counted: int 

94 matches_excluded: dict[str, int] 

95 min_matches: int = MIN_MATCHES 

96 note: str 

97 

98 

99class RankedTeam(BaseModel): 

100 rank: int | None # national rank; null in the conference view and outside the main island 

101 team_id: int 

102 team: str 

103 club_id: int | None = None 

104 club_logo_url: str | None = None 

105 rating: int 

106 # Places moved in this view's rank (national, or conference), up is positive. 

107 # Null when there was no run a week earlier or the team had no such rank in it. 

108 rank_change_7d: int | None = None 

109 rating_change_7d: int | None = None 

110 w: int 

111 d: int 

112 l: int 

113 mp: int 

114 conference: str | None = None 

115 conference_rank: int | None = None 

116 tier: str | None = None # national view only 

117 badges: list[str] 

118 xconf_mp: int 

119 pro_academy: bool = False 

120 comparable_nationally: bool = False 

121 

122 

123class UnrankedTeam(BaseModel): 

124 team_id: int 

125 team: str 

126 club_id: int | None = None 

127 club_logo_url: str | None = None 

128 conference: str | None = None 

129 mp: int 

130 needed: int = MIN_MATCHES 

131 

132 

133class PowerRatingResult(BaseModel): 

134 """One age group's Power Rating, from its latest run. 

135 

136 `teams` [] with `reason` when there is no run or nothing was rated; null with 

137 `error` when MT could not check. 

138 """ 

139 

140 league: str 

141 age_group: str | None = None 

142 season: str | None = None 

143 view: View | None = None # the view served, which may not be the one asked for 

144 conference: str | None = None # the conference filter applied 

145 conferences: list[str] = [] # every conference in the run: the tabs, and what `conference` accepts 

146 run: RunRef | None = None 

147 movement_since: MovementRef | None = None 

148 publication: PublicationState | None = None 

149 coverage: RankingsCoverage | None = None 

150 tiers: list[TierRef] = [] 

151 teams: list[RankedTeam] | None = None 

152 unranked: list[UnrankedTeam] | None = None 

153 reason: str | None = None 

154 error: ToolError | None = None 

155 

156 

157class HistoryPoint(BaseModel): 

158 run_id: int 

159 computed_at: datetime 

160 through_date: date | None = None 

161 rating: int 

162 rank: int | None = None 

163 conference_rank: int | None = None 

164 

165 

166class MatchMove(BaseModel): 

167 """One rated match, from the team's side.""" 

168 

169 match_id: int 

170 match_date: date | None = None # null if the match row is gone 

171 opponent_id: int 

172 opponent: str 

173 result: Literal["W", "D", "L"] # a shoot-out is a draw 

174 goals_for: int | None = None 

175 goals_against: int | None = None 

176 penalties_for: int | None = None 

177 penalties_against: int | None = None 

178 expected: float # the share of the points the team was expected to take 

179 delta: float 

180 

181 

182class ScheduleStrength(BaseModel): 

183 rating: int # mean opponent rating before each rated match 

184 rank: int | None = None # toughest first; null when the team is unranked 

185 of: int | None = None 

186 scope: Literal["national", "conference"] | None = None 

187 

188 

189class PowerRatingTeamResult(BaseModel): 

190 """One team in the latest run: where it stands and why it moved. 

191 

192 `in_run` false with `reason` when the team has no rated match in it (or there 

193 is no run): an answer, not an error. 

194 """ 

195 

196 league: str 

197 age_group: str | None = None 

198 season: str | None = None 

199 team_id: int 

200 team: str | None = None 

201 club_id: int | None = None 

202 club_logo_url: str | None = None 

203 pro_academy: bool = False 

204 run: RunRef | None = None 

205 in_run: bool = False 

206 rating: int | None = None 

207 rank: int | None = None 

208 conference: str | None = None 

209 conference_rank: int | None = None 

210 tier: str | None = None 

211 badges: list[str] = [] 

212 ranked: bool = False 

213 needed: int | None = None # matches still needed to be ranked; null once ranked 

214 mp: int | None = None 

215 w: int | None = None 

216 d: int | None = None 

217 l: int | None = None 

218 xconf_mp: int | None = None 

219 sos: ScheduleStrength | None = None 

220 biggest_movers: list[MatchMove] | None = None # largest |delta| first, at most 3 

221 deltas: list[MatchMove] | None = None # every rated match, oldest first 

222 history: list[HistoryPoint] | None = None # one point per week: the week's last run 

223 reason: str | None = None 

224 error: ToolError | None = None 

225 

226 

227# --- pure building ------------------------------------------------------------- 

228 

229 

230class TeamInfo(NamedTuple): 

231 name: str 

232 club_id: int | None = None 

233 logo_url: str | None = None 

234 pro_academy: bool = False 

235 

236 

237def _moment(value: Any) -> datetime: 

238 moment = value if isinstance(value, datetime) else datetime.fromisoformat(str(value)) 

239 return moment if moment.tzinfo else moment.replace(tzinfo=UTC) 

240 

241 

242def _plural(n: int, word: str) -> str: 

243 return f"{n} {word}{'' if n == 1 else 'es' if word.endswith('ch') else 's'}" 

244 

245 

246def tier_refs() -> list[TierRef]: 

247 return [TierRef(key=key, label=label, min=int(minimum)) for key, label, minimum in TIERS] 

248 

249 

250def run_ref(run: Mapping[str, Any]) -> RunRef: 

251 return RunRef( 

252 id=run["id"], 

253 computed_at=run["computed_at"], 

254 through_date=run.get("through_date"), 

255 matches_counted=run.get("matches_counted") or 0, 

256 params_version=run.get("params_version") or "", 

257 ) 

258 

259 

260def coverage_note( 

261 teams_in_pool: int, ranked: int, matches_counted: int, league: str, age_group: str, *, national_view: bool 

262) -> str: 

263 """The denominator, in words (root CLAUDE.md rule 3).""" 

264 text = ( 

265 f"MT Power Rating from {_plural(teams_in_pool, f'{league} {age_group} team')} in MT, " 

266 f"rated on {_plural(matches_counted, 'match')}; {ranked} with {MIN_MATCHES} or more matches " 

267 f"{'is' if ranked == 1 else 'are'} ranked. {CONFERENCES_MEET}" 

268 ) 

269 if not national_view: 

270 text += " Shown as conference lists: not yet comparable nationally." 

271 return text 

272 

273 

274def _conference_names(payload: Mapping[str, Any]) -> dict[int, str]: 

275 names = {str(k): v for k, v in (payload.get("conferences") or {}).items()} 

276 return { 

277 r["team_id"]: names[str(r["conference_division_id"])] 

278 for r in payload.get("ratings") or [] 

279 if r.get("conference_division_id") is not None and str(r["conference_division_id"]) in names 

280 } 

281 

282 

283def _pick_conference(wanted: str | None, available: Iterable[str]) -> str | None: 

284 if wanted is None: 

285 return None 

286 options = sorted(set(available)) 

287 found = next((c for c in options if c.casefold() == wanted.strip().casefold()), None) 

288 if found is None: 

289 raise _InvalidArgsError(f"conference must be one of {', '.join(options) or '(none in this run)'}.") 

290 return found 

291 

292 

293def build_rankings( 

294 payload: Mapping[str, Any], 

295 previous: Mapping[str, Any] | None, 

296 teams: Mapping[int, TeamInfo], 

297 *, 

298 league: str, 

299 age_group: str, 

300 season: str, 

301 view: View | None = None, 

302 conference: str | None = None, 

303) -> PowerRatingResult: 

304 """The served lists from a run payload (`PowerRatingDAO.run_payload`) and the run a week before it. 

305 

306 Teams missing from `teams` (test content, or since deleted) are left out. 

307 Raises `_InvalidArgsError` for a conference the run does not have. 

308 """ 

309 run = payload["run"] 

310 national_run = bool(run.get("national")) 

311 served: View = "national" if national_run and view in (None, "national") else "conference" 

312 conferences = _conference_names(payload) 

313 ratings = [r for r in payload.get("ratings") or [] if r["team_id"] in teams] 

314 chosen = _pick_conference(conference, conferences.values()) 

315 

316 prev_rows = {r["team_id"]: r for r in (previous or {}).get("ratings") or []} 

317 prev_conferences = _conference_names(previous) if previous else {} 

318 

319 def change(r: Mapping[str, Any]) -> tuple[int | None, int | None]: 

320 before = prev_rows.get(r["team_id"]) 

321 if before is None: 

322 return None, None 

323 rating_change = round(r["rating"]) - round(before["rating"]) 

324 if served == "national": 

325 now_rank, then_rank = r.get("rank"), before.get("rank") 

326 elif conferences.get(r["team_id"]) == prev_conferences.get(r["team_id"]): 

327 now_rank, then_rank = r.get("conference_rank"), before.get("conference_rank") 

328 else: 

329 now_rank = then_rank = None 

330 rank_change = then_rank - now_rank if now_rank is not None and then_rank is not None else None 

331 return rank_change, rating_change 

332 

333 ranked_rows, unranked_rows = [], [] 

334 for r in ratings: 

335 info = teams[r["team_id"]] 

336 conf = conferences.get(r["team_id"]) 

337 if chosen is not None and conf != chosen: 

338 continue 

339 if r["mp"] < MIN_MATCHES: 

340 unranked_rows.append( 

341 UnrankedTeam( 

342 team_id=r["team_id"], 

343 team=info.name, 

344 club_id=info.club_id, 

345 club_logo_url=info.logo_url, 

346 conference=conf, 

347 mp=r["mp"], 

348 ) 

349 ) 

350 continue 

351 rank_change, rating_change = change(r) 

352 ranked_rows.append( 

353 RankedTeam( 

354 rank=r.get("rank") if served == "national" else None, 

355 team_id=r["team_id"], 

356 team=info.name, 

357 club_id=info.club_id, 

358 club_logo_url=info.logo_url, 

359 rating=round(r["rating"]), 

360 rank_change_7d=rank_change, 

361 rating_change_7d=rating_change, 

362 w=r["w"], 

363 d=r["d"], 

364 l=r["l"], 

365 mp=r["mp"], 

366 conference=conf, 

367 conference_rank=r.get("conference_rank"), 

368 tier=r.get("tier") if served == "national" else None, 

369 badges=list(r.get("badges") or []), 

370 xconf_mp=r.get("xconf_mp") or 0, 

371 pro_academy=info.pro_academy, 

372 comparable_nationally=national_run and r.get("rank") is not None, 

373 ) 

374 ) 

375 

376 if served == "national": 

377 ranked_rows.sort(key=lambda t: (t.rank is None, t.rank or 0, -t.rating, t.team_id)) 

378 else: 

379 ranked_rows.sort( 

380 key=lambda t: ( 

381 t.conference is None, 

382 (t.conference or "").casefold(), 

383 t.conference_rank is None, 

384 t.conference_rank or 0, 

385 -t.rating, 

386 t.team_id, 

387 ) 

388 ) 

389 unranked_rows.sort(key=lambda t: (-t.mp, t.team.casefold(), t.team_id)) 

390 

391 in_pool = len(ratings) 

392 ranked_count = sum(1 for r in ratings if r["mp"] >= MIN_MATCHES) 

393 matches_counted = run.get("matches_counted") or 0 

394 previous_run = (previous or {}).get("run") 

395 return PowerRatingResult( 

396 league=league, 

397 age_group=age_group, 

398 season=season, 

399 view=served, 

400 conference=chosen, 

401 conferences=sorted(set(conferences.values()), key=str.casefold), 

402 run=run_ref(run), 

403 movement_since=MovementRef(run_id=previous_run["id"], computed_at=previous_run["computed_at"]) 

404 if previous_run 

405 else None, 

406 publication=PublicationState(national=national_run, reason=run.get("publication_reason")), 

407 coverage=RankingsCoverage( 

408 teams_in_pool=in_pool, 

409 ranked=ranked_count, 

410 unranked_count=in_pool - ranked_count, 

411 matches_counted=matches_counted, 

412 matches_excluded=dict(run.get("matches_excluded") or {}), 

413 note=coverage_note( 

414 in_pool, ranked_count, matches_counted, league, age_group, national_view=served == "national" 

415 ), 

416 ), 

417 tiers=tier_refs() if served == "national" else [], 

418 teams=ranked_rows, 

419 unranked=unranked_rows, 

420 reason=None if ratings else f"No rated matches at {age_group} {league} in {season} yet.", 

421 ) 

422 

423 

424def no_run(league: str, age_group: str, season: str) -> PowerRatingResult: 

425 reason = f"No Power Rating has been computed for {league} {age_group} in {season} yet." 

426 return PowerRatingResult( 

427 league=league, 

428 age_group=age_group, 

429 season=season, 

430 publication=PublicationState(national=False, reason=reason), 

431 teams=[], 

432 unranked=[], 

433 reason=reason, 

434 ) 

435 

436 

437def weekly_history(runs: Iterable[Mapping[str, Any]], ratings: Iterable[Mapping[str, Any]]) -> list[HistoryPoint]: 

438 """One point per ISO week, the week's last run, oldest first. A run without the team adds no point.""" 

439 by_run = {r["run_id"]: r for r in ratings} 

440 last_of_week: dict[tuple[int, int], Mapping[str, Any]] = {} 

441 for run in sorted(runs, key=lambda r: (_moment(r["computed_at"]), r["id"])): 

442 if run["id"] in by_run: 

443 year, week, _ = _moment(run["computed_at"]).isocalendar() 

444 last_of_week[(year, week)] = run 

445 points = [] 

446 for _, run in sorted(last_of_week.items()): 

447 r = by_run[run["id"]] 

448 points.append( 

449 HistoryPoint( 

450 run_id=run["id"], 

451 computed_at=run["computed_at"], 

452 through_date=run.get("through_date"), 

453 rating=round(r["rating"]), 

454 rank=r.get("rank"), 

455 conference_rank=r.get("conference_rank"), 

456 ) 

457 ) 

458 return points 

459 

460 

461def match_moves( 

462 deltas: Iterable[Mapping[str, Any]], matches: Mapping[int, Mapping[str, Any]], teams: Mapping[int, TeamInfo] 

463) -> list[MatchMove]: 

464 """Every rated match from the team's side, oldest first.""" 

465 out = [] 

466 for d in deltas: 

467 m = matches.get(d["match_id"]) or {} 

468 home = m.get("home_team_id") == d["team_id"] 

469 own, other = ("home", "away") if home else ("away", "home") 

470 result = d["result"] 

471 opponent = teams.get(d["opponent_id"]) 

472 out.append( 

473 MatchMove( 

474 match_id=d["match_id"], 

475 match_date=m.get("match_date"), 

476 opponent_id=d["opponent_id"], 

477 opponent=opponent.name if opponent else str(d["opponent_id"]), 

478 result="W" if result == 1 else "D" if result == 0.5 else "L", 

479 goals_for=m.get(f"{own}_score") if m else None, 

480 goals_against=m.get(f"{other}_score") if m else None, 

481 penalties_for=m.get(f"{own}_penalty_score") if m else None, 

482 penalties_against=m.get(f"{other}_penalty_score") if m else None, 

483 expected=round(d["expected"], 3), 

484 delta=round(d["delta"], 1), 

485 ) 

486 ) 

487 out.sort(key=lambda x: (x.match_date is None, x.match_date or date.min, x.match_id)) 

488 return out 

489 

490 

491def biggest_movers(moves: Iterable[MatchMove], n: int = MOVERS) -> list[MatchMove]: 

492 return sorted(moves, key=lambda x: (-abs(x.delta), x.match_id))[:n] 

493 

494 

495def schedule_strength(row: Mapping[str, Any], payload: Mapping[str, Any]) -> ScheduleStrength | None: 

496 """The team's SOS, ranked toughest first among the teams it can be compared with. 

497 

498 National run and nationally ranked: among nationally ranked teams. Otherwise 

499 among ranked teams of its conference: islands are not on one scale. 

500 """ 

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

502 return None 

503 rating = round(row["sos"]) 

504 if row["mp"] < MIN_MATCHES: 

505 return ScheduleStrength(rating=rating) 

506 ratings = [r for r in payload.get("ratings") or [] if r["mp"] >= MIN_MATCHES and r.get("sos") is not None] 

507 if payload["run"].get("national") and row.get("rank") is not None: 

508 scope: Literal["national", "conference"] = "national" 

509 peers = [r for r in ratings if r.get("rank") is not None] 

510 else: 

511 division = row.get("conference_division_id") 

512 if division is None: 512 ↛ 513line 512 didn't jump to line 513 because the condition on line 512 was never true

513 return ScheduleStrength(rating=rating) 

514 scope = "conference" 

515 peers = [r for r in ratings if r.get("conference_division_id") == division] 

516 toughest = sorted(peers, key=lambda r: (-r["sos"], r["team_id"])) 

517 rank = next(i for i, r in enumerate(toughest, start=1) if r["team_id"] == row["team_id"]) 

518 return ScheduleStrength(rating=rating, rank=rank, of=len(peers), scope=scope) 

519 

520 

521def build_team( 

522 team_id: int, 

523 payload: Mapping[str, Any], 

524 runs: Iterable[Mapping[str, Any]], 

525 history_ratings: Iterable[Mapping[str, Any]], 

526 deltas: Iterable[Mapping[str, Any]], 

527 matches: Iterable[Mapping[str, Any]], 

528 teams: Mapping[int, TeamInfo], 

529 *, 

530 league: str, 

531 age_group: str, 

532 season: str, 

533) -> PowerRatingTeamResult: 

534 info = teams.get(team_id) or TeamInfo(name=str(team_id)) 

535 base = { 

536 "league": league, 

537 "age_group": age_group, 

538 "season": season, 

539 "team_id": team_id, 

540 "team": info.name, 

541 "club_id": info.club_id, 

542 "club_logo_url": info.logo_url, 

543 "pro_academy": info.pro_academy, 

544 "run": run_ref(payload["run"]), 

545 } 

546 row = next((r for r in payload.get("ratings") or [] if r["team_id"] == team_id), None) 

547 if row is None: 

548 return PowerRatingTeamResult( 

549 **base, 

550 in_run=False, 

551 reason=f"{info.name} has no rated match at {age_group} {league} in {season}.", 

552 ) 

553 moves = match_moves(deltas, {m["id"]: m for m in matches}, teams) 

554 ranked = row["mp"] >= MIN_MATCHES 

555 return PowerRatingTeamResult( 

556 **base, 

557 in_run=True, 

558 rating=round(row["rating"]), 

559 rank=row.get("rank"), 

560 conference=_conference_names(payload).get(team_id), 

561 conference_rank=row.get("conference_rank"), 

562 tier=row.get("tier"), 

563 badges=list(row.get("badges") or []), 

564 ranked=ranked, 

565 needed=None if ranked else MIN_MATCHES - row["mp"], 

566 mp=row["mp"], 

567 w=row["w"], 

568 d=row["d"], 

569 l=row["l"], 

570 xconf_mp=row.get("xconf_mp") or 0, 

571 sos=schedule_strength(row, payload), 

572 biggest_movers=biggest_movers(moves), 

573 deltas=moves, 

574 history=weekly_history(runs, history_ratings), 

575 ) 

576 

577 

578# --- gathering ----------------------------------------------------------------- 

579 

580 

581def _team_info(index: TeamIndex) -> dict[int, TeamInfo]: 

582 out = {} 

583 for team_id, team in index.teams.items(): 

584 club = index.clubs.get(team.get("club_id") or 0) or {} 

585 out[team_id] = TeamInfo( 

586 name=str(team.get("name") or team_id), 

587 club_id=team.get("club_id"), 

588 logo_url=club.get("logo_url") or None, 

589 pro_academy=bool(club.get("pro_academy")), 

590 ) 

591 return out 

592 

593 

594class _Scope(NamedTuple): 

595 league_id: int 

596 league: str 

597 age_group_id: int 

598 age_group: str 

599 season_id: int 

600 season: str 

601 index: TeamIndex 

602 

603 

604def _scope(deps: ToolDeps, league: str, age_group: str, season: str | None, today: date) -> _Scope: 

605 season_ref = _season(deps, season, today) 

606 index = load_team_index(deps, Viewer(include_test=False)) 

607 league_row, _, _ = _leagues(index, league) 

608 age = _age_group(index, age_group) 

609 name = str(league_row.get("name")) 

610 return _Scope(league_row["id"], name, age.id, age.name, season_ref.id, season_ref.name, index) 

611 

612 

613def _payload(store, run_id: int) -> dict: 

614 payload = store.run_payload(run_id) 

615 if payload is None: 615 ↛ 616line 615 didn't jump to line 616 because the condition on line 615 was never true

616 raise DataUnavailableError(f"run {run_id} vanished") 

617 return payload 

618 

619 

620def get_power_rating( 

621 deps: ToolDeps, 

622 age_group: str, 

623 league: str = "Homegrown", 

624 season: str | None = None, 

625 *, 

626 view: str | None = None, 

627 conference: str | None = None, 

628 today: date | None = None, 

629) -> PowerRatingResult: 

630 """The latest Power Rating run for `league` at `age_group`, as national or conference lists. 

631 

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

633 "national" is served only when the run is national. 

634 """ 

635 

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

637 return PowerRatingResult(league=league, error=ToolError(kind=kind, message=message)) 

638 

639 if view is not None and view not in VIEWS: 

640 return fail("invalid_args", f"view must be one of {', '.join(VIEWS)}.") 

641 store = deps.power_rating 

642 try: 

643 if store is None: 

644 raise DataUnavailableError("no power rating source") 

645 s = _scope(deps, league, age_group, season, today or date.today()) 

646 latest = store.latest_run(s.season_id, s.age_group_id, s.league_id) 

647 if latest is None: 

648 return no_run(s.league, s.age_group, s.season) 

649 payload = _payload(store, latest["id"]) 

650 since = _moment(latest["computed_at"]) - timedelta(days=MOVEMENT_DAYS) 

651 previous_run = store.run_as_of(s.season_id, s.age_group_id, s.league_id, since) 

652 previous = _payload(store, previous_run["id"]) if previous_run else None 

653 result = build_rankings( 

654 payload, 

655 previous, 

656 _team_info(s.index), 

657 league=s.league, 

658 age_group=s.age_group, 

659 season=s.season, 

660 view=view, # type: ignore[arg-type] 

661 conference=conference, 

662 ) 

663 except _InvalidArgsError as exc: 

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

665 except DataUnavailableError as exc: 

666 logger.warning("power_rating_unavailable", error=str(exc)) 

667 return fail("unavailable", UNAVAILABLE) 

668 except Exception: 

669 logger.exception("get_power_rating failed") 

670 return fail("unavailable", UNAVAILABLE) 

671 logger.info( 

672 "power_rating_served", 

673 league=result.league, 

674 age_group=result.age_group, 

675 run_id=result.run.id if result.run else None, 

676 view=result.view, 

677 teams=len(result.teams or []), 

678 ) 

679 return result 

680 

681 

682def get_power_rating_team( 

683 deps: ToolDeps, 

684 team_id: int, 

685 age_group: str, 

686 league: str = "Homegrown", 

687 season: str | None = None, 

688 *, 

689 today: date | None = None, 

690) -> PowerRatingTeamResult: 

691 """One team in the latest run: rating, ranks, SOS, its biggest movers and its weekly history.""" 

692 

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

694 return PowerRatingTeamResult(league=league, team_id=team_id, error=ToolError(kind=kind, message=message)) 

695 

696 store = deps.power_rating 

697 try: 

698 if store is None: 698 ↛ 699line 698 didn't jump to line 699 because the condition on line 698 was never true

699 raise DataUnavailableError("no power rating source") 

700 s = _scope(deps, league, age_group, season, today or date.today()) 

701 teams = _team_info(s.index) 

702 if team_id not in teams: 

703 raise _InvalidArgsError(f"No team with id {team_id}.") 

704 latest = store.latest_run(s.season_id, s.age_group_id, s.league_id) 

705 if latest is None: 

706 info = teams[team_id] 

707 return PowerRatingTeamResult( 

708 league=s.league, 

709 age_group=s.age_group, 

710 season=s.season, 

711 team_id=team_id, 

712 team=info.name, 

713 club_id=info.club_id, 

714 club_logo_url=info.logo_url, 

715 pro_academy=info.pro_academy, 

716 reason=no_run(s.league, s.age_group, s.season).reason, 

717 ) 

718 payload = _payload(store, latest["id"]) 

719 in_run = any(r["team_id"] == team_id for r in payload.get("ratings") or []) 

720 runs = history = deltas = matches = [] 

721 if in_run: 

722 runs = store.runs(s.season_id, s.age_group_id, s.league_id) 

723 history = store.team_ratings(team_id, [r["id"] for r in runs]) 

724 deltas = store.team_deltas(latest["id"], team_id) 

725 matches = store.matches_by_ids(d["match_id"] for d in deltas) 

726 return build_team( 

727 team_id, 

728 payload, 

729 runs, 

730 history, 

731 deltas, 

732 matches, 

733 teams, 

734 league=s.league, 

735 age_group=s.age_group, 

736 season=s.season, 

737 ) 

738 except _InvalidArgsError as exc: 

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

740 except DataUnavailableError as exc: 

741 logger.warning("power_rating_team_unavailable", error=str(exc)) 

742 return fail("unavailable", UNAVAILABLE) 

743 except Exception: 

744 logger.exception("get_power_rating_team failed") 

745 return fail("unavailable", UNAVAILABLE)