Coverage for mt_ai/tools/teams.py: 100.00%
79 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"""search_teams — turn what a person typed into an MT team (and age group).
3Resolution is deliberately conservative, like TeamDAO.resolve_team_by_name:
5- `resolved` only for an exact name or alias match that pins one team in one
6 age group.
7- `ambiguous` when several teams share the name, when a multi-age team was
8 named without an age, or when only near-matches exist. The agent asks
9 rather than guesses.
10- `not_found` when nothing plausible exists — including when the team exists
11 but not at the age asked for (the candidates then list the ages it has).
12"""
14import re
16import structlog
18from dao.team_dao import TeamDAO
19from mt_ai.tools.deps import ToolDeps
20from mt_ai.tools.schemas import ErrorKind, ResolveResult, TeamCandidate, ToolError, ToolMeta, Viewer
21from mt_ai.tools.visibility import DataUnavailableError, TeamIndex, load_team_index
23logger = structlog.get_logger()
25_AGE_TOKEN = re.compile(r"\bu-?(\d{1,2})\b", re.IGNORECASE)
26# ilike treats these as wildcards; a user-typed name containing one must not
27# reach the database as a pattern.
28_LIKE_METACHARS = frozenset("%_\\")
29_STOPWORDS = TeamDAO._SIMILAR_STOPWORDS
30MAX_CANDIDATES = 8
33def _normalize(text: str) -> str:
34 return " ".join(text.casefold().split())
37def split_age_group(query: str) -> tuple[str, str | None]:
38 """'Boston United U15' -> ('Boston United', 'U15')."""
39 match = _AGE_TOKEN.search(query)
40 if not match:
41 return " ".join(query.split()), None
42 name = _AGE_TOKEN.sub(" ", query, count=1)
43 return " ".join(name.split()), f"U{int(match.group(1))}"
46def search_teams(
47 deps: ToolDeps,
48 query: str,
49 viewer: Viewer,
50 age_group: str | None = None,
51 limit: int = MAX_CANDIDATES,
52) -> ResolveResult:
53 name, age_in_query = split_age_group(query or "")
54 age = age_group or age_in_query
55 if not name:
56 return _error("invalid_args", "A team name is required.")
57 if not 1 <= limit <= MAX_CANDIDATES:
58 return _error("invalid_args", f"limit must be between 1 and {MAX_CANDIDATES}.")
60 try:
61 index = load_team_index(deps, viewer)
62 exact = _exact_or_alias(deps, index, name)
63 if exact:
64 return _from_teams(index, exact, age, limit)
65 return _near_matches(index, name, age, limit)
66 except DataUnavailableError as exc:
67 return _error("unavailable", f"Team data is unavailable right now ({exc}).")
68 except Exception:
69 logger.exception("search_teams failed", query=query)
70 return _error("unavailable", "Team data is unavailable right now.")
73def _exact_or_alias(deps: ToolDeps, index: TeamIndex, name: str) -> list[dict]:
74 wanted = _normalize(name)
75 exact = [t for t in index.teams.values() if _normalize(t.get("name", "")) == wanted]
76 if exact:
77 return sorted(exact, key=lambda t: t["id"])
78 if _LIKE_METACHARS & set(name):
79 return []
80 aliased = deps.teams.resolve_team_by_name(name)
81 # A hit on a team this viewer can't see is reported as no hit at all.
82 if aliased and aliased.get("id") in index.teams:
83 return [index.teams[aliased["id"]]]
84 return []
87def _from_teams(index: TeamIndex, teams: list[dict], age: str | None, limit: int) -> ResolveResult:
88 candidates = [c for team in teams for c in index.candidates(team, age)]
89 if not candidates:
90 # The team exists, just not at that age: say which ages it has.
91 every_age = [c for team in teams for c in index.candidates(team)]
92 return ResolveResult(
93 status="not_found",
94 candidates=every_age[:limit],
95 other_ages=_age_names(every_age),
96 meta=_meta(every_age, limit),
97 )
98 if len(candidates) == 1:
99 return ResolveResult(status="resolved", team=candidates[0])
100 return ResolveResult(status="ambiguous", candidates=candidates[:limit], meta=_meta(candidates, limit))
103def _near_matches(index: TeamIndex, name: str, age: str | None, limit: int) -> ResolveResult:
104 words = [w for w in _normalize(name).split() if len(w) >= 4 and w not in _STOPWORDS]
105 scored: list[tuple[int, str, dict]] = []
106 for team in index.teams.values():
107 team_name = _normalize(team.get("name", ""))
108 score = sum(1 for w in words if w in team_name)
109 if score:
110 scored.append((score, team_name, team))
111 scored.sort(key=lambda s: (-s[0], s[1]))
113 candidates = [c for _, _, team in scored for c in index.candidates(team, age)]
114 if not candidates:
115 return ResolveResult(status="not_found")
116 # Near-matches are never resolved, even when there is only one.
117 return ResolveResult(status="ambiguous", candidates=candidates[:limit], meta=_meta(candidates, limit))
120def _age_names(candidates: list[TeamCandidate]) -> list[str]:
121 """Distinct age-group names, in candidate order; age-less candidates add none."""
122 names: list[str] = []
123 for c in candidates:
124 if c.age_group and c.age_group.name not in names:
125 names.append(c.age_group.name)
126 return names
129def _meta(candidates: list[TeamCandidate], limit: int) -> ToolMeta:
130 return ToolMeta(truncated=len(candidates) > limit)
133def _error(kind: ErrorKind, message: str) -> ResolveResult:
134 return ResolveResult(status="not_found", error=ToolError(kind=kind, message=message))