"""Q-17: Split a run into laps -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# On 11 May 2026 the instructor ran a session with a set of short, fast repeats in the middle,
# pressing the lap button at the start and end of each. The watch saved one record a second and
# a summary of each lap. You will split the records into the laps yourself, check your laps
# against the watch's, and pick out the fast ones.
#
# ### Open the records and the laps

# %%
# One record a second, and the watch's laps
import numpy as np
import pandas as pd

rec = pd.read_csv("raw/2026-05-11_1507_running.csv", parse_dates=["time"])
laps = pd.read_csv("raw/laps.csv", parse_dates=["start_time"])
laps = laps[laps["activity_id"] == "2026-05-11_1507_running"].reset_index(drop=True)
gap = rec["time"].diff().dt.total_seconds()
print(f"{len(rec)} records over {rec['elapsed_s'].iloc[-1] / 60:.0f} min of clock time; {len(laps)} laps")
print(f"{int((gap > 1).sum())} pauses (gaps over 1 s), adding up to {gap[gap > 1].sum() / 60:.0f} min")

# %% [markdown]
# The watch was paused 21 times, for over half an hour in all: a pause between repeats is
# normal in a session like this. Time running is what matters for pace, so count only the
# one-second steps.
#
# ### Put each record in its lap
#
# A record belongs to the last lap that started at or before it. `np.searchsorted` finds that
# lap for every record at once. Then each lap's running time is the sum of its one-second steps,
# and its distance is the watch's distance at the next lap's start minus at its own.

# %%
# Split by the lap marks and compare with the watch
rec["lap"] = np.searchsorted(laps["start_time"].values, rec["time"].values, side="right")
rec["step_s"] = gap.where(gap <= 1, 0).fillna(0)          # pauses add no running time
g = rec.groupby("lap")
start = g["distance_m"].first().to_numpy()
mine = pd.DataFrame({"time_s": g["step_s"].sum().to_numpy(),
                     "dist_m": np.diff(np.r_[start, rec["distance_m"].iloc[-1]]),
                     "hr_bpm": g["heart_rate_bpm"].mean().round(0).to_numpy()}, index=laps["lap"])
mine["speed_mps"] = mine["dist_m"] / mine["time_s"]
print(f"largest difference from the watch's laps: time {np.abs(mine['time_s'] - laps['timer_s'].to_numpy()).max():.1f} s, "
      f"distance {np.abs(mine['dist_m'] - laps['distance_m'].to_numpy()).max():.1f} m")
print(mine.round(2).T.to_string())

# %% [markdown]
# The distances agree within a few metres. The times agree within a second on most laps and
# within about 6 seconds on the long ones: the watch counts fractions of a second around each
# pause that whole-second records cannot see.
#
# ### The fast laps

# %%
# Speed lap by lap
import matplotlib.pyplot as plt

fast = mine[mine["speed_mps"] > 5]
print(f"{len(fast)} fast laps: {fast['dist_m'].min():.0f} to {fast['dist_m'].max():.0f} m "
      f"at {fast['speed_mps'].min():.1f} to {fast['speed_mps'].max():.1f} m/s")
edges = np.r_[0, mine["time_s"].cumsum()] / 60
fig, ax = plt.subplots(figsize=(9, 3.2))
ax.stairs(mine["speed_mps"], edges, color="k", lw=1.2)
ax.plot((edges[:-1] + edges[1:])[mine["speed_mps"] > 5] / 2, fast["speed_mps"], "o", mfc="none", label="fast lap")
ax.set(xlabel="running time (min, pauses removed)", ylabel="lap speed (m/s)")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# Nine fast laps stand out, 95 to 311 m each, separated by slow recovery jogs. A lap table is
# the step between a one-second record and a training question: each fast lap is now one row
# with a distance, a time and a speed, ready for the case study CS-7.
#
# **For the athlete:** "Your nine repeats on 11 May ran at 5.5 to 6.4 metres a second; the lap
# button did its job, and the laps we rebuilt from your records match your watch's."
