Coverage for mt_cli.py: 67.57%
1920 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1#!/usr/bin/env python3
2"""
3Match Tracking CLI for MissingTable
5Chat with Claw during matches to post live events.
7Usage:
8 mt login tom
9 mt search --age U14 --days 30
10 mt match start 1053
11 mt match goal --team home --player "Matt"
12 mt match message "Great pass by Carter"
13 mt match status
14 mt match halftime
15 mt match secondhalf
16 mt match end
17"""
19from __future__ import annotations
21import json
22import os
23import re
24import subprocess
25import sys
26from collections import Counter
27from datetime import UTC, datetime
28from getpass import getpass
29from pathlib import Path
30from typing import TYPE_CHECKING, Any, NoReturn
32import httpx
33import typer
34from pydantic import BaseModel
35from rich.console import Console
36from rich.panel import Panel
37from rich.table import Table
39from api_client import APIError, AuthenticationError, MissingTableClient
40from api_client.models import (
41 GoalEvent,
42 LiveMatchClock,
43 MessageEvent,
44 Team,
45 TournamentCreate,
46 TournamentMatchCreate,
47 TournamentMatchUpdate,
48)
50if TYPE_CHECKING:
51 from collections.abc import Callable
53app = typer.Typer(help="MT Match Tracking CLI")
54match_app = typer.Typer(help="Live match tracking commands")
55tournament_app = typer.Typer(help="Tournament + bracket seeding commands (admin)")
56team_app = typer.Typer(help="Team stats, matches, and admin edits")
57player_app = typer.Typer(help="Player stats (read-only)")
58club_app = typer.Typer(help="Club admin: create, rename, crest and colours")
59alias_app = typer.Typer(help="Team name aliases (admin)")
60mapping_app = typer.Typer(help="Team age-group / division registrations (admin)")
61ingest_app = typer.Typer(help="Ingest: unresolved names, and planned fixes for a tournament's teams (admin)")
62app.add_typer(match_app, name="match")
63app.add_typer(tournament_app, name="tournament")
64app.add_typer(team_app, name="team")
65app.add_typer(player_app, name="player")
66app.add_typer(club_app, name="club")
67team_app.add_typer(alias_app, name="alias")
68team_app.add_typer(mapping_app, name="mapping")
69guest_app = typer.Typer(help="Teams with no row in a table they play fixtures in (admin)")
70team_app.add_typer(guest_app, name="guest")
71app.add_typer(ingest_app, name="ingest")
72ai_app = typer.Typer(help="MT AI: what it could not answer (admin)")
73app.add_typer(ai_app, name="ai")
74mcp_app = typer.Typer(help="mt-mcp: credentials for MCP clients such as Claude Code (SB-1304)")
75app.add_typer(mcp_app, name="mcp")
76motw_app = typer.Typer(help="Match of the Week: candidates and the current pick (admin)")
77app.add_typer(motw_app, name="motw")
78console = Console()
81@app.callback()
82def main(
83 env: str = typer.Option(
84 None,
85 "--env",
86 metavar="local|prod",
87 help="Target this environment for one command. Does not change .mt-config.",
88 ),
89) -> None:
90 """MT Match Tracking CLI."""
91 global _ENV_OVERRIDE
92 if env is None:
93 return
94 if env not in KNOWN_ENVS:
95 console.print(f"[red]Unknown environment {env!r}[/red] Known: {', '.join(KNOWN_ENVS)}")
96 raise typer.Exit(1)
97 _ENV_OVERRIDE = env
100# Valid tournament_round values accepted by the backend (mirrors
101# tournament_dao.VALID_ROUNDS). group_stage is the default for bracket pools.
102# What -c/--competition accepts beyond a competition name. 'all' is no filter;
103# 'qualifying' is the union of the types flagged counts_for_qualification.
104QUALIFYING = "qualifying"
106VALID_ROUNDS = {
107 "group_stage",
108 "crossover",
109 "round_of_32",
110 "round_of_16",
111 "quarterfinal",
112 "semifinal",
113 "final",
114 "third_place",
115 "wildcard",
116 "silver_semifinal",
117 "bronze_semifinal",
118 "silver_final",
119 "bronze_final",
120 "showcase",
121 "consolation",
122 "placement_final",
123}
125# Paths
126REPO_ROOT = Path(__file__).parent.parent
127BACKEND_DIR = Path(__file__).parent
128MT_CONFIG_FILE = REPO_ROOT / ".mt-config"
129STATE_FILE = BACKEND_DIR / ".mt-cli-state.json"
131# Environments `mt` knows how to target. Each needs a backend/.env.<name>.
132KNOWN_ENVS = ("local", "prod")
134# Set by the --env option for the lifetime of one invocation. Nothing is
135# written to disk: targeting prod is an act, not a mode you can forget you are
136# in (SB-841).
137_ENV_OVERRIDE: str | None = None
140# --- Models ---
143class CLIState(BaseModel):
144 """Persistent state for CLI (login session + active match)."""
146 access_token: str | None = None
147 refresh_token: str | None = None
148 username: str | None = None
149 match_id: int | None = None
150 home_team_name: str | None = None
151 away_team_name: str | None = None
154# --- Config Helpers ---
157def mt_config_get(key: str, default: str = "") -> str:
158 """Read a key from .mt-config."""
159 if MT_CONFIG_FILE.exists():
160 with open(MT_CONFIG_FILE) as f:
161 for line in f: 161 ↛ 165line 161 didn't jump to line 165
162 line = line.strip()
163 if line.startswith(f"{key}="): 163 ↛ 161line 163 didn't jump to line 161 because the condition on line 163 was always true
164 return line.split("=", 1)[1]
165 return default
168def resolve_env() -> tuple[str, str]:
169 """The environment this invocation targets, and where that came from.
171 Precedence: --env, then APP_ENV, then .mt-config, then local.
173 APP_ENV used to lose to .mt-config, which is the surprising half:
174 `APP_ENV=prod mt ...` looks like it should work and silently did nothing.
175 A value someone typed for this command beats a mode left on disk.
176 """
177 if _ENV_OVERRIDE is not None:
178 return _ENV_OVERRIDE, "--env"
179 from_environ = os.getenv("APP_ENV")
180 if from_environ:
181 return from_environ, "APP_ENV"
182 config_val = mt_config_get("supabase_env")
183 if config_val:
184 return config_val, MT_CONFIG_FILE.name
185 return "local", "default"
188def get_current_env() -> str:
189 """Get current environment (local or prod)."""
190 return resolve_env()[0]
193def get_base_url() -> str:
194 """Get API base URL for current environment."""
195 env = get_current_env()
196 env_file = BACKEND_DIR / f".env.{env}"
197 if not env_file.exists(): 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true
198 console.print(f"[red]Environment file not found: {env_file}[/red]")
199 raise typer.Exit(1)
201 env_vars = {}
202 with open(env_file) as f:
203 for line in f:
204 line = line.strip()
205 if line and not line.startswith("#") and "=" in line: 205 ↛ 203line 205 didn't jump to line 203 because the condition on line 205 was always true
206 key, value = line.split("=", 1)
207 env_vars[key] = value
209 if env == "local":
210 return env_vars.get("BACKEND_URL", "http://localhost:8000")
212 base_url = env_vars.get("BACKEND_URL")
213 if not base_url: 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true
214 console.print(
215 "[red]BACKEND_URL not set in .env.prod[/red]\n"
216 "[yellow]Add this line to backend/.env.prod:[/yellow]\n"
217 "BACKEND_URL=https://your-prod-api.com"
218 )
219 raise typer.Exit(1)
220 return base_url
223# --- State Management ---
226def _read_raw_state() -> dict:
227 """The state file as stored, or {} when there is none."""
228 if not STATE_FILE.exists():
229 return {}
230 with open(STATE_FILE) as f:
231 return json.load(f) or {}
234def _write_raw_state(environments: dict, users: dict) -> None:
235 with open(STATE_FILE, "w") as f:
236 json.dump({"environments": environments, "users": users}, f, indent=2)
239def _read_state_file() -> dict:
240 """The whole state file, as {env: session}.
242 Sessions are per environment. They were not, and with --env making the
243 target easy to change that would be actively dangerous: a token minted
244 against prod would be sent to localhost, and an active prod match id would
245 be the id of some unrelated local fixture.
247 A pre-SB-841 file is a bare session at the top level. It is migrated under
248 whichever environment is current when it is first read — the only
249 information available about where that token came from.
250 """
251 data = _read_raw_state()
252 if isinstance(data, dict) and "environments" in data:
253 return data["environments"] or {}
254 if data:
255 return {get_current_env(): data}
256 return {}
259def load_state() -> CLIState:
260 """The session for the environment this command targets."""
261 return CLIState(**_read_state_file().get(get_current_env(), {}))
264def save_state(state: CLIState) -> None:
265 """Write the session back, leaving other environments' sessions alone."""
266 environments = _read_state_file()
267 environments[get_current_env()] = state.model_dump()
268 _write_raw_state(environments, _read_users())
271def _read_users() -> dict:
272 """Every stored login, as {env: {username: session}} (SB-1331)."""
273 data = _read_raw_state()
274 users = data.get("users") if isinstance(data, dict) else None
275 return users or {}
278def load_user_state(username: str) -> CLIState:
279 """The session `mt login <username>` left for the targeted environment.
281 The environment's current session, rather than per-user storage, is what
282 every other command uses. A login made before per-user storage existed is
283 only there, so it still counts when it belongs to this user.
284 """
285 env = get_current_env()
286 stored = _read_users().get(env, {}).get(username)
287 if stored:
288 return CLIState(**stored)
289 current = load_state()
290 if current.username == username and current.access_token:
291 return CLIState(access_token=current.access_token, refresh_token=current.refresh_token, username=username)
292 return CLIState(username=username)
295def save_user_state(state: CLIState) -> None:
296 """Keep this user's tokens for the targeted environment, beside everyone else's.
298 Only the tokens: an active match belongs to the environment's session.
299 """
300 if not state.username: 300 ↛ 301line 300 didn't jump to line 301 because the condition on line 300 was never true
301 return
302 users = _read_users()
303 users.setdefault(get_current_env(), {})[state.username] = {
304 "access_token": state.access_token,
305 "refresh_token": state.refresh_token,
306 "username": state.username,
307 }
308 _write_raw_state(_read_state_file(), users)
311def announce_target() -> None:
312 """Say so, out loud, whenever a command is aimed somewhere other than local.
314 The ticket asked for this on writes. Every command gets it instead: a read
315 that quietly answers about production is its own kind of wrong, and one
316 rule cannot be applied to the wrong half of the command list.
317 """
318 env, source = resolve_env()
319 if env != "local":
320 console.print(f"[yellow]→ {env}[/yellow] [dim](from {source})[/dim]")
323def get_client() -> tuple[MissingTableClient, CLIState]:
324 """Get an authenticated MissingTableClient and current state."""
325 announce_target()
326 state = load_state()
327 if not state.access_token: 327 ↛ 328line 327 didn't jump to line 328 because the condition on line 327 was never true
328 console.print(
329 f"[red]Not logged in to {get_current_env()}[/red]\n[yellow]Login first:[/yellow] mt login <username>"
330 )
331 raise typer.Exit(1)
333 if state.refresh_token and _near_expiry(state.access_token):
334 try:
335 fresh_access_token(state, get_base_url(), persist=_persist_session)
336 except (AuthenticationError, APIError):
337 _session_expired()
339 client = MissingTableClient(
340 base_url=get_base_url(),
341 access_token=state.access_token,
342 )
343 # A token revoked or expired early still gets one refresh-and-retry (SB-1410).
344 client._refresh_token = state.refresh_token
345 client.on_token_refresh = lambda tokens: _persist_session(_with_tokens(state, tokens))
346 return client, state
349def _near_expiry(access_token: str) -> bool:
350 """A readable token within the refresh margin of expiry. An unreadable one
351 goes to the server as-is: a 401 there still triggers the refresh."""
352 import time
354 expires = token_expires_at(access_token)
355 return expires is not None and expires - time.time() <= MCP_REFRESH_MARGIN_S
358def _with_tokens(state: CLIState, tokens: dict) -> CLIState:
359 state.access_token = tokens["access_token"]
360 state.refresh_token = tokens.get("refresh_token") or state.refresh_token
361 return state
364def _persist_session(state: CLIState) -> None:
365 """Save refreshed tokens to the environment's session and the user's copy.
367 Refresh tokens rotate, so a copy left holding the old one could never
368 refresh again.
369 """
370 save_state(state)
371 save_user_state(state)
374def _session_expired() -> NoReturn:
375 env = get_current_env()
376 console.print(f"[red]Session expired for {env}[/red]\n[yellow]Log in again:[/yellow] mt --env {env} login")
377 raise typer.Exit(1)
380def require_active_match(state: CLIState) -> int:
381 """Return the active match_id from state, or exit with an error."""
382 if not state.match_id:
383 console.print("[red]No active match[/red]\n[yellow]Start a match first:[/yellow] mt match start <match_id>")
384 raise typer.Exit(1)
385 return state.match_id
388# --- Helpers ---
391def op_reference(username: str) -> str:
392 """Where mt looks in 1Password for this environment's login.
394 Overridable with MT_OP_ITEM or an `op_item` line in .mt-config, so a second
395 account or vault does not need a code change. Defaults to the mt-<env> item
396 the account already uses for infrastructure secrets.
397 """
398 explicit = os.environ.get("MT_OP_ITEM") or mt_config_get("op_item")
399 if explicit:
400 return explicit.replace("{env}", get_current_env()).replace("{user}", username)
401 return f"op://agents/mt-{get_current_env()}/credential"
404def password_from_op(username: str) -> str | None:
405 """Read the login password from 1Password, or None if unavailable.
407 Never raises: 1Password not installed, locked, or the field missing are all
408 ordinary situations that should fall through to the next source rather than
409 stop the command. Output is deliberately not logged — a password in a
410 terminal transcript is permanent.
411 """
412 reference = op_reference(username)
413 try:
414 result = subprocess.run( # noqa: S603
415 ["op", "read", reference], # noqa: S607
416 capture_output=True,
417 text=True,
418 timeout=30,
419 check=False,
420 )
421 except (FileNotFoundError, subprocess.TimeoutExpired):
422 return None
423 if result.returncode != 0:
424 return None
425 return result.stdout.strip() or None
428def _load_env_vars() -> dict[str, str]:
429 """Load env vars for the current environment."""
430 env = get_current_env()
431 env_file = BACKEND_DIR / f".env.{env}"
432 if not env_file.exists():
433 return {}
434 env_vars = {}
435 with open(env_file) as f:
436 for line in f:
437 line = line.strip()
438 if line and not line.startswith("#") and "=" in line:
439 key, value = line.split("=", 1)
440 env_vars[key] = value
441 return env_vars
444def _resolve_team(live: dict, team_arg: str) -> tuple[int, str]:
445 """Resolve a team argument to (team_id, team_name).
447 Accepts "home", "away", or a case-insensitive substring of a team name.
448 """
449 home_id = live["home_team_id"]
450 away_id = live["away_team_id"]
451 home_name = live.get("home_team_name", "Home")
452 away_name = live.get("away_team_name", "Away")
454 lower = team_arg.lower()
456 if lower == "home":
457 return home_id, home_name
458 if lower == "away":
459 return away_id, away_name
461 # Try case-insensitive substring match against team names
462 home_match = lower in home_name.lower()
463 away_match = lower in away_name.lower()
465 if home_match and away_match:
466 console.print(
467 f"[red]'{team_arg}' matches both teams:[/red] {home_name} and {away_name}\n"
468 "[yellow]Use 'home' or 'away' to disambiguate[/yellow]"
469 )
470 raise typer.Exit(1)
472 if home_match:
473 return home_id, home_name
474 if away_match:
475 return away_id, away_name
477 console.print(
478 f"[red]'{team_arg}' doesn't match either team[/red]\n"
479 f" Home: {home_name}\n"
480 f" Away: {away_name}\n"
481 "[yellow]Use 'home', 'away', or part of a team name[/yellow]"
482 )
483 raise typer.Exit(1)
486def _resolve_player(
487 client: MissingTableClient, team_id: int, season_id: int | None, player_arg: str
488) -> tuple[int | None, str | None]:
489 """Resolve a player argument to (player_id, display_name).
491 Accepts a jersey number or a player name (case-insensitive substring).
492 Returns (None, None) if roster lookup fails gracefully.
493 """
494 # Try as jersey number first
495 try:
496 jersey = int(player_arg)
497 except ValueError:
498 jersey = None
500 # Fetch roster
501 roster = []
502 if season_id:
503 try:
504 result = client.get_team_roster(team_id, season_id=season_id)
505 roster = result.get("roster", [])
506 except Exception as e:
507 console.print(f"[yellow]Could not fetch roster: {e}[/yellow]")
509 if jersey is not None:
510 # Look up by jersey number
511 player = next((p for p in roster if p.get("jersey_number") == jersey), None)
512 if not player:
513 if roster:
514 console.print(f"[yellow]No player #{jersey} on roster — recording goal without player[/yellow]")
515 return None, f"#{jersey}"
517 display = player.get("display_name") or player.get("first_name") or f"#{jersey}"
518 return player.get("id"), display
520 # Look up by name (case-insensitive substring)
521 if roster:
522 matches = []
523 for p in roster:
524 name = p.get("display_name") or p.get("first_name") or ""
525 if player_arg.lower() in name.lower():
526 matches.append(p)
528 if len(matches) == 1:
529 p = matches[0]
530 display = p.get("display_name") or p.get("first_name") or f"#{p.get('jersey_number')}"
531 return p.get("id"), display
533 if len(matches) > 1:
534 console.print(f"[yellow]'{player_arg}' matches multiple players:[/yellow]")
535 for p in matches:
536 name = p.get("display_name") or p.get("first_name") or "?"
537 console.print(f" #{p.get('jersey_number')} {name}")
538 console.print("[yellow]Use the jersey number instead[/yellow]")
539 raise typer.Exit(1)
541 # No roster match — use as free-text name
542 return None, player_arg
545def _parse_ts(value: str | None) -> datetime | None:
546 """Parse an ISO timestamp string to datetime."""
547 if not value:
548 return None
549 return datetime.fromisoformat(value.replace("Z", "+00:00"))
552def _match_clock(live: dict) -> tuple[str, str]:
553 """Calculate current period and match minute from live state.
555 Returns (period, minute_display) e.g. ("1st Half", "23'") or ("Halftime", "40'").
556 """
557 kickoff_time = _parse_ts(live.get("kickoff_time"))
558 halftime_start = _parse_ts(live.get("halftime_start"))
559 second_half_start = _parse_ts(live.get("second_half_start"))
560 match_end_time = _parse_ts(live.get("match_end_time"))
561 half_duration = live.get("half_duration") or 45
563 if not kickoff_time:
564 return "Pre-match", "-"
566 if match_end_time:
567 return "Full time", f"{half_duration * 2}'"
569 now = datetime.now(UTC)
571 if second_half_start:
572 elapsed = int((now - second_half_start).total_seconds() / 60) + 1
573 minute = half_duration + elapsed
574 full_time = half_duration * 2
575 if minute > full_time:
576 return "2nd Half", f"{full_time}+{minute - full_time}'"
577 return "2nd Half", f"{minute}'"
579 if halftime_start:
580 return "Halftime", f"{half_duration}'"
582 elapsed = int((now - kickoff_time).total_seconds() / 60) + 1
583 if elapsed > half_duration:
584 return "1st Half", f"{half_duration}+{elapsed - half_duration}'"
585 return "1st Half", f"{elapsed}'"
588# --- Top-level Commands ---
591@app.command()
592def login(username: str = typer.Argument("tom", help="Username to login with (default: tom)")):
593 """Login to the MT API."""
594 # Before a password is read, not after: which environment is about to be
595 # handed a credential is the thing worth knowing early.
596 announce_target()
598 # Try to find password from env file: TEST_USER_PASSWORD_<USERNAME>
599 env_vars = _load_env_vars()
600 env_key = f"TEST_USER_PASSWORD_{username.upper().replace('-', '_')}"
601 password = env_vars.get(env_key)
603 if password:
604 console.print(f"[dim]Using password from {env_key}[/dim]")
605 elif os.environ.get("MT_PASSWORD"):
606 password = os.environ["MT_PASSWORD"]
607 console.print("[dim]Using password from MT_PASSWORD[/dim]")
608 elif (from_op := password_from_op(username)) is not None:
609 password = from_op
610 console.print(f"[dim]Using password from {op_reference(username)}[/dim]")
611 elif not sys.stdin.isatty():
612 # getpass cannot turn off echo without a terminal, so it warns, echoes
613 # the password and aborts. Refuse up front instead: an agent shell or a
614 # piped session should be told what to do, not shown a typed password.
615 console.print("[red]No terminal available for a password prompt.[/red]")
616 console.print(
617 f"Set [cyan]MT_PASSWORD[/cyan] or [cyan]{env_key}[/cyan], or run [cyan]mt login[/cyan] in a terminal."
618 )
619 raise typer.Exit(1)
620 else:
621 password = getpass(f"Password for {username}: ")
623 base_url = get_base_url()
624 client = MissingTableClient(base_url=base_url)
626 try:
627 result = client.login(username, password)
628 except AuthenticationError as e:
629 console.print(f"[red]Login failed: {e}[/red]")
630 raise typer.Exit(1) from None
631 finally:
632 client.close()
634 # Preserve any existing match state
635 state = load_state()
636 state.access_token = result.get("access_token")
637 state.refresh_token = result.get("refresh_token")
638 state.username = username
639 save_state(state)
640 save_user_state(state)
642 user = result.get("user", {})
643 role = user.get("role", "unknown")
644 console.print(f"[green]Logged in as {username} ({role})[/green]")
645 console.print(f"[dim]Environment: {get_current_env()}[/dim]")
648# --- mt-mcp (SB-1304) ---
650# Refresh a session token this close to expiry, so a long Claude Code session
651# never hands mt-mcp - or any mt command (SB-1410) - a token that dies mid-call.
652MCP_REFRESH_MARGIN_S = 300
653MCP_CLIENT = "claude-code"
656def token_expires_at(token: str) -> int | None:
657 """The `exp` claim of a JWT, read without verifying it — the server verifies."""
658 import jwt
660 try:
661 exp = jwt.decode(token, options={"verify_signature": False}).get("exp")
662 except jwt.PyJWTError:
663 return None
664 return int(exp) if exp is not None else None
667def fresh_access_token(
668 state: CLIState,
669 base_url: str,
670 now: float | None = None,
671 persist: Callable[[CLIState], None] | None = None,
672) -> str:
673 """The stored session token, refreshed first if it is near expiry or unreadable.
675 A refreshed token is written back with `persist` (default: the environment's session).
676 """
677 import time
679 if not state.access_token:
680 raise AuthenticationError(f"Not logged in to {get_current_env()}")
681 expires = token_expires_at(state.access_token)
682 if expires is not None and expires - (now or time.time()) > MCP_REFRESH_MARGIN_S:
683 return state.access_token
685 client = MissingTableClient(base_url=base_url, access_token=state.access_token)
686 client._refresh_token = state.refresh_token
687 try:
688 refreshed = client.refresh_access_token()
689 finally:
690 client.close()
691 state.access_token = refreshed["access_token"]
692 state.refresh_token = refreshed.get("refresh_token") or state.refresh_token
693 (persist or save_state)(state)
694 return state.access_token
697@mcp_app.command("headers")
698def mcp_headers(
699 user: str | None = typer.Option(
700 None,
701 "--user",
702 "-u",
703 help="Speak as this user's `mt login` session instead of the environment's current one (SB-1331).",
704 ),
705):
706 """Print mt-mcp auth headers as JSON, for Claude Code's headersHelper.
708 Stdout is the JSON object and nothing else; every message goes to stderr.
709 Uses the `mt login` session for the targeted environment — or, with --user,
710 that user's — refreshing it when it is within five minutes of expiry.
711 """
712 err = Console(stderr=True)
713 if user:
714 state, persist = load_user_state(user), save_user_state
715 else:
716 state, persist = load_state(), save_state
717 try:
718 token = fresh_access_token(state, get_base_url(), persist=persist)
719 except (AuthenticationError, APIError) as e:
720 who = f"mt login {user}" if user else "mt login"
721 err.print(f"[red]mt-mcp: {e}[/red] — run [cyan]{who}[/cyan] for {get_current_env()}")
722 raise typer.Exit(1) from None
723 sys.stdout.write(json.dumps({"Authorization": f"Bearer {token}", "X-MT-Client": MCP_CLIENT}))
726@app.command()
727def logout():
728 """Logout and clear stored credentials for the targeted environment."""
729 env = get_current_env()
730 state = load_state()
731 state.access_token = None
732 state.refresh_token = None
733 state.username = None
734 save_state(state)
735 console.print(f"[green]Logged out of {env}[/green]")
738@app.command()
739def config():
740 """Show current configuration, including where the environment came from."""
741 env, source = resolve_env()
742 base_url = get_base_url()
743 state = load_state()
745 table = Table(title="MT CLI Configuration", show_header=False)
746 table.add_column("Setting", style="cyan")
747 table.add_column("Value", style="white")
749 table.add_row("Environment", f"{env} [dim](from {source})[/dim]")
750 table.add_row("API URL", base_url)
751 table.add_row("Logged in as", state.username or "Not logged in")
752 if state.match_id: 752 ↛ 753line 752 didn't jump to line 753 because the condition on line 752 was never true
753 match_label = f"#{state.match_id}"
754 if state.home_team_name and state.away_team_name:
755 match_label += f" ({state.home_team_name} vs {state.away_team_name})"
756 table.add_row("Active match", match_label)
758 console.print(table)
759 console.print(f"\n[dim]Config file: {MT_CONFIG_FILE}[/dim]")
760 console.print(f"[dim]State file: {STATE_FILE}[/dim]")
763@app.command()
764def search(
765 age_group: str = typer.Option(None, "--age", "-a", help="Filter by age group (e.g., 'U13', 'U14')"),
766 team: str = typer.Option(None, "--team", "-t", help="Filter by team name (substring match)"),
767 days: int = typer.Option(7, "--days", "-d", help="Number of days to search (default: 7)"),
768):
769 """Search for upcoming matches by age group, team, and date range."""
770 client, _ = get_client()
772 now = datetime.now(UTC)
773 start = datetime(now.year, now.month, now.day, tzinfo=UTC)
774 end = datetime.fromtimestamp(start.timestamp() + (days * 86400), tz=UTC)
776 start_str = start.strftime("%Y-%m-%d")
777 end_str = end.strftime("%Y-%m-%d")
779 matches = client.get_games(start_date=start_str, end_date=end_str)
781 # Filter by age group and team if provided
782 filtered = []
783 for match in matches:
784 home_name = match.get("home_team_name", "Unknown")
785 away_name = match.get("away_team_name", "Unknown")
786 age_name = match.get("age_group_name", "Unknown")
788 if age_group:
789 if age_group.lower() not in age_name.lower():
790 continue
792 if team:
793 if team.lower() not in home_name.lower() and team.lower() not in away_name.lower():
794 continue
796 filtered.append(match)
798 if not filtered:
799 console.print("[yellow]No matches found matching your criteria.[/yellow]")
800 return
802 table = Table(title=f"Upcoming Matches (Next {days} days)")
803 table.add_column("ID", style="cyan", no_wrap=True)
804 table.add_column("Date", style="magenta")
805 table.add_column("Home", style="white")
806 table.add_column("Away", style="white")
807 table.add_column("Age", style="yellow")
809 for m in filtered:
810 match_id = str(m.get("id", "?"))
811 date_str = m.get("match_date", "?")
812 home = m.get("home_team_name", "Unknown")
813 away = m.get("away_team_name", "Unknown")
814 age = m.get("age_group_name", "?")
816 table.add_row(match_id, date_str, home, away, age)
818 console.print(table)
819 console.print(f"\n[dim]Found {len(filtered)} match(es)[/dim]")
820 console.print("[green]Use 'mt match start <match_id>' to start tracking[/green]")
823# --- Match Subcommands ---
826@match_app.command()
827def start(
828 match_id: int = typer.Argument(..., help="Match ID to track"),
829 half: int = typer.Option(40, "--half", help="Half duration in minutes (default: 40)"),
830):
831 """Start tracking a match and kick off the first half."""
832 client, state = get_client()
834 console.print(f"[dim]Fetching match {match_id}...[/dim]")
835 try:
836 match = client.get_game(match_id)
837 except AuthenticationError:
838 console.print("[red]Session expired[/red]\n[yellow]Login again:[/yellow] mt login <username>")
839 raise typer.Exit(1) from None
840 except APIError as e:
841 console.print(f"[red]{e}[/red]")
842 raise typer.Exit(1) from None
844 # Start the match clock (sets status to live, records kickoff time)
845 clock = LiveMatchClock(action="start_first_half", half_duration=half)
846 client.update_match_clock(match_id, clock)
848 # Save match_id and team names to state
849 home_name = match.get("home_team_name") or "Unknown"
850 away_name = match.get("away_team_name") or "Unknown"
851 state.match_id = match_id
852 state.home_team_name = home_name
853 state.away_team_name = away_name
854 save_state(state)
856 table = Table(title=f"Match #{match_id}", show_header=False)
857 table.add_column("Field", style="cyan")
858 table.add_column("Value", style="white")
860 table.add_row("Home", home_name)
861 table.add_row("Away", away_name)
862 table.add_row("Date", match.get("match_date", "Unknown"))
863 table.add_row("Half Duration", f"{half} min/half = {half * 2} min total")
864 table.add_row("Status", "live")
866 console.print(table)
867 console.print(f"[green]Match {match_id} kicked off![/green]")
868 console.print(f"[dim]Environment: {get_current_env()}[/dim]")
871@match_app.command()
872def goal(
873 team: str = typer.Option(..., "--team", "-t", help="Team: 'home', 'away', or team name"),
874 player: str = typer.Option(None, "--player", "-p", help="Player: jersey number or name (optional)"),
875):
876 """Record a goal."""
877 client, state = get_client()
878 match_id = require_active_match(state)
880 live = client.get_live_match_state(match_id)
881 team_id, team_name = _resolve_team(live, team)
883 # Resolve player if provided
884 player_id = None
885 player_display = None
886 if player:
887 player_id, player_display = _resolve_player(client, team_id, live.get("season_id"), player)
889 # Build and post goal event
890 goal_event = GoalEvent(
891 team_id=team_id,
892 player_id=player_id,
893 player_name=player_display,
894 )
895 client.post_goal(match_id, goal_event)
897 # Calculate current minute for display
898 _, minute = _match_clock(live)
900 scorer = f" - {player_display}" if player_display else ""
901 console.print(
902 Panel(
903 f"[bold]{team_name}[/bold]{scorer} ({minute})",
904 title="Goal!",
905 border_style="green",
906 )
907 )
910@match_app.command()
911def message(
912 text: str = typer.Argument(..., help="Message text"),
913):
914 """Post a chat message to the match."""
915 client, state = get_client()
916 match_id = require_active_match(state)
918 msg = MessageEvent(message=text)
919 client.post_message(match_id, msg)
921 console.print(f"[dim]{text}[/dim]")
924@match_app.command()
925def status(
926 match_id_arg: int = typer.Argument(None, metavar="MATCH_ID", help="Match ID (uses active match if omitted)"),
927):
928 """Show live match status."""
929 client, state = get_client()
930 match_id = match_id_arg if match_id_arg is not None else require_active_match(state)
932 live = client.get_live_match_state(match_id)
934 home_name = live.get("home_team_name", "Home")
935 away_name = live.get("away_team_name", "Away")
936 period, minute = _match_clock(live)
938 home_score = live.get("home_score", 0)
939 away_score = live.get("away_score", 0)
941 table = Table(title=f"Match #{match_id}", show_header=False)
942 table.add_column("Field", style="cyan", width=15)
943 table.add_column("Value", style="white")
945 table.add_row("Home", f"{home_name} — {home_score}")
946 table.add_row("Away", f"{away_name} — {away_score}")
947 table.add_row("Status", live.get("match_status", "Unknown"))
948 table.add_row("Period", period)
949 table.add_row("Minute", minute)
950 table.add_row("Half Duration", f"{live.get('half_duration', '-')} min")
952 console.print(table)
954 # Fetch full event list and filter out status-change noise so every goal is shown.
955 # The /live endpoint returns events newest-first; using [-N:] on that list would
956 # show only the oldest entries, hiding recent goals (the original bug).
957 events_to_show: list[dict] = []
958 try:
959 all_events = client.get_match_events(match_id)
960 # all_events is newest-first; reverse to chronological order.
961 # Exclude status_change events (kickoff, halftime, etc.) from the CLI display —
962 # those are already surfaced via the Period/Status rows above.
963 _SKIP_TYPES = {"status_change"}
964 events_to_show = [e for e in reversed(all_events) if e.get("event_type") not in _SKIP_TYPES]
965 except Exception:
966 # Graceful fallback: use whatever recent_events the /live response included,
967 # but fix the ordering bug by taking the first (newest) entries, not the last.
968 raw = live.get("recent_events") or []
969 events_to_show = list(reversed(raw[:10]))
971 if events_to_show:
972 console.print("\n[bold]Match Events:[/bold]")
973 for event in events_to_show:
974 event_type = event.get("event_type", "")
975 msg = event.get("message", "")
976 minute = event.get("match_minute")
977 extra = event.get("extra_time")
978 if minute is not None:
979 minute_str = f"{minute}+{extra}'" if extra else f"{minute}'"
980 console.print(f" [dim]{minute_str}[/dim] {msg}")
981 else:
982 console.print(f" [dim]{event_type}:[/dim] {msg}")
985@match_app.command()
986def halftime():
987 """End the first half (start halftime)."""
988 client, state = get_client()
989 match_id = require_active_match(state)
991 clock = LiveMatchClock(action="start_halftime")
992 client.update_match_clock(match_id, clock)
993 console.print(f"[green]Match {match_id} — Halftime[/green]")
996@match_app.command()
997def secondhalf():
998 """Start the second half."""
999 client, state = get_client()
1000 match_id = require_active_match(state)
1002 clock = LiveMatchClock(action="start_second_half")
1003 client.update_match_clock(match_id, clock)
1004 console.print(f"[green]Match {match_id} — Second half kicked off[/green]")
1007@match_app.command()
1008def end():
1009 """End the match (full time) and clear active match."""
1010 client, state = get_client()
1011 match_id = require_active_match(state)
1013 clock = LiveMatchClock(action="end_match")
1014 client.update_match_clock(match_id, clock)
1016 console.print(f"[green]Match {match_id} — Full time[/green]")
1018 # Clear match state
1019 state.match_id = None
1020 state.home_team_name = None
1021 state.away_team_name = None
1022 save_state(state)
1025# --- Tournament helpers ---
1028def _resolve_age_group(client: MissingTableClient, name: str) -> dict:
1029 """Resolve an age-group name (e.g. 'U14') to its row ({id, name}). Exits on no match."""
1030 groups = client.get_age_groups()
1031 lower = name.lower()
1032 # Exact (case-insensitive) first, then substring.
1033 for g in groups:
1034 if g.get("name", "").lower() == lower:
1035 return g
1036 for g in groups:
1037 if lower in g.get("name", "").lower(): 1037 ↛ 1038line 1037 didn't jump to line 1038 because the condition on line 1037 was never true
1038 return g
1039 available = ", ".join(sorted(g.get("name", "?") for g in groups))
1040 console.print(f"[red]Age group '{name}' not found[/red]\n[yellow]Available:[/yellow] {available}")
1041 raise typer.Exit(1)
1044def _resolve_age_group_id(client: MissingTableClient, name: str) -> int:
1045 """Resolve an age-group name (e.g. 'U14') to its id. Exits on no match."""
1046 return _resolve_age_group(client, name)["id"]
1049def _resolve_season_id(client: MissingTableClient, season: str | None) -> int:
1050 """Resolve a season name to its id, or use the current season when omitted."""
1051 if season:
1052 lower = season.lower()
1053 for s in client.get_seasons():
1054 if lower in s.get("name", "").lower():
1055 return s["id"]
1056 console.print(f"[red]Season '{season}' not found[/red]")
1057 raise typer.Exit(1)
1058 current = client.get_current_season()
1059 if not current or "id" not in current:
1060 console.print(
1061 "[red]No current season set[/red]\n[yellow]Pass --season explicitly (e.g. --season 2025-2026)[/yellow]"
1062 )
1063 raise typer.Exit(1)
1064 return current["id"]
1067def _resolve_team_id(client: MissingTableClient, name: str) -> tuple[int, str]:
1068 """Resolve a team name to (id, name) via the admin lookup endpoint.
1070 Requires an exact match — seeding should never silently pick the wrong team.
1071 """
1072 result = client.lookup_team(name)
1073 exact = result.get("exact")
1074 if exact:
1075 return exact["id"], exact["name"]
1076 similar = result.get("similar") or []
1077 hint = ""
1078 if similar:
1079 hint = "\n[yellow]Did you mean:[/yellow] " + ", ".join(t.get("name", "?") for t in similar[:5])
1080 console.print(f"[red]No exact team match for '{name}'[/red]{hint}")
1081 raise typer.Exit(1)
1084# --- Tournament Subcommands ---
1087@tournament_app.command("create")
1088def tournament_create(
1089 name: str = typer.Option(..., "--name", "-n", help="Tournament name"),
1090 start: str = typer.Option(..., "--start", "-s", help="Start date (YYYY-MM-DD)"),
1091 end: str = typer.Option(None, "--end", "-e", help="End date (YYYY-MM-DD)"),
1092 age: list[str] = typer.Option(None, "--age", "-a", help="Age group(s), e.g. -a U14 (repeatable)"),
1093 location: str = typer.Option(None, "--location", help="Location"),
1094 description: str = typer.Option(None, "--description", help="Description"),
1095 inactive: bool = typer.Option(False, "--inactive", help="Create as inactive"),
1096):
1097 """Create a new tournament (admin). Prints the new tournament id."""
1098 client, _ = get_client()
1099 age_group_ids = [_resolve_age_group_id(client, a) for a in (age or [])]
1100 payload = TournamentCreate(
1101 name=name,
1102 start_date=start,
1103 end_date=end,
1104 location=location,
1105 description=description,
1106 age_group_ids=age_group_ids,
1107 is_active=not inactive,
1108 )
1109 try:
1110 created = client.create_tournament(payload)
1111 except APIError as e:
1112 console.print(f"[red]{e}[/red]")
1113 raise typer.Exit(1) from None
1115 tid = created.get("id")
1116 console.print(f"[green]Created tournament #{tid}:[/green] {name}")
1117 console.print(f"[dim]Environment: {get_current_env()}[/dim]")
1118 console.print(
1119 f"[dim]Add matches:[/dim] mt tournament add-match --tournament {tid} "
1120 '--home "Team A" --away "Team B" --age U14 --bracket "Bracket A" --date '
1121 f"{start}"
1122 )
1125@tournament_app.command("list")
1126def tournament_list():
1127 """List active tournaments."""
1128 client, _ = get_client()
1129 tournaments = client.get_active_tournaments()
1130 if not tournaments:
1131 console.print("[yellow]No active tournaments.[/yellow]")
1132 return
1133 table = Table(title="Active Tournaments")
1134 table.add_column("ID", style="cyan", no_wrap=True)
1135 table.add_column("Name", style="white")
1136 table.add_column("Start", style="magenta")
1137 table.add_column("End", style="magenta")
1138 for t in tournaments:
1139 table.add_row(
1140 str(t.get("id", "?")),
1141 t.get("name", "?"),
1142 str(t.get("start_date", "")),
1143 str(t.get("end_date", "") or ""),
1144 )
1145 console.print(table)
1148@tournament_app.command("show")
1149def tournament_show(
1150 tournament_id: int = typer.Argument(..., help="Tournament ID"),
1151):
1152 """Show a tournament's matches grouped by bracket + round."""
1153 client, _ = get_client()
1154 try:
1155 t = client.get_tournament(tournament_id)
1156 except APIError as e:
1157 console.print(f"[red]{e}[/red]")
1158 raise typer.Exit(1) from None
1160 console.print(f"[bold]{t.get('name', '?')}[/bold] (#{tournament_id})")
1161 matches = t.get("matches", []) or []
1162 if not matches:
1163 console.print("[yellow]No matches yet.[/yellow]")
1164 return
1165 table = Table(title=f"{len(matches)} matches")
1166 table.add_column("ID", style="cyan", no_wrap=True)
1167 table.add_column("Bracket", style="yellow")
1168 table.add_column("Age", style="yellow")
1169 table.add_column("Round", style="blue")
1170 table.add_column("Home", style="white")
1171 table.add_column("Away", style="white")
1172 table.add_column("Score", style="green")
1173 table.add_column("Status", style="magenta")
1174 for m in matches:
1175 score = ""
1176 if m.get("home_score") is not None and m.get("away_score") is not None:
1177 score = f"{m['home_score']}-{m['away_score']}"
1178 table.add_row(
1179 str(m.get("id", "?")),
1180 str(m.get("tournament_group") or ""),
1181 str((m.get("age_group") or {}).get("name") or m.get("age_group_name") or ""),
1182 str(m.get("tournament_round") or ""),
1183 str(m.get("home_team_name") or (m.get("home_team") or {}).get("name") or "?"),
1184 str(m.get("away_team_name") or (m.get("away_team") or {}).get("name") or "?"),
1185 score,
1186 str(m.get("match_status") or ""),
1187 )
1188 console.print(table)
1191@tournament_app.command("add-match")
1192def tournament_add_match(
1193 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1194 home: str = typer.Option(..., "--home", help="Home team name (must exist exactly)"),
1195 away: str = typer.Option(..., "--away", help="Away team name (created if new)"),
1196 age: str = typer.Option(..., "--age", "-a", help="Age group, e.g. U14"),
1197 date: str = typer.Option(..., "--date", "-d", help="Match date (YYYY-MM-DD)"),
1198 bracket: str = typer.Option(None, "--bracket", "-b", help="Bracket / tournament_group, e.g. 'Bracket A'"),
1199 round_: str = typer.Option("group_stage", "--round", "-r", help=f"Round ({', '.join(sorted(VALID_ROUNDS))})"),
1200 order: int = typer.Option(None, "--order", help="tournament_round_order (bracket position)"),
1201 kickoff: str = typer.Option(None, "--kickoff", "-k", help="Scheduled kickoff ISO ts, e.g. 2026-06-07T14:00:00Z"),
1202 home_score: int = typer.Option(None, "--home-score", help="Home score"),
1203 away_score: int = typer.Option(None, "--away-score", help="Away score"),
1204 status: str = typer.Option("scheduled", "--status", help="Match status"),
1205 season: str = typer.Option(None, "--season", help="Season name (default: current)"),
1206):
1207 """Add a match to a tournament bracket (admin).
1209 The home team must already exist; the away team is created on the fly if
1210 its name doesn't match an existing team (backend get_or_create).
1211 """
1212 if round_ not in VALID_ROUNDS:
1213 console.print(f"[red]Invalid round '{round_}'[/red]\n[yellow]Valid:[/yellow] {', '.join(sorted(VALID_ROUNDS))}")
1214 raise typer.Exit(1)
1216 client, _ = get_client()
1217 age_group_id = _resolve_age_group_id(client, age)
1218 season_id = _resolve_season_id(client, season)
1219 home_id, home_name = _resolve_team_id(client, home)
1221 payload = TournamentMatchCreate(
1222 home_team_id=home_id,
1223 away_team_name=away,
1224 match_date=date,
1225 age_group_id=age_group_id,
1226 season_id=season_id,
1227 home_score=home_score,
1228 away_score=away_score,
1229 match_status=status,
1230 tournament_group=bracket,
1231 tournament_round=round_,
1232 tournament_round_order=order,
1233 scheduled_kickoff=kickoff,
1234 )
1235 try:
1236 created = client.create_tournament_match(tournament, payload)
1237 except APIError as e:
1238 console.print(f"[red]{e}[/red]")
1239 raise typer.Exit(1) from None
1241 mid = created.get("id", "?")
1242 bracket_label = f" [{bracket}]" if bracket else ""
1243 console.print(f"[green]Added match #{mid}[/green]{bracket_label} {home_name} vs {away} ({age}, {round_})")
1246@tournament_app.command("remove-match")
1247def tournament_remove_match(
1248 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1249 match: int = typer.Option(..., "--match", "-m", help="Match ID to delete"),
1250):
1251 """Delete a match from a tournament (admin)."""
1252 client, _ = get_client()
1253 try:
1254 client.delete_tournament_match(tournament, match)
1255 except APIError as e:
1256 console.print(f"[red]{e}[/red]")
1257 raise typer.Exit(1) from None
1258 console.print(f"[green]Removed match #{match} from tournament #{tournament}[/green]")
1261motd_app = typer.Typer(help="Tournament Match of the Day: one featured match per tournament, day and age group (admin)")
1262tournament_app.add_typer(motd_app, name="motd")
1265def _motd_teams(match: dict[str, Any]) -> str:
1266 home = match.get("home_team_name") or (match.get("home_team") or {}).get("name") or "?"
1267 away = match.get("away_team_name") or (match.get("away_team") or {}).get("name") or "?"
1268 return f"{home} vs {away}"
1271def _print_motd(pick: dict[str, Any]) -> None:
1272 match = pick.get("match") or {}
1273 age = pick.get("age_group") or match.get("age_group_name")
1274 age_label = f"{age} " if age else ""
1275 console.print(f"[bold]{pick.get('match_date')}[/bold] {age_label}#{match.get('id', '?')} {_motd_teams(match)}")
1276 if pick.get("blurb"):
1277 console.print(f" {pick['blurb']}")
1278 reasons = pick.get("reasons")
1279 if reasons:
1280 for r in reasons:
1281 console.print(f" • {r.get('text')}")
1282 elif reasons == []:
1283 console.print(" [dim](reasons left empty)[/dim]")
1286@motd_app.command("show")
1287def tournament_motd_show(
1288 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1289 date: str = typer.Option(None, "--date", "-d", help="Day (YYYY-MM-DD); omit to list every pick"),
1290 age: str = typer.Option(None, "--age", "-a", help="Age group (e.g. U15); omit for every age group"),
1291):
1292 """Show a day's Match of the Day picks, or every pick in the tournament."""
1293 client, _ = get_client()
1294 try:
1295 age_group_id = _resolve_age_group_id(client, age) if age else None
1296 result = client.get_tournament_motd(tournament, date, age_group_id)
1297 except APIError as e:
1298 console.print(f"[red]{e}[/red]")
1299 raise typer.Exit(1) from None
1300 slot = f" ({age})" if age else ""
1301 if date:
1302 # With an age group the answer is that slot's pick; without, every age group's.
1303 one = [result["motd"]] if result.get("motd") else []
1304 picks = one if age else result.get("picks") or one
1305 if not picks:
1306 console.print(f"[yellow]No Match of the Day picked for {result.get('match_date')}{slot}.[/yellow]")
1307 for pick in picks:
1308 _print_motd(pick)
1309 return
1310 picks = result.get("picks") or []
1311 if not picks:
1312 console.print(f"[yellow]No Match of the Day picked yet for tournament #{tournament}{slot}.[/yellow]")
1313 for pick in picks:
1314 _print_motd(pick)
1317@motd_app.command("set")
1318def tournament_motd_set(
1319 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1320 match: int = typer.Option(..., "--match", "-m", help="Match ID to feature (must be in the tournament)"),
1321 date: str = typer.Option(None, "--date", "-d", help="Guard: refuse unless the match is on this day"),
1322 age: str = typer.Option(None, "--age", "-a", help="Guard: refuse unless the match is in this age group"),
1323 blurb: str = typer.Option(None, "--blurb", "-b", help="One-line headline"),
1324 reason: list[str] = typer.Option(None, "--reason", "-r", help="'Why this match' line; repeat for more (max 6)"),
1325):
1326 """Feature a match as its day's Match of the Day for its age group, replacing that slot's pick."""
1327 client, _ = get_client()
1328 reasons = [{"text": r} for r in reason] if reason else None
1329 try:
1330 age_group_id = _resolve_age_group_id(client, age) if age else None
1331 pick = client.set_tournament_motd(
1332 tournament, match, match_date=date, age_group_id=age_group_id, blurb=blurb, reasons=reasons
1333 )
1334 except APIError as e:
1335 console.print(f"[red]{e}[/red]")
1336 raise typer.Exit(1) from None
1337 console.print("[green]Match of the Day set[/green]")
1338 _print_motd(pick)
1341@motd_app.command("clear")
1342def tournament_motd_clear(
1343 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1344 date: str = typer.Option(..., "--date", "-d", help="Day to unpick (YYYY-MM-DD)"),
1345 age: str = typer.Option(None, "--age", "-a", help="Age group to unpick (e.g. U15); omit to unpick every one"),
1346):
1347 """Unpick a tournament day: one age group's pick, or every pick that day."""
1348 client, _ = get_client()
1349 try:
1350 age_group_id = _resolve_age_group_id(client, age) if age else None
1351 result = client.clear_tournament_motd(tournament, date, age_group_id)
1352 except APIError as e:
1353 console.print(f"[red]{e}[/red]")
1354 raise typer.Exit(1) from None
1355 slot = f" ({age})" if age else ""
1356 cleared = int(result.get("cleared") or 0)
1357 if cleared:
1358 noun = "pick" if cleared == 1 else "picks"
1359 console.print(f"[green]Cleared {cleared} Match of the Day {noun} for {result.get('match_date')}{slot}[/green]")
1360 else:
1361 console.print(f"[yellow]Nothing was picked for {result.get('match_date')}{slot}.[/yellow]")
1364def _motw_team(team: dict[str, Any]) -> str:
1365 pos = team.get("position")
1366 where = f"{pos}/{team.get('table_size')}" if pos else "no games"
1367 return f"{team.get('name')} ({where})"
1370@motw_app.command("suggest")
1371def motw_suggest(
1372 week: str = typer.Option(None, "--week", "-w", help="Any date (YYYY-MM-DD) in the week; default this week"),
1373 limit: int = typer.Option(5, "--limit", "-n", min=1, max=10, help="How many candidates"),
1374 facts: bool = typer.Option(False, "--facts", "-f", help="Show every fact id and text"),
1375 as_json: bool = typer.Option(False, "--json", help="Print the raw result"),
1376):
1377 """Rank this week's Match of the Week candidates (SB-1551)."""
1378 client, _ = get_client()
1379 try:
1380 result = client.get_motw_candidates(week, limit=limit)
1381 except APIError as e:
1382 console.print(f"[red]{e}[/red]")
1383 raise typer.Exit(1) from None
1384 if as_json: 1384 ↛ 1385line 1384 didn't jump to line 1385 because the condition on line 1384 was never true
1385 console.print_json(data=result)
1386 return
1387 console.print(f"[bold]Week {result['week_start']} - {result['week_end']}[/bold]")
1388 pick = result.get("current_pick")
1389 if pick:
1390 console.print(f"[yellow]Already picked: match #{pick['match_id']}. Candidates are for reference.[/yellow]")
1391 cov = result.get("coverage") or {}
1392 console.print(
1393 f"[dim]{cov.get('eligible', 0)} eligible of {cov.get('fixtures_in_week', 0)} pool fixtures; "
1394 f"{cov.get('teams_low_sample', 0)} teams with under 3 games; rules {cov.get('rules_season') or 'none'}[/dim]"
1395 )
1396 candidates = result.get("candidates") or []
1397 if not candidates:
1398 console.print(f"[yellow]{result.get('reason') or 'No candidates.'}[/yellow]")
1399 return
1400 for rank, c in enumerate(candidates, start=1):
1401 s = c["score"]
1402 console.print(
1403 f"\n[bold]#{rank}[/bold] {s['total']:.3f} match #{c['match_id']} {c['match_date']} "
1404 f"{c['age_group']['name']} {c['division']['name']} ({c['competition']})"
1405 )
1406 console.print(f" {_motw_team(c['home'])} vs {_motw_team(c['away'])}")
1407 console.print(
1408 f" [dim]quality {s['quality']} closeness {s['closeness']} stakes {s['stakes']} "
1409 f"form {s['form']} x{s['penalty']} {' '.join(c.get('flags') or [])}[/dim]"
1410 )
1411 if facts:
1412 for fact in c.get("facts") or []:
1413 console.print(f" [cyan]{fact['id']}[/cyan] {fact['text']}")
1416@tournament_app.command("score")
1417def tournament_score(
1418 tournament: int = typer.Option(..., "--tournament", "-T", help="Tournament ID"),
1419 match: int = typer.Option(..., "--match", "-m", help="Match ID"),
1420 home_score: int = typer.Option(..., "--home", help="Home score"),
1421 away_score: int = typer.Option(..., "--away", help="Away score"),
1422 status: str = typer.Option("completed", "--status", help="Match status"),
1423):
1424 """Set a tournament match's final score (admin).
1426 Goes through the admin match-write path, which fires the 'fulltime'
1427 follower notification — this is what bracket followers receive.
1428 """
1429 client, _ = get_client()
1430 payload = TournamentMatchUpdate(home_score=home_score, away_score=away_score, match_status=status)
1431 try:
1432 client.update_tournament_match(tournament, match, payload)
1433 except APIError as e:
1434 console.print(f"[red]{e}[/red]")
1435 raise typer.Exit(1) from None
1436 console.print(
1437 f"[green]Match #{match} → {home_score}-{away_score} ({status})[/green] "
1438 "[dim]fulltime notification fired to bracket + team followers[/dim]"
1439 )
1442# --- Read commands (SB-672) -------------------------------------------------
1443#
1444# `mt` could drive a match but not ask about one, so a data question ("why does
1445# this squad show 3 games played after 2 friendlies?") meant reading source and
1446# running SQL by hand. These go over HTTP with the existing `mt login` session —
1447# no database credentials anywhere.
1450class ResolutionError(Exception):
1451 """A name did not resolve to exactly one thing."""
1454# Mirrors GoldenBoot.vue, in the same order. A stat that disagrees between the
1455# CLI and the web board is worse than one missing from either.
1456STAT_FIELDS = [
1457 ("GP", "games_played"),
1458 ("GS", "games_started"),
1459 ("G", "total_goals"),
1460 ("A", "total_assists"),
1461 ("YC", "total_yellow_cards"),
1462 ("RC", "total_red_cards"),
1463]
1465SORT_FIELDS = {key.lower(): field for key, field in STAT_FIELDS}
1468def resolve_team(client, term: str) -> dict:
1469 """One team, by id or by name.
1471 Team names carry no age group — the squad shown as "IFA U15 HG" on the team
1472 page is the team named "IFA" — so a plausible-looking query matches nothing.
1473 A bare "no team" is a dead end, so near-misses are offered instead.
1474 """
1475 teams = client.get_teams() or []
1477 # By id, from the list rather than GET /api/teams/{id} — that route does not
1478 # exist. /api/teams/{team_id} serves only PUT and DELETE, so the by-id
1479 # lookup returned 405 for every numeric argument (SB-824). The list is
1480 # already fetched for name resolution, so this costs nothing extra.
1481 if str(term).isdigit():
1482 target = int(term)
1483 for t in teams:
1484 if t.get("id") == target:
1485 return t
1486 raise ResolutionError(f"No team with id {target}")
1488 needle = term.lower().strip()
1490 # An exact name wins outright: "IFA" should resolve, even though a dozen
1491 # other teams have it as a prefix.
1492 exact = [t for t in teams if (t.get("name") or "").lower().strip() == needle]
1493 if len(exact) == 1:
1494 return exact[0]
1496 matches = [t for t in teams if needle in (t.get("name") or "").lower()]
1497 if len(matches) == 1:
1498 return matches[0]
1499 if len(matches) > 1:
1500 names = ", ".join(t.get("name", "?") for t in matches[:6])
1501 more = "" if len(matches) <= 6 else f" (+{len(matches) - 6} more)"
1502 raise ResolutionError(f"{len(matches)} teams match {term!r}: {names}{more}")
1504 # Nothing contains the whole string. Fall back to word-by-word so a query
1505 # that mixes a club with an age group still points somewhere useful.
1506 tokens = [w for w in needle.split() if w]
1507 near = [t for t in teams if any(w in (t.get("name") or "").lower() for w in tokens)]
1508 if near:
1509 names = ", ".join(t.get("name", "?") for t in near[:8])
1510 more = "" if len(near) <= 8 else f" (+{len(near) - 8} more)"
1511 raise ResolutionError(f"No team named {term!r}. Did you mean: {names}{more}")
1512 raise ResolutionError(f"No team matching {term!r}")
1515def resolve_season(client, name: str | None = None) -> dict | None:
1516 """The named season, or the current one."""
1517 seasons = client.get_seasons() or []
1518 if name:
1519 needle = name.lower()
1520 matches = [s for s in seasons if needle in (s.get("name") or "").lower()]
1521 if not matches: 1521 ↛ 1522line 1521 didn't jump to line 1522 because the condition on line 1521 was never true
1522 raise ResolutionError(f"No season matching {name!r}")
1523 return matches[0]
1524 return next((s for s in seasons if s.get("is_current")), seasons[0] if seasons else None)
1527def resolve_match_type(client, name: str | None = None) -> dict | None:
1528 """The named competition, or League by default. None means every competition.
1530 Defaulting to League matches the web board: a squad total that silently
1531 folds friendlies in is not comparable with the league table beside it.
1533 One competition only. `qualifying` spans several, so it belongs to
1534 resolve_match_types and to the commands that can filter a list client-side
1535 — this returns one type; /api/teams/{id}/stats can total several (SB-1599).
1536 """
1537 if name and name.lower() == "all":
1538 return None
1539 if name and name.lower() == QUALIFYING:
1540 raise ResolutionError(
1541 f"{QUALIFYING!r} spans several competitions and is not available here — "
1542 "name one, or use 'all'. `mt team matches -c qualifying` does support it."
1543 )
1545 types = client.get_match_types() or []
1546 needle = (name or "league").lower()
1547 matches = [t for t in types if needle in (t.get("name") or "").lower()]
1548 if matches:
1549 return matches[0]
1550 if name:
1551 raise ResolutionError(f"No competition matching {name!r}")
1552 # No League configured is not an error — show everything rather than nothing.
1553 return None
1556def resolve_match_types(client, name: str | None = None) -> list[dict] | None:
1557 """Every competition a selection covers, or None for all of them.
1559 Unlike resolve_match_type this defaults to *all*. A schedule should open
1560 showing the schedule: hiding four fixtures because they are friendlies is
1561 the surprise, not the service. Stats default to League for the opposite
1562 reason — see resolve_match_type.
1564 `qualifying` is the union of the types flagged counts_for_qualification,
1565 read from the API rather than listed here, so the next qualifying
1566 competition is one flag in one row and not an edit in the CLI, the Matches
1567 filter and the standings separately (SB-849).
1568 """
1569 if name is None or name.lower() == "all":
1570 return None
1572 types = client.get_match_types() or []
1573 needle = name.lower()
1575 if needle == QUALIFYING:
1576 flagged = [t for t in types if t.get("counts_for_qualification")]
1577 if not flagged:
1578 raise ResolutionError(
1579 "No competition is flagged as counting for qualification, "
1580 "so there is nothing to combine under 'qualifying'."
1581 )
1582 return flagged
1584 matches = [t for t in types if needle in (t.get("name") or "").lower()]
1585 if not matches:
1586 known = ", ".join(t.get("name") or "?" for t in types) or "none configured"
1587 raise ResolutionError(f"No competition matching {name!r}. Known: {known}")
1588 return [matches[0]]
1591def match_type_id_of(match: dict) -> int | None:
1592 """The match's competition id, from either shape the API returns."""
1593 return match.get("match_type_id") or (match.get("match_type") or {}).get("id")
1596def took_part(player: dict) -> bool:
1597 """Did this player do anything recordable? Mirrors the web board (SB-670)."""
1598 return any((player.get(field) or 0) > 0 for _, field in STAT_FIELDS)
1601def _player_label(p: dict) -> str:
1602 name = f"{p.get('first_name') or ''} {p.get('last_name') or ''}".strip()
1603 jersey = p.get("jersey_number")
1604 if name and jersey:
1605 return f"#{jersey} {name}"
1606 return name or (f"#{jersey}" if jersey else "?")
1609def sort_stats(players: list[dict], sort_key: str = "g") -> list[dict]:
1610 """Sort as the web board does: chosen column, then goals, then assists, then name."""
1611 primary = SORT_FIELDS.get(sort_key.lower(), "total_goals")
1613 def key(p: dict):
1614 return (
1615 -(p.get(primary) or 0),
1616 -(p.get("total_goals") or 0),
1617 -(p.get("total_assists") or 0),
1618 _player_label(p),
1619 )
1621 return sorted(players, key=key)
1624def _fail(message: str) -> None:
1625 console.print(f"[red]{message}[/red]")
1626 raise typer.Exit(1)
1629def _api(fn, *args, **kwargs):
1630 """Call the API, turning a dead session into advice rather than a traceback.
1632 The write commands already catch this; the read commands did not, so an
1633 expired token dumped a full rich traceback at someone who only asked for a
1634 table (SB-672).
1635 """
1636 try:
1637 return fn(*args, **kwargs)
1638 except AuthenticationError:
1639 console.print("[red]Session expired.[/red] Run [cyan]mt login[/cyan] and try again.")
1640 raise typer.Exit(1) from None
1641 except ResolutionError as exc:
1642 console.print(f"[red]{exc}[/red]")
1643 raise typer.Exit(1) from None
1644 except APIError as exc:
1645 console.print(f"[red]API error: {exc}[/red]")
1646 raise typer.Exit(1) from None
1649@team_app.command("stats")
1650def team_stats(
1651 team: str = typer.Argument(..., help="Team name or id"),
1652 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
1653 competition: str = typer.Option(
1654 None, "--competition", "-c", help="League (default), Friendly, Tournament, or 'all'"
1655 ),
1656 sort: str = typer.Option("g", "--sort", help="Column to sort by: gp, gs, g, a, yc, rc"),
1657 everyone: bool = typer.Option(False, "--everyone", help="Include players who have not played"),
1658):
1659 """The Golden Boot board for a team."""
1660 client, _ = get_client()
1662 team_row = _api(resolve_team, client, team)
1663 season_row = _api(resolve_season, client, season)
1664 match_type = _api(resolve_match_type, client, competition)
1666 if not season_row: 1666 ↛ 1667line 1666 didn't jump to line 1667 because the condition on line 1666 was never true
1667 _fail("No season configured")
1669 payload = _api(
1670 client.get_team_stats,
1671 team_row["id"],
1672 season_id=season_row["id"],
1673 match_type_id=(match_type or {}).get("id"),
1674 )
1675 players = payload.get("players") if isinstance(payload, dict) else payload
1676 players = players or []
1677 if not everyone:
1678 players = [p for p in players if took_part(p)]
1680 scope = (match_type or {}).get("name", "All competitions")
1681 title = f"Golden Boot — {team_row.get('name', team)} · {season_row.get('name', '?')} · {scope}"
1683 if not players:
1684 console.print(f"[yellow]Nothing recorded for {team_row.get('name', team)} in {scope}.[/yellow]")
1685 console.print("[dim]Appearances and goals appear once matches are scored in the app.[/dim]")
1686 return
1688 table = Table(title=title)
1689 table.add_column("#", style="dim", no_wrap=True)
1690 table.add_column("Player", style="white")
1691 for label, _field in STAT_FIELDS:
1692 table.add_column(label, justify="right", style="cyan")
1694 for rank, p in enumerate(sort_stats(players, sort), start=1):
1695 table.add_row(str(rank), _player_label(p), *[str(p.get(f) or 0) for _, f in STAT_FIELDS])
1697 console.print(table)
1698 console.print(f"[dim]{len(players)} player(s) · sorted by {sort.upper()}[/dim]")
1701@team_app.command("matches")
1702def team_matches(
1703 team: str = typer.Argument(..., help="Team name or id"),
1704 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
1705 competition: str = typer.Option(
1706 None,
1707 "--competition",
1708 "-c",
1709 help="Competition name, 'qualifying', or 'all' (default). See: mt competitions",
1710 ),
1711 age_group: str = typer.Option(
1712 None,
1713 "--age-group",
1714 "-a",
1715 help="Age group, e.g. U14 — a team name is not unique to one (e.g. IFA plays U14 and U15)",
1716 ),
1717 limit: int = typer.Option(20, "--limit", "-l", help="How many to show"),
1718):
1719 """Matches for a team, with the status that decides whether they count."""
1720 client, _ = get_client()
1722 team_row = _api(resolve_team, client, team)
1723 season_row = _api(resolve_season, client, season)
1724 wanted = _api(resolve_match_types, client, competition)
1725 age_group_row = _api(_resolve_age_group, client, age_group) if age_group else None
1727 matches = (
1728 _api(
1729 client.get_games_by_team,
1730 team_row["id"],
1731 season_id=(season_row or {}).get("id"),
1732 age_group_id=(age_group_row or {}).get("id"),
1733 )
1734 or []
1735 )
1736 if not matches: 1736 ↛ 1737line 1736 didn't jump to line 1737 because the condition on line 1736 was never true
1737 console.print(f"[yellow]No matches for {team_row.get('name', team)}.[/yellow]")
1738 return
1740 scope = "All competitions"
1741 if wanted is not None:
1742 names = [t.get("name") or "?" for t in wanted]
1743 scope = "Qualifying (" + " + ".join(names) + ")" if len(names) > 1 else names[0]
1744 keep = {t.get("id") for t in wanted}
1745 matches = [m for m in matches if match_type_id_of(m) in keep]
1747 # Named ahead of the competition so a same-day pair across two age groups
1748 # (a team row spans every age group it plays) reads as what it is, not as
1749 # a double-ingest — e.g. "26 of 26 U14 League match(es)".
1750 if age_group_row:
1751 scope = f"{age_group_row.get('name', age_group)} {scope}"
1753 if not matches:
1754 console.print(f"[yellow]No {scope} matches for {team_row.get('name', team)}.[/yellow]")
1755 console.print("[dim]Other competitions may have matches — drop -c to see the whole schedule.[/dim]")
1756 return
1758 # The scope is in the title on purpose: a filtered list of 6 must not read
1759 # as a 6-match season.
1760 table = Table(title=f"Matches — {team_row.get('name', team)} · {scope}")
1761 table.add_column("ID", style="cyan", no_wrap=True)
1762 table.add_column("Date", style="magenta", no_wrap=True, min_width=10)
1763 table.add_column("Status", style="yellow")
1764 # Always shown, even unfiltered: a team row covers every age group it
1765 # plays, so a same-day pair across two of them looks like a duplicate
1766 # without this column (SB-866).
1767 table.add_column("Age", style="dim", no_wrap=True)
1768 table.add_column("Competition", style="dim")
1769 table.add_column("Home", style="white")
1770 table.add_column("Away", style="white")
1771 table.add_column("Score", justify="right")
1773 for m in matches[:limit]:
1774 home_score, away_score = m.get("home_score"), m.get("away_score")
1775 score = f"{home_score}-{away_score}" if home_score is not None and away_score is not None else "-"
1776 table.add_row(
1777 str(m.get("id", "?")),
1778 str(m.get("match_date", "?")),
1779 str(m.get("match_status", "?")),
1780 str(m.get("age_group_name") or (m.get("age_group") or {}).get("name") or "?"),
1781 str(m.get("match_type_name") or (m.get("match_type") or {}).get("name") or "?"),
1782 str(m.get("home_team_name", "?")),
1783 str(m.get("away_team_name", "?")),
1784 score,
1785 )
1787 console.print(table)
1788 shown = min(len(matches), limit)
1789 console.print(f"[dim]{shown} of {len(matches)} {scope} match(es).[/dim]")
1790 console.print("[dim]Only live, completed and forfeit matches count towards season stats (SB-671).[/dim]")
1793def _dash(value, fmt: str = "{}") -> str:
1794 """An absent value renders as absent, never as 0 (CLAUDE.md rule 2)."""
1795 return "—" if value is None else fmt.format(value)
1798@team_app.command("dossier")
1799def team_dossier(
1800 team: str = typer.Argument(..., help="Team name or id"),
1801 age: str = typer.Option(None, "--age", "-a", help="Age group, e.g. U15 (or give --match)"),
1802 match_id: int = typer.Option(None, "--match", "-m", help="Use the team's age in this match; shows playing up"),
1803 as_json: bool = typer.Option(False, "--json", help="Print the raw result"),
1804):
1805 """A team inside its own conference tables, at one age group (SB-1780).
1807 Positions and percentiles are within each table: conferences are never compared.
1808 """
1809 if age is None and match_id is None:
1810 _fail("Give --age (e.g. U15) or --match")
1811 client, _ = get_client()
1812 team_row = _api(resolve_team, client, team)
1813 age_row = _resolve_age_group(client, age) if age else None
1814 result = _api(
1815 client.get_team_dossier,
1816 team_row["id"],
1817 age_group_id=(age_row or {}).get("id"),
1818 for_match_id=match_id,
1819 )
1820 if as_json:
1821 console.print_json(data=result)
1822 return
1824 t = result.get("team") or {}
1825 age_name = (result.get("age_group") or {}).get("name", "?")
1826 season_name = (result.get("season") or {}).get("name", "?")
1827 console.print(f"[bold]{t.get('name', team)} · {age_name} · {season_name}[/bold]")
1828 ctx = result.get("context")
1829 if ctx and ctx.get("playing_up"):
1830 how = "inferred from registrations" if ctx.get("playing_up_inferred") else "recorded on the match"
1831 console.print(
1832 f"[yellow]Playing up in match {ctx['match_id']}: {ctx['season_age_group']['name']} side in a "
1833 f"{ctx['bracket_age_group']['name']} match ({how}).[/yellow]"
1834 )
1835 console.print(f"[dim]{(result.get('coverage') or {}).get('note', '')}[/dim]")
1836 if result.get("flags"):
1837 console.print(f"[yellow]Flags: {', '.join(result['flags'])}[/yellow]")
1839 confs = result.get("conferences") or []
1840 if not confs:
1841 console.print(f"[yellow]No {age_name} registration: no conference table to place the team in.[/yellow]")
1842 else:
1843 table = Table(title="Conferences (each its own table)")
1844 table.add_column("Kind", style="dim")
1845 table.add_column("Conference", style="cyan")
1846 table.add_column("Pos", justify="right")
1847 table.add_column("GP", justify="right")
1848 table.add_column("W-D-L", justify="right")
1849 table.add_column("GF-GA", justify="right")
1850 table.add_column("PPG", justify="right")
1851 table.add_column("CS", justify="right")
1852 table.add_column("Pctl", justify="right")
1853 for c in confs:
1854 division = c.get("division") or {}
1855 pos = "—" if c.get("position") is None else f"{c['position']}/{c.get('table_size')}"
1856 record = "—" if c.get("wins") is None else f"{c['wins']}-{c['draws']}-{c['losses']}"
1857 goals = "—" if c.get("gf") is None else f"{c['gf']}-{c['ga']}"
1858 label = f"{c.get('league') or ''} {division.get('name', '?')}".strip()
1859 if c.get("low_sample") and not c.get("no_results"): 1859 ↛ 1860line 1859 didn't jump to line 1860 because the condition on line 1859 was never true
1860 label += " (small sample)"
1861 table.add_row(
1862 c.get("kind", "?"),
1863 label,
1864 pos,
1865 str(c.get("played", 0)),
1866 record,
1867 goals,
1868 _dash(c.get("ppg"), "{:.2f}"),
1869 _dash(c.get("clean_sheets")),
1870 _dash(c.get("strength_percentile")),
1871 )
1872 console.print(table)
1874 wins = result.get("key_wins") or []
1875 if wins: 1875 ↛ 1893line 1875 didn't jump to line 1893 because the condition on line 1875 was always true
1876 table = Table(title="Key wins (strongest opponent first)")
1877 table.add_column("Date", style="magenta", no_wrap=True)
1878 table.add_column("Opponent", style="white")
1879 table.add_column("Score", justify="right")
1880 table.add_column("Why", style="cyan")
1881 table.add_column("Opponent's table", style="dim")
1882 for w in wins:
1883 where = (
1884 "—"
1885 if w.get("opponent_position") is None
1886 else f"{w['opponent_position']}/{w.get('opponent_table_size')} {w.get('opponent_conference')}"
1887 )
1888 table.add_row(
1889 str(w.get("date", "?")), w["opponent"]["name"], w.get("score", "?"), w.get("kind", "?"), where
1890 )
1891 console.print(table)
1893 form = result.get("form") or []
1894 if form: 1894 ↛ 1897line 1894 didn't jump to line 1897 because the condition on line 1894 was always true
1895 recent = ", ".join(f"{f['result']} {f['score']} v {f['opponent']['name']}" for f in form)
1896 console.print(f"Form (newest first): {recent}")
1897 streak_id = result.get("streak_fact_id")
1898 streak = next((f for f in result.get("facts") or [] if f.get("id") == streak_id), None)
1899 if streak: 1899 ↛ exitline 1899 didn't return from function 'team_dossier' because the condition on line 1899 was always true
1900 console.print(f"[dim]{streak['text']}[/dim]")
1903@app.command("coverage")
1904def coverage(
1905 season_id: int = typer.Option(None, "--season", help="Season id (default: current)"),
1906 all_rows: bool = typer.Option(False, "--all", help="Every row, not just the gaps"),
1907):
1908 """Are we tracking everything? Expected conferences vs fixtures that arrived.
1910 Every other view of competitions is built from fixtures that showed up, so
1911 none of them can report a conference that sent nothing. This one can.
1912 """
1913 client, _ = get_client()
1914 payload = _api(client.get_competition_coverage, season_id=season_id)
1916 if not payload.get("available", True):
1917 console.print("[red]Coverage could not be read.[/red]")
1918 raise typer.Exit(1)
1920 summary = payload.get("summary") or {}
1921 rows = payload.get("rows") or []
1923 table = Table(title="Competition coverage")
1924 table.add_column("League", style="cyan")
1925 table.add_column("Conference", style="white")
1926 table.add_column("Age", style="dim", no_wrap=True)
1927 table.add_column("Fixtures", justify="right")
1928 table.add_column("Teams", justify="right", style="dim")
1929 table.add_column("Status")
1931 # Undeclared rows are real fixtures in a league nobody wrote expectations
1932 # for. They are context, not a finding, so they stay out of the default
1933 # view — the gaps are what this command is for.
1934 interesting = {"empty", "unexpected"}
1935 shown = rows if all_rows else [r for r in rows if r.get("status") in interesting]
1936 for row in shown:
1937 status = row.get("status")
1938 colour = {
1939 "empty": "red",
1940 "unexpected": "yellow",
1941 "undeclared": "dim",
1942 }.get(status, "green")
1943 table.add_row(
1944 str(row.get("league_name") or "?"),
1945 str(row.get("division_name") or "?"),
1946 str(row.get("age_group_name") or "?"),
1947 str(row.get("fixtures", 0)),
1948 str(row.get("teams_registered", 0)),
1949 f"[{colour}]{status}[/{colour}]",
1950 )
1952 if shown:
1953 console.print(table)
1954 else:
1955 console.print("[green]Every expected conference has fixtures.[/green]")
1957 # The denominator ships with the figure — a coverage percentage without
1958 # one is the aggregate CLAUDE.md rule 3 forbids.
1959 console.print(
1960 f"[dim]{summary.get('covered', 0)} of {summary.get('expected', 0)} expected "
1961 f"brackets covered · {summary.get('empty', 0)} empty · "
1962 f"{summary.get('unexpected', 0)} unexpected[/dim]"
1963 )
1965 # A league nobody wrote expectations for is not the same as a league with
1966 # full coverage, and the report must not let the two look alike.
1967 undeclared = [lg for lg in (payload.get("leagues") or []) if not lg.get("declared")]
1968 for lg in undeclared:
1969 console.print(
1970 f"[yellow]{lg['league']}[/yellow][dim]: no expected coverage on file — "
1971 f"{lg.get('divisions', 0)} division(s) present, so this report cannot say "
1972 "whether anything is missing.[/dim]"
1973 )
1976LEADER_BOARDS = ("pts", "ppg", "gf", "gf_pg", "ga", "ga_pg", "gd", "gd_pg", "unbeaten", "pro_wins")
1979def _leader_cells(row: dict[str, Any]) -> list[str]:
1980 team = row.get("team") or {}
1981 conference = row.get("conference") or "[yellow]no conference[/yellow]"
1982 value = "" if row.get("value") is None else str(row["value"])
1983 if row.get("pro_games") is not None:
1984 value += f" of {row['pro_games']}"
1985 return [
1986 "" if row.get("rank") is None else str(row["rank"]),
1987 str(team.get("name") or "?"),
1988 conference,
1989 str(row.get("gp", 0)),
1990 f"{row.get('w', 0)}-{row.get('d', 0)}-{row.get('l', 0)}",
1991 value,
1992 ]
1995@app.command("leaders")
1996def leaders(
1997 age_group: str = typer.Argument(..., help="Age group, e.g. U15"),
1998 league: str = typer.Option("Homegrown", "--league", "-l", help="League (its Flex is included)"),
1999 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
2000 limit: int = typer.Option(20, "--limit", "-n", min=1, max=50, help="Top N per board"),
2001 board: str = typer.Option(None, "--board", "-b", help=f"One board: {', '.join(LEADER_BOARDS)}"),
2002 as_json: bool = typer.Option(False, "--json", help="Print the raw result"),
2003):
2004 """Cross-conference stat boards for a league and age group (SB-1781).
2006 A stat board, not a ranking: conferences only meet at tournaments.
2007 """
2008 if board is not None and board not in LEADER_BOARDS:
2009 _fail(f"--board must be one of {', '.join(LEADER_BOARDS)}")
2010 client, _ = get_client()
2011 result = _api(client.get_leaderboards, age_group, league=league, season=season, limit=limit)
2012 if as_json:
2013 console.print_json(data=result)
2014 return
2016 # The denominator and the caveat come first (CLAUDE.md rule 3).
2017 cov = result.get("coverage") or {}
2018 season_name = (result.get("season") or {}).get("name", "?")
2019 console.print(f"[bold]{result.get('league')} {age_group.upper()} · {season_name}[/bold]")
2020 console.print(f"[dim]{cov.get('matches', 0)} matches · {cov.get('note', '')}[/dim]")
2021 if result.get("reason"):
2022 console.print(f"[yellow]{result['reason']}[/yellow]")
2023 return
2025 for b in result.get("boards") or []:
2026 if board is not None and b.get("key") != board:
2027 continue
2028 table = Table(title=f"{b.get('title')} · {b.get('key')}")
2029 table.add_column("#", style="dim", no_wrap=True)
2030 table.add_column("Team", style="white")
2031 table.add_column("Conference", style="cyan")
2032 table.add_column("MP", justify="right")
2033 table.add_column("W-D-L", justify="right", style="dim")
2034 table.add_column("Value", justify="right", style="bold")
2035 for row in b.get("rows") or []:
2036 table.add_row(*_leader_cells(row))
2037 unranked = f" · {b['unranked_count']} unranked" if b.get("unranked_count") else ""
2038 if not b.get("rows"):
2039 console.print(f"[dim]{b.get('title')}: nobody ranked yet{unranked}.[/dim]")
2040 continue
2041 table.caption = unranked.lstrip(" ·") or None
2042 console.print(table)
2044 # Listed once, not per board: early in a season that is most teams.
2045 unranked_rows = result.get("unranked") or []
2046 if unranked_rows: 2046 ↛ exitline 2046 didn't return from function 'leaders' because the condition on line 2046 was always true
2047 console.print(
2048 f"\n[dim]Unranked: under {cov.get('min_gp', '?')} matches "
2049 f"({len(unranked_rows)} of {result.get('unranked_count', len(unranked_rows))}, most matches first)[/dim]"
2050 )
2051 table = Table(style="dim")
2052 table.add_column("Team")
2053 table.add_column("Conference")
2054 table.add_column("MP", justify="right")
2055 table.add_column("W-D-L", justify="right")
2056 for row in unranked_rows:
2057 _, name, conference, gp, record, _ = _leader_cells(row)
2058 table.add_row(name, conference, gp, record, style="dim")
2059 console.print(table)
2062RANKING_VIEWS = ("national", "conference")
2065def _ordinal(n: int) -> str:
2066 suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
2067 return f"{n}{suffix}"
2070def _movement(row: dict[str, Any]) -> str:
2071 """Places and points since the run a week earlier. Absent is "—", never "0" (CLAUDE.md rule 2)."""
2072 places, points = row.get("rank_change_7d"), row.get("rating_change_7d")
2073 if places is None and points is None:
2074 return "—"
2075 moved = "—" if places is None else f"▲{places}" if places > 0 else f"▼{-places}" if places < 0 else "="
2076 return f"{moved} · {_dash(points, '{:+d}')}"
2079def _ranking_cells(row: dict[str, Any]) -> list[str]:
2080 conference = row.get("conference") or "[yellow]no conference[/yellow]"
2081 if row.get("conference") and row.get("conference_rank"): 2081 ↛ 2083line 2081 didn't jump to line 2083 because the condition on line 2081 was always true
2082 conference += f" · {_ordinal(row['conference_rank'])}"
2083 badges = [b.replace("_", " ") for b in row.get("badges") or []]
2084 if row.get("pro_academy"):
2085 badges.append("pro academy")
2086 return [
2087 "" if row.get("rank") is None else str(row["rank"]),
2088 str(row.get("team") or "?"),
2089 conference,
2090 f"{row.get('rating', 0):,}",
2091 _movement(row),
2092 f"{row.get('w', 0)}-{row.get('d', 0)}-{row.get('l', 0)}",
2093 str(row.get("mp", 0)),
2094 ", ".join(badges),
2095 ]
2098def _ranking_table(title: str, rows: list[dict[str, Any]]) -> Table:
2099 table = Table(title=title)
2100 table.add_column("#", style="dim", no_wrap=True)
2101 table.add_column("Team", style="white")
2102 table.add_column("Conference", style="cyan")
2103 table.add_column("Rating", justify="right", style="bold")
2104 table.add_column("Move", justify="right")
2105 table.add_column("W-D-L", justify="right", style="dim")
2106 table.add_column("MP", justify="right")
2107 table.add_column("Badges", style="dim")
2108 for row in rows:
2109 table.add_row(*_ranking_cells(row))
2110 return table
2113def _print_rankings(result: dict[str, Any], age_group: str) -> None:
2114 run = result.get("run") or {}
2115 console.print(
2116 f"[bold]MT Power Rating · {result.get('league')} {result.get('age_group') or age_group.upper()} · "
2117 f"{result.get('season') or '?'}[/bold]"
2118 )
2119 # The denominator comes first (CLAUDE.md rule 3).
2120 cov = result.get("coverage") or {}
2121 if cov.get("note"):
2122 console.print(f"[dim]{cov['note']}[/dim]")
2123 if run:
2124 since = result.get("movement_since")
2125 moved = f" · movement since run {since['run_id']}" if since else " · no run a week earlier: no movement"
2126 console.print(
2127 f"[dim]Run {run.get('id')} · computed {str(run.get('computed_at', '?'))[:10]} · "
2128 f"through {run.get('through_date') or '—'}{moved}[/dim]"
2129 )
2130 publication = result.get("publication") or {}
2131 if result.get("reason"):
2132 console.print(f"[yellow]{result['reason']}[/yellow]")
2133 return
2134 if not publication.get("national"):
2135 console.print(f"[yellow]No national list: {publication.get('reason') or 'not yet comparable'}[/yellow]")
2137 teams = result.get("teams") or []
2138 if result.get("view") == "national":
2139 tiers = result.get("tiers") or []
2140 for tier in tiers:
2141 rows = [t for t in teams if t.get("rank") is not None and t.get("tier") == tier["key"]]
2142 if rows:
2143 console.print(_ranking_table(f"{tier['label']} · {tier['min']:,}+", rows))
2144 lowest = min((t["min"] for t in tiers), default=None)
2145 rest = [t for t in teams if t.get("rank") is not None and t.get("tier") is None]
2146 if rest: 2146 ↛ 2148line 2146 didn't jump to line 2148 because the condition on line 2146 was always true
2147 console.print(_ranking_table(f"Below {lowest:,}" if lowest is not None else "Ranked", rest))
2148 apart = [t for t in teams if t.get("rank") is None]
2149 if apart: 2149 ↛ 2158line 2149 didn't jump to line 2158 because the condition on line 2149 was always true
2150 console.print(_ranking_table("Not yet comparable nationally", apart))
2151 else:
2152 groups: dict[str | None, list[dict[str, Any]]] = {}
2153 for t in teams:
2154 groups.setdefault(t.get("conference"), []).append(t)
2155 for name, rows in groups.items():
2156 console.print(_ranking_table(name or "No conference", rows))
2158 unranked = result.get("unranked") or []
2159 if unranked: 2159 ↛ exitline 2159 didn't return from function '_print_rankings' because the condition on line 2159 was always true
2160 console.print(f"\n[dim]Unranked: fewer than {cov.get('min_matches', '?')} matches ({len(unranked)})[/dim]")
2161 table = Table(style="dim")
2162 table.add_column("Team")
2163 table.add_column("Conference")
2164 table.add_column("Matches", justify="right")
2165 for row in unranked:
2166 table.add_row(
2167 str(row.get("team") or "?"),
2168 row.get("conference") or "no conference",
2169 f"{row.get('mp', 0)} of {row.get('needed', '?')}",
2170 style="dim",
2171 )
2172 console.print(table)
2175def _move_score(move: dict[str, Any]) -> str:
2176 if move.get("goals_for") is None or move.get("goals_against") is None: 2176 ↛ 2177line 2176 didn't jump to line 2177 because the condition on line 2176 was never true
2177 return "—"
2178 score = f"{move['goals_for']}-{move['goals_against']}"
2179 if move.get("penalties_for") is not None and move.get("penalties_against") is not None:
2180 score += f" ({move['penalties_for']}-{move['penalties_against']} pens)"
2181 return score
2184def _print_ranking_team(result: dict[str, Any]) -> None:
2185 console.print(
2186 f"[bold]{result.get('team') or result.get('team_id')} · MT Power Rating · {result.get('league')} "
2187 f"{result.get('age_group') or '?'} · {result.get('season') or '?'}[/bold]"
2188 )
2189 if not result.get("in_run"):
2190 console.print(f"[yellow]{result.get('reason') or 'Not in the latest run.'}[/yellow]")
2191 return
2192 where = []
2193 if result.get("rank") is not None: 2193 ↛ 2194line 2193 didn't jump to line 2194 because the condition on line 2193 was never true
2194 where.append(f"national rank {result['rank']}")
2195 if result.get("conference"): 2195 ↛ 2198line 2195 didn't jump to line 2198 because the condition on line 2195 was always true
2196 place = f" · {_ordinal(result['conference_rank'])}" if result.get("conference_rank") else ""
2197 where.append(f"{result['conference']}{place}")
2198 if result.get("tier"): 2198 ↛ 2199line 2198 didn't jump to line 2199 because the condition on line 2198 was never true
2199 where.append(str(result["tier"]).replace("_", " "))
2200 console.print(f"Rating [bold]{result.get('rating', 0):,}[/bold]" + "".join(f" · {w}" for w in where))
2201 console.print(
2202 f"[dim]{result.get('mp', 0)} matches · {result.get('w', 0)}-{result.get('d', 0)}-{result.get('l', 0)} · "
2203 f"{result.get('xconf_mp', 0)} against other conferences[/dim]"
2204 )
2205 if not result.get("ranked"):
2206 mp = result.get("mp", 0)
2207 console.print(f"[yellow]Unranked: {mp} of {mp + (result.get('needed') or 0)} matches[/yellow]")
2208 if result.get("badges"): 2208 ↛ 2210line 2208 didn't jump to line 2210 because the condition on line 2208 was always true
2209 console.print(f"[dim]Badges: {', '.join(b.replace('_', ' ') for b in result['badges'])}[/dim]")
2210 sos = result.get("sos")
2211 if sos:
2212 ranked = f" — {_ordinal(sos['rank'])} toughest of {sos['of']} ({sos['scope']})" if sos.get("rank") else ""
2213 console.print(f"Strength of schedule {sos['rating']:,}{ranked}")
2215 movers = result.get("biggest_movers") or []
2216 if movers: 2216 ↛ 2235line 2216 didn't jump to line 2235 because the condition on line 2216 was always true
2217 table = Table(title="Biggest movers")
2218 table.add_column("Date", style="magenta", no_wrap=True)
2219 table.add_column("Opponent", style="white")
2220 table.add_column("Result", justify="center")
2221 table.add_column("Score", justify="right")
2222 table.add_column("Expected", justify="right", style="dim")
2223 table.add_column("Change", justify="right", style="bold")
2224 for m in movers:
2225 table.add_row(
2226 str(m.get("match_date") or "—"),
2227 str(m.get("opponent") or "?"),
2228 str(m.get("result") or "?"),
2229 _move_score(m),
2230 f"{m.get('expected', 0):.0%}",
2231 f"{m.get('delta', 0):+.1f}",
2232 )
2233 console.print(table)
2235 history = result.get("history") or []
2236 if history: 2236 ↛ exitline 2236 didn't return from function '_print_ranking_team' because the condition on line 2236 was always true
2237 table = Table(title="Weekly history", style="dim")
2238 table.add_column("Run", style="dim")
2239 table.add_column("Computed", no_wrap=True)
2240 table.add_column("Rating", justify="right")
2241 table.add_column("Rank", justify="right")
2242 table.add_column("Conf. rank", justify="right")
2243 for h in history:
2244 table.add_row(
2245 str(h.get("run_id")),
2246 str(h.get("computed_at", "?"))[:10],
2247 f"{h.get('rating', 0):,}",
2248 _dash(h.get("rank")),
2249 _dash(h.get("conference_rank")),
2250 )
2251 console.print(table)
2254@app.command("rankings")
2255def rankings(
2256 target: str = typer.Argument(..., help='Age group, e.g. U17; or "team" followed by a team'),
2257 team: str = typer.Argument(None, help='After "team": team name or id'),
2258 age: str = typer.Option(None, "--age", "-a", help='With "team": the age group, e.g. U15'),
2259 league: str = typer.Option("Homegrown", "--league", "-l", help="Top-level league"),
2260 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
2261 view: str = typer.Option(None, "--view", help="national or conference (national only when published)"),
2262 conference: str = typer.Option(None, "--conference", "-c", help="One conference, e.g. Northeast"),
2263 as_json: bool = typer.Option(False, "--json", help="Print the raw result"),
2264):
2265 """The MT Power Rating (SB-1808): `mt rankings U17`, or `mt rankings team "IFA" --age U15`.
2267 National lists only once the conferences are connected by matches; until
2268 then each conference is ranked on its own.
2269 """
2270 if target.casefold() == "team":
2271 if not team or not age:
2272 _fail('Usage: mt rankings team "<team>" --age U15')
2273 client, _ = get_client()
2274 team_row = _api(resolve_team, client, team)
2275 result = _api(client.get_power_rating_team, team_row["id"], age, league=league, season=season)
2276 if as_json: 2276 ↛ 2277line 2276 didn't jump to line 2277 because the condition on line 2276 was never true
2277 console.print_json(data=result)
2278 return
2279 _print_ranking_team(result)
2280 return
2282 if team is not None:
2283 _fail(f'Unexpected argument {team!r}. For one team: mt rankings team "<team>" --age U15')
2284 if view is not None and view not in RANKING_VIEWS:
2285 _fail(f"--view must be one of {', '.join(RANKING_VIEWS)}")
2286 client, _ = get_client()
2287 result = _api(client.get_power_rating, target, league=league, season=season, view=view, conference=conference)
2288 if as_json:
2289 console.print_json(data=result)
2290 return
2291 _print_rankings(result, target)
2294# The ingest_failures kinds that are feed-vs-person conflicts rather than
2295# names (SB-1787). Mirrors CONFLICT_KINDS in dao/ingest_failures_dao.py: the
2296# CLI is an HTTP client and does not import the DAO layer.
2297_CONFLICT_KINDS = "score_locked,scraped_overrode_manual"
2300@ingest_app.command("failures")
2301def ingest_failures(
2302 since: str = typer.Option(None, "--since", help="ISO timestamp; only names seen since then"),
2303 limit: int = typer.Option(50, "--limit", "-l", help="How many to show"),
2304 conflicts: bool = typer.Option(
2305 False, "--conflicts", help="Matches where the feed disagreed with a person's result, instead"
2306 ),
2307):
2308 """Names the ingest could not resolve, and what each one cost.
2310 --conflicts lists the feed-vs-person disagreements instead (SB-1787): a
2311 locked result the feed tried to change, or a person's score the feed
2312 replaced. One row per match; the sample says what differed.
2313 """
2314 client, _ = get_client()
2315 kind = _CONFLICT_KINDS if conflicts else None
2316 payload = _api(client.get_ingest_failures, since=since, limit=limit, kind=kind)
2317 rows = payload.get("failures") or []
2319 if not rows:
2320 console.print("[green]No open conflicts.[/green]" if conflicts else "[green]Nothing unresolved.[/green]")
2321 return
2323 if conflicts:
2324 table = Table(title="Feed conflicts")
2325 table.add_column("ID", style="cyan", no_wrap=True)
2326 table.add_column("Kind", style="dim")
2327 table.add_column("Match", style="white")
2328 table.add_column("What differed", style="white")
2329 table.add_column("Times", justify="right", style="yellow")
2330 table.add_column("Last seen", style="magenta")
2331 for row in rows:
2332 table.add_row(
2333 str(row.get("id", "?")),
2334 str(row.get("kind", "?")),
2335 str(row.get("raw_name", "?")),
2336 str(row.get("sample") or "—"),
2337 str(row.get("match_count", 0)),
2338 str(row.get("last_seen", "?"))[:10],
2339 )
2340 console.print(table)
2341 console.print("[dim]Close one with [/dim][cyan]mt ingest resolve <id>[/cyan]")
2342 return
2344 table = Table(title="Ingest failures")
2345 table.add_column("ID", style="cyan", no_wrap=True)
2346 table.add_column("Kind", style="dim")
2347 table.add_column("Name", style="white")
2348 table.add_column("League", style="dim")
2349 table.add_column("Matches", justify="right", style="yellow")
2350 table.add_column("Last seen", style="magenta")
2351 table.add_column("", style="dim")
2353 for row in rows:
2354 table.add_row(
2355 str(row.get("id", "?")),
2356 str(row.get("kind", "?")),
2357 str(row.get("raw_name", "?")),
2358 str(row.get("league") or "—"),
2359 str(row.get("match_count", 0)),
2360 str(row.get("last_seen", "?"))[:10],
2361 "stale" if row.get("stale") else "",
2362 )
2364 console.print(table)
2365 console.print(
2366 f"[dim]{payload.get('count', len(rows))} open · {payload.get('matches_dropped', 0)} matches dropped[/dim]"
2367 )
2369 stale_count = payload.get("stale_count") or 0
2370 if stale_count:
2371 # Stale means unseen, not fixed. Saying which is the point.
2372 days = payload.get("stale_after_days")
2373 console.print(
2374 f"[dim]{stale_count} not seen in {days} days. That is not the same as fixed — "
2375 "close one with [/dim][cyan]mt ingest resolve <id>[/cyan]"
2376 )
2379@ingest_app.command("resolve")
2380def ingest_resolve(
2381 failure_id: int = typer.Argument(..., help="Ingest failure id (from mt ingest failures)"),
2382 note: str = typer.Option(None, "--note", "-n", help="Why it is no longer a problem"),
2383):
2384 """Close an ingest failure that was fixed at the sender.
2386 The automatic resolve only fires when the same name resolves later. A name
2387 that will never be submitted again cannot trigger it, so the row would be
2388 reported forever as a problem that no longer exists (SB-845).
2389 """
2390 client, _ = get_client()
2391 row = _api(client.resolve_ingest_failure, failure_id, note)
2393 console.print(f"[green]Resolved #{row.get('id')}[/green] {row.get('raw_name')}")
2394 if row.get("resolution_note"):
2395 console.print(f"[dim]{row['resolution_note']}[/dim]")
2396 console.print("[dim]The row is kept — it is the record of which names were wrong and when.[/dim]")
2399# What `mt ingest plan` sends of each item in the --teams file. A scraper
2400# message carries a dozen more fields; the plan reads none of them.
2401_PLAN_MATCH_FIELDS = ("home_team", "away_team", "age_group", "league", "competition")
2402_PLAN_ENTRY_FIELDS = ("name", "age_group", "league")
2404# Actions sent per request by `mt ingest apply`. Each approved action costs
2405# the server several database round trips; a whole plan in one request can
2406# outlast the HTTP timeout, and a small batch bounds what an interrupted one
2407# leaves in doubt.
2408_APPLY_BATCH = 10
2411def _read_json_file(path: Path, what: str) -> Any:
2412 try:
2413 return json.loads(path.read_text())
2414 except OSError as exc:
2415 console.print(f"[red]Cannot read {what} {path}: {exc.strerror}[/red]")
2416 raise typer.Exit(1) from None
2417 except json.JSONDecodeError as exc:
2418 console.print(f"[red]{what} {path} is not JSON: {exc}[/red]")
2419 raise typer.Exit(1) from None
2422def _plan_teams_payload(items: Any, path: Path) -> list[dict]:
2423 """The --teams file cut down to the fields a plan reads."""
2424 if not isinstance(items, list) or not all(isinstance(item, dict) for item in items): 2424 ↛ 2425line 2424 didn't jump to line 2425 because the condition on line 2424 was never true
2425 console.print(f"[red]{path} must be a JSON list of objects[/red]")
2426 raise typer.Exit(1)
2427 payload = []
2428 for item in items:
2429 fields = _PLAN_MATCH_FIELDS if "home_team" in item or "away_team" in item else _PLAN_ENTRY_FIELDS
2430 payload.append({key: item[key] for key in fields if item.get(key) is not None})
2431 return payload
2434def _print_plan_report(report: dict) -> None:
2435 table = Table(title="Team names by side")
2436 for column, style in (("Side", "white"), ("Entries", "dim"), ("Resolved", "green"), ("Ambiguous", "yellow")):
2437 table.add_column(column, style=style, justify="left" if column == "Side" else "right")
2438 for column in ("Missing", "alias-fixable", "needs-create", "unknown"):
2439 table.add_column(column, justify="right", style="red" if column == "Missing" else "dim")
2440 for name, side in (report.get("sides") or {}).items():
2441 missing = side.get("missing") or {}
2442 table.add_row(
2443 name,
2444 str(side.get("entries", 0)),
2445 str(side.get("resolved", 0)),
2446 str(side.get("ambiguous", 0)),
2447 str(missing.get("total", 0)),
2448 str(missing.get("alias_fixable", 0)),
2449 str(missing.get("needs_create", 0)),
2450 str(missing.get("unknown", 0)),
2451 )
2452 console.print(table)
2454 for name, side in (report.get("sides") or {}).items():
2455 dropped = ("unknown_league", "unknown_age_group")
2456 other = [f"{side[key]} {key.replace('_', ' ')}" for key in dropped if side.get(key)]
2457 if other: 2457 ↛ 2458line 2457 didn't jump to line 2458 because the condition on line 2457 was never true
2458 console.print(f"[yellow]{name}[/yellow][dim]: {', '.join(other)} — ingest drops these matches[/dim]")
2460 matches = report.get("matches")
2461 if matches:
2462 console.print(
2463 f"Matches that would land: [green]{matches['would_land']}[/green] of {matches['total']} now, "
2464 f"[cyan]{matches['would_land_after_plan']}[/cyan] if every action were applied"
2465 )
2466 else:
2467 console.print("[dim]The input carries no matches, so there is no count of matches that would land.[/dim]")
2469 conferences = report.get("conferences") or {}
2470 for row in conferences.get("placed") or []:
2471 console.print(
2472 f"[dim]Conference[/dim] {row['league']} / {row['conference']}: "
2473 f"{row['teams']} team(s), {row['registrations']} age group registration(s)"
2474 )
2475 if conferences.get("unplaced"): 2475 ↛ 2476line 2475 didn't jump to line 2476 because the condition on line 2475 was never true
2476 console.print(
2477 f"[yellow]{conferences['unplaced']} team(s) to create have no conference[/yellow] "
2478 "[dim]— they get a league and no registration, so they appear in no picker[/dim]"
2479 )
2480 for row in conferences.get("unknown") or []:
2481 console.print(f"[yellow]Bracket not used:[/yellow] {row['league']} / {row['conference']} — {row['reason']}")
2483 for row in report.get("ambiguous") or []:
2484 console.print(
2485 f"[yellow]Ambiguous:[/yellow] {row['name']} ({row['age_group']}, {row.get('league') or 'no hint'}) "
2486 f"[dim]{row.get('reason') or ''}[/dim]"
2487 )
2490@ingest_app.command("plan")
2491def ingest_plan(
2492 teams: Path = typer.Option(..., "--teams", help="JSON: scraper dry-run messages, or {name, age_group, league}"),
2493 brackets: Path = typer.Option(None, "--brackets", help="JSON: [{league, conference, age_group, teams}]"),
2494 output: Path = typer.Option(..., "--output", "-o", help="Where to write the plan file"),
2495):
2496 """Report what a tournament's team names resolve to, and propose fixes. Read-only.
2498 Writes the proposed aliases and teams to a plan file. Nothing in it is
2499 applied until someone edits an action's status to "approved" and runs
2500 `mt ingest apply` (SB-1763).
2501 """
2502 payload = _plan_teams_payload(_read_json_file(teams, "teams file"), teams)
2503 bracket_rows = _read_json_file(brackets, "brackets file") if brackets else None
2505 client, state = get_client()
2506 result = _api(client.plan_ingest, payload, bracket_rows)
2508 plan = {
2509 "plan_id": result["plan_id"],
2510 "generated_at": datetime.now(UTC).isoformat(timespec="seconds"),
2511 "generated_by": getattr(state, "username", None),
2512 "environment": get_current_env(),
2513 "database": result.get("database"),
2514 "inputs": {"teams": teams.name, "brackets": brackets.name if brackets else None},
2515 "review": (
2516 'Nothing here is applied as generated. Set "status" to "approved" on each action to apply, '
2517 'and fill in whatever a "needs_review" action asks for first.'
2518 ),
2519 "report": result["report"],
2520 "actions": result["actions"],
2521 }
2522 output.write_text(json.dumps(plan, indent=2, ensure_ascii=False) + "\n")
2524 _print_plan_report(result["report"])
2525 counts = result["report"].get("actions") or {}
2526 for kind, by_status in counts.items():
2527 console.print(
2528 f"{kind}: [green]{by_status.get('proposed', 0)} proposed[/green], "
2529 f"[yellow]{by_status.get('needs_review', 0)} needs review[/yellow]"
2530 )
2531 console.print(f"[green]Plan {plan['plan_id']} written to {output}[/green] — {len(plan['actions'])} action(s)")
2532 console.print(
2533 '[dim]Nothing has been changed. Review the file, set "status": "approved" on the actions to apply, '
2534 "then:[/dim] [cyan]mt ingest apply " + str(output) + " --dry-run[/cyan]"
2535 )
2538_APPLY_STYLES = {
2539 "applied": "green",
2540 "would_apply": "cyan",
2541 "already_applied": "dim",
2542 "refused": "red",
2543 "failed": "red",
2544}
2547def _print_apply_rows(rows: list[dict]) -> None:
2548 for row in rows:
2549 outcome = row.get("outcome")
2550 if outcome == "skipped":
2551 continue
2552 style = _APPLY_STYLES.get(outcome, "white")
2553 detail = row.get("detail") or "; ".join(row.get("steps") or [])
2554 console.print(
2555 f"[{style}]{str(outcome).replace('_', ' ')}[/{style}] "
2556 f"{row.get('id') or '?'} {row.get('type') or '?'} {row.get('external_name') or ''}"
2557 + (f" [dim]— {detail}[/dim]" if detail else "")
2558 )
2561def _applied_log_path(plan_file: Path) -> Path:
2562 """`plan.json` → `plan.applied.json`, beside it."""
2563 return plan_file.with_name(f"{plan_file.stem}.applied.json")
2566def _read_applied_log(path: Path, plan: dict, env: str) -> dict:
2567 """The applied log for this plan: what is there, or a new one.
2569 Stops if the file belongs to another plan — appending to it would mix two
2570 plans' ids in the one record there is of what each created.
2571 """
2572 if not path.exists():
2573 return {"plan_id": plan["plan_id"], "environment": env, "database": plan["database"], "batches": []}
2574 log = _read_json_file(path, "applied log")
2575 if not isinstance(log, dict) or log.get("plan_id") != plan["plan_id"] or not isinstance(log.get("batches"), list):
2576 console.print(
2577 f"[red]{path} is not the applied log of plan {plan['plan_id']}.[/red] "
2578 "[yellow]Move it aside and run again.[/yellow]"
2579 )
2580 raise typer.Exit(1)
2581 return log
2584def _record_applied(path: Path, log: dict, batch: int, response: dict) -> None:
2585 """Append what one batch wrote to the applied log, and save it at once.
2587 `teams` and `team_mappings` carry no creator column, so this file — the
2588 ids each action created or touched — is the record an undo works from.
2589 """
2590 wrote = [
2591 {key: row.get(key) for key in ("id", "type", "external_name", "outcome", "ids", "steps")}
2592 for row in response.get("results") or []
2593 if row.get("ids")
2594 ]
2595 closed = response.get("failures_closed") or []
2596 if not wrote and not closed:
2597 return
2598 log["batches"].append(
2599 {
2600 "batch": batch,
2601 "applied_at": datetime.now(UTC).isoformat(timespec="seconds"),
2602 "actions": wrote,
2603 "failures_closed": closed,
2604 }
2605 )
2606 path.write_text(json.dumps(log, indent=2, ensure_ascii=False) + "\n")
2609@ingest_app.command("apply")
2610def ingest_apply(
2611 plan_file: Path = typer.Argument(..., help="A reviewed plan file from mt ingest plan"),
2612 dry_run: bool = typer.Option(False, "--dry-run", help="Check everything on the server; write nothing"),
2613):
2614 """Apply the approved actions of a reviewed plan. Idempotent (admin).
2616 Only actions whose status is "approved" are applied; the server re-checks
2617 each one and refuses any whose precondition no longer holds or that would
2618 duplicate a team name. What each action created is appended to
2619 <plan>.applied.json beside the plan file (SB-1763).
2620 """
2621 plan = _read_json_file(plan_file, "plan file")
2622 if not isinstance(plan, dict) or not plan.get("plan_id") or not isinstance(plan.get("actions"), list):
2623 console.print(f"[red]{plan_file} is not a plan file: it needs a plan_id and an actions list[/red]")
2624 raise typer.Exit(1)
2626 # Team and club ids are per database: an id from one names a different row
2627 # in another. The server checks the fingerprint; this is the readable half,
2628 # and a plan that does not say where it was made is not taken on trust.
2629 env = get_current_env()
2630 if not plan.get("environment") or not plan.get("database"):
2631 missing = "environment" if not plan.get("environment") else "database"
2632 console.print(
2633 f'[red]{plan_file} has no "{missing}" in its header, so there is no telling which database '
2634 "it was made against.[/red]\n[yellow]Plan again:[/yellow] mt ingest plan --teams … -o …"
2635 )
2636 raise typer.Exit(1)
2637 if plan["environment"] != env:
2638 console.print(
2639 f"[red]This plan was generated against {plan['environment']}, and this command targets {env}.[/red]\n"
2640 f"[yellow]Plan again against {env}, or run:[/yellow] "
2641 f"mt --env {plan['environment']} ingest apply {plan_file}"
2642 )
2643 raise typer.Exit(1)
2645 actions = plan["actions"]
2646 log_path = _applied_log_path(plan_file)
2647 log = None if dry_run else _read_applied_log(log_path, plan, env)
2648 client, _ = get_client()
2650 # A dry run goes as one request: the server then judges two actions that
2651 # share a new club or team as the real run would. A real run goes in
2652 # batches, each reported as it returns.
2653 size = max(len(actions), 1) if dry_run else _APPLY_BATCH
2654 batches = [actions[start : start + size] for start in range(0, len(actions), size)]
2655 counts: Counter = Counter()
2656 closed = 0
2657 for number, batch in enumerate(batches, start=1):
2658 first = (number - 1) * size + 1
2659 label = f"Batch {number} of {len(batches)} (actions {first}-{first + len(batch) - 1})"
2660 try:
2661 response = client.apply_ingest_plan(plan["plan_id"], batch, plan["database"], dry_run)
2662 except (httpx.TransportError, APIError) as exc:
2663 reason = str(exc) or type(exc).__name__
2664 console.print(f"[red]{label} did not complete: {reason}[/red]")
2665 console.print(
2666 f"{number - 1} of {len(batches)} batch(es) completed before it."
2667 + ("" if dry_run else f" What they wrote is in {log_path}.")
2668 )
2669 if not dry_run:
2670 console.print(
2671 "[yellow]This batch may have been partly applied[/yellow] — the server carries on after the "
2672 "client stops waiting. Run the same command again: apply is idempotent, so what is already "
2673 "there is reported as already applied and the rest is finished."
2674 )
2675 raise typer.Exit(1) from None
2677 rows = response.get("results") or []
2678 if len(batches) > 1:
2679 console.print(f"[dim]{label}[/dim]")
2680 _print_apply_rows(rows)
2681 counts.update(row.get("outcome") for row in rows)
2682 closed += len(response.get("failures_closed") or [])
2683 if log is not None:
2684 _record_applied(log_path, log, number, response)
2686 done = "would apply" if dry_run else "applied"
2687 console.print(
2688 f"{counts.get('would_apply' if dry_run else 'applied', 0)} {done} · "
2689 f"{counts.get('already_applied', 0)} already applied · "
2690 f"{counts.get('refused', 0)} refused · {counts.get('failed', 0)} failed"
2691 )
2692 skipped = counts.get("skipped", 0)
2693 if skipped:
2694 console.print(
2695 f"[yellow]{skipped} of {len(actions)} action(s) skipped: not approved.[/yellow] "
2696 '[dim]Set "status": "approved" in the plan file to apply one.[/dim]'
2697 )
2698 if dry_run:
2699 console.print("[dim]Dry run: nothing was written.[/dim]")
2700 else:
2701 if closed:
2702 console.print(f"[green]{closed} ingest failure(s) closed[/green] [dim](note: plan {plan['plan_id']})[/dim]")
2703 if log and log["batches"]:
2704 console.print(f"[dim]What was written is recorded in {log_path} — commit it with the plan.[/dim]")
2705 if counts.get("refused") or counts.get("failed"):
2706 raise typer.Exit(1)
2709@ai_app.command("gaps")
2710def ai_gaps(
2711 days: int = typer.Option(30, "--days", "-d", help="How far back to look"),
2712 tool: str = typer.Option(None, "--tool", "-t", help="One tool only, e.g. search_teams"),
2713 limit: int = typer.Option(50, "--limit", "-l", help="How many to show"),
2714):
2715 """What MT AI could not answer: not_found and ambiguous tool calls, most asked first.
2717 A not_found name that is a real team wants an alias; a recurring one is an
2718 eval case; a recurring question no tool answers is the next tool (SB-1308).
2719 """
2720 client, _ = get_client()
2721 payload = _api(client.get_ai_gaps, days=days, tool=tool)
2722 rows = payload.get("gaps") or []
2723 total = payload.get("total_calls")
2725 if not rows:
2726 console.print(f"[green]Nothing unanswered in the last {payload.get('days', days)} days.[/green]")
2727 if total is not None: 2727 ↛ 2729line 2727 didn't jump to line 2729 because the condition on line 2727 was always true
2728 console.print(f"[dim]{total} tool call(s) in that window.[/dim]")
2729 return
2731 table = Table(title=f"MT AI gaps — last {payload.get('days', days)} days")
2732 table.add_column("Tool", style="dim")
2733 table.add_column("Query", style="white")
2734 table.add_column("Age", style="dim")
2735 table.add_column("Asked", justify="right", style="yellow")
2736 table.add_column("Not found", justify="right")
2737 table.add_column("Ambiguous", justify="right")
2738 table.add_column("Last seen", style="magenta")
2740 for row in rows[:limit]:
2741 table.add_row(
2742 str(row.get("tool", "?")),
2743 str(row.get("query") or "—"),
2744 ", ".join(row.get("age_groups") or []) or "—",
2745 str(row.get("count", 0)),
2746 str(row.get("not_found", 0)),
2747 str(row.get("ambiguous", 0)),
2748 str(row.get("last_seen") or "?")[:10],
2749 )
2751 console.print(table)
2752 # The denominator ships with the figure (CLAUDE.md rule 3).
2753 of_total = f" of {total} tool calls" if total is not None else ""
2754 console.print(
2755 f"[dim]{payload.get('gap_calls', 0)} unanswered{of_total} · {payload.get('count', len(rows))} distinct"
2756 + (f" · showing {limit}" if len(rows) > limit else "")
2757 + "[/dim]"
2758 )
2759 if payload.get("truncated"): 2759 ↛ 2760line 2759 didn't jump to line 2760 because the condition on line 2759 was never true
2760 console.print("[yellow]Hit the row cap — narrow with --days or --tool.[/yellow]")
2763@app.command("competitions")
2764def competitions():
2765 """The competitions the API knows, and which of them qualify for the cup.
2767 `-c` on team stats and team matches accepts any of these, but nothing else
2768 told you what they were — which is how six Flex fixtures stayed invisible
2769 for a day.
2770 """
2771 client, _ = get_client()
2772 types = _api(client.get_match_types) or []
2774 if not types:
2775 console.print("[yellow]No competitions configured.[/yellow]")
2776 return
2778 table = Table(title="Competitions")
2779 table.add_column("ID", style="cyan", no_wrap=True)
2780 table.add_column("Name", style="white")
2781 table.add_column("Qualifies", justify="center", style="green")
2782 table.add_column("Shootout pts", justify="center", style="magenta")
2783 table.add_column("Table", justify="center", style="blue")
2785 for t in types:
2786 table.add_row(
2787 str(t.get("id", "?")),
2788 str(t.get("name", "?")),
2789 "yes" if t.get("counts_for_qualification") else "",
2790 "2 / 1" if t.get("shootout_points") else "",
2791 "yes" if t.get("has_standings") else "",
2792 )
2794 console.print(table)
2795 if any(t.get("shootout_points") for t in types): 2795 ↛ 2796line 2795 didn't jump to line 2796 because the condition on line 2795 was never true
2796 console.print("[dim]Shootout pts: a match level after regulation goes to penalties; winner 2, loser 1.[/dim]")
2797 console.print(f"[dim]Also accepted by -c: '{QUALIFYING}' (every qualifying competition) and 'all'.[/dim]")
2800@match_app.command("show")
2801def match_show(match_id: int = typer.Argument(..., help="Match ID")):
2802 """One match: status, lineups and events."""
2803 client, _ = get_client()
2805 match = _api(client.get_game, match_id)
2807 status = match.get("match_status", "?")
2808 counts = status in ("live", "completed", "forfeit")
2809 console.print(
2810 Panel(
2811 f"[bold]{match.get('home_team_name', '?')}[/bold] vs [bold]{match.get('away_team_name', '?')}[/bold]\n"
2812 f"{match.get('match_date', '?')} · status [yellow]{status}[/yellow]\n"
2813 f"Counts towards season stats: {'[green]yes[/green]' if counts else '[red]no[/red]'}",
2814 title=f"Match {match_id}",
2815 )
2816 )
2818 for side in ("home", "away"):
2819 team_id = match.get(f"{side}_team_id")
2820 if not team_id: 2820 ↛ 2821line 2820 didn't jump to line 2821 because the condition on line 2820 was never true
2821 continue
2822 try:
2823 lineup = client.get_lineup(match_id, team_id)
2824 except APIError:
2825 lineup = None
2826 positions = (lineup or {}).get("positions") or []
2827 label = match.get(f"{side}_team_name", side)
2828 if not positions: 2828 ↛ 2829line 2828 didn't jump to line 2829 because the condition on line 2828 was never true
2829 console.print(f"[dim]{label}: no lineup saved[/dim]")
2830 continue
2831 table = Table(title=f"{label} lineup ({len(positions)})")
2832 table.add_column("Position", style="dim")
2833 table.add_column("Player", style="white")
2834 for pos in positions:
2835 table.add_row(str(pos.get("position", "?")), _player_label(pos))
2836 console.print(table)
2838 try:
2839 events = client.get_match_events(match_id) or []
2840 except APIError:
2841 events = []
2842 if events: 2842 ↛ 2843line 2842 didn't jump to line 2843 because the condition on line 2842 was never true
2843 table = Table(title="Events")
2844 table.add_column("Min", justify="right", style="dim")
2845 table.add_column("Type", style="yellow")
2846 table.add_column("Message", style="white")
2847 for e in reversed(events):
2848 table.add_row(str(e.get("match_minute") or "-"), str(e.get("event_type", "?")), str(e.get("message", "")))
2849 console.print(table)
2851 # Appearance rows are not exposed by the API, so this shows who was listed,
2852 # not who is counted. Saying so beats implying completeness.
2853 console.print("[dim]Per-player appearance records are not exposed by the API; lineup shown instead.[/dim]")
2856@player_app.command("stats")
2857def player_stats(
2858 player_id: int = typer.Argument(..., help="Roster player id"),
2859 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
2860):
2861 """A player's season line."""
2862 client, _ = get_client()
2864 season_row = _api(resolve_season, client, season)
2866 stats = _api(client.get_roster_player_stats, player_id, season_id=(season_row or {}).get("id"))
2867 if not stats: 2867 ↛ 2868line 2867 didn't jump to line 2868 because the condition on line 2867 was never true
2868 console.print("[yellow]No stats for that player.[/yellow]")
2869 return
2871 table = Table(title=f"Player {player_id} · {(season_row or {}).get('name', '?')}")
2872 for label, _f in STAT_FIELDS:
2873 table.add_column(label, justify="right", style="cyan")
2874 table.add_row(*[str(stats.get(f) or 0) for _, f in STAT_FIELDS])
2875 console.print(table)
2878# ---------------------------------------------------------------------------
2879# Team and club admin writes (SB-824)
2880#
2881# `team` was read-only, so a season's identity changes — renames, new clubs —
2882# had to be clicked through Admin forms. Rollover is a scripted, repeatable,
2883# reviewable operation, and it happens against a deadline.
2884# ---------------------------------------------------------------------------
2887# U19 is id 7; there is no id 6. Resolved by name so nobody has to know that.
2888def _resolve_division_id(client, term: str) -> int:
2889 """Resolve a division name (e.g. 'Northeast') to its id."""
2890 if str(term).isdigit(): 2890 ↛ 2891line 2890 didn't jump to line 2891 because the condition on line 2890 was never true
2891 return int(term)
2892 divisions = _api(client.get_divisions) or []
2893 needle = str(term).lower().strip()
2894 for d in divisions:
2895 if (d.get("name") or "").lower().strip() == needle:
2896 return d["id"]
2897 matches = [d for d in divisions if needle in (d.get("name") or "").lower()]
2898 if len(matches) == 1: 2898 ↛ 2899line 2898 didn't jump to line 2899 because the condition on line 2898 was never true
2899 return matches[0]["id"]
2900 available = ", ".join(sorted({d.get("name", "?") for d in divisions}))
2901 raise ResolutionError(f"Division {term!r} not found. Available: {available}")
2904def _resolve_club(client, term: str) -> dict:
2905 """One club, by id or name."""
2906 if str(term).isdigit():
2907 target = int(term)
2908 for c in _api(client.get_clubs) or []: 2908 ↛ 2911line 2908 didn't jump to line 2911 because the loop on line 2908 didn't complete
2909 if c.get("id") == target:
2910 return c
2911 raise ResolutionError(f"No club with id {target}")
2913 clubs = _api(client.get_clubs) or []
2914 needle = term.lower().strip()
2915 exact = [c for c in clubs if (c.get("name") or "").lower().strip() == needle]
2916 if len(exact) == 1:
2917 return exact[0]
2918 matches = [c for c in clubs if needle in (c.get("name") or "").lower()]
2919 if len(matches) == 1: 2919 ↛ 2920line 2919 didn't jump to line 2920 because the condition on line 2919 was never true
2920 return matches[0]
2921 if len(matches) > 1:
2922 names = ", ".join(c.get("name", "?") for c in matches[:6])
2923 raise ResolutionError(f"{len(matches)} clubs match {term!r}: {names}")
2924 raise ResolutionError(f"No club matches {term!r}")
2927@team_app.command("rename")
2928def team_rename(
2929 team: str = typer.Argument(..., help="Team name or id"),
2930 name: str = typer.Option(..., "--name", "-n", help="New team name"),
2931 yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
2932):
2933 """Rename a team, preserving its club, city and academy flag.
2935 Renaming is safe for history: matches reference teams by id, not by name,
2936 so every past fixture follows the team.
2937 """
2938 client, _ = get_client()
2939 current = _api(resolve_team, client, team)
2940 old_name = current.get("name")
2942 if old_name == name:
2943 console.print(f"[yellow]{old_name!r} already has that name.[/yellow]")
2944 return
2946 console.print(f"[bold]{old_name}[/bold] -> [bold]{name}[/bold] (team #{current['id']})")
2947 console.print(f"[dim]club_id {current.get('club_id')} and city {current.get('city')!r} preserved[/dim]")
2948 if not yes and not typer.confirm("Apply?"): 2948 ↛ 2949line 2948 didn't jump to line 2949 because the condition on line 2948 was never true
2949 raise typer.Exit(1)
2951 updated = _api(
2952 client.update_team_profile,
2953 current["id"],
2954 name=name,
2955 city=current.get("city") or "",
2956 academy_team=bool(current.get("academy_team")),
2957 club_id=current.get("club_id"),
2958 )
2959 console.print(f"[green]Renamed team #{current['id']}[/green] -> {updated.get('name', name)}")
2960 console.print(
2961 f"[dim]Record the old name so a stale feed cannot re-split it:[/dim] "
2962 f'mt team alias add {current["id"]} --alias "{old_name}" --kind former_name'
2963 )
2966@team_app.command("set-club")
2967def team_set_club(
2968 team: str = typer.Argument(..., help="Team name or id"),
2969 club: str = typer.Option(..., "--club", "-c", help="Club name or id"),
2970 yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
2971):
2972 """Point a team at a different club. Crest and colours come from the club."""
2973 client, _ = get_client()
2974 current = _api(resolve_team, client, team)
2975 target = _api(_resolve_club, client, club)
2977 console.print(
2978 f"[bold]{current.get('name')}[/bold] club {current.get('club_id')} -> "
2979 f"{target['id']} ([bold]{target.get('name')}[/bold])"
2980 )
2981 if not yes and not typer.confirm("Apply?"): 2981 ↛ 2982line 2981 didn't jump to line 2982 because the condition on line 2981 was never true
2982 raise typer.Exit(1)
2984 _api(
2985 client.update_team_profile,
2986 current["id"],
2987 name=current.get("name"),
2988 city=current.get("city") or "",
2989 academy_team=bool(current.get("academy_team")),
2990 club_id=target["id"],
2991 )
2992 console.print(f"[green]{current.get('name')} now belongs to {target.get('name')}[/green]")
2995def _print_merge(result: dict, title: str) -> list[dict]:
2996 """The per-table counts of a merge, then its blockers. Returns the blockers."""
2997 tables = result.get("tables") or {}
2998 # A blocked dry run can stop before counting anything; an empty table
2999 # would read as "nothing references this".
3000 if tables:
3001 table = Table(title=title)
3002 table.add_column("Table", style="cyan")
3003 table.add_column("Moved", justify="right")
3004 table.add_column("Dropped", justify="right")
3005 for name, counts in sorted(tables.items()):
3006 moved, dropped = counts.get("moved", 0), counts.get("dropped", 0)
3007 style = None if moved or dropped else "dim"
3008 table.add_row(name, str(moved), str(dropped), style=style)
3009 console.print(table)
3010 console.print("[dim]dropped = the target already had that row, or it is derived and gets recomputed[/dim]")
3012 blockers = result.get("blockers") or []
3013 for b in blockers:
3014 ref = ", ".join(f"{k} {v}" for k, v in b.items() if k not in ("kind", "detail"))
3015 console.print(f"[red]blocked[/red] {b.get('kind')}: {b.get('detail')} ({ref})")
3016 return blockers
3019def _resolve_exact(items: list[dict], term: str, kind: str) -> dict:
3020 """One row by id or by its exact full name (case-insensitive).
3022 Merges delete a row, so the near-miss matching every other command offers
3023 is refused here: "City SC" must not quietly become "City SC San Diego".
3024 """
3025 if str(term).isdigit():
3026 target = int(term)
3027 for item in items:
3028 if item.get("id") == target:
3029 return item
3030 raise ResolutionError(f"No {kind} with id {target}")
3031 needle = term.lower().strip()
3032 exact = [i for i in items if (i.get("name") or "").lower().strip() == needle]
3033 if len(exact) == 1:
3034 return exact[0]
3035 if exact:
3036 ids = ", ".join(f"#{i['id']}" for i in exact)
3037 raise ResolutionError(f"{len(exact)} {kind}s are named {term!r} ({ids}); use the id")
3038 raise ResolutionError(f"No {kind} named exactly {term!r}; merges need the exact name or the id")
3041def _run_merge(kind: str, source: dict, target: dict, merge_fn, yes: bool) -> dict:
3042 """Dry run, show it, confirm, then merge for real. Shared by team and club."""
3043 if source["id"] == target["id"]:
3044 _fail(f"Both arguments are {kind} #{source['id']}")
3046 console.print(
3047 f"[bold]{source.get('name')}[/bold] ({kind} #{source['id']}) -> "
3048 f"[bold]{target.get('name')}[/bold] ({kind} #{target['id']})"
3049 )
3050 preview = _api(merge_fn, source["id"], target["id"], dry_run=True)
3051 blockers = _print_merge(preview, f"Dry run: merge {kind} #{source['id']} into #{target['id']}")
3052 # A dry run stops early at the first constraint it trips (often the one a
3053 # blocker names); the payload says which, as a SQLSTATE and table.
3054 error = preview.get("error") or {}
3055 if error:
3056 where = ", ".join(f"{k} {v}" for k, v in error.items())
3057 console.print(f"[yellow]dry run stopped early: {where}[/yellow]")
3058 if blockers:
3059 _fail(f"{len(blockers)} blocker(s); nothing was changed. Resolve them and run again.")
3060 if not preview.get("complete", True):
3061 _fail("The dry run did not complete; nothing was changed.")
3063 if not yes and not typer.confirm(f"Merge and delete {kind} #{source['id']}?"):
3064 raise typer.Exit(1)
3065 result = _api(merge_fn, source["id"], target["id"], dry_run=False)
3066 console.print(f"[green]Merged {kind} #{source['id']} into #{target['id']} ({target.get('name')})[/green]")
3067 return result
3070@team_app.command("merge")
3071def team_merge(
3072 source: str = typer.Argument(..., help="Duplicate team (id or exact name) — deleted after the merge"),
3073 target: str = typer.Argument(..., help="Team to keep (id or exact name)"),
3074 yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation after the dry run"),
3075):
3076 """Fold a duplicate team into the one to keep (SB-1822).
3078 Matches, mappings, aliases, rosters, managers and follows move to the
3079 target; rows the target already has are dropped, and power ratings are
3080 dropped for the next run to recompute. The duplicate's name is kept as a
3081 former_name alias, so the feed resolves either spelling. Always shows a
3082 dry run first.
3083 """
3084 client, _ = get_client()
3085 teams = _api(client.get_teams) or []
3086 src = _api(_resolve_exact, teams, source, "team")
3087 dst = _api(_resolve_exact, teams, target, "team")
3088 result = _run_merge("team", src, dst, client.merge_team, yes)
3089 alias = result.get("alias")
3090 if alias == "added": 3090 ↛ 3092line 3090 didn't jump to line 3092 because the condition on line 3090 was always true
3091 console.print(f"[dim]{src.get('name')!r} kept as a former_name alias of #{dst['id']}[/dim]")
3092 elif alias == "exists":
3093 console.print(f"[dim]{src.get('name')!r} was already an alias of #{dst['id']}; left as it was[/dim]")
3094 copied = result.get("copied") or []
3095 if copied: 3095 ↛ exitline 3095 didn't return from function 'team_merge' because the condition on line 3095 was always true
3096 console.print(f"[dim]copied from #{src['id']} because #{dst['id']} had none: {', '.join(copied)}[/dim]")
3099@team_app.command("create")
3100def team_create(
3101 name: str = typer.Option(..., "--name", "-n", help="Team name (globally unique)"),
3102 city: str = typer.Option("", "--city", help="City"),
3103 division: str = typer.Option(..., "--division", "-d", help="Division name or id"),
3104 age: list[str] = typer.Option(..., "--age", "-a", help="Age group, repeatable (e.g. -a U13 -a U14)"),
3105 club: str = typer.Option(None, "--club", "-c", help="Club name or id"),
3106 academy: bool = typer.Option(False, "--academy", help="Mark as an academy team"),
3107):
3108 """Create a team.
3110 One team row covers every age group it plays — teams.name is globally
3111 unique, so a row per age group is impossible. The age groups given here
3112 become team_mappings rows, and league_id is derived from the division.
3113 """
3114 client, _ = get_client()
3115 age_group_ids = [_resolve_age_group_id(client, a) for a in age]
3116 division_id = _api(_resolve_division_id, client, division)
3117 club_row = _api(_resolve_club, client, club) if club else None
3119 payload = Team(
3120 name=name,
3121 city=city,
3122 age_group_ids=age_group_ids,
3123 division_id=division_id,
3124 club_id=(club_row or {}).get("id"),
3125 academy_team=academy,
3126 )
3127 created = _api(client.create_team, payload)
3128 team_row = created.get("team", created)
3129 console.print(f"[green]Created team #{team_row.get('id')}:[/green] {name}")
3130 console.print(f"[dim]division {division_id}, age groups {age_group_ids}, club {(club_row or {}).get('id')}[/dim]")
3133def _mapping_rows(team: dict) -> list[dict]:
3134 """The team's registrations, flattened for display."""
3135 rows = []
3136 for mapping in team.get("team_mappings") or []:
3137 age_group = mapping.get("age_groups") or {}
3138 division = mapping.get("divisions") or {}
3139 rows.append(
3140 {
3141 "age_group": age_group.get("name") or "?",
3142 "age_group_id": age_group.get("id"),
3143 "division": division.get("name") or "?",
3144 "division_id": division.get("id"),
3145 "league": (division.get("leagues") or {}).get("name") or "?",
3146 }
3147 )
3148 return sorted(rows, key=lambda r: (r["age_group"], r["league"], r["division"]))
3151def _print_mappings(team: dict) -> None:
3152 rows = _mapping_rows(team)
3153 if not rows:
3154 console.print(f"[yellow]{team.get('name')} is registered in no age group.[/yellow]")
3155 console.print("[dim]It will not appear in any age-group team picker until it is.[/dim]")
3156 return
3158 table = Table(title=f"Registrations — {team.get('name')}")
3159 table.add_column("Age Group", style="cyan", no_wrap=True)
3160 table.add_column("League", style="white")
3161 table.add_column("Division", style="white")
3162 for row in rows:
3163 table.add_row(row["age_group"], row["league"], row["division"])
3164 console.print(table)
3167@mapping_app.command("list")
3168def team_mapping_list(team: str = typer.Argument(..., help="Team name or id")):
3169 """Which age groups and divisions a team is registered in.
3171 This is what /api/teams turns into a team's age_groups, and what every
3172 age-group team picker filters on. A team with matches at an age group it is
3173 not registered in is invisible there (SB-852).
3174 """
3175 client, _ = get_client()
3176 _print_mappings(_api(resolve_team, client, team))
3179@mapping_app.command("add")
3180def team_mapping_add(
3181 team: str = typer.Argument(..., help="Team name or id"),
3182 age: str = typer.Option(..., "--age", "-a", help="Age group, e.g. U15"),
3183 division: str = typer.Option(..., "--division", "-d", help="Division name or id"),
3184):
3185 """Register a team in an age group and division."""
3186 client, _ = get_client()
3188 team_row = _api(resolve_team, client, team)
3189 age_group_id = _resolve_age_group_id(client, age)
3190 division_id = _api(_resolve_division_id, client, division)
3192 _api(client.create_team_mapping, team_row["id"], age_group_id, division_id)
3193 console.print(f"[green]Registered {team_row.get('name')}[/green] · {age} · division {division_id}")
3195 # Re-read and print rather than claim success and stop. The Admin UI's
3196 # equivalent shows a stale list after writing, which reads as a failed save
3197 # and invites a duplicate attempt — worth not repeating here.
3198 _print_mappings(_api(resolve_team, client, team_row["id"]))
3201@mapping_app.command("remove")
3202def team_mapping_remove(
3203 team: str = typer.Argument(..., help="Team name or id"),
3204 age: str = typer.Option(..., "--age", "-a", help="Age group, e.g. U15"),
3205 division: str = typer.Option(..., "--division", "-d", help="Division name or id"),
3206):
3207 """Remove a team's registration in an age group and division.
3209 The matches stay. This only says the team no longer plays there, which is
3210 what the age-group pickers read.
3211 """
3212 client, _ = get_client()
3214 team_row = _api(resolve_team, client, team)
3215 age_group_id = _resolve_age_group_id(client, age)
3216 division_id = _api(_resolve_division_id, client, division)
3218 _api(client.delete_team_mapping, team_row["id"], age_group_id, division_id)
3219 console.print(f"[green]Removed registration[/green] {team_row.get('name')} · {age} · division {division_id}")
3220 _print_mappings(_api(resolve_team, client, team_row["id"]))
3223def _resolve_division_in_league(client, name: str, league: str) -> int:
3224 """A division by name within one league.
3226 Names repeat across leagues: "New England" is both an Academy conference and
3227 a Flex conference, so a name alone could hide a team from the wrong table.
3228 """
3229 needle = name.lower().strip()
3230 found = [
3231 d
3232 for d in _api(client.get_divisions) or []
3233 if (d.get("name") or "").lower().strip() == needle
3234 and ((d.get("leagues") or {}).get("name") or "").lower() == league.lower().strip()
3235 ]
3236 if len(found) != 1:
3237 raise ResolutionError(f"Expected one {league} division named {name!r}, found {len(found)}")
3238 return found[0]["id"]
3241def _print_guests(client, season_id: int, age_group_id: int | None = None) -> None:
3242 guests = _api(client.list_division_guests, season_id, age_group_id) or []
3243 if not guests:
3244 console.print("[dim]No guests: every team that plays in a table has a row.[/dim]")
3245 return
3246 table = Table(title="Division guests — no table row, results still count for opponents")
3247 for column in ("ID", "Team", "Age", "League", "Division", "Reason"):
3248 table.add_column(column)
3249 for guest in guests:
3250 division = guest.get("division") or {}
3251 table.add_row(
3252 str(guest["id"]),
3253 (guest.get("team") or {}).get("name") or "?",
3254 (guest.get("age_group") or {}).get("name") or "?",
3255 (division.get("leagues") or {}).get("name") or "?",
3256 division.get("name") or "?",
3257 guest.get("reason") or "",
3258 )
3259 console.print(table)
3262def _guest_target(client, team: str, age: str, division: str, league: str, season: str | None):
3263 team_row = _api(resolve_team, client, team)
3264 age_group_id = _resolve_age_group_id(client, age)
3265 try:
3266 division_id = _resolve_division_in_league(client, division, league)
3267 except ResolutionError as e:
3268 console.print(f"[red]{e}[/red]")
3269 raise typer.Exit(1) from e
3270 season_id = _resolve_season_id(client, season)
3271 return team_row, division_id, age_group_id, season_id
3274@guest_app.command("list")
3275def team_guest_list(
3276 age: str = typer.Option(None, "--age", "-a", help="Age group, e.g. U15"),
3277 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
3278):
3279 """Which teams have no row in a table they play fixtures in."""
3280 client, _ = get_client()
3281 _print_guests(client, _resolve_season_id(client, season), _resolve_age_group_id(client, age) if age else None)
3284@guest_app.command("add")
3285def team_guest_add(
3286 team: str = typer.Argument(..., help="Team name or id"),
3287 age: str = typer.Option(..., "--age", "-a", help="Age group, e.g. U15"),
3288 division: str = typer.Option(..., "--division", "-d", help="Division name"),
3289 reason: str = typer.Option(..., "--reason", "-r", help="Why this team is not in the table"),
3290 league: str = typer.Option("Flex", "--league", "-l", help="League the division belongs to"),
3291 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
3292):
3293 """Hide a team from one table. Its matches still count for its opponents."""
3294 client, _ = get_client()
3295 team_row, division_id, age_group_id, season_id = _guest_target(client, team, age, division, league, season)
3296 _api(client.add_division_guest, team_row["id"], division_id, age_group_id, season_id, reason)
3297 console.print(f"[green]{team_row.get('name')} has no row[/green] in {age} {league} {division}")
3298 _print_guests(client, season_id, age_group_id)
3301@guest_app.command("remove")
3302def team_guest_remove(
3303 team: str = typer.Argument(..., help="Team name or id"),
3304 age: str = typer.Option(..., "--age", "-a", help="Age group, e.g. U15"),
3305 division: str = typer.Option(..., "--division", "-d", help="Division name"),
3306 league: str = typer.Option("Flex", "--league", "-l", help="League the division belongs to"),
3307 season: str = typer.Option(None, "--season", "-s", help="Season name (default: current)"),
3308):
3309 """Give a team its row in a table back."""
3310 client, _ = get_client()
3311 team_row, division_id, age_group_id, season_id = _guest_target(client, team, age, division, league, season)
3312 guests = _api(client.list_division_guests, season_id, age_group_id) or []
3313 guest = next((g for g in guests if g["team_id"] == team_row["id"] and g["division_id"] == division_id), None)
3314 if guest is None:
3315 console.print(f"[yellow]{team_row.get('name')} is not a guest in {age} {league} {division}.[/yellow]")
3316 raise typer.Exit(1)
3317 _api(client.remove_division_guest, guest["id"])
3318 console.print(f"[green]{team_row.get('name')} has its row back[/green] in {age} {league} {division}")
3319 _print_guests(client, season_id, age_group_id)
3322@club_app.command("list")
3323def club_list(
3324 search: str = typer.Argument(None, help="Filter by name substring"),
3325):
3326 """List clubs."""
3327 client, _ = get_client()
3328 clubs = _api(client.get_clubs) or []
3329 if search:
3330 needle = search.lower()
3331 clubs = [c for c in clubs if needle in (c.get("name") or "").lower()]
3332 if not clubs:
3333 console.print("[yellow]No clubs.[/yellow]")
3334 return
3335 table = Table(title=f"Clubs ({len(clubs)})")
3336 table.add_column("id", justify="right")
3337 table.add_column("name")
3338 table.add_column("city")
3339 for c in sorted(clubs, key=lambda x: (x.get("name") or "").lower()):
3340 table.add_row(str(c.get("id")), c.get("name") or "", c.get("city") or "")
3341 console.print(table)
3344@club_app.command("create")
3345def club_create(
3346 name: str = typer.Option(..., "--name", "-n", help="Club name (unique)"),
3347 city: str = typer.Option(None, "--city", help="City"),
3348 pro_academy: bool = typer.Option(False, "--pro-academy", help="Mark as a professional club academy (MLS academy)"),
3349):
3350 """Create a club. Crest and colours are set afterwards in the Admin UI."""
3351 client, _ = get_client()
3352 created = _api(client.create_club, name=name, city=city, pro_academy=pro_academy)
3353 club_row = created.get("club", created)
3354 console.print(f"[green]Created club #{club_row.get('id')}:[/green] {name}")
3355 console.print(f'[dim]Attach a team:[/dim] mt team create --name "..." --club {club_row.get("id")}')
3358def _print_club(club: dict) -> None:
3359 """A club's fields, including the ones a careless write would blank."""
3360 table = Table(title=f"Club #{club.get('id')} — {club.get('name')}", show_header=False)
3361 table.add_column("Field", style="cyan")
3362 table.add_column("Value", style="white")
3363 for label, key in (
3364 ("City", "city"),
3365 ("Website", "website"),
3366 ("Description", "description"),
3367 ("Crest", "logo_url"),
3368 ("Primary", "primary_color"),
3369 ("Secondary", "secondary_color"),
3370 ):
3371 table.add_row(label, str(club.get(key) or "—"))
3372 table.add_row("Pro academy", "yes" if club.get("pro_academy") else "no")
3373 console.print(table)
3376@club_app.command("show")
3377def club_show(club: str = typer.Argument(..., help="Club name or id")):
3378 """One club, with every field a write has to preserve.
3380 There was no way to read a club from the CLI, which is why correcting one
3381 meant querying the database first (SB-872).
3382 """
3383 client, _ = get_client()
3384 _print_club(_api(_resolve_club, client, club))
3387@club_app.command("set-pro-academy")
3388def club_set_pro_academy(
3389 club: str = typer.Argument(..., help="Club name or id"),
3390 on: bool = typer.Option(True, "--on/--off", help="Flag or unflag the club"),
3391):
3392 """Mark a club as an MLS pro academy, or unmark it.
3394 `mt club create` takes --pro-academy; nothing could set it afterwards, so a
3395 club that already existed had to be corrected by hand through
3396 update_club_profile (SB-872).
3398 PUT /api/clubs/{id} is a **replace, not a patch**: every field it is not
3399 given is blanked. So this reads the club first and resends all of it,
3400 changing only the flag. Omitting logo_url and the brand colours is how a
3401 crest gets destroyed — SB-824 and SB-842 are both that bug.
3402 """
3403 client, _ = get_client()
3404 current = _api(_resolve_club, client, club)
3406 if bool(current.get("pro_academy")) == on:
3407 console.print(f"[yellow]{current.get('name')} is already {'flagged' if on else 'unflagged'}.[/yellow]")
3408 return
3410 updated = _api(
3411 client.update_club_profile,
3412 current["id"],
3413 current.get("name"),
3414 current.get("city") or "",
3415 current.get("website"),
3416 current.get("description"),
3417 current.get("logo_url"),
3418 current.get("primary_color"),
3419 current.get("secondary_color"),
3420 on,
3421 )
3423 was = "yes" if current.get("pro_academy") else "no"
3424 now = "yes" if updated.get("pro_academy") else "no"
3425 console.print(f"[green]{current.get('name')}[/green] pro academy: {was} → {now}")
3426 console.print("[dim]Every other field was read and resent unchanged.[/dim]")
3427 _print_club(updated)
3430@club_app.command("rename")
3431def club_rename(
3432 club: str = typer.Argument(..., help="Club name or id"),
3433 name: str = typer.Option(..., "--name", "-n", help="New club name"),
3434 yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
3435):
3436 """Rename a club.
3438 Teams keep pointing at it by id, so their crest and colours are unaffected.
3439 """
3440 client, _ = get_client()
3441 current = _api(_resolve_club, client, club)
3442 if current.get("name") == name: 3442 ↛ 3443line 3442 didn't jump to line 3443 because the condition on line 3442 was never true
3443 console.print(f"[yellow]{name!r} already has that name.[/yellow]")
3444 return
3446 console.print(f"[bold]{current.get('name')}[/bold] -> [bold]{name}[/bold] (club #{current['id']})")
3447 if not yes and not typer.confirm("Apply?"): 3447 ↛ 3448line 3447 didn't jump to line 3448 because the condition on line 3447 was never true
3448 raise typer.Exit(1)
3450 # Read-then-resend: PUT /api/clubs/{id} replaces the whole record, so
3451 # anything omitted is blanked — including logo_url and the brand colours
3452 # the IG cards read.
3453 full = _api(client.get_club, current["id"]) or current
3454 _api(
3455 client.update_club_profile,
3456 current["id"],
3457 name=name,
3458 city=full.get("city") or "",
3459 website=full.get("website"),
3460 description=full.get("description"),
3461 logo_url=full.get("logo_url"),
3462 primary_color=full.get("primary_color"),
3463 secondary_color=full.get("secondary_color"),
3464 pro_academy=bool(full.get("pro_academy")),
3465 )
3466 console.print(f"[green]Renamed club #{current['id']}[/green] -> {name}")
3467 console.print("[dim]crest, colours and pro-academy flag preserved[/dim]")
3470# The server's own limits for POST /api/clubs/{id}/logo, checked here so a bad
3471# file fails before it is sent rather than as a 400 after.
3472LOGO_SUFFIXES = {".png", ".jpg", ".jpeg"}
3473LOGO_MAX_BYTES = 2 * 1024 * 1024
3475_HEX_COLOUR = re.compile(r"^#[0-9A-Fa-f]{6}$")
3478@club_app.command("set-logo")
3479def club_set_logo(
3480 club: str = typer.Argument(..., help="Club name or id"),
3481 file: Path = typer.Argument(..., help="PNG or JPG crest, 2MB at most"),
3482 if_missing: bool = typer.Option(False, "--if-missing", help="Do nothing if the club already has a crest"),
3483 yes: bool = typer.Option(False, "--yes", "-y", help="Replace an existing crest without asking"),
3484):
3485 """Upload a club's crest.
3487 The server stores it, writes the 64px and 128px variants the app and IG
3488 cards use, and sets logo_url itself — so unlike set-colors this is not a
3489 read-modify-write, and nothing else on the club changes (SB-1777).
3490 """
3491 if not file.is_file():
3492 _fail(f"No such file: {file}")
3493 if file.suffix.lower() not in LOGO_SUFFIXES:
3494 _fail(f"Crest must be PNG or JPG, got {file.suffix or 'no extension'}")
3495 size = file.stat().st_size
3496 if size > LOGO_MAX_BYTES:
3497 _fail(f"Crest is {size / 1024 / 1024:.2f}MB; the server takes 2MB at most")
3499 client, _ = get_client()
3500 current = _api(_resolve_club, client, club)
3501 name = current.get("name")
3503 if current.get("logo_url"):
3504 if if_missing:
3505 console.print(f"[yellow]{name} already has a crest; left alone (--if-missing).[/yellow]")
3506 return
3507 console.print(f"{name} already has a crest: {current['logo_url']}")
3508 if not yes and not typer.confirm("Replace it?"):
3509 raise typer.Exit(1)
3511 result = _api(client.upload_club_logo, current["id"], str(file))
3512 console.print(f"[green]{name}[/green] (club #{current['id']}) crest set: {result.get('logo_url')}")
3515@club_app.command("set-colors")
3516def club_set_colors(
3517 club: str = typer.Argument(..., help="Club name or id"),
3518 primary: str | None = typer.Option(None, "--primary", "-p", help="Primary colour, #RRGGBB"),
3519 secondary: str | None = typer.Option(None, "--secondary", "-s", help="Secondary colour, #RRGGBB"),
3520):
3521 """Set a club's brand colours, which the IG cards and team headers use.
3523 PUT /api/clubs/{id} is a replace, not a patch, so this reads the club and
3524 resends every field, changing only the colours given. Sending a subset is
3525 how a crest gets blanked (SB-824, SB-842).
3526 """
3527 if primary is None and secondary is None:
3528 _fail("Give --primary, --secondary or both")
3529 for label, value in (("primary", primary), ("secondary", secondary)):
3530 if value is not None and not _HEX_COLOUR.match(value):
3531 _fail(f"{label} colour must look like #1E3A8A, got {value!r}")
3533 client, _ = get_client()
3534 current = _api(_resolve_club, client, club)
3535 full = _api(client.get_club, current["id"]) or current
3537 new_primary = primary.upper() if primary else full.get("primary_color")
3538 new_secondary = secondary.upper() if secondary else full.get("secondary_color")
3540 updated = _api(
3541 client.update_club_profile,
3542 current["id"],
3543 name=full.get("name"),
3544 city=full.get("city") or "",
3545 website=full.get("website"),
3546 description=full.get("description"),
3547 logo_url=full.get("logo_url"),
3548 primary_color=new_primary,
3549 secondary_color=new_secondary,
3550 pro_academy=bool(full.get("pro_academy")),
3551 )
3552 console.print(
3553 f"[green]{full.get('name')}[/green] colours: "
3554 f"{full.get('primary_color')} / {full.get('secondary_color')} → {new_primary} / {new_secondary}"
3555 )
3556 console.print("[dim]crest, website, description and pro-academy flag preserved[/dim]")
3557 _print_club(updated or full)
3560@club_app.command("merge")
3561def club_merge(
3562 source: str = typer.Argument(..., help="Duplicate club (id or exact name) — deleted after the merge"),
3563 target: str = typer.Argument(..., help="Club to keep (id or exact name)"),
3564 yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation after the dry run"),
3565):
3566 """Fold a duplicate club into the one to keep (SB-1822).
3568 Teams, members, invitations and channels move to the target. The target
3569 keeps its own crest and colours; the duplicate's only fill ones it lacks.
3570 Merge duplicate teams first (mt team merge) — a team of the same name in
3571 both clubs blocks this. Always shows a dry run first.
3572 """
3573 client, _ = get_client()
3574 clubs = _api(client.get_clubs) or []
3575 src = _api(_resolve_exact, clubs, source, "club")
3576 dst = _api(_resolve_exact, clubs, target, "club")
3577 result = _run_merge("club", src, dst, client.merge_club, yes)
3578 copied = result.get("copied") or []
3579 if copied: 3579 ↛ exitline 3579 didn't return from function 'club_merge' because the condition on line 3579 was always true
3580 console.print(f"[dim]copied from #{src['id']} because #{dst['id']} had none: {', '.join(copied)}[/dim]")
3583@club_app.command("logo-gaps")
3584def club_logo_gaps(
3585 season_id: int = typer.Option(None, "--season", help="Season id (default: current)"),
3586 include_all: bool = typer.Option(False, "--all", help="Every team and club, not only those with matches"),
3587):
3588 """Where crests are missing: teams with no club, clubs with no logo, hot-linked logos (SB-1815).
3590 Scoped to teams with a match in the season and their clubs, so the list
3591 is what visitors actually see. A hot-linked logo is one not stored in our
3592 club-logos bucket — it breaks whenever the other site changes.
3593 """
3594 client, _ = get_client()
3595 payload = _api(client.get_club_logo_gaps, season_id=season_id, include_all=include_all)
3596 scope = "every team and club" if include_all else f"teams with matches in season {payload.get('season_id')}"
3597 console.print(f"[dim]Scope: {scope}[/dim]")
3599 teams = payload.get("teams_without_club") or []
3600 console.print(f"\n[bold]Teams with no club[/bold] ({len(teams)})")
3601 for t in teams:
3602 console.print(f" #{t['id']:<5} {t.get('name')} [dim]{t.get('match_count', 0)} matches[/dim]")
3603 if not teams:
3604 console.print(" none")
3606 missing = payload.get("clubs_without_logo") or []
3607 console.print(f"\n[bold]Clubs with no logo[/bold] ({len(missing)})")
3608 for c in missing:
3609 console.print(f" #{c['id']:<5} {c.get('name')}")
3610 if not missing:
3611 console.print(" none")
3613 external = payload.get("clubs_external_logo") or []
3614 console.print(f"\n[bold]Clubs with a hot-linked logo[/bold] ({len(external)})")
3615 for c in external:
3616 console.print(f" #{c['id']:<5} {c.get('name')} [dim]{c.get('host') or c.get('logo_url')}[/dim]")
3617 if not external:
3618 console.print(" none")
3619 if external:
3620 console.print("\n[dim]Fix one with: mt club set-logo <club> <file>[/dim]")
3623@alias_app.command("add")
3624def team_alias_add(
3625 team: str = typer.Argument(..., help="Team name or id"),
3626 alias: str = typer.Option(..., "--alias", "-a", help="String that should resolve to this team"),
3627 kind: str = typer.Option("feed_variant", "--kind", "-k", help="feed_variant | former_name"),
3628 source: str = typer.Option("mlssoccer.com", "--source", "-s", help="Which feed uses this spelling"),
3629):
3630 """Record a string that should resolve to this team.
3632 Makes a rename durable: once the old name is recorded, a stale feed
3633 carrying it resolves to the renamed team instead of creating a second one.
3634 """
3635 client, _ = get_client()
3636 if kind not in ("feed_variant", "former_name"):
3637 console.print("[red]--kind must be feed_variant or former_name[/red]")
3638 raise typer.Exit(1)
3640 current = _api(resolve_team, client, team)
3641 _api(client.add_team_alias, current["id"], external_name=alias, source=source, kind=kind)
3642 console.print(f"[green]{alias!r} now resolves to[/green] {current.get('name')} (#{current['id']})")
3645@alias_app.command("list")
3646def team_alias_list(team: str = typer.Argument(..., help="Team name or id")):
3647 """Every alternate string that resolves to a team."""
3648 client, _ = get_client()
3649 current = _api(resolve_team, client, team)
3650 aliases = (_api(client.get_team_aliases, current["id"]) or {}).get("aliases", [])
3651 if not aliases:
3652 console.print(f"[yellow]No aliases for {current.get('name')}.[/yellow]")
3653 return
3654 table = Table(title=f"Aliases for {current.get('name')}")
3655 table.add_column("alias")
3656 table.add_column("kind")
3657 table.add_column("source")
3658 for a in aliases:
3659 table.add_row(a.get("external_name") or "", a.get("kind") or "", a.get("source") or "")
3660 console.print(table)
3663if __name__ == "__main__":
3664 app()