"""Q-11: Write a data dictionary for one file -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### A file does not say what it means
#
# A **data dictionary** is a table with one row per field of a file: its name, its meaning, its
# unit, its type, its allowed range and its **missing-value code**, the way the file writes "no
# value" (Section 4.2.5). The file here is one of the instructor's real runs, the 11 May 2026
# afternoon run from the course case file: one row per second the watch recorded, 12 columns, GPS
# positions removed. Open it and list what is there.

# %%
# What is in the file?
import pandas as pd

run = pd.read_csv("raw/2026-05-11_1507_running.csv", dtype=str)    # as text first: see what is written
print(run.shape)
print(run.iloc[[0, 1, 1000]].to_string(index=False))
print("empty cells per column:", run.isna().sum().to_dict())

# %% [markdown]
# 3,746 rows for a run whose last `elapsed_s` is 5,640: the watch writes no rows while it is
# paused. The `temperature_c` column is empty in every row. Now write the dictionary **before**
# checking the values against it. The meanings and units come from the case file's own
# description; the allowed ranges are your rules, set from what a runner can do, not from this file.

# %%
# The dictionary, written first
FIELDS = [  # field, meaning, unit, type, low, high, missing code
    ("time", "time of the sample", "ISO 8601, UTC", "time", None, None, "never"),
    ("elapsed_s", "seconds since the start, pauses included", "s", "decimal", 0, 36000, "never"),
    ("distance_m", "distance since the start", "m", "decimal", 0, 100000, "never"),
    ("speed_mps", "speed from the watch", "m/s", "decimal", 0, 12, "empty"),
    ("heart_rate_bpm", "optical heart rate at the wrist", "beats/min", "integer", 30, 220, "empty"),
    ("cadence_spm", "steps a minute, both feet", "steps/min", "decimal", 0, 240, "empty"),
    ("altitude_m", "barometric altitude", "m", "decimal", -500, 5000, "empty"),
    ("power_w", "running power estimated by the watch", "W", "integer", 0, 1500, "empty"),
    ("stance_time_ms", "ground contact time", "ms", "integer", 100, 400, "empty or 0"),
    ("vertical_oscillation_mm", "vertical bounce of the torso", "mm", "integer", 30, 150, "empty or 0"),
    ("step_length_mm", "step length", "mm", "integer", 0, 2500, "empty"),
    ("temperature_c", "watch temperature sensor", "deg C", "decimal", -30, 60, "empty"),
]
dictionary = pd.DataFrame(FIELDS, columns=["field", "meaning", "unit", "type", "low", "high", "missing"])
import os
os.makedirs("clean", exist_ok=True)
dictionary.to_csv("clean/data_dictionary.csv", index=False)
print(dictionary[["field", "unit", "low", "high", "missing"]].to_string(index=False))

# %% [markdown]
# Two rows carry most of the value. Cadence here counts **both** feet (a watch's own file often
# counts one, Section 4.2.5), so the range is up to 240. And a stance time of 0 ms is not a
# contact; the case file notes that the watch writes 0 when it did not estimate one, so 0 is a
# second missing-value code for stance time and vertical bounce.
#
# ### Check the file against it

# %%
# Count what breaks each rule
rows = []
for f in dictionary.itertuples():
    if pd.isna(f.low):                          # no range to check (the time stamps)
        continue
    empty = run[f.field].isna()
    x = pd.to_numeric(run[f.field], errors="coerce")
    zero_code = (x == 0) if "0" in f.missing else pd.Series(False, index=x.index)
    outside = ((x < f.low) | (x > f.high)) & ~zero_code
    rows.append({"field": f.field, "empty": int(empty.sum()), "not a number": int((x.isna() & ~empty).sum()),
                 "0 = no estimate": int(zero_code.sum()), "outside range": int(outside.sum())})
check = pd.DataFrame(rows).set_index("field")
print(check.to_string())
st, sp = run["stance_time_ms"].astype(float), run["speed_mps"].astype(float)
print(f"stance time 0 while slower than 2 m/s (walking or stopped): {int(((st == 0) & (sp < 2)).sum())} of {int((st == 0).sum())}")
print(f"stance times outside 100-400 ms: shortest {st[st > 0].min():.0f}, longest {st.max():.0f}")

# %% [markdown]
# ### One chart

# %%
# Where the file breaks its dictionary
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 4))
left = pd.Series(0, index=check.index)
for col, hatch, shade in [("empty", "", "0.3"), ("0 = no estimate", "//", "0.6"), ("outside range", "xx", "0.9")]:
    ax.barh(check.index, check[col], left=left, color=shade, hatch=hatch, edgecolor="k", label=col)
    left = left + check[col]
ax.set(xlabel="rows (of 3,746)", xlim=(0, 3746))
ax.legend(loc="lower right")
plt.tight_layout()

# %% [markdown]
# The file passes most of its rules, and the failures are informative. Temperature was never
# recorded. Stance time and vertical bounce use 0 for "no estimate" in several hundred rows,
# mostly while walking or stopped, which an average would otherwise count as real contacts of zero
# length. The few values outside range, 24 stance times and one vertical bounce, are for Q-12 to
# mark, not to delete. Update the dictionary with what you found:
# the zero code is now written down for the next person.
#
# **For the athlete:** "Your watch file is in good shape for pace, heart rate and cadence; contact
# time is missing for about one second in six, so we'll report it only from the seconds where the
# watch measured it."
