"""Q-16: Open an activity file and list its fields -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# A running watch saves each run as a FIT file: compact, binary, and unreadable in a text
# editor. This one is the instructor's run of 14 May 2026, the example run of Chapter 6, as his
# watch wrote it, except that every position value has been blanked (set to FIT's "no value"
# code) so the file shows no route. You will open it, list what it holds, and save it as plain
# tables.
#
# ### Read the binary file
#
# The first cell needs the `fitdecode` package, which does not run in a web page, so it runs on
# your computer or in Colab (`pip install fitdecode`). It writes three CSV files under `clean/`;
# the cells after it run here, in the page, from those files.

# %%
# Decode the FIT file into tables
# Needs fitdecode (pip install fitdecode); runs on your computer or in Colab.
import os
import warnings
import fitdecode
import pandas as pd

warnings.simplefilter("ignore")                       # the watch writes one odd field definition
rows, fields, session = [], {}, {}
with fitdecode.FitReader("raw/2026-05-14_0726_running_nogps.fit") as fit:
    for m in fit:
        if not isinstance(m, fitdecode.FitDataMessage):
            continue                                  # skip headers and definitions
        for f in m.fields:
            key = (m.name, f.name)
            n, unit, ex = fields.get(key, (0, f.units, None))
            fields[key] = (n + (f.value is not None), unit, ex if ex is not None else f.value)
        if m.name == "record":
            rows.append({f.name: f.value for f in m.fields})
        elif m.name == "session":
            session = {f.name: f.value for f in m.fields}
os.makedirs("clean", exist_ok=True)
table = pd.DataFrame([(a, b, n, u, ex) for (a, b), (n, u, ex) in fields.items()],
                     columns=["message", "field", "values", "units", "example"])
table.to_csv("clean/fields.csv", index=False)
pd.DataFrame(rows).dropna(axis=1, how="all").to_csv("clean/records.csv", index=False)
pd.Series(session).to_csv("clean/session.csv", header=["value"])
print(table.groupby("message")["field"].count().to_string())

# %% [markdown]
# Nine kinds of message. Most of the file is `record` messages, one per sample; `lap` and
# `session` messages are the watch's own summaries; `event` messages mark the timer starting
# and stopping. The position fields come out empty, so `dropna` leaves them out of the records
# table.
#
# ### List the fields of a record

# %%
# What a record holds
import pandas as pd

fields = pd.read_csv("clean/fields.csv")
rec = fields[fields["message"] == "record"].drop(columns="message")
print(rec.to_string(index=False))

# %% [markdown]
# Read the units column before anything else. Distance is in metres and speed in metres per
# second, but `cadence` is in "rpm", one leg's steps a minute, so a runner's cadence is twice
# it. `position_lat` and `position_long` have no values here; in a file straight from a watch they
# are in semicircles (2³¹ of them make 180°), not degrees.
#
# ### Three facts before any analysis

# %%
# Pauses, timer time and cadence
import matplotlib.pyplot as plt

rec = pd.read_csv("clean/records.csv", parse_dates=["timestamp"])
ses = pd.read_csv("clean/session.csv", index_col=0)["value"]
gaps = rec["timestamp"].diff().dt.total_seconds()
print(f"{len(rec)} records; gaps over 1 s: {gaps[gaps > 1].tolist()}")
print(f"first to last record {(rec['timestamp'].iloc[-1] - rec['timestamp'].iloc[0]).total_seconds():.0f} s; "
      f"watch timer {float(ses['total_timer_time']):.1f} s; distance {float(ses['total_distance']):.1f} m")
print(f"cadence field {float(ses['avg_running_cadence']):.0f} per leg -> {2 * float(ses['avg_running_cadence']):.0f} steps/min")

minutes = (rec["timestamp"] - rec["timestamp"].iloc[0]).dt.total_seconds() / 60
fig, ax = plt.subplots(figsize=(9, 3.2))
ax.plot(minutes, rec["enhanced_speed"], ".", ms=1.5, label="speed (m/s)")
ax2 = ax.twinx()
broken = rec["heart_rate"].where(gaps.shift(-1).fillna(1) <= 1)   # no line across a pause
ax2.plot(minutes, broken, "k-", lw=0.6, label="heart rate")
ax.set(xlabel="time from the first record (min)", ylabel="speed (m/s), dots")
ax2.set_ylabel("heart rate (beats/min), line")
plt.tight_layout()

# %% [markdown]
# The watch was paused twice, once for more than an hour and once for 23 seconds, so the first
# and last records are over 90 minutes apart while the watch ran for 30. Any pace computed from
# the clock instead of the timer would be three times too slow. Chapter 6 (Section 6.3) reads
# the same file and finds the same facts.
#
# **For the athlete:** "Your watch file holds 1803 one-second records of speed, heart rate,
# cadence and running dynamics; we saved them as plain tables and checked the pauses before
# measuring anything."
