"""Q-35: Three tests: normal, missing, invalid -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# Users will feed your app the wrong file, an empty file, or a file in the wrong units. Section
# 12.4.4 asks every app to pass three tests before anything else:
#
# * **Normal input**: a good file gives the right answer, checked by hand.
# * **Missing input**: an empty file, a header with no rows, or no `rr` column gives no number
#   and a message that says what is missing.
# * **Invalid input**: values that are present but cannot be right, such as RR intervals in
#   seconds (0.80) instead of milliseconds (800), give no number and a message that says how to
#   fix the file.
#
# The functions are a Python copy of the book's student app, *Resting heart check*: read the
# `rr` column, refuse what cannot be used, and compute RMSSD.
#
# ### The functions under test

# %%
# Read, check, compute
import math

def parse_rr(text):
    lines = text.strip().splitlines() or [""]
    head = [s.strip().lower() for s in lines[0].split(",")]
    has_header = any(s and not s.replace(".", "", 1).isdigit() for s in head)
    col = next((i for i, s in enumerate(head) if s in ("rr", "rr_ms")), -1) if has_header else 0
    if col < 0:
        raise ValueError('No "rr" or "rr_ms" column in this file.')
    cells = [line.split(",") for line in lines[1 if has_header else 0:]]
    vals = [num(c[col]) for c in cells if len(c) > col]
    return [v for v in vals if v > 0]                 # blank or text cells are skipped

def num(s):
    try:
        return float(s)
    except ValueError:
        return 0.0

def check_input(rr, lo=300, hi=2000):
    if len(rr) < 3:
        return "Fewer than three RR intervals in this file."
    if sum(lo <= v <= hi for v in rr) < 3:
        return f"Fewer than three intervals between {lo} and {hi} ms. Are the values in milliseconds?"
    return None                                       # fit to analyze

def rmssd(rr):
    d = [b - a for a, b in zip(rr, rr[1:])]
    return math.sqrt(sum(x * x for x in d) / len(d))

# %% [markdown]
# ### The three tests
#
# Each test states the expected behavior first, exactly as the hand answer was written before
# the known-answer test. `assert` stops with an error if the expectation fails; silence means it
# passed. The normal case is the book's hand calculation: 800, 820, 790, 810 and 800 ms give an
# RMSSD of √450 = 21.21 ms.

# %%
# Normal, missing, invalid
def test_normal():
    rr = parse_rr("rr\n800\n820\n790\n810\n800\n")
    assert check_input(rr) is None
    assert abs(rmssd(rr) - math.sqrt(450)) <= 0.01

def test_missing():
    assert "Fewer than three RR" in check_input(parse_rr(""))
    assert "Fewer than three RR" in check_input(parse_rr("time,rr\n"))
    try:
        parse_rr("time,hr\n1,60\n")
        assert False, "a file with no rr column must be refused"
    except ValueError as e:
        assert 'No "rr"' in str(e)

def test_invalid():
    rr = parse_rr("rr\n0.80\n0.82\n0.79\n0.81\n")
    assert len(rr) == 4                               # read, but not usable
    assert "in milliseconds?" in check_input(rr)

for test in (test_normal, test_missing, test_invalid):
    test()
    print("ok -", test.__name__)
hand = parse_rr("rr\n800\n820\n790\n810\n800\n")
print(f"normal case: RMSSD {rmssd(hand):.2f} ms")

# %% [markdown]
# The invalid test is the one that earned its place. Before the check existed, four intervals
# in seconds passed the only guard ("at least three intervals"), the cleaning rule then removed
# all four, and the page printed `NaN` where the number belongs (Section 12.4.4).
#
# The same three tests in the app's own language, for `node --test`, from the book's student
# app (`test/inputs.test.js`):
#
# ```js
# test('normal: the five hand-worked beats pass and give the hand answer', () => {
#   const rr = parseRR('rr\n800\n820\n790\n810\n800\n');
#   assert.equal(checkInput(rr), null);
#   assert.ok(Math.abs(analyze(rr).rmssd - Math.sqrt(450)) <= 0.01); // 21.21 ms
# });
# test('missing: an empty file, a header alone, no rr column', () => {
#   assert.match(checkInput(parseRR('')), /Fewer than three RR/);
#   assert.match(checkInput(parseRR('time,rr\n')), /Fewer than three RR/);
#   assert.throws(() => parseRR('time,hr\n1,60\n'), /No "rr"/);
# });
# test('invalid: intervals in seconds are refused, never shown as NaN', () => {
#   const rr = parseRR('rr\n0.80\n0.82\n0.79\n0.81\n');
#   assert.equal(rr.length, 4); // read, but not usable
#   assert.match(checkInput(rr), /in milliseconds\?/);
# });
# ```
#
# ### A real-sized file, right and wrong
#
# Now the book's synthetic example file, 331 intervals, as it is and as it would arrive if a
# logger had written seconds.

# %%
# The example file in milliseconds and in seconds
import matplotlib.pyplot as plt

text = open("raw/rest-rr-synthetic.csv").read()
ms = parse_rr(text)
sec = parse_rr("rr\n" + "\n".join(f"{v / 1000:.3f}" for v in ms))
for name, rr in [("milliseconds", ms), ("seconds", sec)]:
    print(f"{name:12s} {len(rr)} intervals -> {check_input(rr) or 'ok, analyze'}")

fig, ax = plt.subplots(1, 2, figsize=(7.0, 2.8), sharey=True)
for a, rr, name in [(ax[0], ms, "as written (ms)"), (ax[1], sec, "written in seconds")]:
    a.axhspan(300, 2000, color="0.88", lw=0)
    a.plot(range(1, len(rr) + 1), rr, ".", color="black", ms=2)
    a.set(title=name, xlabel="beat number")
ax[0].set_ylabel("value in the rr column")
fig.suptitle("Shaded: the 300-2000 ms an app can use", fontsize=10)
plt.tight_layout()

# %% [markdown]
# The first file passes and goes on to the analysis; the second is refused with a message the
# user can act on, and no number is shown. "It does not crash" was never the test.
#
# **For the athlete:** "If the app says your file is not in milliseconds, export it again from
# the strap's app; it will never show you a number it could not check."
