krz/nba-scores
A CLI/TUI app for NBA scores.
clone: git clone https://gitbay.org/krz/nba-scores.git
1"""
2Fetches and formats the NBA playoff picture.
3"""
4
5import json
6
7from nba_api.stats.endpoints.playoffpicture import PlayoffPicture
8from tabulate import tabulate
9
10BOLD = "\033[1m"
11END = "\033[0m"
12RED = "\033[91m"
13GREEN = "\033[32m"
14YELLOW = "\033[33m"
15
16
17def fetch_playoff_picture() -> dict:
18 endpoint = PlayoffPicture()
19 return json.loads(endpoint.get_json())
20
21
22def _clinch_status(row: list, idx: dict) -> str:
23 """Return a color-coded status string from clinch/elimination columns."""
24
25 def val(col):
26 return row[idx[col]] if col in idx else None
27
28 if val("CLINCHED_CONFERENCE"):
29 return f"{BOLD}{GREEN}z-Clinched Conf{END}"
30 if val("CLINCHED_DIVISION") or val("CLINCHED_PLAYOFFS"):
31 return f"{GREEN}x-Clinched{END}"
32 if val("Clinched_Play_In"):
33 return f"{YELLOW}pi-Play-In{END}"
34 if val("ELIMINATED_PLAYOFFS"):
35 return f"{RED}e-Eliminated{END}"
36 return ""
37
38
39def _build_conference_table(result_sets: list, name: str) -> str:
40 """Build a formatted playoff standings table for one conference."""
41 rs = next((r for r in result_sets if r["name"] == name), None)
42 if rs is None or not rs["rowSet"]:
43 return "No data available."
44
45 headers = rs["headers"]
46 rows = rs["rowSet"]
47 idx = {h: i for i, h in enumerate(headers)}
48
49 def get(row, col, default=""):
50 return row[idx[col]] if col in idx else default
51
52 table_data = []
53 for row in rows:
54 wins = get(row, "WINS")
55 losses = get(row, "LOSSES")
56 pct = get(row, "PCT")
57 pct_str = f"{float(pct):.3f}" if pct not in ("", None) else ""
58 table_data.append(
59 [
60 get(row, "RANK"),
61 get(row, "TEAM"),
62 f"{wins}-{losses}",
63 pct_str,
64 get(row, "GB"),
65 get(row, "HOME"),
66 get(row, "AWAY"),
67 get(row, "CONF"),
68 _clinch_status(row, idx),
69 ]
70 )
71
72 display_headers = [
73 "#",
74 "Team",
75 "W-L",
76 "PCT",
77 "GB",
78 "HOME",
79 "AWAY",
80 "CONF",
81 "Status",
82 ]
83 conf_label = "Eastern" if "East" in name else "Western"
84 title = f"{BOLD}{conf_label} Conference Playoff Picture:{END}"
85 return title + "\n" + tabulate(table_data, headers=display_headers, tablefmt="grid")
86
87
88def get_west_playoff_table(data: dict) -> str:
89 return _build_conference_table(data["resultSets"], "WestConfStandings")
90
91
92def get_east_playoff_table(data: dict) -> str:
93 return _build_conference_table(data["resultSets"], "EastConfStandings")