Coverage for mt_ai/tools/results.py: 96.30%

61 statements  

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

1"""get_recent_results — a team's last played matches, scored from its side (SB-1526). 

2 

3"How did we do last weekend?", "our last five games", "how have we done against 

4Boston?". The other half of get_upcoming_matches, with the same "today": the club's 

5calendar day, so a game finished at 9pm in Boston is in the results, not tomorrow's. 

6 

7Played means completed or forfeit with both scores recorded. A result is from the 

8regulation score, as in the standings: a level match decided on penalties is a draw, 

9with the shootout alongside. Newest first. `opponent_id` narrows to head-to-head, 

10across seasons. 

11""" 

12 

13from datetime import UTC, date, datetime 

14 

15import structlog 

16 

17from mt_ai.tools.deps import ToolDeps 

18from mt_ai.tools.matches import _club, _newest, _provenance 

19from mt_ai.tools.schemas import ( 

20 ErrorKind, 

21 RecentResult, 

22 RecentResultsResult, 

23 ResultsSummary, 

24 TeamRef, 

25 ToolError, 

26 ToolMeta, 

27 Viewer, 

28) 

29from mt_ai.tools.visibility import DataUnavailableError, load_team_index 

30 

31logger = structlog.get_logger() 

32 

33PLAYED_STATUSES = frozenset({"completed", "forfeit"}) 

34MAX_LIMIT = 20 

35 

36 

37def get_recent_results( 

38 deps: ToolDeps, 

39 team_id: int, 

40 viewer: Viewer, 

41 age_group_id: int | None = None, 

42 limit: int = 5, 

43 opponent_id: int | None = None, 

44 now: datetime | None = None, 

45) -> RecentResultsResult: 

46 def fail(kind: ErrorKind, message: str) -> RecentResultsResult: 

47 return RecentResultsResult( 

48 team_id=team_id, 

49 age_group_id=age_group_id, 

50 opponent_id=opponent_id, 

51 error=ToolError(kind=kind, message=message), 

52 ) 

53 

54 if not 1 <= limit <= MAX_LIMIT: 

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

56 if opponent_id == team_id: 

57 return fail("invalid_args", "opponent_id must be a different team.") 

58 

59 try: 

60 index = load_team_index(deps, viewer) 

61 team = index.teams.get(team_id) 

62 if team is None: 

63 return fail("not_found", f"No team with id {team_id}.") 

64 if opponent_id is not None and opponent_id not in index.teams: 

65 return fail("not_found", f"No team with id {opponent_id}.") 

66 

67 tz = index.timezone(team) 

68 current = now or datetime.now(UTC) 

69 if current.tzinfo is None: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true

70 current = current.replace(tzinfo=UTC) 

71 today = current.astimezone(tz).date() 

72 

73 rows = deps.matches.get_all_matches( 

74 team_id=team_id, 

75 age_group_id=age_group_id, 

76 end_date=today.isoformat(), 

77 include_test=viewer.include_test, 

78 raise_on_error=True, 

79 ) 

80 except DataUnavailableError as exc: 

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

82 except Exception: 

83 logger.exception("get_recent_results failed", team_id=team_id) 

84 return fail("unavailable", "Match data is unavailable right now.") 

85 

86 played = [] 

87 for row in rows: 

88 if opponent_id is not None and opponent_id not in (row.get("home_team_id"), row.get("away_team_id")): 

89 continue 

90 result = _to_result(row, team_id) 

91 if result and result.match_date <= today: 

92 played.append((result, row)) 

93 played.sort(key=lambda r: (r[0].match_date, r[0].match_id), reverse=True) 

94 

95 kept = played[:limit] 

96 results = [r for r, _ in kept] 

97 return RecentResultsResult( 

98 team_id=team_id, 

99 age_group_id=age_group_id, 

100 opponent_id=opponent_id, 

101 today=today, 

102 timezone=tz.key, 

103 matches=results, 

104 summary=_summary(results), 

105 meta=ToolMeta( 

106 source=_provenance([r for _, r in kept]), 

107 as_of=_newest([r for _, r in kept]), 

108 truncated=len(played) > limit, 

109 ), 

110 ) 

111 

112 

113def _to_result(row: dict, team_id: int) -> RecentResult | None: 

114 """A played match from `team_id`'s side; None when not played or malformed.""" 

115 if row.get("match_status") not in PLAYED_STATUSES: 

116 return None 

117 home_score, away_score = row.get("home_score"), row.get("away_score") 

118 if home_score is None or away_score is None: 

119 return None # played but unscored: unknown, not 0-0 

120 try: 

121 home_id, away_id = row["home_team_id"], row["away_team_id"] 

122 is_home = home_id == team_id 

123 scored, conceded = (home_score, away_score) if is_home else (away_score, home_score) 

124 return RecentResult( 

125 match_id=row["id"], 

126 match_date=date.fromisoformat(str(row["match_date"])[:10]), 

127 status=row["match_status"], 

128 home_team=TeamRef( 

129 id=home_id, name=row.get("home_team_name") or "", club_name=_club(row.get("home_team_club")) 

130 ), 

131 away_team=TeamRef( 

132 id=away_id, name=row.get("away_team_name") or "", club_name=_club(row.get("away_team_club")) 

133 ), 

134 is_home=is_home, 

135 home_score=home_score, 

136 away_score=away_score, 

137 home_penalty_score=row.get("home_penalty_score"), 

138 away_penalty_score=row.get("away_penalty_score"), 

139 result="W" if scored > conceded else "L" if scored < conceded else "D", 

140 goals_for=scored, 

141 goals_against=conceded, 

142 age_group=row.get("age_group_name"), 

143 division=row.get("division_name"), 

144 competition=row.get("match_type_name"), 

145 league=row.get("league_name"), 

146 season=row.get("season_name"), 

147 ) 

148 except (KeyError, TypeError, ValueError): 

149 logger.warning("Skipping malformed match row", match_id=row.get("id")) 

150 return None 

151 

152 

153def _summary(results: list[RecentResult]) -> ResultsSummary: 

154 return ResultsSummary( 

155 played=len(results), 

156 wins=sum(r.result == "W" for r in results), 

157 draws=sum(r.result == "D" for r in results), 

158 losses=sum(r.result == "L" for r in results), 

159 goals_for=sum(r.goals_for for r in results), 

160 goals_against=sum(r.goals_against for r in results), 

161 )