Coverage for mt_ai/tools/matches.py: 93.62%

74 statements  

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

1"""get_upcoming_matches — a team's next fixtures, from the club's point of view. 

2 

3"Today" is the club's calendar day (clubs.timezone), worked out here and not 

4by the model: at 9pm in Boston it is already tomorrow in UTC, and "who do we 

5play next?" must not skip tonight's game or include last night's. 

6 

7Upcoming means dated today or later and not finished: scheduled, tbd, live or 

8postponed. Postponed fixtures are included and labelled, because "our game 

9Saturday was postponed" is part of the answer. Cancelled, completed and 

10forfeit matches are not upcoming. 

11""" 

12 

13from datetime import UTC, date, datetime 

14from zoneinfo import ZoneInfo 

15 

16import structlog 

17 

18from mt_ai.tools.deps import ToolDeps 

19from mt_ai.tools.schemas import ( 

20 ErrorKind, 

21 Provenance, 

22 TeamRef, 

23 ToolError, 

24 ToolMeta, 

25 UpcomingMatch, 

26 UpcomingMatchesResult, 

27 Viewer, 

28) 

29from mt_ai.tools.visibility import DataUnavailableError, load_team_index 

30 

31logger = structlog.get_logger() 

32 

33UPCOMING_STATUSES = frozenset({"scheduled", "tbd", "live", "postponed"}) 

34MAX_LIMIT = 20 

35SCRAPER_SOURCE = "match-scraper" 

36 

37 

38def get_upcoming_matches( 

39 deps: ToolDeps, 

40 team_id: int, 

41 viewer: Viewer, 

42 age_group_id: int | None = None, 

43 limit: int = 5, 

44 now: datetime | None = None, 

45) -> UpcomingMatchesResult: 

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

47 return UpcomingMatchesResult( 

48 team_id=team_id, age_group_id=age_group_id, error=ToolError(kind=kind, message=message) 

49 ) 

50 

51 if not 1 <= limit <= MAX_LIMIT: 

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

53 

54 try: 

55 index = load_team_index(deps, viewer) 

56 team = index.teams.get(team_id) 

57 if team is None: 

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

59 

60 tz = index.timezone(team) 

61 current = now or datetime.now(UTC) 

62 if current.tzinfo is None: 

63 current = current.replace(tzinfo=UTC) 

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

65 

66 rows = deps.matches.get_all_matches( 

67 team_id=team_id, 

68 age_group_id=age_group_id, 

69 start_date=today.isoformat(), 

70 include_test=viewer.include_test, 

71 raise_on_error=True, 

72 ) 

73 except DataUnavailableError as exc: 

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

75 except Exception: 

76 logger.exception("get_upcoming_matches failed", team_id=team_id) 

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

78 

79 upcoming = [] 

80 for row in rows: 

81 match = _to_match(row, team_id, tz) 

82 if match and match.status in UPCOMING_STATUSES and match.match_date >= today: 

83 upcoming.append((match, row)) 

84 upcoming.sort(key=lambda m: (m[0].match_date, m[0].kickoff or datetime.max.replace(tzinfo=UTC))) 

85 

86 kept = upcoming[:limit] 

87 return UpcomingMatchesResult( 

88 team_id=team_id, 

89 age_group_id=age_group_id, 

90 today=today, 

91 timezone=tz.key, 

92 matches=[m for m, _ in kept], 

93 meta=ToolMeta( 

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

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

96 truncated=len(upcoming) > limit, 

97 ), 

98 ) 

99 

100 

101def _to_match(row: dict, team_id: int, tz: ZoneInfo) -> UpcomingMatch | None: 

102 """Shape one DAO row, or None (logged) if it is too malformed to use.""" 

103 try: 

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

105 return UpcomingMatch( 

106 match_id=row["id"], 

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

108 kickoff=_kickoff(row.get("scheduled_kickoff"), tz), 

109 status=row.get("match_status") or "scheduled", 

110 home_team=TeamRef( 

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

112 ), 

113 away_team=TeamRef( 

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

115 ), 

116 is_home=home_id == team_id, 

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

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

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

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

121 ) 

122 except (KeyError, TypeError, ValueError): 

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

124 return None 

125 

126 

127def _kickoff(value: str | None, tz: ZoneInfo) -> datetime | None: 

128 if not value: 

129 return None 

130 try: 

131 parsed = datetime.fromisoformat(value) 

132 except ValueError: 

133 return None 

134 if parsed.tzinfo is None: 134 ↛ 135line 134 didn't jump to line 135 because the condition on line 134 was never true

135 parsed = parsed.replace(tzinfo=UTC) # the column is timestamptz; naive means UTC 

136 return parsed.astimezone(tz) 

137 

138 

139def _club(club: dict | None) -> str | None: 

140 return club.get("name") if isinstance(club, dict) else None 

141 

142 

143def _provenance(rows: list[dict]) -> Provenance | None: 

144 scraped = {(r.get("source") or "") == SCRAPER_SOURCE for r in rows} 

145 if not scraped: 

146 return None 

147 if len(scraped) > 1: 

148 return "mixed" 

149 return "scraper" if scraped.pop() else "user" 

150 

151 

152def _newest(rows: list[dict]) -> datetime | None: 

153 stamps = [] 

154 for row in rows: 

155 try: 

156 stamp = datetime.fromisoformat(row["updated_at"]) 

157 except (KeyError, TypeError, ValueError): 

158 continue 

159 stamps.append(stamp if stamp.tzinfo else stamp.replace(tzinfo=UTC)) 

160 return max(stamps, default=None)