Coverage for mt_tools/motw_candidates.py: 96.17%
473 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""Match of the Week candidates: which fixtures this week are worth featuring (SB-1550).
3Two layers, so the scoring is testable without a database:
5- **Gathering** (`suggest_motw_candidates`) reads the pool's fixtures, results and
6 standings through the same DAO protocols MT AI uses (`ToolDeps`), plus the
7 recent Match of the Week picks.
8- **Scoring** (`score_fixture`, `team_strengths`, `form_score`, `build_facts`...) is
9 pure functions over plain dicts.
11## Pool
13`POOL` names the leagues, conferences, age groups and match types the suggestion
14draws from. Names are resolved against the divisions MT actually has; a name that
15does not resolve is an error, not a silently smaller pool. `PRO_PATHWAY_POOL` is
16the Northeast Pro Player Pathway on its own, for a separate pick.
18Eligible: League or Flex, status scheduled/tbd, not test, dated in the target week
19(Monday-Sunday) and not before today.
21## Score (v1 weights)
23 total = 0.40 quality + 0.25 closeness + 0.20 stakes + 0.15 form (x 0.5 if recently featured)
25- **strength** of a team is its percentile in its own table (the one the fixture
26 counts in) on points per game and goal difference per game, averaged. A
27 percentile, so a U15 and a U19 table compare on equal terms. Fewer than 3 games
28 played damps strength towards 0.5 and flags `low_sample`. A team with no row
29 has not played a counted match: strength 0.5, `low_sample`.
30- **quality** = the weaker team's strength: a great match needs two good teams.
31- **closeness** = 1 - |strength difference|.
32- **stakes** = the strongest of: adjacent in the table, both near the top, both
33 in contention at a rank a qualification rule selects (Flex conference winner), and
34 a rematch: the teams already played in League or Flex this season (more if that
35 game was a draw or decided by one goal).
36 Only a rule from `qualification_rules` creates a "line"; a Homegrown league
37 table has none, because no source ties a league finish to a Cup place.
38- **form** = both teams' last five League/Flex results, newest weighted most,
39 win 1 / draw 0.5 / loss 0, averaged. No results → 0.5.
41## Facts
43Each candidate carries facts with stable ids (`<match_id>:<slug>`) - table position,
44points gap, streaks, scoring rate, earlier meeting, common opponents, games left,
45and the qualification rules its table feeds. The agent writing "Why this is the
46Match of the Week" must cite a fact id for every reason. Player facts are not
47produced: goals are user data, tracked for few teams, and absent is never zero.
49Coverage is always reported: how many fixtures the pool had this week, how many
50were eligible, and how many teams had too few games to judge.
51"""
53from collections.abc import Callable, Iterable
54from dataclasses import dataclass, replace
55from datetime import UTC, date, datetime, timedelta
56from typing import Any, Literal
57from zoneinfo import ZoneInfo
59import structlog
60from pydantic import BaseModel
62from mt_ai.tools.deps import ToolDeps
63from mt_ai.tools.schemas import AgeGroupRef, DivisionRef, SeasonRef, TeamRef, ToolError, Viewer
64from mt_ai.tools.visibility import DataUnavailableError, TeamIndex, load_team_index
65from mt_tools.qualification_rules import (
66 QualificationRule,
67 RulesError,
68 conference_kind,
69 load_rules,
70 season_key,
71 tier_of,
72)
74logger = structlog.get_logger()
76POOL_TIMEZONE = ZoneInfo("America/New_York")
78WEIGHTS: dict[str, float] = {"quality": 0.40, "closeness": 0.25, "stakes": 0.20, "form": 0.15}
79FEATURED_PENALTY = 0.5 # multiplier for a team picked in the last FEATURED_WEEKS weeks
80FEATURED_WEEKS = 2
81LOW_SAMPLE_GAMES = 3
82FORM_GAMES = 5
83FORM_WEIGHTS = (5, 4, 3, 2, 1) # newest first
84LINE_MARGIN_POINTS = 3 # "in contention" for a ranked place: within this many points of it
85REMATCH = 0.7 # the teams already played each other this season
86REMATCH_CLOSE = 1.0 # ...and their latest meeting was a draw or this close
87CLOSE_MARGIN = 1
88MAX_LIMIT = 10
90ELIGIBLE_STATUSES = frozenset({"scheduled", "tbd"})
91PLAYED_STATUSES = frozenset({"completed", "forfeit"})
92OPEN_STATUSES = frozenset({"scheduled", "tbd", "postponed"})
94FactKind = Literal["standings", "form", "stakes", "rivalry", "storyline"]
97@dataclass(frozen=True)
98class Pool:
99 age_groups: tuple[str, ...]
100 match_types: tuple[str, ...]
101 # (league, division) pairs, as MT names them.
102 conferences: tuple[tuple[str, str], ...]
103 # The slot key MT stores picks under (match_of_the_week.pool, SB-1638).
104 key: str = "main"
107# League from Homegrown Northeast, Flex from the three conferences around it (SB-1635).
108# Each holds a single match type, so a conference list is enough.
109POOL = Pool(
110 age_groups=("U15", "U16", "U17", "U19"),
111 match_types=("League", "Flex"),
112 conferences=(
113 ("Homegrown", "Northeast"),
114 ("Flex", "Empire"),
115 ("Flex", "New England"),
116 ("Flex", "Turnpike"),
117 ),
118)
120# The pro academies get a pick of their own rather than competing in POOL: their
121# table is a different competition, and teams there play up an age group (SB-1635).
122PRO_PATHWAY_POOL = Pool(
123 age_groups=("U16", "U17", "U19"), # the pathway has no U15
124 match_types=("League",),
125 conferences=(("Homegrown", "Northeast (Pro Player Pathway)"),),
126 key="pathway",
127)
129# One Match of the Week per age group in each pool (SB-1638).
130POOLS: dict[str, Pool] = {p.key: p for p in (POOL, PRO_PATHWAY_POOL)}
133class PoolConfigError(Exception):
134 """The pool names a league/division MT does not have."""
137# --- result models -----------------------------------------------------------
140class MotwFact(BaseModel):
141 """One thing that is true about a candidate, with an id a reason can cite."""
143 id: str
144 kind: FactKind
145 text: str
146 team_id: int | None = None
147 rule_id: str | None = None
148 # For a fact stated from a qualification rule: whether that rule is confirmed.
149 # An unconfirmed rule may only be repeated as unconfirmed.
150 confirmed: bool | None = None
153class CandidateTeam(TeamRef):
154 position: int | None = None # null: no row in the table yet
155 table_size: int | None = None
156 played: int = 0
157 points: int | None = None
158 strength: float
159 form: float | None = None # null: no League/Flex results yet
160 low_sample: bool = False
163class ScoreBreakdown(BaseModel):
164 quality: float
165 closeness: float
166 stakes: float
167 form: float
168 penalty: float = 1.0
169 total: float
172class RuleRef(BaseModel):
173 id: str
174 pathway: str
175 confirmed: bool
176 summary: str
177 source_url: str | None = None
180class MotwCandidate(BaseModel):
181 match_id: int
182 match_date: date
183 scheduled_kickoff: str | None = None
184 age_group: AgeGroupRef
185 division: DivisionRef
186 competition: str
187 home: CandidateTeam
188 away: CandidateTeam
189 score: ScoreBreakdown
190 flags: list[str] = []
191 facts: list[MotwFact] = []
192 rules: list[RuleRef] = []
195class CurrentPick(BaseModel):
196 match_id: int
197 blurb: str | None = None
198 has_reasons: bool = False
201class CandidatesCoverage(BaseModel):
202 divisions: int
203 fixtures_in_week: int # every pool fixture dated in the week, any status
204 eligible: int # still to be played, League/Flex, not before today
205 teams_low_sample: int
206 rules_season: str | None = None # null: no rules file for this season
209class MotwCandidatesResult(BaseModel):
210 """Ranked candidates for one week's slot: a pool, and an age group or all of them.
212 `candidates` is [] with `reason` when the week has nothing eligible, and null
213 with `error` when MT could not check. `current_pick` is the slot's pick if one
214 exists: candidates are still returned, but an agent must not overwrite a pick.
215 """
217 week_start: date
218 week_end: date
219 pool: str = "main"
220 age_group: str | None = None # null: every age group in the pool
221 today: date | None = None
222 season: SeasonRef | None = None
223 current_pick: CurrentPick | None = None
224 candidates: list[MotwCandidate] | None = None
225 reason: str | None = None
226 coverage: CandidatesCoverage | None = None
227 weights: dict[str, float] = WEIGHTS
228 error: ToolError | None = None
231# --- pure scoring --------------------------------------------------------------
234@dataclass(frozen=True)
235class TeamStanding:
236 team_id: int
237 position: int
238 played: int
239 points: int
240 wins: int
241 draws: int
242 losses: int
243 goals_for: int
244 goals_against: int
247def standings_from_rows(rows: list[dict]) -> dict[int, TeamStanding]:
248 """`MatchDAO.get_standings` rows (already in table order) by team id."""
249 out: dict[int, TeamStanding] = {}
250 for position, row in enumerate(rows, start=1):
251 team_id = row.get("team_id")
252 if team_id is None: 252 ↛ 253line 252 didn't jump to line 253 because the condition on line 252 was never true
253 continue
254 out[team_id] = TeamStanding(
255 team_id=team_id,
256 position=position,
257 played=row.get("played") or 0,
258 points=row.get("points") or 0,
259 wins=row.get("wins") or 0,
260 draws=row.get("draws") or 0,
261 losses=row.get("losses") or 0,
262 goals_for=row.get("goals_for") or 0,
263 goals_against=row.get("goals_against") or 0,
264 )
265 return out
268def _percentiles(values: dict[int, float]) -> dict[int, float]:
269 """Rank percentile in [0, 1], ties sharing their average rank; one team → 0.5."""
270 n = len(values)
271 if n == 0:
272 return {}
273 if n == 1:
274 return dict.fromkeys(values, 0.5)
275 ordered = sorted(values.values())
276 out = {}
277 for key, value in values.items():
278 below = sum(1 for v in ordered if v < value)
279 equal = sum(1 for v in ordered if v == value)
280 out[key] = (below + (equal - 1) / 2) / (n - 1)
281 return out
284def team_strengths(table: dict[int, TeamStanding]) -> dict[int, tuple[float, bool]]:
285 """team_id → (strength in [0, 1], low_sample) for every team with a row."""
286 played = {t: s for t, s in table.items() if s.played > 0}
287 ppg = _percentiles({t: s.points / s.played for t, s in played.items()})
288 gdpg = _percentiles({t: (s.goals_for - s.goals_against) / s.played for t, s in played.items()})
289 out: dict[int, tuple[float, bool]] = {}
290 for team_id, standing in table.items():
291 if team_id not in played:
292 out[team_id] = (0.5, True)
293 continue
294 raw = (ppg[team_id] + gdpg[team_id]) / 2
295 if standing.played < LOW_SAMPLE_GAMES:
296 out[team_id] = (0.5 + (raw - 0.5) * standing.played / LOW_SAMPLE_GAMES, True)
297 else:
298 out[team_id] = (raw, False)
299 return out
302def result_for(match: dict, team_id: int) -> Literal["W", "D", "L"] | None:
303 """A played match's result from `team_id`'s side, on the regulation score."""
304 if match.get("match_status") not in PLAYED_STATUSES:
305 return None
306 hs, as_ = match.get("home_score"), match.get("away_score")
307 if hs is None or as_ is None: 307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true
308 return None
309 ours, theirs = (hs, as_) if match.get("home_team_id") == team_id else (as_, hs)
310 return "W" if ours > theirs else "L" if ours < theirs else "D"
313def team_results(matches: Iterable[dict], team_id: int, before: date) -> list[tuple[dict, str]]:
314 """Played League/Flex matches of a team before `before`, newest first, with its result."""
315 out = []
316 for m in matches:
317 if team_id not in (m.get("home_team_id"), m.get("away_team_id")):
318 continue
319 if m.get("match_type_name") not in POOL.match_types:
320 continue
321 if _date(m.get("match_date")) >= before:
322 continue
323 result = result_for(m, team_id)
324 if result:
325 out.append((m, result))
326 out.sort(key=lambda r: (_date(r[0].get("match_date")), r[0].get("id") or 0), reverse=True)
327 return out
330def form_score(results: list[str]) -> float | None:
331 """Recency-weighted form over the last five results (newest first); None if none."""
332 recent = results[:FORM_GAMES]
333 if not recent:
334 return None
335 value = {"W": 1.0, "D": 0.5, "L": 0.0}
336 weights = FORM_WEIGHTS[: len(recent)]
337 return sum(w * value[r] for w, r in zip(weights, recent, strict=True)) / sum(weights)
340def meetings_between(history: Iterable[dict], home_id: int, away_id: int, match_id: int) -> list[dict]:
341 """Played matches between the two teams in `history`, other than this fixture."""
342 return [
343 m
344 for m in history
345 if {m.get("home_team_id"), m.get("away_team_id")} == {home_id, away_id}
346 and m.get("id") != match_id
347 and result_for(m, home_id)
348 ]
351def in_pool_types(matches: Iterable[dict]) -> list[dict]:
352 """The League and Flex matches, the ones a season's rematch counts."""
353 return [m for m in matches if m.get("match_type_name") in POOL.match_types]
356def rematch_score(meetings: list[dict]) -> float:
357 """What earlier League/Flex meetings this season add to stakes; the latest decides."""
358 if not meetings:
359 return 0.0
360 last = max(meetings, key=lambda m: _date(m.get("match_date")))
361 return REMATCH_CLOSE if abs(last["home_score"] - last["away_score"]) <= CLOSE_MARGIN else REMATCH
364def stakes_score(
365 home: TeamStanding | None,
366 away: TeamStanding | None,
367 table_size: int,
368 line_ranks: Iterable[int],
369 table: dict,
370 *,
371 rematch: float = 0.0,
372) -> tuple[float, list[str]]:
373 """How much rides on it, in [0, 1], and why (flag names).
375 A rematch counts even without table rows: two teams can meet in Flex before either
376 has a row in the League table their next meeting counts in.
377 """
378 components: dict[str, float] = {}
379 if rematch:
380 components["rematch"] = rematch
381 if home is not None and away is not None and table_size >= 2:
382 gap = abs(home.position - away.position)
383 if gap == 1:
384 components["adjacent"] = 0.7
385 elif gap == 2: 385 ↛ 386line 385 didn't jump to line 386 because the condition on line 385 was never true
386 components["adjacent"] = 0.45
387 top = max(home.position, away.position)
388 if top <= 3:
389 components["top_of_table"] = 1.0
390 elif min(home.position, away.position) <= 2 and top <= 5: 390 ↛ 391line 390 didn't jump to line 391 because the condition on line 390 was never true
391 components["top_of_table"] = 0.7
392 by_position = {s.position: s for s in table.values()}
393 for rank in line_ranks:
394 line = by_position.get(rank)
395 if line is None: 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 continue
397 if all(t.points >= line.points - LINE_MARGIN_POINTS for t in (home, away)):
398 components["qualifying_line"] = 1.0
399 if not components:
400 return 0.0, []
401 best = max(components.values())
402 return best, sorted(k for k, v in components.items() if v > 0)
405def score_fixture(
406 strength_home: float,
407 strength_away: float,
408 stakes: float,
409 form_home: float | None,
410 form_away: float | None,
411 *,
412 featured: bool,
413) -> ScoreBreakdown:
414 quality = min(strength_home, strength_away)
415 closeness = 1 - abs(strength_home - strength_away)
416 form = ((0.5 if form_home is None else form_home) + (0.5 if form_away is None else form_away)) / 2
417 penalty = FEATURED_PENALTY if featured else 1.0
418 total = (
419 WEIGHTS["quality"] * quality
420 + WEIGHTS["closeness"] * closeness
421 + WEIGHTS["stakes"] * stakes
422 + WEIGHTS["form"] * form
423 ) * penalty
424 return ScoreBreakdown(
425 quality=round(quality, 3),
426 closeness=round(closeness, 3),
427 stakes=round(stakes, 3),
428 form=round(form, 3),
429 penalty=penalty,
430 total=round(total, 4),
431 )
434# --- facts ---------------------------------------------------------------------
437def _ordinal(n: int) -> str:
438 suffix = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
439 return f"{n}{suffix}"
442def _plural(n: int, word: str) -> str:
443 if n == 1:
444 return f"{n} {word}"
445 return f"{n} {word}es" if word.endswith(("s", "x", "ch", "sh")) else f"{n} {word}s"
448def streak_text(name: str, results: list[str]) -> str | None:
449 """A run of 3+ wins or unbeaten games from the newest result, or a perfect record."""
450 if len(results) >= 3 and all(r == "W" for r in results):
451 return f"{name} have won all {len(results)} of their League/Flex matches this season."
452 wins = 0
453 for r in results:
454 if r != "W":
455 break
456 wins += 1
457 if wins >= 3:
458 return f"{name} have won {wins} League/Flex matches in a row."
459 unbeaten = 0
460 for r in results:
461 if r == "L":
462 break
463 unbeaten += 1
464 if unbeaten >= 3:
465 return f"{name} are unbeaten in {unbeaten} League/Flex matches."
466 losses = 0
467 for r in results:
468 if r != "L":
469 break
470 losses += 1
471 if losses >= 3:
472 return f"{name} have lost {losses} in a row and need a result."
473 return None
476def build_facts(
477 match: dict,
478 table_label: str,
479 table: dict[int, TeamStanding],
480 names: dict[int, str],
481 history: list[dict],
482 today: date,
483 rules: list[QualificationRule],
484) -> list[MotwFact]:
485 """Every fact about one fixture that the data supports. Pure."""
486 mid = match["id"]
487 home_id, away_id = match["home_team_id"], match["away_team_id"]
488 facts: list[MotwFact] = []
489 table_size = len(table)
491 for side, team_id in (("home", home_id), ("away", away_id)):
492 s = table.get(team_id)
493 if s is None or s.played == 0:
494 continue
495 facts.append(
496 MotwFact(
497 id=f"{mid}:pos:{side}",
498 kind="standings",
499 team_id=team_id,
500 text=(
501 f"{names[team_id]} are {_ordinal(s.position)} of {table_size} in {table_label} with "
502 f"{_plural(s.points, 'point')} from {_plural(s.played, 'match')} ({s.wins}-{s.draws}-{s.losses})."
503 ),
504 )
505 )
506 if s.played >= LOW_SAMPLE_GAMES: 506 ↛ 491line 506 didn't jump to line 491 because the condition on line 506 was always true
507 facts.append(
508 MotwFact(
509 id=f"{mid}:rate:{side}",
510 kind="form",
511 team_id=team_id,
512 text=(
513 f"{names[team_id]} score {s.goals_for / s.played:.1f} and concede "
514 f"{s.goals_against / s.played:.1f} goals per match in {table_label}."
515 ),
516 )
517 )
519 h, a = table.get(home_id), table.get(away_id)
520 if h and a and h.played and a.played:
521 gap = abs(h.points - a.points)
522 text = (
523 f"{names[home_id]} and {names[away_id]} are level on {_plural(h.points, 'point')}."
524 if gap == 0
525 else f"{_plural(gap, 'point')} separate {names[home_id]} ({h.points}) and {names[away_id]} ({a.points})."
526 )
527 facts.append(MotwFact(id=f"{mid}:gap", kind="standings", text=text))
529 for side, team_id in (("home", home_id), ("away", away_id)):
530 results = [r for _, r in team_results(history, team_id, today)]
531 text = streak_text(names[team_id], results)
532 if text:
533 facts.append(MotwFact(id=f"{mid}:streak:{side}", kind="form", team_id=team_id, text=text))
535 meetings = meetings_between(history, home_id, away_id, mid)
536 if meetings:
537 rematches = in_pool_types(meetings)
538 last = max(rematches or meetings, key=lambda m: _date(m.get("match_date")))
539 nth = f"{_ordinal(len(rematches) + 1)} meeting this season. " if rematches else ""
540 facts.append(
541 MotwFact(
542 id=f"{mid}:h2h",
543 kind="rivalry",
544 text=(
545 f"{nth}They met on {_date(last['match_date']):%b %-d} ({last.get('match_type_name')}): "
546 f"{names.get(last['home_team_id'], last.get('home_team_name'))} {last['home_score']}-"
547 f"{last['away_score']} {names.get(last['away_team_id'], last.get('away_team_name'))}."
548 ),
549 )
550 )
552 common = _common_opponents(history, home_id, away_id, today)
553 if len(common) >= 2:
555 def record(team_id: int) -> str:
556 rs = [r for opp in common for r in common[opp][team_id]]
557 return f"{rs.count('W')}-{rs.count('D')}-{rs.count('L')}"
559 facts.append(
560 MotwFact(
561 id=f"{mid}:common",
562 kind="storyline",
563 text=(
564 f"Against the {len(common)} opponents both have played, {names[home_id]} went "
565 f"{record(home_id)} and {names[away_id]} {record(away_id)}."
566 ),
567 )
568 )
570 for side, team_id in (("home", home_id), ("away", away_id)):
571 left = sum(
572 1
573 for m in history
574 if m.get("id") != mid
575 and m.get("division_id") == match.get("division_id")
576 and m.get("match_status") in OPEN_STATUSES
577 and team_id in (m.get("home_team_id"), m.get("away_team_id"))
578 and _date(m.get("match_date")) >= _date(match.get("match_date"))
579 )
580 if left:
581 facts.append(
582 MotwFact(
583 id=f"{mid}:left:{side}",
584 kind="stakes",
585 team_id=team_id,
586 text=f"{names[team_id]} have {_plural(left, 'match')} left in {table_label} after this one.",
587 )
588 )
590 for rule in rules:
591 prefix = "" if rule.confirmed else "Unconfirmed: "
592 facts.append(
593 MotwFact(
594 id=f"{mid}:rule:{rule.id}",
595 kind="stakes",
596 rule_id=rule.id,
597 confirmed=rule.confirmed,
598 text=f"{prefix}{rule.competition} → {rule.pathway}. {rule.summary}",
599 )
600 )
601 return facts
604def _common_opponents(history: list[dict], home_id: int, away_id: int, today: date) -> dict[int, dict[int, list[str]]]:
605 seen: dict[int, dict[int, list[str]]] = {}
606 for team_id in (home_id, away_id):
607 for m, r in team_results(history, team_id, today):
608 opp = m["away_team_id"] if m["home_team_id"] == team_id else m["home_team_id"]
609 if opp in (home_id, away_id):
610 continue
611 seen.setdefault(opp, {home_id: [], away_id: []})[team_id].append(r)
612 return {opp: rs for opp, rs in seen.items() if rs[home_id] and rs[away_id]}
615# --- gathering -----------------------------------------------------------------
618@dataclass(frozen=True)
619class PoolDivision:
620 id: int
621 name: str
622 league: str
623 age_groups: tuple[AgeGroupRef, ...]
626def resolve_pool(index: TeamIndex, pool: Pool = POOL) -> list[PoolDivision]:
627 """The pool's (league, division) names → MT divisions, with the pool ages each runs.
629 Raises PoolConfigError naming every pair MT does not have.
630 """
631 found: dict[tuple[str, str], tuple[int, dict[int, AgeGroupRef]]] = {}
632 for team in index.teams.values():
633 for mapping in team.get("team_mappings") or []:
634 division, age = mapping.get("divisions") or {}, mapping.get("age_groups") or {}
635 league = index.leagues.get(division.get("league_id") or 0) or division.get("leagues") or {}
636 key = (str(league.get("name") or ""), str(division.get("name") or ""))
637 if key not in pool.conferences or division.get("id") is None:
638 continue
639 entry = found.setdefault(key, (division["id"], {}))
640 if age.get("name") in pool.age_groups:
641 entry[1][age["id"]] = AgeGroupRef(id=age["id"], name=age["name"])
642 missing = [f"{league} / {name}" for league, name in pool.conferences if (league, name) not in found]
643 if missing:
644 raise PoolConfigError(f"MOTW pool names divisions MT does not have: {', '.join(missing)}")
645 return [
646 PoolDivision(id=div_id, name=name, league=league, age_groups=tuple(sorted(ages.values(), key=lambda a: a.name)))
647 for (league, name), (div_id, ages) in found.items()
648 ]
651PickReader = Callable[[str], dict | list[dict] | None]
654def week_bounds(week: str | date | None, today: date) -> tuple[date, date]:
655 """Monday and Sunday of the week containing `week` (any date in it), default this week."""
656 day = today if week is None else (week if isinstance(week, date) else date.fromisoformat(str(week)[:10]))
657 start = day - timedelta(days=day.weekday())
658 return start, start + timedelta(days=6)
661def suggest_motw_candidates(
662 deps: ToolDeps,
663 week: str | date | None = None,
664 *,
665 picks: PickReader,
666 limit: int = 5,
667 now: datetime | None = None,
668 pool: Pool = POOL,
669 age_group: str | None = None,
670) -> MotwCandidatesResult:
671 """Top `limit` Match of the Week candidates for a week's slot, public data only.
673 `age_group` (e.g. "U16") narrows the pool to that age's fixtures and its pick;
674 None ranks every age group in the pool together.
675 """
676 current = now or datetime.now(UTC)
677 if current.tzinfo is None: 677 ↛ 678line 677 didn't jump to line 678 because the condition on line 677 was never true
678 current = current.replace(tzinfo=UTC)
679 today = current.astimezone(POOL_TIMEZONE).date()
680 try:
681 week_start, week_end = week_bounds(week, today)
682 except ValueError:
683 start = today - timedelta(days=today.weekday())
684 return MotwCandidatesResult(
685 week_start=start,
686 week_end=start + timedelta(days=6),
687 pool=pool.key,
688 age_group=age_group,
689 error=ToolError(kind="invalid_args", message="week must be a date (YYYY-MM-DD) in the week wanted."),
690 )
692 def fail(kind: Literal["unavailable", "invalid_args"], message: str) -> MotwCandidatesResult:
693 return MotwCandidatesResult(
694 week_start=week_start,
695 week_end=week_end,
696 pool=pool.key,
697 age_group=age_group,
698 today=today,
699 error=ToolError(kind=kind, message=message),
700 )
702 if not 1 <= limit <= MAX_LIMIT:
703 return fail("invalid_args", f"limit must be between 1 and {MAX_LIMIT}.")
704 if age_group is not None and age_group not in pool.age_groups:
705 return fail("invalid_args", f"age_group must be one of {', '.join(pool.age_groups)} for the {pool.key} pool.")
706 scope = replace(pool, age_groups=(age_group,)) if age_group else pool
708 viewer = Viewer(include_test=False)
709 try:
710 season_row = deps.seasons.get_current_season()
711 if not season_row: 711 ↛ 712line 711 didn't jump to line 712 because the condition on line 711 was never true
712 raise DataUnavailableError("no current season")
713 season = SeasonRef(id=season_row["id"], name=season_row["name"])
714 index = load_team_index(deps, viewer)
715 divisions = resolve_pool(index, scope)
716 history: dict[tuple[int, int], list[dict]] = {}
717 for division in divisions:
718 for age in division.age_groups:
719 history[(division.id, age.id)] = deps.matches.get_all_matches(
720 season_id=season.id,
721 age_group_id=age.id,
722 division_id=division.id,
723 include_test=False,
724 raise_on_error=True,
725 )
726 current_pick = _current_pick(picks, week_start, pool.key, age_group)
727 featured = _recently_featured(picks, week_start, pool.key, age_group)
728 except PoolConfigError as exc:
729 logger.error("motw_pool_config", error=str(exc))
730 return fail("unavailable", str(exc))
731 except DataUnavailableError as exc:
732 return fail("unavailable", f"MOTW candidates are unavailable right now ({exc}).")
733 except Exception:
734 logger.exception("suggest_motw_candidates failed")
735 return fail("unavailable", "MOTW candidates are unavailable right now.")
737 rules_key = season_key(season.name)
738 try:
739 ruleset = load_rules(rules_key) if rules_key else None
740 except RulesError:
741 logger.warning("motw_no_rules", season=season.name)
742 ruleset = None
744 every = [m for ms in history.values() for m in ms]
745 by_division = {d.id: d for d in divisions}
746 in_week = [m for m in every if week_start <= _date(m.get("match_date")) <= week_end]
747 eligible = [
748 m
749 for m in in_week
750 if m.get("match_status") in ELIGIBLE_STATUSES
751 and m.get("match_type_name") in pool.match_types
752 and _date(m.get("match_date")) >= today
753 ]
755 candidates: list[MotwCandidate] = []
756 low_sample_teams: set[int] = set()
757 tables: dict[tuple[int, int], dict[int, TeamStanding]] = {}
758 for match in eligible:
759 division = by_division[match["division_id"]]
760 key = (division.id, match["age_group_id"])
761 try:
762 if key not in tables:
763 data = deps.matches.get_standings(
764 season_id=season.id,
765 age_group_id=match["age_group_id"],
766 division_id=division.id,
767 match_type=match["match_type_name"],
768 include_test=False,
769 raise_on_error=True,
770 )
771 tables[key] = standings_from_rows(data.get("standings") or [])
772 except Exception:
773 logger.exception("motw standings failed", division_id=division.id, age_group_id=match["age_group_id"])
774 return fail("unavailable", "MOTW candidates are unavailable right now (standings).")
775 # One team row plays every age group (a club in a league), so history is
776 # scoped to the fixture's age group: IFA U16's form is not IFA U19's.
777 age_history = [m for m in every if m.get("age_group_id") == match["age_group_id"]]
778 candidate = _candidate(
779 match, division, tables[key], age_history, index, today, featured, ruleset, low_sample_teams
780 )
781 candidates.append(candidate)
783 candidates.sort(key=lambda c: (-c.score.total, c.match_date, c.match_id))
784 coverage = CandidatesCoverage(
785 divisions=len(divisions),
786 fixtures_in_week=len(in_week),
787 eligible=len(eligible),
788 teams_low_sample=len(low_sample_teams),
789 rules_season=ruleset.season if ruleset else None,
790 )
791 logger.info(
792 "motw_candidates_scored",
793 week_start=week_start.isoformat(),
794 pool=pool.key,
795 age_group=age_group,
796 divisions=coverage.divisions,
797 fixtures_in_week=coverage.fixtures_in_week,
798 eligible=coverage.eligible,
799 teams_low_sample=coverage.teams_low_sample,
800 returned=min(limit, len(candidates)),
801 candidates=[_score_log(c) for c in candidates],
802 )
803 reason = None
804 if not candidates:
805 reason = (
806 f"No pool fixtures are dated {week_start:%b %-d}-{week_end:%b %-d}."
807 if not in_week
808 else f"None of the {len(in_week)} pool fixtures that week are still to be played."
809 )
810 return MotwCandidatesResult(
811 week_start=week_start,
812 week_end=week_end,
813 pool=pool.key,
814 age_group=age_group,
815 today=today,
816 season=season,
817 current_pick=current_pick,
818 candidates=candidates[:limit],
819 reason=reason,
820 coverage=coverage,
821 )
824def _score_log(c: MotwCandidate) -> dict[str, Any]:
825 """Why a candidate ranked where it did. Every eligible fixture, so near misses show too."""
826 return {
827 "match_id": c.match_id,
828 "fixture": f"{c.home.name} vs {c.away.name}",
829 "age_group": c.age_group.name,
830 "division": c.division.name,
831 "competition": c.competition,
832 **c.score.model_dump(),
833 "flags": c.flags,
834 }
837def _candidate(
838 match: dict,
839 division: PoolDivision,
840 table: dict[int, TeamStanding],
841 history: list[dict],
842 index: TeamIndex,
843 today: date,
844 featured: set[int],
845 ruleset: Any,
846 low_sample_teams: set[int],
847) -> MotwCandidate:
848 age = AgeGroupRef(id=match["age_group_id"], name=match.get("age_group_name") or "")
849 competition = match.get("match_type_name") or ""
850 label = f"{age.name} {division.name}" + (f" ({competition})" if competition != "League" else "")
851 strengths = team_strengths(table)
852 home_id, away_id = match["home_team_id"], match["away_team_id"]
853 names = {
854 home_id: match.get("home_team_name") or str(home_id),
855 away_id: match.get("away_team_name") or str(away_id),
856 }
857 for m in history:
858 names.setdefault(m["home_team_id"], m.get("home_team_name") or str(m["home_team_id"]))
859 names.setdefault(m["away_team_id"], m.get("away_team_name") or str(m["away_team_id"]))
861 kind = conference_kind(division.league, division.name)
862 rules: list[QualificationRule] = (
863 ruleset.applicable(age.name, kind, tier=tier_of(division.league)) if ruleset and kind else []
864 )
865 line_ranks = [r.selector.rank for r in rules if r.selector and r.selector.rank]
867 teams: dict[str, CandidateTeam] = {}
868 forms: dict[int, float | None] = {}
869 flags: list[str] = []
870 for side, team_id in (("home", home_id), ("away", away_id)):
871 strength, low = strengths.get(team_id, (0.5, True))
872 forms[team_id] = form_score([r for _, r in team_results(history, team_id, today)])
873 standing = table.get(team_id)
874 team = index.teams.get(team_id) or {}
875 teams[side] = CandidateTeam(
876 id=team_id,
877 name=names[team_id],
878 club_name=index.club_name(team) if team else None,
879 position=standing.position if standing else None,
880 table_size=len(table) or None,
881 played=standing.played if standing else 0,
882 points=standing.points if standing else None,
883 strength=round(strength, 3),
884 form=None if forms[team_id] is None else round(forms[team_id], 3),
885 low_sample=low,
886 )
887 if low:
888 low_sample_teams.add(team_id)
889 if "low_sample" not in flags:
890 flags.append("low_sample")
892 rematch = rematch_score(in_pool_types(meetings_between(history, home_id, away_id, match["id"])))
893 stakes, stake_flags = stakes_score(
894 table.get(home_id), table.get(away_id), len(table), line_ranks, table, rematch=rematch
895 )
896 flags.extend(stake_flags)
897 is_featured = bool({home_id, away_id} & featured)
898 if is_featured:
899 flags.append("recently_featured")
900 score = score_fixture(
901 teams["home"].strength, teams["away"].strength, stakes, forms[home_id], forms[away_id], featured=is_featured
902 )
903 return MotwCandidate(
904 match_id=match["id"],
905 match_date=_date(match["match_date"]),
906 scheduled_kickoff=match.get("scheduled_kickoff"),
907 age_group=age,
908 division=DivisionRef(id=division.id, name=division.name, league=division.league),
909 competition=competition,
910 home=teams["home"],
911 away=teams["away"],
912 score=score,
913 flags=flags,
914 facts=build_facts(match, label, table, names, history, today, rules),
915 rules=[
916 RuleRef(id=r.id, pathway=r.pathway, confirmed=r.confirmed, summary=r.summary, source_url=r.source_url)
917 for r in rules
918 ],
919 )
922def _slot_picks(picks: PickReader, week: date, pool_key: str, age_group: str | None) -> list[dict]:
923 """The picks a reader returns for a week that sit in this slot.
925 A reader returns one pick, a list of the week's picks (SB-1638), or None. A pick
926 that does not say its pool or age group counts as in the slot: before SB-1638
927 there was one pick a week, and it was everyone's.
928 """
929 got = picks(week.isoformat())
930 items = got if isinstance(got, list) else ([got] if got else [])
932 def in_slot(pick: dict) -> bool:
933 if (pick.get("pool") or pool_key) != pool_key:
934 return False
935 age = pick.get("age_group") or (pick.get("match") or {}).get("age_group_name")
936 return age_group is None or age in (None, age_group)
938 return [p for p in items if in_slot(p)]
941def _current_pick(picks: PickReader, week_start: date, pool_key: str, age_group: str | None) -> CurrentPick | None:
942 found = _slot_picks(picks, week_start, pool_key, age_group)
943 if not found:
944 return None
945 pick = found[0]
946 match = pick.get("match") or {}
947 return CurrentPick(
948 match_id=match.get("id") or pick.get("match_id"),
949 blurb=pick.get("blurb"),
950 has_reasons=bool(pick.get("reasons")),
951 )
954def _recently_featured(picks: PickReader, week_start: date, pool_key: str, age_group: str | None) -> set[int]:
955 """Teams in the slot's picks of the FEATURED_WEEKS weeks before this one."""
956 teams: set[int] = set()
957 for back in range(1, FEATURED_WEEKS + 1):
958 for pick in _slot_picks(picks, week_start - timedelta(weeks=back), pool_key, age_group):
959 match = pick.get("match") or {}
960 teams.update(t for t in (match.get("home_team_id"), match.get("away_team_id")) if t is not None)
961 return teams
964def _date(value: Any) -> date:
965 if isinstance(value, date): 965 ↛ 966line 965 didn't jump to line 966 because the condition on line 965 was never true
966 return value
967 return date.fromisoformat(str(value)[:10])
970def suggest_from_deps(
971 deps: ToolDeps,
972 week: str | None = None,
973 *,
974 limit: int = 5,
975 pool: str = "main",
976 age_group: str | None = None,
977 now: datetime | None = None,
978) -> MotwCandidatesResult:
979 """`suggest_motw_candidates` reading the picks from `deps.motw` (mt-mcp, the API)."""
980 motw = deps.motw
981 chosen = POOLS.get(pool)
982 if motw is None or chosen is None:
983 start, end = week_bounds(None, (now or datetime.now(UTC)).astimezone(POOL_TIMEZONE).date())
984 kind: Literal["unavailable", "invalid_args"] = "unavailable" if motw is None else "invalid_args"
985 message = (
986 "MOTW candidates are unavailable right now." if motw is None else f"pool must be one of {', '.join(POOLS)}."
987 )
988 return MotwCandidatesResult(
989 week_start=start, week_end=end, pool=pool, age_group=age_group, error=ToolError(kind=kind, message=message)
990 )
991 return suggest_motw_candidates(
992 deps, week, picks=lambda w: motw.list_for_week(w), limit=limit, now=now, pool=chosen, age_group=age_group
993 )