"""Q-39: Turn a table into an action card -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q39-action-card/
Data:     https://apopt.com/data/tutorials/q39-action-card/ (keep raw/ next to this file)
"""

# %% [markdown]
# A results table answers "what was measured". An **action card** answers what the athlete
# should do: five lines, written for them (the course's case-study template):
#
# 1. **Finding**: the one thing the data showed.
# 2. **Evidence**: the numbers behind it, in the athlete's units.
# 3. **How sure**: in words, with the reason.
# 4. **Action**: one thing to do, specific enough to do tomorrow.
# 5. **Retest**: when and how to look again.
#
# The table is Chapter 10's **synthetic** set of ten jump shots by one player: five measures
# from the basketball app's results files for each shot, and whether it went in. The player's
# question: what separates my makes from my misses?
#
# ### The table, made against missed

# %%
# Medians of made and missed shots
import numpy as np
import pandas as pd

shots = pd.read_csv("raw/shot_trials_synthetic.csv")
METRICS = ["Ball Release Angle", "Ball Release Height", "Elbow Angle", "Knee Flexion", "Release Timing vs Apex"]
made, missed = shots[shots["made"] == 1], shots[shots["made"] == 0]
print(f"{len(shots)} shots, {len(made)} made")
print(pd.DataFrame({"made median": made[METRICS].median(), "missed median": missed[METRICS].median()}).to_string())

# %% [markdown]
# A difference in medians is not yet a finding. With six makes and four misses, the
# **probability of superiority** (Section 10.6) says how often a made shot beats a missed one
# on a measure (0.5 means no difference), and a bootstrap gives it a range.

# %%
# Probability of superiority, with a range, for every measure
rng = np.random.default_rng(493)

def superiority(a, b):
    diff = a[:, None] - b[None, :]                  # every made shot against every missed shot
    return (diff > 0).mean() + 0.5 * (diff == 0).mean()

rows = []
for m in METRICS:
    a, b = made[m].to_numpy(), missed[m].to_numpy()
    boot = [superiority(rng.choice(a, a.size), rng.choice(b, b.size)) for _ in range(2000)]
    lo, hi = np.percentile(boot, [2.5, 97.5])
    rows.append({"measure": m, "A": superiority(a, b), "low": lo, "high": hi,
                 "clear": not lo <= 0.5 <= hi})
table = pd.DataFrame(rows).sort_values("A", key=lambda s: (s - 0.5).abs(), ascending=False)
print(table.round(2).to_string(index=False))

# %% [markdown]
# ### From the table to the card
#
# The card is filled from the table by rules, so the words cannot claim more than the numbers:
# a measure goes in the finding only if its range leaves out 0.5; otherwise the finding says so,
# and the action is to collect what would decide it.

# %%
# Five lines for the player
import matplotlib.pyplot as plt

UNITS = {"Release Timing vs Apex": "ms; minus is before the top of the jump"}
PLAIN = {("Release Timing vs Apex", "lower"): "let the ball go earlier, on the way up"}
SIDE = {"Release Timing vs Apex": {"lower": "earlier", "higher": "later"}}
top = table.iloc[0]
m = top["measure"]
share, side = (top["A"], "higher") if top["A"] >= 0.5 else (1 - top["A"], "lower")
said = PLAIN.get((m, side), f"had a {side} {m.lower()}")
card = {"Finding": f"On your makes you {said}." if top["clear"] else "No measure separates your makes from your misses yet.",
        "Evidence": f"{m}: median {made[m].median():.1f} on makes, {missed[m].median():.1f} on misses "
                    f"({UNITS.get(m, 'app units')}); the make was {SIDE.get(m, {}).get(side, side)} in {share:.0%} of make-miss pairs.",
        "How sure": (f"Moderate: ten shots in one session, and {len(table)} measures checked, so one clear result could be luck."
                     if top["clear"] else "Unclear: every range includes no difference."),
        "Action": "Next session, aim to let the ball go on the way up, before the top of your jump.",
        "Retest": "Film 20 more shots from the same spot over two sessions and rerun this card."}
for k, v in card.items():
    print(f"{k:9s} {v}")

fig, ax = plt.subplots(figsize=(6.0, 2.2))
for y, d, fill in [(1, made, "black"), (0, missed, "white")]:
    ax.plot(d[m], [y] * len(d), "o", mfc=fill, mec="black", ms=8)
    ax.plot([d[m].median()] * 2, [y - 0.3, y + 0.3], "-" if y else "--", color="black")
ax.set(yticks=[0, 1], yticklabels=["missed", "made"], ylim=(-0.6, 1.6), xlabel=f"{m.lower()} ({UNITS.get(m, 'app units')})",
       title="Makes left the hand earlier before the top")
plt.tight_layout()

# %% [markdown]
# The release angle, the measure the chapter looked at first, does not separate the shots: its
# range runs from 0.33 to 1.00. Release timing does: in 96% of make-miss pairs the make left the
# hand earlier before the top of the jump, and release height points the same way. Two cautions
# go on the card in words, not numbers: ten shots from one session, and five measures checked,
# so one clear result could still be luck. That is why the action is one small change and the
# retest is already booked. Had no range left out 0.5, the rule would have written "not yet",
# which is a finding too.
#
# **For the athlete:** "On your makes you let the ball go a little earlier, on the way up; try
# that on purpose next session, and we will film 20 more to see if it holds."
