Coverage for mt_tools/team_dossier.py: 96.39%
408 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:53 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:53 +0000
1"""Team dossier: where one team stands in its own conferences, at one age group (SB-1780).
3A scouting summary for the Match of the Day agent and a Fest match preview. Two
4teams from different conferences have never played a common table, so the
5dossier describes each team *inside its own tables* and never compares across
6them: every position, percentile and "top third" is measured in one conference,
7and every fact names only that conference.
9Two layers, so the facts are testable without a database:
11- **Gathering** (`get_team_dossier`) resolves the season, the team and its age
12 group (from a match when `for_match_id` is given), and reads the team's tables
13 and matches through the DAO protocols MT AI uses (`ToolDeps`).
14- **Facts** (`detect_playing_up`, `conference_line`, `key_wins`, `form_lines`,
15 `dossier_facts`) are pure functions over plain dicts.
17## Conferences
19One line per `team_mappings` row at the age group: a Homegrown conference, a Flex
20conference and a Pro Player Pathway division stay separate. Position, record and
21goals come from `MatchDAO.get_standings` (the table /api/table shows), never a
22re-tally. Strength percentile is `team_strengths` (points and goal difference per
23game, damped under 3 games). A registered team with no counted results keeps its
24line with null position and stats and `no_results`: absent is never 0.
26## Key wins
28League and Flex wins (never a Friendly, a tournament or a showcase) over a team
29in the top third of its *own* table (position <= ceil(N/3), N >= 3). The
30opponent's table is, in order: the division the match counted in, if the
31opponent is registered there; else its registration in the match's competition
32(League or Flex); else its first registration, League before Pro Player Pathway
33before Flex. Opponent tables are loaded lazily, and at most `MAX_OPPONENT_TABLES`
34distinct ones beyond the team's own.
36A win over a pro academy is not a key win by itself (SB-1887): academies often
37field a younger squad in Flex, so the scoreline overstates it. It is one when the
38academy is top third of its own table, like any other opponent.
40Forfeits are never key wins. Strongest opponent first (its strength in its own
41table), then newest. Registrations outside Homegrown, Academy and Flex are no table.
43## Playing up
45Given a match, the bracket age is the match's. A recorded side age
46(`home_age_group_id` / `away_age_group_id`) is the team's age; younger than the
47bracket is playing up, older is `playing_down` (no playing-up claim). Scraped
48tournament matches never record side ages, so a team with no registration at the
49bracket age and exactly one at a lower age is inferred to be playing up from it
50(`playing_up_inferred`). A pro academy has no registration at its own age:
51its sides play their league a year up. In a U15 bracket every academy reads its
52U16 tables, registered at U15 (Flex only: the younger squad) or not (SB-1901);
53at other brackets, with none at the bracket, its nearest registration above is
54the side's age (`league_age_up`, not `playing_down`: SB-1900). An `age_group_id` given with the match only picks the
55tables: it must agree with a recorded side age (else invalid_args), and playing
56up derived from it is inferred. The match must be in the current season. The
57dossier describes the team at its season age: that is where its tables are.
59Fact ids are `t<team>:a<age>:<kind>:<division_id>:<slug>`, `t<team>:a<age>:win:<match_id>`
60and `t<team>:a<age>:form:<slug>`: the same whether or not a match was given.
61"""
63from collections.abc import Callable, Iterable
64from dataclasses import dataclass, field
65from datetime import UTC, date, datetime, timedelta
66from math import ceil
67from typing import Literal
69import structlog
70from pydantic import BaseModel
72from dao.side_age_groups import effective_side_age_groups
73from mt_ai.tools.deps import ToolDeps
74from mt_ai.tools.matches import SCRAPER_SOURCE
75from mt_ai.tools.schemas import AgeGroupRef, DivisionRef, Provenance, SeasonRef, TeamRef, ToolError, Viewer
76from mt_ai.tools.visibility import DataUnavailableError, TeamIndex, load_team_index
77from mt_tools.motw_candidates import (
78 FORM_GAMES,
79 LOW_SAMPLE_GAMES,
80 PLAYED_STATUSES,
81 POOL_TIMEZONE,
82 MotwFact,
83 TeamStanding,
84 result_for,
85 standings_from_rows,
86 streak_text,
87 team_results,
88 team_strengths,
89)
90from mt_tools.qualification_rules import conference_kind
92logger = structlog.get_logger()
94MAX_OPPONENT_TABLES = 10
95UNAVAILABLE = "The team dossier is unavailable right now."
96NOT_COMPARED = (
97 "Positions, percentiles and key wins are measured inside each team's own conference table. "
98 "Conferences only meet at tournaments, so they are never compared."
99)
101Kind = Literal["league", "flex", "pathway"]
102KeyWinKind = Literal["top_third"]
103# The competitions a key win can come from (SB-1887): a Friendly proves nothing.
104KEY_WIN_COMPETITIONS = frozenset({"League", "Flex"})
107# --- result models -----------------------------------------------------------
110class DossierTeam(TeamRef):
111 club_id: int | None = None
112 logo_url: str | None = None
113 pro_academy: bool = False
116class DossierContext(BaseModel):
117 """The match the dossier was asked for, and the age the team plays it at."""
119 match_id: int
120 bracket_age_group: AgeGroupRef
121 season_age_group: AgeGroupRef
122 playing_up: bool = False # the side is younger than the bracket
123 playing_up_inferred: bool = False # ...and the match did not record its age
124 playing_down: bool = False # the side is older: no playing-up claim
125 # A pro academy's side at this bracket plays its league a year up (SB-1900):
126 # the tables are at season_age_group, and the squad is not an older one.
127 league_age_up: bool = False
130class ConferenceLine(BaseModel):
131 """The team in one of its tables. Null stats: no counted result there yet."""
133 kind: Kind
134 competition: str # League or Flex: the table's match type
135 division: DivisionRef
136 league: str | None = None
137 position: int | None = None
138 table_size: int | None = None
139 played: int = 0
140 wins: int | None = None
141 draws: int | None = None
142 losses: int | None = None
143 gf: int | None = None
144 ga: int | None = None
145 gd: int | None = None
146 ppg: float | None = None
147 gf_per_game: float | None = None
148 ga_per_game: float | None = None
149 clean_sheets: int | None = None
150 strength_percentile: int | None = None # 0-100, inside this table only
151 low_sample: bool = False
152 no_results: bool = False
153 fact_ids: list[str] = []
156class DossierTotals(BaseModel):
157 """Counts over the team's played League/Flex matches at the age. Counts only:
158 a rate across two conferences would compare them."""
160 played: int
161 wins: int
162 draws: int
163 losses: int
164 goals_for: int
165 goals_against: int
166 clean_sheets: int
169class KeyWin(BaseModel):
170 match_id: int
171 date: date
172 competition: str | None = None
173 opponent: TeamRef
174 opponent_conference: str | None = None # the table the opponent's position is in
175 opponent_position: int | None = None
176 opponent_table_size: int | None = None
177 opponent_pro_academy: bool = False
178 top_third: bool = False
179 score: str # the team's goals first
180 kind: KeyWinKind
181 fact_id: str
184class FormEntry(BaseModel):
185 match_id: int
186 date: date
187 opponent: TeamRef
188 score: str # the team's goals first
189 result: Literal["W", "D", "L"]
190 competition: str | None = None
191 forfeit: bool = False
194class DossierCoverage(BaseModel):
195 results_counted: int # played League/Flex matches of the team at the age
196 tables_loaded: int
197 opponent_tables_skipped: int = 0 # distinct tables over MAX_OPPONENT_TABLES: wins there not judged on table
198 source: Provenance | None = None
199 note: str = NOT_COMPARED
202class TeamDossierResult(BaseModel):
203 """One team at one age group this season.
205 `conferences` [] means no registration at the age (flag `no_conference`);
206 `totals` null means no counted League/Flex result (flag `no_results`). Lists
207 are null only with `error`, when MT could not check.
208 """
210 team: DossierTeam | None = None
211 age_group: AgeGroupRef | None = None
212 season: SeasonRef | None = None
213 context: DossierContext | None = None
214 conferences: list[ConferenceLine] | None = None
215 totals: DossierTotals | None = None
216 key_wins: list[KeyWin] | None = None
217 form: list[FormEntry] | None = None
218 streak_fact_id: str | None = None
219 flags: list[str] = []
220 facts: list[MotwFact] = []
221 coverage: DossierCoverage | None = None
222 error: ToolError | None = None
225# --- pure facts ----------------------------------------------------------------
228@dataclass(frozen=True)
229class Conference:
230 """One team_mappings row at an age group: a table the team plays in."""
232 kind: Kind
233 competition: str
234 division_id: int
235 division: str
236 league: str | None
238 def label(self, age_name: str) -> str:
239 return " ".join(p for p in (age_name, self.league, self.division) if p)
242def conference_of(division: dict, index: TeamIndex) -> Conference | None:
243 if division.get("id") is None: 243 ↛ 244line 243 didn't jump to line 244 because the condition on line 243 was never true
244 return None
245 league = (index.leagues.get(division.get("league_id") or 0) or division.get("leagues") or {}).get("name")
246 rules_kind = conference_kind(league, division.get("name"))
247 if rules_kind is None:
248 # Not a Homegrown, Academy or Flex table: nothing the dossier can place a team in.
249 return None
250 kind: Kind = "flex" if rules_kind == "flex" else "pathway" if rules_kind == "ppp" else "league"
251 return Conference(
252 kind=kind,
253 competition="Flex" if kind == "flex" else "League",
254 division_id=division["id"],
255 division=str(division.get("name") or ""),
256 league=league,
257 )
260def visible_mappings(team: dict, index: TeamIndex) -> list[dict]:
261 """The team's registrations this viewer may see (test leagues hidden)."""
262 return [
263 m
264 for m in team.get("team_mappings") or []
265 if (m.get("age_groups") or {}).get("id") is not None
266 and (index.include_test or (m.get("divisions") or {}).get("league_id") not in index.test_league_ids)
267 ]
270def conferences_at(team: dict, age_group_id: int, index: TeamIndex) -> list[Conference]:
271 out: list[Conference] = []
272 for m in visible_mappings(team, index):
273 if m["age_groups"]["id"] != age_group_id:
274 continue
275 conf = conference_of(m.get("divisions") or {}, index)
276 if conf and all(c.division_id != conf.division_id for c in out):
277 out.append(conf)
278 kinds = {"league": 0, "pathway": 1, "flex": 2}
279 return sorted(out, key=lambda c: (kinds[c.kind], c.division))
282def age_number(name: str | None) -> int | None:
283 digits = "".join(ch for ch in str(name or "") if ch.isdigit())
284 return int(digits) if digits else None
287# Bracket age → the age a pro academy's side of that age plays its league at.
288# Pro academies do not play the U15 league: their U15 side plays the U16 Pro
289# Player Pathway (and U16 Flex). A U15 registration is their U14 squad playing
290# up in Flex. Applied to every academy, registered at U15 or not (SB-1901).
291PRO_ACADEMY_LEAGUE_AGE: dict[int, int] = {15: 16}
294def detect_playing_up(
295 match: dict, team_id: int, mappings: Iterable[dict], *, pro_academy: bool = False
296) -> tuple[int, int, bool]:
297 """(the team's season age, the match's bracket age, whether the match recorded the side's age).
299 `mappings` are the team's visible registrations. A recorded side age is
300 returned as is, younger or older: `age_direction` says which. Unrecorded, the
301 season age is inferred: no registration at the bracket and exactly one below.
302 A pro academy in a U15 bracket is at U16 whenever it is registered there,
303 even with a U15 registration (`PRO_ACADEMY_LEAGUE_AGE`, SB-1901). At other
304 brackets an academy with no registration at the bracket plays its league a
305 year up (SB-1900): its nearest registration above the bracket is the side's age.
306 """
307 bracket = match["age_group_id"]
308 home_age, away_age = effective_side_age_groups(match)
309 side = home_age if match.get("home_team_id") == team_id else away_age
310 if side is not None and side != bracket:
311 return side, bracket, True
312 ages = {(m.get("age_groups") or {}).get("id"): (m.get("age_groups") or {}).get("name") for m in mappings}
313 bracket_n = age_number(match.get("age_group_name"))
314 league_n = PRO_ACADEMY_LEAGUE_AGE.get(bracket_n or 0)
315 if pro_academy and league_n:
316 # Every academy alike: a U15 registration holds only the younger
317 # squad's Flex games, never the U15 side's league (SB-1901).
318 league = next((a for a, name in ages.items() if a is not None and age_number(name) == league_n), None)
319 if league is not None:
320 return league, bracket, False
321 if bracket in ages:
322 return bracket, bracket, False
323 if pro_academy and bracket_n: 323 ↛ 324line 323 didn't jump to line 324 because the condition on line 323 was never true
324 above = sorted(
325 (n, a) for a, name in ages.items() if a is not None and (n := age_number(name)) and n > bracket_n
326 )
327 if above:
328 return above[0][1], bracket, False
329 lower = {a for a, name in ages.items() if a is not None and bracket_n and (n := age_number(name)) and n < bracket_n}
330 if len(lower) == 1:
331 return lower.pop(), bracket, False
332 return bracket, bracket, False
335def age_direction(season_name: str | None, bracket_name: str | None) -> Literal["up", "down", "same"]:
336 """Whether a side at `season_name` plays up (younger than the bracket) or down."""
337 season_n, bracket_n = age_number(season_name), age_number(bracket_name)
338 if season_n is None or bracket_n is None or season_n == bracket_n:
339 return "same"
340 return "up" if season_n < bracket_n else "down"
343def _score(match: dict, team_id: int) -> str:
344 hs, as_ = match.get("home_score"), match.get("away_score")
345 return f"{hs}-{as_}" if match.get("home_team_id") == team_id else f"{as_}-{hs}"
348def _scored(match: dict, team_id: int) -> int:
349 return match["home_score"] if match.get("home_team_id") == team_id else match["away_score"]
352def _conceded(match: dict, team_id: int) -> int:
353 return match["away_score"] if match.get("home_team_id") == team_id else match["home_score"]
356def _opponent(match: dict, team_id: int) -> tuple[int, str]:
357 if match.get("home_team_id") == team_id:
358 return match["away_team_id"], match.get("away_team_name") or str(match["away_team_id"])
359 return match["home_team_id"], match.get("home_team_name") or str(match["home_team_id"])
362def conference_line(
363 team_id: int, conf: Conference, table: dict[int, TeamStanding], league_results: list[dict]
364) -> ConferenceLine:
365 """The team's line in one table. `league_results` are its played League/Flex matches."""
366 base = {
367 "kind": conf.kind,
368 "competition": conf.competition,
369 "division": DivisionRef(id=conf.division_id, name=conf.division, league=conf.league),
370 "league": conf.league,
371 "table_size": len(table) or None,
372 }
373 s = table.get(team_id)
374 if s is None or s.played == 0:
375 return ConferenceLine(**base, low_sample=True, no_results=True)
376 strength, low = team_strengths(table)[team_id]
377 here = [
378 m
379 for m in league_results
380 if m.get("division_id") == conf.division_id and m.get("match_type_name") == conf.competition
381 ]
382 return ConferenceLine(
383 **base,
384 position=s.position,
385 played=s.played,
386 wins=s.wins,
387 draws=s.draws,
388 losses=s.losses,
389 gf=s.goals_for,
390 ga=s.goals_against,
391 gd=s.goals_for - s.goals_against,
392 ppg=round(s.points / s.played, 2),
393 gf_per_game=round(s.goals_for / s.played, 2),
394 ga_per_game=round(s.goals_against / s.played, 2),
395 clean_sheets=sum(1 for m in here if _conceded(m, team_id) == 0),
396 strength_percentile=round(strength * 100),
397 low_sample=low,
398 )
401@dataclass(frozen=True)
402class OpponentTable:
403 conference: str # its label, e.g. "U15 Flex Turnpike"
404 standing: TeamStanding | None
405 size: int
406 strength: float | None
409def is_top_third(t: OpponentTable | None) -> bool:
410 if t is None or t.standing is None or t.standing.played == 0 or t.size < 3:
411 return False
412 return t.standing.position <= ceil(t.size / 3)
415def key_wins(
416 team_id: int,
417 prefix: str,
418 played: Iterable[dict],
419 *,
420 is_pro: Callable[[int], bool],
421 opponent_table: Callable[[dict, int], OpponentTable | None],
422 refs: Callable[[int, str], TeamRef],
423) -> list[KeyWin]:
424 """League/Flex wins over a team top third of its own table, strongest first."""
425 out: list[tuple[float, KeyWin]] = []
426 for m in played:
427 # A forfeit is a result, not a win anyone earned on the pitch.
428 if m.get("match_status") == "forfeit" or result_for(m, team_id) != "W":
429 continue
430 if m.get("match_type_name") not in KEY_WIN_COMPETITIONS:
431 continue
432 opp_id, opp_name = _opponent(m, team_id)
433 table = opponent_table(m, opp_id)
434 if not is_top_third(table):
435 continue
436 assert table is not None and table.standing is not None # is_top_third guarantees both
437 win = KeyWin(
438 match_id=m["id"],
439 date=_date(m["match_date"]),
440 competition=m.get("match_type_name"),
441 opponent=refs(opp_id, opp_name),
442 opponent_conference=table.conference,
443 opponent_position=table.standing.position,
444 opponent_table_size=table.size,
445 opponent_pro_academy=is_pro(opp_id),
446 top_third=True,
447 score=_score(m, team_id),
448 kind="top_third",
449 fact_id=f"{prefix}:win:{m['id']}",
450 )
451 strength = table.strength if table.strength is not None else -1.0
452 out.append((strength, win))
453 out.sort(key=lambda sw: (-sw[0], -sw[1].date.toordinal(), sw[1].match_id))
454 return [w for _, w in out]
457def form_lines(results: list[tuple[dict, str]], team_id: int, refs: Callable[[int, str], TeamRef]) -> list[FormEntry]:
458 """The last FORM_GAMES results, newest first (`results` as team_results returns them)."""
459 out = []
460 for m, r in results[:FORM_GAMES]:
461 opp_id, opp_name = _opponent(m, team_id)
462 out.append(
463 FormEntry(
464 match_id=m["id"],
465 date=_date(m["match_date"]),
466 opponent=refs(opp_id, opp_name),
467 score=_score(m, team_id),
468 result=r,
469 competition=m.get("match_type_name"),
470 forfeit=m.get("match_status") == "forfeit",
471 )
472 )
473 return out
476def _ordinal(n: int) -> str:
477 suffix = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
478 return f"{n}{suffix}"
481def _plural(n: int, word: str) -> str:
482 if n == 1:
483 return f"{n} {word}"
484 return f"{n} {word}es" if word.endswith(("s", "x", "ch", "sh")) else f"{n} {word}s"
487def dossier_facts(
488 team_id: int,
489 prefix: str,
490 name: str,
491 age_name: str,
492 lines: list[tuple[Conference, ConferenceLine]],
493 wins: list[KeyWin],
494 form: list[FormEntry],
495 results: list[str],
496 context: DossierContext | None,
497) -> tuple[list[MotwFact], str | None]:
498 """Every fact the dossier supports, and the streak fact's id. Sets each line's fact_ids.
500 Each fact names at most one conference: its own.
501 """
502 facts: list[MotwFact] = []
503 for conf, line in lines:
504 label = conf.label(age_name)
505 cid = f"{prefix}:{conf.kind}:{conf.division_id}"
506 own: list[MotwFact] = []
507 if line.no_results:
508 own.append(
509 MotwFact(
510 team_id=team_id,
511 id=f"{cid}:no_results",
512 kind="standings",
513 text=f"{name} are registered in {label} but have no counted results there yet.",
514 )
515 )
516 else:
517 small = " (fewer than 3 matches: a small sample)" if line.low_sample else ""
518 own.append(
519 MotwFact(
520 team_id=team_id,
521 id=f"{cid}:pos",
522 kind="standings",
523 text=(
524 f"{name} are {_ordinal(line.position)} of {line.table_size} in {label} with "
525 f"{line.ppg:.2f} points per match from {_plural(line.played, 'match')} "
526 f"({line.wins}-{line.draws}-{line.losses}){small}."
527 ),
528 )
529 )
530 own.append(
531 MotwFact(
532 team_id=team_id,
533 id=f"{cid}:rate",
534 kind="form",
535 text=(
536 f"{name} score {line.gf_per_game:.1f} and concede {line.ga_per_game:.1f} goals per match "
537 f"in {label} (goal difference {line.gd:+d})."
538 ),
539 )
540 )
541 own.append(
542 MotwFact(
543 team_id=team_id,
544 id=f"{cid}:strength",
545 kind="standings",
546 text=(
547 f"{name} are in the {_ordinal(line.strength_percentile)} percentile within {label} "
548 f"on points and goal difference per match{small}."
549 ),
550 )
551 )
552 own.append(
553 MotwFact(
554 team_id=team_id,
555 id=f"{cid}:clean_sheets",
556 kind="form",
557 text=f"{name} kept {_plural(line.clean_sheets, 'clean sheet')} in {label}.",
558 )
559 )
560 line.fact_ids = [f.id for f in own]
561 facts.extend(own)
563 for w in wins:
564 when = f"{w.date:%b %-d}" + (f" ({w.competition})" if w.competition else "")
565 text = f"{name} beat {w.opponent.name} {w.score} on {when}."
566 if w.opponent_position is not None: 566 ↛ 569line 566 didn't jump to line 569 because the condition on line 566 was always true
567 standing = f"{_ordinal(w.opponent_position)} of {w.opponent_table_size}"
568 text += f" {w.opponent.name} are {standing} in {w.opponent_conference}."
569 facts.append(MotwFact(team_id=team_id, id=w.fact_id, kind="storyline", text=text))
571 if form:
572 recent = ", ".join(
573 f"{f.result} {f.score} v {f.opponent.name}" + (" (forfeit)" if f.forfeit else "") for f in form
574 )
575 facts.append(
576 MotwFact(
577 team_id=team_id,
578 id=f"{prefix}:form:last{len(form)}",
579 kind="form",
580 text=f"{name}'s last {_plural(len(form), 'League/Flex result')}, newest first: {recent}.",
581 )
582 )
583 streak_id = None
584 streak = streak_text(name, results)
585 if streak:
586 streak_id = f"{prefix}:form:streak"
587 facts.append(MotwFact(team_id=team_id, id=streak_id, kind="form", text=streak))
589 if context and context.playing_up:
590 how = (
591 f"{name} are taken to be their {context.season_age_group.name} side in this "
592 f"{context.bracket_age_group.name} match, so playing up (inferred: the match does not record it)."
593 if context.playing_up_inferred
594 else f"{name} fielded their {context.season_age_group.name} side in this "
595 f"{context.bracket_age_group.name} match: playing up."
596 )
597 facts.append(
598 MotwFact(team_id=team_id, id=f"{prefix}:context:m{context.match_id}:playing_up", kind="storyline", text=how)
599 )
600 if context and context.league_age_up:
601 facts.append(
602 MotwFact(
603 team_id=team_id,
604 id=f"{prefix}:context:m{context.match_id}:league_age_up",
605 kind="storyline",
606 text=(
607 f"{name} are a pro academy: their {context.bracket_age_group.name} side plays its league "
608 f"at {context.season_age_group.name}, so these are their {context.season_age_group.name} tables."
609 ),
610 )
611 )
612 return facts, streak_id
615def totals_of(results: list[tuple[dict, str]], team_id: int) -> DossierTotals | None:
616 if not results:
617 return None
618 rs = [r for _, r in results]
619 return DossierTotals(
620 played=len(rs),
621 wins=rs.count("W"),
622 draws=rs.count("D"),
623 losses=rs.count("L"),
624 goals_for=sum(_scored(m, team_id) for m, _ in results),
625 goals_against=sum(_conceded(m, team_id) for m, _ in results),
626 clean_sheets=sum(1 for m, _ in results if _conceded(m, team_id) == 0),
627 )
630def provenance(rows: list[dict]) -> Provenance | None:
631 scraped = {(r.get("source") or "") == SCRAPER_SOURCE for r in rows}
632 if not scraped:
633 return None
634 if len(scraped) > 1: 634 ↛ 635line 634 didn't jump to line 635 because the condition on line 634 was never true
635 return "mixed"
636 return "scraper" if scraped.pop() else "user"
639# --- gathering -----------------------------------------------------------------
642class _InvalidArgsError(Exception):
643 pass
646def _date(value) -> date:
647 return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
650def _ages(index: TeamIndex) -> dict[int, AgeGroupRef]:
651 """Every age group MT has a visible registration at."""
652 out: dict[int, AgeGroupRef] = {}
653 for team in index.teams.values():
654 for m in visible_mappings(team, index):
655 age = m["age_groups"]
656 out.setdefault(age["id"], AgeGroupRef(id=age["id"], name=str(age.get("name") or age["id"])))
657 return out
660@dataclass
661class _Tables:
662 """Standings tables read so far, by (age, division, competition)."""
664 deps: ToolDeps
665 season_id: int
666 include_test: bool
667 loaded: dict[tuple[int, int, str], dict[int, TeamStanding]] = field(default_factory=dict)
668 extra: int = 0
669 skipped: set[tuple[int, int, str]] = field(default_factory=set)
671 def get(self, age_id: int, conf: Conference, *, opponent: bool = False) -> dict[int, TeamStanding] | None:
672 key = (age_id, conf.division_id, conf.competition)
673 if key not in self.loaded:
674 if opponent:
675 if self.extra >= MAX_OPPONENT_TABLES:
676 self.skipped.add(key)
677 return None
678 self.extra += 1
679 data = self.deps.matches.get_standings(
680 season_id=self.season_id,
681 age_group_id=age_id,
682 division_id=conf.division_id,
683 match_type=conf.competition,
684 include_test=self.include_test,
685 raise_on_error=True,
686 )
687 self.loaded[key] = standings_from_rows((data or {}).get("standings") or [])
688 return self.loaded[key]
691def get_team_dossier(
692 deps: ToolDeps,
693 team_id: int,
694 age_group_id: int | None = None,
695 *,
696 for_match_id: int | None = None,
697 viewer: Viewer,
698 now: datetime | None = None,
699) -> TeamDossierResult:
700 """The dossier for `team_id` at `age_group_id` (or at its age in `for_match_id`), this season."""
702 def fail(kind: Literal["unavailable", "invalid_args"], message: str) -> TeamDossierResult:
703 return TeamDossierResult(error=ToolError(kind=kind, message=message))
705 if age_group_id is None and for_match_id is None:
706 return fail("invalid_args", "Give age_group_id, or for_match_id to use the team's age in that match.")
707 current = now or datetime.now(UTC)
708 if current.tzinfo is None: 708 ↛ 709line 708 didn't jump to line 709 because the condition on line 708 was never true
709 current = current.replace(tzinfo=UTC)
710 today = current.astimezone(POOL_TIMEZONE).date()
712 try:
713 season_row = deps.seasons.get_current_season()
714 if not season_row: 714 ↛ 715line 714 didn't jump to line 715 because the condition on line 714 was never true
715 raise DataUnavailableError("no current season")
716 season = SeasonRef(id=season_row["id"], name=season_row["name"])
717 index = load_team_index(deps, viewer)
718 team = index.teams.get(team_id)
719 if team is None:
720 raise _InvalidArgsError(f"No team with id {team_id}.")
721 mappings = visible_mappings(team, index)
722 ages = _ages(index)
723 if age_group_id is not None and age_group_id not in ages:
724 raise _InvalidArgsError(f"No age group with id {age_group_id}.")
726 context: DossierContext | None = None
727 if for_match_id is not None:
728 match = deps.matches.get_match_by_id(for_match_id, include_test=viewer.include_test, raise_on_error=True)
729 if not match:
730 raise _InvalidArgsError(f"No match with id {for_match_id}.")
731 if match.get("season_id") != season.id:
732 raise _InvalidArgsError(f"Match {for_match_id} is not in the current season.")
733 if team_id not in (match.get("home_team_id"), match.get("away_team_id")):
734 raise _InvalidArgsError(f"Team {team_id} does not play in match {for_match_id}.")
735 team_is_pro = bool((index.clubs.get(team.get("club_id") or 0) or {}).get("pro_academy"))
736 season_age, bracket, recorded = detect_playing_up(match, team_id, mappings, pro_academy=team_is_pro)
737 if age_group_id is not None:
738 # The given age only picks the tables; it may not contradict the match.
739 if recorded and age_group_id != season_age:
740 raise _InvalidArgsError(
741 f"Match {for_match_id} records team {team_id} at another age group than {age_group_id}."
742 )
743 season_age = age_group_id
744 bracket_ref = ages.get(bracket) or AgeGroupRef(id=bracket, name=str(match.get("age_group_name") or bracket))
745 season_ref = ages.get(season_age) or AgeGroupRef(id=season_age, name=str(season_age))
746 direction = age_direction(season_ref.name, bracket_ref.name)
747 # Older tables for a pro academy: its league age, not an older
748 # squad (SB-1900, SB-1901).
749 league_up = team_is_pro and direction == "down" and not recorded and age_group_id is None
750 context = DossierContext(
751 match_id=for_match_id,
752 bracket_age_group=bracket_ref,
753 season_age_group=season_ref,
754 playing_up=direction == "up",
755 # Inferred whenever the match did not record the side's age.
756 playing_up_inferred=direction == "up" and not recorded,
757 playing_down=direction == "down" and not league_up,
758 league_age_up=league_up,
759 )
760 age = season_ref
761 else:
762 age = ages[age_group_id]
764 own = deps.matches.get_all_matches(
765 season_id=season.id,
766 age_group_id=age.id,
767 team_id=team_id,
768 include_test=viewer.include_test,
769 raise_on_error=True,
770 )
771 tables = _Tables(deps, season.id, viewer.include_test)
772 confs = conferences_at(team, age.id, index)
773 own_tables = [(c, tables.get(age.id, c)) for c in confs]
775 def opponent_table(m: dict, opp_id: int) -> OpponentTable | None:
776 opp = index.teams.get(opp_id)
777 if opp is None: 777 ↛ 778line 777 didn't jump to line 778 because the condition on line 777 was never true
778 return None
779 home_age, away_age = effective_side_age_groups(m)
780 opp_age = home_age if m.get("home_team_id") == opp_id else away_age
781 options = conferences_at(opp, opp_age, index)
782 if not options:
783 return None
784 conf = (
785 next((c for c in options if c.division_id == m.get("division_id")), None)
786 or next((c for c in options if c.competition == m.get("match_type_name")), None)
787 or options[0]
788 )
789 table = tables.get(opp_age, conf, opponent=True)
790 if table is None:
791 return None
792 standing = table.get(opp_id)
793 strength = team_strengths(table).get(opp_id, (None, True))[0] if standing else None
794 label = conf.label((ages.get(opp_age) or AgeGroupRef(id=opp_age, name="")).name)
795 return OpponentTable(conference=label, standing=standing, size=len(table), strength=strength)
797 def is_pro(tid: int) -> bool:
798 t = index.teams.get(tid) or {}
799 return bool((index.clubs.get(t.get("club_id") or 0) or {}).get("pro_academy"))
801 def refs(tid: int, name: str) -> TeamRef:
802 t = index.teams.get(tid)
803 return TeamRef(id=tid, name=name, club_name=index.club_name(t) if t else None)
805 results = team_results(own, team_id, today + timedelta(days=1))
806 league_results = [m for m, _ in results]
807 played = sorted(
808 (m for m in own if m.get("match_status") in PLAYED_STATUSES and result_for(m, team_id)),
809 key=lambda m: (_date(m["match_date"]), m["id"]),
810 reverse=True,
811 )
812 prefix = f"t{team_id}:a{age.id}"
813 wins = key_wins(
814 team_id,
815 prefix,
816 played,
817 is_pro=is_pro,
818 opponent_table=opponent_table,
819 refs=refs,
820 )
821 except _InvalidArgsError as exc:
822 return fail("invalid_args", str(exc))
823 except DataUnavailableError as exc:
824 logger.warning("team_dossier_unavailable", error=str(exc))
825 return fail("unavailable", UNAVAILABLE)
826 except Exception:
827 logger.exception("get_team_dossier failed", team_id=team_id)
828 return fail("unavailable", UNAVAILABLE)
830 lines = [(c, conference_line(team_id, c, table, league_results)) for c, table in own_tables]
831 form = form_lines(results, team_id, refs)
832 facts, streak_id = dossier_facts(
833 team_id, prefix, team["name"], age.name, lines, wins, form, [r for _, r in results], context
834 )
835 totals = totals_of(results, team_id)
837 flags: list[str] = []
838 if totals is None:
839 flags.append("no_results")
840 elif totals.played < LOW_SAMPLE_GAMES:
841 flags.append("low_sample")
842 if not confs:
843 flags.append("no_conference")
844 if context and context.playing_up:
845 flags.append("playing_up")
846 if context.playing_up_inferred:
847 flags.append("playing_up_inferred")
848 if context and context.playing_down:
849 flags.append("playing_down")
850 if context and context.league_age_up:
851 flags.append("league_age_up")
853 club = index.clubs.get(team.get("club_id") or 0) or {}
854 logger.info(
855 "team_dossier_built",
856 team_id=team_id,
857 age_group=age.name,
858 for_match_id=for_match_id,
859 conferences=len(lines),
860 results=len(results),
861 key_wins=len(wins),
862 tables_loaded=len(tables.loaded),
863 opponent_tables_skipped=len(tables.skipped),
864 flags=flags,
865 )
866 return TeamDossierResult(
867 team=DossierTeam(
868 id=team_id,
869 name=team["name"],
870 club_name=club.get("name"),
871 club_id=team.get("club_id"),
872 logo_url=club.get("logo_url"),
873 pro_academy=bool(club.get("pro_academy")),
874 ),
875 age_group=age,
876 season=season,
877 context=context,
878 conferences=[line for _, line in lines],
879 totals=totals,
880 key_wins=wins,
881 form=form,
882 streak_fact_id=streak_id,
883 flags=flags,
884 facts=facts,
885 coverage=DossierCoverage(
886 results_counted=len(results),
887 tables_loaded=len(tables.loaded),
888 opponent_tables_skipped=len(tables.skipped),
889 source=provenance(league_results),
890 ),
891 )