"""Q-34: A calculation in a web page -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# A calculation reaches an athlete when it runs in a page on their phone. The Python cells on
# this page already run in your browser: they use **Pyodide**, a version of Python compiled to
# WebAssembly, so nothing is sent to a server. A page an athlete opens, though, is usually
# written in **JavaScript**, the browser's own language, and loads in a fraction of a second.
# So the same calculation is written twice, and the two must agree.
#
# The calculation is the force of a foot plant from its timing (Section 3.7.2): over a step the
# ground's push must average one body weight, and with a half-sine shape the peak is
#
# F_peak / body weight = (π/2) × (1 + flight time / contact time).
#
# ### The Python version, on three test cases
#
# The three cases were typed before any code was written, from the book's examples, so each has
# a hand answer to check against.

# %%
# The function in Python
import math
import pandas as pd

def peak_force_bw(contact_s, flight_s):
    """Peak vertical force in body weights from one contact and the flight after it."""
    return math.pi / 2 * (1 + flight_s / contact_s)

cases = pd.read_csv("raw/test_cases.csv")
cases["python_bw"] = [peak_force_bw(c, f) for c, f in zip(cases["contact_s"], cases["flight_s"])]
print(cases[["case", "contact_s", "flight_s", "python_bw"]].round(4).to_string(index=False))

# %% [markdown]
# ### The same function in JavaScript
#
# This is what goes in the page. Read it line by line against the Python: `Math.PI` is `math.pi`,
# and `export` lets the page and a test file import it.
#
# ```js
# // force.js: peak force of a foot plant, in body weights (Section 3.7.2)
# export function peakForceBW(contactS, flightS) {
#   return (Math.PI / 2) * (1 + flightS / contactS);
# }
# ```
#
# ### Run the JavaScript on the same cases
#
# This cell runs the JavaScript with Node.js, the JavaScript engine for a computer, so it is
# marked to run on your computer, not in the page. It writes the answers to a file that the
# next cell, back in the browser, compares with Python.

# %%
# Run force.js with Node.js
import subprocess, os

JS = """export function peakForceBW(contactS, flightS) {
  return (Math.PI / 2) * (1 + flightS / contactS);
}"""
CHECK = """import { readFileSync, writeFileSync } from 'node:fs';
import { peakForceBW } from './force.mjs';
const rows = readFileSync('raw/test_cases.csv', 'utf8').trim().split('\\n').slice(1);
const out = rows.map((r) => { const [name, c, f] = r.split(',');
  return `${name},${peakForceBW(Number(c), Number(f))}`; });
writeFileSync('clean/force_js.csv', 'case,js_bw\\n' + out.join('\\n') + '\\n');"""
os.makedirs("clean", exist_ok=True)
open("force.mjs", "w").write(JS + "\n")
open("check_force.mjs", "w").write(CHECK + "\n")
run = subprocess.run(["node", "check_force.mjs"], capture_output=True, text=True)
print("node exit code", run.returncode, run.stderr.strip())
print(open("clean/force_js.csv").read().strip())

# %% [markdown]
# ### Do they agree?

# %%
# Compare the two, and draw the curve
import matplotlib.pyplot as plt

js = pd.read_csv("clean/force_js.csv")
both = cases.merge(js, on="case")
both["difference"] = both["js_bw"] - both["python_bw"]
print(both[["case", "python_bw", "js_bw", "difference"]].to_string(index=False))
print("largest difference:", both["difference"].abs().max())

ratio = [r / 100 for r in range(0, 141)]
fig, ax = plt.subplots(figsize=(5.6, 3.2))
ax.plot(ratio, [peak_force_bw(1, r) for r in ratio], "-", color="black", label="Python")
ax.plot(both["flight_s"] / both["contact_s"], both["js_bw"], "s", ms=8, mfc="white", mec="black", label="JavaScript, 3 cases")
ax.set(xlabel="flight time / contact time", ylabel="peak force (body weights)",
       title="Two languages, one answer")
ax.legend()
plt.tight_layout()

# %% [markdown]
# Both languages use the same 64-bit floating-point numbers, so for a formula this simple the
# answers agree to every printed digit. For longer calculations they can differ in the last
# digit or two, so tests compare with a tolerance, such as 0.0001 body weights, not with `==`.
#
# **For the athlete:** "The page on your phone uses the same formula we checked here: with
# a 0.25 s contact and a 0.1 s flight, each foot plant pushes about 2.2 times your body weight."
