"""Q-3: Pace from distance and time, checked three ways -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### A function you can trust
#
# Pace is time per kilometer: pace = t / (d / 1000), with t in seconds and d in meters. It is one
# line of code and still easy to get wrong: kilometers typed as meters, minutes as seconds, or a
# pace in decimal minutes read as minutes and seconds. The habit from Section 4.1.1 is to check
# a function against **three known cases** before it touches real data: one ordinary case, one
# round-number case, and one that tests a unit. An `assert` line stops the notebook if a case
# fails, which is what you want.
#
# Work the three cases by hand first: 10 km in 50:00, 5 km in 22:30, and one mile (1609.344 m,
# exact) in 8:00.

# %%
# A pace function and three known cases
def speed_pace(distance_m, seconds):
    """Speed (m/s) and pace (s per km) from a distance in meters and a time in seconds."""
    if distance_m <= 0 or seconds <= 0:
        raise ValueError("distance and time must both be positive")
    v = distance_m / seconds
    return v, 1000 / v

def mmss(s):
    return f"{int(s // 60)}:{s % 60:04.1f}"

assert abs(speed_pace(10_000, 50 * 60)[1] - 300) < 1e-9          # ordinary: 5:00 /km
assert abs(speed_pace(5_000, 22 * 60 + 30)[1] - 270) < 1e-9      # round number: 4:30 /km
assert abs(speed_pace(1609.344, 8 * 60)[1] - 298.26) < 0.01      # a unit: miles to meters
try:
    speed_pace(0, 600)
    raised = False
except ValueError:
    raised = True
assert raised                                                     # an empty activity stops it
for d, t in [(10_000, 3000), (5_000, 1350), (1609.344, 480)]:
    v, p = speed_pace(d, t)
    print(f"{d:9.3f} m in {mmss(t)}: {v:.3f} m/s, pace {mmss(p)} /km")
print("all four checks pass")

# %% [markdown]
# The mile is the case that catches a function written for kilometers: 8:00 a mile is 4:58.3 a
# kilometer, not 8:00. A distance of zero stops with a clear message instead of an infinite pace.
#
# ### Apply it to the instructor's watch
#
# The course's case file holds 19 of the instructor's runs from spring 2026, one row each, with the
# distance, the **moving time** (the watch stops counting while he stands still) and the
# **elapsed time** (start to finish, stops included). Compute the pace both ways.

# %%
# Moving pace and elapsed pace for 19 runs
import pandas as pd

runs = pd.read_csv("raw/activities.csv")
d_m = runs["distance_km"] * 1000
runs["pace_moving_s"] = [speed_pace(d, 60 * t)[1] for d, t in zip(d_m, runs["moving_time_min"])]
runs["pace_elapsed_s"] = [speed_pace(d, 60 * t)[1] for d, t in zip(d_m, runs["elapsed_time_min"])]
show = runs[["date", "distance_km", "moving_time_min", "elapsed_time_min"]].copy()
show["moving"] = runs["pace_moving_s"].map(mmss)
show["elapsed"] = runs["pace_elapsed_s"].map(mmss)
print(show.head(5).to_string(index=False))
assert (runs["pace_moving_s"] <= runs["pace_elapsed_s"]).all()    # stops never make you faster
print(f"elapsed pace is slower by a median of {mmss((runs['pace_elapsed_s'] - runs['pace_moving_s']).median())} per km")

# %% [markdown]
# ### The third way: the file's own pace column
#
# The file already has a column `pace_min_per_km`. Which time does it use, and in which unit?

# %%
# Check the file's pace column
first = runs.iloc[0]
print(f"file says {first['pace_min_per_km']} min/km; moving pace {mmss(first['pace_moving_s'])}, "
      f"elapsed pace {mmss(first['pace_elapsed_s'])}")
gap = (runs["pace_min_per_km"] * 60 - runs["pace_moving_s"]).abs().max()
print(f"largest difference from the moving pace, all 19 runs: {gap:.1f} s/km")
print(f"read as 5 min 18 s by mistake, the first run would be {5 * 60 + 18 - first['pace_moving_s']:.0f} s/km too slow")

# %% [markdown]
# The column is the moving pace, in **decimal minutes**: 5.18 means 5.18 minutes, which is
# 5:10.8, not 5:18. Every one of the 19 runs agrees with the function's moving pace to within
# 0.3 s per kilometer, the rounding of the column. Reading the decimal as minutes and seconds
# would make the first run 7 s per kilometer slower than it was.
#
# ### One chart

# %%
# Moving against elapsed pace, run by run
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 3.4))
x = range(1, len(runs) + 1)
ax.plot(x, runs["pace_moving_s"] / 60, "o", label="moving time")
ax.plot(x, runs["pace_elapsed_s"] / 60, "s", mfc="none", label="elapsed time")
ax.set(xlabel="run number (in date order)", ylabel="pace (min per km)", xticks=range(1, len(runs) + 1, 2))
ax.invert_yaxis()                      # faster at the top, as runners read pace
ax.legend()
plt.tight_layout()
print(f"slowest elapsed pace {runs['pace_elapsed_s'].max() / 60:.1f} min/km on {runs.loc[runs['pace_elapsed_s'].idxmax(), 'date']}")

# %% [markdown]
# On runs with no stops the two markers sit on top of each other. On others, stops at lights,
# water and conversations make the elapsed pace minutes slower. Neither is wrong; a report must
# say which it used.
#
# **For the athlete:** "On your 10 April run you averaged 5:11 a kilometer while moving; counting
# the stops it was 7:22, so when we compare runs we will always use the moving pace."
