"""CS-18: A one-page progress report -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs18-progress-report/
Data:     https://apopt.com/data/tutorials/cs18-progress-report/ (keep raw/ next to this file)
"""

# %% [markdown]
# CS-15 decided, from a twelve-week record, that the athlete's jump had likely improved. That
# decision is useless until the athlete and the coach can read it in a minute. This case study
# turns the same **simulated** record into the one-page report of Section 13.4: question,
# answer, one chart, evidence, how sure, one limit, one recommendation, a retest date, and a
# footer that says who may see it. Every number on the page is produced from the record by the
# code below, so none can be copied wrong.
#
# ### Step 3 · Visualize: the record, on one scale
#
# First repeat CS-15's rules in one cell: weeks 3 to 6 are the baseline, a session is the mean
# of its jumps, and the new phone of weeks 11–12 is put on the old phone's scale with the offset
# measured by the bridge in week 12.

# %%
# Step 3 · CS-15's rules, applied in one cell
import os
import numpy as np
import pandas as pd

rec = pd.read_csv("raw/athlete-record-simulated.csv")
jump = rec[rec["metric"] == "jump_height_cm"].dropna(subset=["value"]).copy()
jump["week"] = pd.factorize(jump["date"])[0] + 1
pair = jump[jump["week"] == 12].pivot(index="trial", columns="device", values="value")
offset = (pair["phone-60fps"] - pair["phone-120fps"]).mean()          # the bridge
jump["height"] = jump["value"] - np.where(jump["device"] == "phone-60fps", offset, 0)
jump = jump[~((jump["week"] == 12) & (jump["device"] == "phone-60fps"))]  # week 12: keep the old phone
weekly = jump.groupby("week")["height"].mean()
base = weekly.loc[3:6]
te, swc = base.std(), 0.65                                            # as in CS-15
late = weekly.loc[9:12]
change = late.mean() - base.mean()
se = te * np.sqrt(1 / len(late) + 1 / len(base))
print(f"bridge offset {offset:.2f} cm; baseline {base.mean():.2f} cm, typical error {te:.2f}, SWC {swc}")
print(f"weeks 9-12: {late.mean():.2f} cm; change {change:+.2f} cm, standard error {se:.2f}")
os.makedirs("clean", exist_ok=True)
rec.dropna(subset=["value"]).to_csv("clean/athlete-record.csv", index=False)   # rows with a value

# %% [markdown]
# ### Step 3 · The one chart
#
# Section 13.5 gives five rules: one message as the title; the athlete's own baseline as the
# reference; the single jumps as well as the means; nothing that depends on color; and no
# digits the test cannot support. The band is the baseline mean ± one typical error, the dashed
# line the smallest worthwhile change above it, as in CS-15.

# %%
# Step 3 · The progress chart, to the template
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

def progress_chart(ax):
    ax.axhspan(base.mean() - te, base.mean() + te, color="0.88", lw=0)
    ax.axhline(base.mean() + swc, color="0.3", ls="--", lw=0.8)
    ax.axvspan(6.5, 10.5, fill=False, hatch="////", edgecolor="0.85", lw=0)
    ax.text(8.5, 0.04, "jump block", ha="center", fontsize=7, transform=ax.get_xaxis_transform())
    ax.text(4.55, base.mean() - te + 0.1, "your usual range (weeks 3-6)", fontsize=7)
    ax.text(12.4, base.mean() + swc + 0.08, "worth having", fontsize=7, ha="right")
    ax.plot(jump["week"], jump["height"], ".", color="0.6", ms=4)
    ax.plot(weekly.index, weekly, "-o", color="black", ms=4, lw=1.2)
    ax.plot([11], [weekly.loc[11]], "o", mfc="white", mec="black", ms=6)        # corrected by the bridge
    ax.set(xlabel="week", ylabel="jump height (cm)", xticks=range(1, 13))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.set_title(f"Your jump rose about {change:.0f} cm and stayed up", fontsize=10)

fig, ax = plt.subplots(figsize=(6.0, 3.0))
progress_chart(ax)
plt.tight_layout()

# %% [markdown]
# Week 11 is drawn open: its value comes through the bridge correction, and the page says so.
# Week 12 is the old phone's own reading of the bridge jumps. Weeks 1 and 2 stay on the chart but outside the band's weeks; they were practice.
# The record itself, every row with a value, can also be explored below.

