"""CS-17: From a notebook to a page an athlete can open -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# Every case study so far ends in a notebook. An athlete will not open a notebook. This one
# moves one calculation, the force of each foot plant from its timing (Section 3.7.2, CS-12),
# into the form a phone page needs: a JavaScript function that refuses bad input, tested
# against the Python version on the same normal, missing and invalid cases (Section 12.4.4).
# Then it asks what changes when the same function reads a whole file afterwards (**batch**)
# or one step at a time as it happens (**streaming**).
#
# ### Step 1 · Gather
#
# The raw file is the book's ankle trace of a runner on a treadmill, filmed from behind at 30
# frames per second (Chapter 9): one row per frame, with the image height of each ankle. A
# contact is where the ankle sits lowest in the image (largest *y*); Chapter 9's percentile rule
# finds it. Each contact is followed by a flight that ends at the other foot's next contact.

# %%
# Step 1 · From an ankle trace to a table of foot plants
import os
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30.0
ank = pd.read_csv("raw/form1_ankles.csv")
rows = []
for side in "lr":
    y = ank[f"{side}_ankle_y"].rolling(3, center=True, min_periods=1).mean().to_numpy()
    hi, lo = np.percentile(y, 85), np.percentile(y, 70)       # bottom 15% and 30% of the foot's range
    for p in find_peaks(y, height=hi, distance=int(0.2 * FPS))[0]:
        i, j = p, p
        while i > 0 and y[i - 1] >= lo: i -= 1
        while j < len(y) - 1 and y[j + 1] >= lo: j += 1
        rows.append({"side": side, "first": i, "last": j})
plants = pd.DataFrame(rows).sort_values("first").reset_index(drop=True)
plants["contact_s"] = (plants["last"] - plants["first"] + 1) / FPS
plants["flight_s"] = (plants["first"].shift(-1) - plants["last"] - 1) / FPS   # to the next contact
plants["t_s"] = plants["first"] / FPS
os.makedirs("clean", exist_ok=True)
plants.to_csv("clean/foot_plants.csv", index=False)
print(f"{len(plants)} foot plants ({(plants['side'] == 'l').sum()} left, {(plants['side'] == 'r').sum()} right)")
print(plants.head(3).round(3).to_string(index=False))
print(plants.tail(2).round(3).to_string(index=False))
print("contact times seen (s):", sorted(float(v) for v in plants["contact_s"].round(3).unique()))

# %% [markdown]
# Three facts about this table decide how the function must behave. Times come in whole
# frames, so a contact is 0.167, 0.200 or 0.233 s and nothing between. The first contact starts
# on frame 0, so it may have begun before the clip did. And the last plant has no flight: the
# clip ends before the next foot lands, so that value is **missing**.
#
# ### Step 9 · The function, with its rules
#
# The page will receive numbers typed by a person or read from a file, so the function checks
# its input before computing. It returns a value and a message, never a wrong number:
#
# * **missing**: a contact or flight time is absent;
# * **invalid**: times that look like milliseconds, a contact outside the 0.08 to 0.45 s that the
#   running app accepts as a stance (Chapter 9), or a negative flight (feet overlapping, as in
#   walking, where the model does not apply).

# %%
# Step 9 · The force function in Python, rules first
import math

def foot_force(contact_s, flight_s):
    """Peak vertical force of one foot plant, in body weights, or a message saying why not."""
    if any(v is None or not math.isfinite(v) for v in (contact_s, flight_s)):
        return None, "Missing contact or flight time."
    if contact_s > 2:
        return None, "Times look like milliseconds; enter seconds."
    if not 0.08 <= contact_s <= 0.45:
        return None, "Contact time outside 0.08-0.45 s: not a running step."
    if flight_s < 0:
        return None, "Negative flight: the feet overlap, as in walking."
    return math.pi / 2 * (1 + flight_s / contact_s), None

out = [foot_force(c, f) for c, f in zip(plants["contact_s"], plants["flight_s"])]
plants["force_bw"] = [v for v, _ in out]
plants["message"] = [m for _, m in out]
print(plants.groupby("side")["force_bw"].agg(["count", "mean", "min", "max"]).round(2).to_string())
print("refused:", plants.loc[plants["force_bw"].isna(), ["side", "t_s", "message"]].to_string(index=False))
step = 0.200 + 0.133
print(f"one frame shorter contact, same step: {foot_force(0.200, 0.133)[0]:.2f} -> {foot_force(0.167, step - 0.167)[0]:.2f} BW")

# %% [markdown]
# The right foot reads about 0.2 body weights higher than the left on average. Before calling
# that an asymmetry, look at what one frame does: the same step with a contact one frame
# shorter reads about 20% higher, half a body weight. At 30 frames per second a left–right
# difference of 0.2 is inside the frame budget of Chapter 9, and the page must say so (Step 9
# below).
#
# The same function in JavaScript, for the page. Each rule has the same words, in the same
# order, so the two can be compared message for message:
#
# ```js
# // force.js: peak force of one foot plant in body weights, or a message (Section 3.7.2)
# export function footForce(contactS, flightS) {
#   if (!Number.isFinite(contactS) || !Number.isFinite(flightS))
#     return { value: null, message: 'Missing contact or flight time.' };
#   if (contactS > 2) return { value: null, message: 'Times look like milliseconds; enter seconds.' };
#   if (contactS < 0.08 || contactS > 0.45)
#     return { value: null, message: 'Contact time outside 0.08-0.45 s: not a running step.' };
#   if (flightS < 0) return { value: null, message: 'Negative flight: the feet overlap, as in walking.' };
#   return { value: (Math.PI / 2) * (1 + flightS / contactS), message: null };
# }
# ```
#
# ### Step 9 · Normal, missing and invalid: the tests
#
# The expected behavior of each case is written down first. The normal case is the book's hand
# calculation (contact 0.25 s, flight 0.099 s: 2.19 body weights).

# %%
# Step 9 · Eight cases, expected answers first
NAN = float("nan")
CASES = [  # name, contact_s, flight_s, expected value (or None), expected message start
    ("normal: book runner", 0.25, 0.099, 2.1928, None),
    ("normal: this clip", 0.200, 0.133, 2.6154, None),
    ("missing: no flight", 0.200, NAN, None, "Missing"),
    ("missing: no contact", NAN, 0.133, None, "Missing"),
    ("invalid: milliseconds", 200, 133, None, "Times look like milliseconds"),
    ("invalid: walking contact", 0.60, 0.10, None, "Contact time outside"),
    ("invalid: zero contact", 0.0, 0.10, None, "Contact time outside"),
    ("invalid: negative flight", 0.20, -0.05, None, "Negative flight"),
]
for name, c, f, want, msg in CASES:
    value, message = foot_force(c, f)
    if want is None:
        assert value is None and message.startswith(msg), name
    else:
        assert message is None and abs(value - want) < 1e-4, name
print(f"all {len(CASES)} Python tests pass")
pd.DataFrame(CASES, columns=["case", "contact_s", "flight_s", "want", "msg"]).to_csv("clean/cases.csv", index=False)

# %% [markdown]
# ### Step 9 · The same cases in JavaScript
#
# Node.js runs the JavaScript on a computer; the page would run the same file in the phone's
# browser. This cell writes `force.js`, feeds it the eight cases and every foot plant, and saves
# the answers. One trap had to be handled in the test harness: in JavaScript, `Number("")` is
# **0**, not "missing", so a blank cell would have passed as a zero contact. The harness turns a
# blank cell into `NaN` first, as the page must.

# %%
# Step 9 · Run force.js with Node.js on the same inputs
import subprocess

FORCE_JS = """export function footForce(contactS, flightS) {
  if (!Number.isFinite(contactS) || !Number.isFinite(flightS))
    return { value: null, message: 'Missing contact or flight time.' };
  if (contactS > 2) return { value: null, message: 'Times look like milliseconds; enter seconds.' };
  if (contactS < 0.08 || contactS > 0.45)
    return { value: null, message: 'Contact time outside 0.08-0.45 s: not a running step.' };
  if (flightS < 0) return { value: null, message: 'Negative flight: the feet overlap, as in walking.' };
  return { value: (Math.PI / 2) * (1 + flightS / contactS), message: null };
}"""
HARNESS = """import { readFileSync, writeFileSync } from 'node:fs';
import { footForce } from './force.mjs';
const num = (s) => (s === undefined || s.trim() === '' || s === 'nan' ? NaN : Number(s));  // blank is missing, not 0
const run = (file, a, b, key) => { const [head, ...rows] = readFileSync(file, 'utf8').trim().split('\\n');
  const h = head.split(','); return rows.map((r) => { const c = r.split(','); const o = footForce(num(c[h.indexOf(a)]), num(c[h.indexOf(b)]));
    return [c[h.indexOf(key)], o.value ?? '', JSON.stringify(o.message ?? '')].join(','); }); };
