"""Q-36: Read a results file in the browser -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# The course's movement apps write their results next to the video, in your browser, with
# nothing uploaded: a report (PDF), a highlight video, the measurements as text (`.md`) and a
# **receipt** (`.json`), written last, that records how the analysis was run (Section 4.8).
# A page you build can read the same files, also without uploading them: the user drops the
# file on the page and the browser reads it locally.
#
# The files here are the book's **synthetic** jump results: seven clips of an invented athlete
# 1.75 m tall, written by the jump app's own results code. One week-3 clip was filmed at 120
# frames per second but analyzed at the 30 its file header claims.
#
# ### Open one receipt

# %%
# One receipt, field by field
import json

r = json.load(open("raw/results/results_jump_wk3_t3.json"))
print("fields:", list(r))
print("input:", r["input"], "| saved:", r["savedAt"])
print("options:", r["options"])
print(f"file says {r['sourceFps']} fps; analysis used {r['actualCaptureFps']} fps; "
      f"analyzed {r['analyzedRange']['start']} to {r['analyzedRange']['end']} s of video")
for w in r["warnings"]:
    print("warning:", w[:90] + "...")

# %% [markdown]
# Three frame-rate fields, and they mean different things (checked against the apps' shared
# job code, `shared/automation-jobs.ts`): `options.captureFps` is what the user asked for
# (`"auto"` means "trust the file"), `sourceFps` is the rate written in the video file, and
# `actualCaptureFps` is the rate every time and speed was computed with. In a web page the same
# fields are one line away:
#
# ```js
# const r = JSON.parse(await file.text());   // file: the File the user dropped on the page
# if (r.actualCaptureFps !== loggedFps) showWarning(`${r.input}: analyzed at ${r.actualCaptureFps} fps`);
# ```
#
# ### All seven receipts, checked against the session log
#
# A receipt can only say what the app was told. Whether that was right is in your own log: the
# week-1 clips were filmed at 30 frames per second, the week-3 clips at 120.

# %%
# Seven receipts as a table
import glob
import pandas as pd

LOG_FPS = {"wk1": 30, "wk3": 120}                     # from the filming log sheet
rows = []
for path in sorted(glob.glob("raw/results/results_*.json")):
    r = json.load(open(path))
    week = r["input"].split("_")[1]
    rows.append({"clip": r["input"], "asked": r["options"]["captureFps"], "file_fps": r["sourceFps"],
                 "used_fps": r["actualCaptureFps"], "warnings": len(r["warnings"]),
                 "ok": r["actualCaptureFps"] == LOG_FPS[week], "md": path.replace(".json", ".md")})
receipts = pd.DataFrame(rows)
print(receipts.drop(columns="md").to_string(index=False))

# %% [markdown]
# ### Join the measurement, and draw it
#
# The jump height is in the `.md` file's Metrics table, one row per metric with the unit in the
# text (`31.2 cm / 12.3 in`).

# %%
# Jump height from each results file, the bad clip marked
import re
import matplotlib.pyplot as plt

def jump_height(md_path):
    m = re.search(r"^\| Jump Outcome \| Jump Height \| ([\d.]+) cm", open(md_path, encoding="utf-8").read(), re.M)
    return float(m.group(1)) if m else None

receipts["height_cm"] = receipts["md"].map(jump_height)
receipts["week"] = receipts["clip"].str.split("_").str[1]
good = receipts[receipts["ok"]].groupby("week")["height_cm"].mean()
print(receipts[["clip", "ok", "height_cm"]].to_string(index=False))
print(f"week 1 mean {good['wk1']:.1f} cm, week 3 mean {good['wk3']:.1f} cm (wrong-rate clip left out)")

fig, ax = plt.subplots(figsize=(6.0, 3.0))
for (wk, ok), d in receipts.groupby(["week", "ok"]):
    style = dict(marker="x", ms=9, color="black") if not ok else dict(marker="o", ms=7, color="black", mfc="white" if wk == "wk1" else "black")
    ax.plot(d.index, d["height_cm"], ls="", label=f"{wk}{'' if ok else ', wrong frame rate'}", **style)
ax.set_xticks(receipts.index, receipts["clip"].str[5:11])
ax.set(xlabel="clip", ylabel="jump height (cm)", title="Week 3 is higher; one clip is left out")
ax.legend(fontsize=8)
plt.tight_layout()

# %% [markdown]
# The wrong-rate clip's height looks plausible, because the jump app scales height from the
# body, not from the clock; only its times are wrong, which is why the app withheld them and
# wrote two warnings. The receipt and your log together catch it; the height alone never would.
#
# **For the athlete:** "Six of your seven clips were analyzed at the rate you filmed them; we
# left the seventh out, and your week-3 jumps average about 3 cm higher than week 1."