# %% [markdown]
# ### Step 9 · Deploy: the words, with the uncertainty
#
# Use one named scale of likelihood words for the whole report. This report uses Chapter 13's
# calibrated scale (Table 13.4), whose words a reader outside sport science already meets. CS-15
# used the sport-science scale of Chapter 11, which calls the same chance "likely"; the page
# names its scale and gives the number, so a reader of either can check.

# %%
# Step 9 · The range, the chance and the word
from scipy.stats import norm

WORDS = [(0.99, "virtually certain"), (0.90, "very likely"), (0.66, "likely"),
         (0.33, "about as likely as not"), (0.10, "unlikely"), (0.0, "very unlikely")]
p = 1 - norm.cdf((swc - change) / se)                   # chance of a gain worth having
word = next(w for cut, w in WORDS if p >= cut)
lo, hi = change - 1.645 * se, change + 1.645 * se       # 90% range of the change
answer = f"Yes. About {late.mean():.0f} cm over the last four Mondays, up from about {base.mean():.0f} cm before the block."
how_sure = (f"The rise is somewhere between {lo:.1f} and {hi:.1f} cm. Your Mondays usually vary by about "
            f"{te:.0f} cm, so it is {word} ({p:.0%}) that the rise is more than the {swc} cm we agreed was worth having.")
print(answer)
print(how_sure)

# %% [markdown]
# Read the second sentence against the rules of Section 13.3. It gives the range in the
# athlete's units, rounded to what the test supports; the noise in plain words; one likelihood
# word with its number; and the threshold that was agreed in advance.
#
# ### Step 9 · Deploy: the page
#
# The page follows the order of Section 13.4, which is the order of the reader's questions.
# The text is built first, every number formatted from the record; then the page is drawn with
# matplotlib on a letter-size sheet and saved as PNG (to send to a phone) and PDF (to print).

# %%
# Step 9 · The page's text, every number from the record
import textwrap

LINES = [
    ("Question", "Did the four-week jump block (weeks 7-10) raise your countermovement jump, and did it hold?"),
    ("Answer", answer),
    (None, None),                                               # the chart goes here
    ("Evidence", f"Three jumps every Monday for 12 weeks with the jump app, filmed from the side at 3 m. "
                 f"Baseline weeks 3-6 ({base.mean():.1f} cm); weeks 1-2 were practice. Weeks 11-12 used a new phone, "
                 f"which reads {offset:.1f} cm high on the same jumps (week-12 bridge); week 11 is corrected for it."),
    ("How sure", how_sure),
    ("One limit", "The new phone needed a correction measured from only three jumps."),
    ("One recommendation", "Keep the jump work in your plan. Film every Monday with the new phone, from the same spot."),
    ("Retest", "Monday of week 16, three jumps, same phone and spot, after the usual warm-up."),
]
for head, body in LINES:
    print(f"{head}: {body}" if head else "[the chart]")

# %%
# Step 9 · Draw the page, save it as PNG and PDF
page = plt.figure(figsize=(8.5, 11))
page.text(0.07, 0.95, "Countermovement jump: progress report", fontsize=16, weight="bold")
page.text(0.93, 0.95, "week 12 | simulated athlete", fontsize=9, ha="right", color="0.3")
y = 0.90
for head, body in LINES:
    if head is None:
        progress_chart(page.add_axes([0.12, y - 0.33, 0.80, 0.30]))
        y -= 0.39
        continue
    page.text(0.07, y, head + ".", fontsize=10.5, weight="bold", va="top")
    page.text(0.31, y, "\n".join(textwrap.wrap(body, 68)), fontsize=10, va="top", linespacing=1.4)
    y -= 0.021 * (len(textwrap.wrap(body, 68)) + 0.7)
page.text(0.07, 0.025, "\n".join(textwrap.wrap(
    "Training information, not a medical assessment. Likelihood words: Chapter 13 calibrated scale. "
    "Who sees this page: you and your coach, nobody else without your OK. SIMULATED data for teaching.", 110)),
    fontsize=8, color="0.3")
page.savefig("progress_report.png", dpi=110)
page.savefig("progress_report.pdf")
print("wrote progress_report.png and progress_report.pdf")

# %% [markdown]
# ### Step 9 · Read it back
#
# Section 13.12 lists the errors between a measurement and a sentence. Two are removed already:
# every number on the page came from the record by code, and the chart was drawn to a fixed
# template. The last check is a person: read each sentence against its number, and ask the
# athlete to say the finding back in their own words. If they say "my jump went up about two
# centimeters and it's probably real", the page worked.