writeFileSync('clean/force_js_cases.csv', 'case,js_value,js_message\\n' + run('clean/cases.csv', 'contact_s', 'flight_s', 'case').join('\\n') + '\\n');
writeFileSync('clean/force_js_plants.csv', 'first,js_value,js_message\\n' + run('clean/foot_plants.csv', 'contact_s', 'flight_s', 'first').join('\\n') + '\\n');"""
open("force.mjs", "w").write(FORCE_JS + "\n")
open("run_force.mjs", "w").write(HARNESS + "\n")
done = subprocess.run(["node", "run_force.mjs"], capture_output=True, text=True)
print("node exit code", done.returncode, done.stderr.strip()[:200])
print(open("clean/force_js_cases.csv").read().strip())

# %% [markdown]
# ### Step 9 · Do the two languages agree?
#
# Read the JavaScript answers back in the browser and compare them with Python, value by value
# and message by message.

# %%
# Step 9 · Python against JavaScript, cases and plants
js = pd.read_csv("clean/force_js_cases.csv").fillna({"js_message": ""})   # no message: empty
py = [foot_force(c, f) for _, c, f, _, _ in CASES]
cmp = pd.DataFrame({"case": [c[0] for c in CASES], "py_value": [v for v, _ in py],
                    "py_message": [m or "" for _, m in py]}).merge(js, on="case")
same_msg = (cmp["py_message"] == cmp["js_message"]).sum()
dv = (cmp["py_value"].astype(float) - cmp["js_value"]).abs().max()
jp = pd.read_csv("clean/force_js_plants.csv").merge(plants, on="first")
dp = (jp["force_bw"] - jp["js_value"]).abs().max()
print(f"cases: {same_msg} of {len(cmp)} messages identical; largest value difference {dv:.1e} BW")
print(f"plants: {len(jp)} compared; largest difference {dp:.1e} BW; "
      f"refused by both: {int((jp['force_bw'].isna() & jp['js_value'].isna()).sum())}")

# %% [markdown]
# Every value and every message agrees. That is what lets you put the JavaScript in the page and
# keep the Python as the reference.
#
# ### Step 9 · Batch or streaming?
#
# The notebook read the whole file afterwards: a **batch** analysis. It knew the clip's first
# and last frames, could compute the median contact of the whole run, and could wait for the
# next foot to land before computing a flight. A page that reads steps **as they happen**, from
# a live camera or a sensor (the way the Heart app's live capture reads a chest strap), sees one
# step at a time and never the future. Replay the plants in order to see the difference.

# %%
# Step 9 · The same steps, as a file and as a stream
import matplotlib.pyplot as plt

ok = plants.dropna(subset=["force_bw"])
batch_mean = ok["force_bw"].mean()
stream = ok["force_bw"].expanding().mean()            # what a live page could show at each step
median_batch = ok["contact_s"].median()
median_live = ok["contact_s"].shift(1).rolling(6, min_periods=6).median()   # past steps only
print(f"batch: {len(ok)} plants, mean {batch_mean:.2f} BW, median contact {median_batch:.3f} s")
print(f"stream: after 6 plants {stream.iloc[5]:.2f}, after 20 {stream.iloc[19]:.2f}, at the end {stream.iloc[-1]:.2f} BW")
print(f"stream has no contact baseline for the first {int(median_live.isna().sum())} plants; "
      f"each force is known one step late (it needs the next landing)")

fig, ax = plt.subplots(figsize=(6.6, 3.2))
for side, mk, fill in [("l", "o", "white"), ("r", "s", "black")]:
    d = ok[ok["side"] == side]
    ax.plot(d["t_s"], d["force_bw"], mk, mfc=fill, mec="black", ms=5, label="left" if side == "l" else "right")
ax.axhline(batch_mean, color="0.4", ls="--", label="batch mean (whole file)")
ax.plot(ok["t_s"], stream, "-", color="black", lw=1.5, label="streaming running mean")
ax.set(xlabel="time in the clip (s)", ylabel="peak force (body weights)",
       title="A stream settles on the file's answer; it cannot see ahead", ylim=(2.1, 3.45))
ax.legend(fontsize=8, ncol=2, loc="upper right")
plt.tight_layout()

# %% [markdown]
# The two end at the same number, as they must. The stream's early answers wander, it cannot
# judge a contact against a baseline until it has seen a few, and every force arrives one step
# late. Choose by the question: a report after a session is a batch job; a cue
# while running needs a stream, and a stream needs rules that use the past only.
#
# ### Step 9 · The page, described
#
# Nothing here is put online; this is the specification of the page the athlete would open
# (Section 12.1), built from the tested `force.js`:
#
# * **One screen, Basic first** (Section 12.6). Two boxes, contact and flight time in seconds,
#   or a dropped foot-plant table. Below them, one large number per foot, for example
#   "Left 2.6, right 2.8 body weights", and one line: "A one-frame error at 30 fps changes this
#   by about 20%."
# * **Messages, never wrong numbers.** The three rules above, word for word.
# * **Privacy.** The page is static files; the numbers never leave the phone. The footer says
#   "Training information, not a medical assessment. Nothing is uploaded."
# * **A link.** The folder (`index.html`, `force.js`, a stylesheet) is copied to any static host
#   with an `https` address, and the address is printed as a QR code for the athlete (Section
#   12.9). The tests in `force.test.js` run with `node --test` before every upload.
#
# ```html
# <label>Contact time (s) <input id="contact" inputmode="decimal"></label>
# <label>Flight time (s) <input id="flight" inputmode="decimal"></label>
# <p id="result" role="status"></p>
# <script type="module">
#   import { footForce } from './force.js';
#   const show = () => { const num = (id) => { const s = document.getElementById(id).value.trim(); return s ? Number(s) : NaN; };
#     const r = footForce(num('contact'), num('flight'));
#     document.getElementById('result').textContent = r.message ?? `${r.value.toFixed(1)} body weights`; };
#   document.querySelectorAll('input').forEach((i) => i.addEventListener('input', show));
# </script>
# ```
