Coverage for mt_ai/tools/live.py: 92.62%
103 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""get_live_match — one match's live state: score, clock, goals and cards (SB-1584).
3What the live-match view shows, read-only: the score (and a shootout), which half
4it is and the current minute, and every goal and card with its minute and team.
5Chat is never read: it is user content, and `match_events.message` is free text
6that can hold anyone's name.
8Players are minors. Whatever the roster holds, a player leaves this tool as at
9most "#7 Tom D." (jersey number, first name, last initial) and "#7" when there
10is no first name (SB-1583). The rule is enforced here, not trusted to the data.
11"""
13from datetime import UTC, datetime
14from typing import Any
16import structlog
18from mt_ai.tools.deps import ToolDeps
19from mt_ai.tools.schemas import (
20 ErrorKind,
21 LiveEvent,
22 LiveMatchResult,
23 LivePeriod,
24 TeamRef,
25 ToolError,
26 ToolMeta,
27 Viewer,
28)
30logger = structlog.get_logger()
32NOT_TRACKED = (
33 "Goals and cards are recorded live in the MT app by a team manager; this match "
34 "was not tracked live, so only its score is known."
35)
38def get_live_match(
39 deps: ToolDeps,
40 match_id: int,
41 viewer: Viewer,
42 now: datetime | None = None,
43) -> LiveMatchResult:
44 def fail(kind: ErrorKind, message: str) -> LiveMatchResult:
45 return LiveMatchResult(match_id=match_id, error=ToolError(kind=kind, message=message))
47 if deps.live is None or deps.events is None or deps.roster is None:
48 return fail("unavailable", "Live match data is not available here.")
50 try:
51 state = deps.live.get_live_match_state(match_id, include_test=viewer.include_test)
52 except Exception:
53 logger.exception("get_live_match failed", match_id=match_id)
54 return fail("unavailable", "Live match data is unavailable right now.")
55 if not state:
56 # The DAO reports a read failure as None too, so this may also be an outage.
57 return fail("not_found", f"No match with id {match_id}.")
59 home_id, away_id = state.get("home_team_id"), state.get("away_team_id")
60 teams = {home_id: state.get("home_team_name"), away_id: state.get("away_team_name")}
61 period = _period(state)
62 minute, extra = _clock(state, period, now or datetime.now(UTC))
64 # Absent is not zero: a match nobody has kicked off has no score yet, not 0-0.
65 scored = period != "not_started"
67 rows = deps.events.get_key_events(match_id)
68 events = None if rows is None else _events(rows, teams, deps)
69 tracked = bool(state.get("kickoff_time"))
71 return LiveMatchResult(
72 match_id=match_id,
73 status=state.get("match_status"),
74 period=period,
75 minute=minute,
76 extra_time=extra,
77 home_team=TeamRef(id=home_id, name=teams[home_id] or "") if home_id else None,
78 away_team=TeamRef(id=away_id, name=teams[away_id] or "") if away_id else None,
79 home_score=state.get("home_score") if scored else None,
80 away_score=state.get("away_score") if scored else None,
81 home_penalty_score=state.get("home_penalty_score"),
82 away_penalty_score=state.get("away_penalty_score"),
83 age_group=state.get("age_group_name"),
84 competition=state.get("match_type_name"),
85 events=events,
86 error=(
87 ToolError(kind="unavailable", message="Goals and cards are unavailable right now.")
88 if rows is None
89 else None
90 ),
91 meta=ToolMeta(coverage=None if tracked or events else NOT_TRACKED),
92 )
95def _period(state: dict) -> LivePeriod:
96 if state.get("match_end_time") or state.get("match_status") in ("completed", "forfeit"):
97 return "full_time"
98 if state.get("second_half_start"):
99 return "second_half"
100 if state.get("halftime_start"):
101 return "halftime"
102 if state.get("kickoff_time"):
103 return "first_half"
104 return "not_started"
107def _clock(state: dict, period: LivePeriod, now: datetime) -> tuple[int | None, int | None]:
108 """The running minute, as the live view counts it; None unless the clock runs."""
109 half = state.get("half_duration") or 45
110 if period == "halftime":
111 return half, None
112 if period == "first_half":
113 start, base, end = _when(state.get("kickoff_time")), 0, half
114 elif period == "second_half":
115 start, base, end = _when(state.get("second_half_start")), half, half * 2
116 else:
117 return None, None
118 if start is None:
119 return None, None
120 total = base + int((now - start).total_seconds() // 60) + 1
121 return (end, total - end) if total > end else (max(total, base + 1), None)
124def _when(value: Any) -> datetime | None:
125 if isinstance(value, datetime): 125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true
126 parsed = value
127 elif isinstance(value, str) and value: 127 ↛ 133line 127 didn't jump to line 133 because the condition on line 127 was always true
128 try:
129 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
130 except ValueError:
131 return None
132 else:
133 return None
134 return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
137def _events(rows: list[dict], teams: dict, deps: ToolDeps) -> list[LiveEvent]:
138 players: dict[int, dict | None] = {}
140 def lookup(player_id: Any) -> dict | None:
141 if not isinstance(player_id, int):
142 return None
143 if player_id not in players: 143 ↛ 149line 143 didn't jump to line 149 because the condition on line 143 was always true
144 try:
145 players[player_id] = deps.roster.get_player_by_id(player_id) # type: ignore[union-attr]
146 except Exception:
147 logger.warning("roster lookup failed", player_id=player_id)
148 players[player_id] = None
149 return players[player_id]
151 out = []
152 for row in rows:
153 kind = row.get("event_type")
154 if kind not in ("goal", "yellow_card", "red_card"):
155 continue
156 team_id = row.get("team_id")
157 out.append(
158 LiveEvent(
159 type=kind,
160 minute=row.get("match_minute"),
161 extra_time=row.get("extra_time"),
162 team_id=team_id,
163 team=teams.get(team_id),
164 player=player_label(lookup(row.get("player_id")), row.get("player_name")),
165 assist=player_label(lookup(row.get("assist_player_id")), row.get("assist_player_name")),
166 )
167 )
168 return out
171def player_label(player: dict | None, recorded_name: str | None = None) -> str | None:
172 """'#7 Tom D.': jersey number, first name, last initial — never more (SB-1583).
174 From the roster entry when there is one (its own names, else the linked
175 account's); otherwise parsed from the name recorded on the event, whose
176 first word is taken as the first name and last word as the surname.
177 """
178 number: Any = None
179 first = last = None
180 if player:
181 number = player.get("jersey_number")
182 profile = player.get("user_profile") or {}
183 first = player.get("first_name") or profile.get("first_name")
184 last = player.get("last_name") or profile.get("last_name")
185 elif recorded_name:
186 words = recorded_name.split()
187 if words and words[0].startswith("#"):
188 number, words = words[0][1:], words[1:]
189 if words:
190 first, last = words[0], (words[-1] if len(words) > 1 else None)
192 parts = []
193 if number not in (None, ""):
194 parts.append(f"#{number}")
195 if first and first.strip():
196 parts.append(first.strip())
197 if last and last.strip():
198 parts.append(f"{last.strip()[0].upper()}.")
199 return " ".join(parts) or None