# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "numpy",
#   "pyarrow",
# ]
# ///
"""
Extracts everything analysis.py needs from the raw recordings, for
"Resampling discontinuous power to 1 Hz".

    uv run static/files/resampling-discontinuous-power/extract_sessions.py \\
        --wse-parser ../sweatstack-tools/apps/wattbike-wse-viewer \\
        --wse ../sweatstack-tools/apps/wattbike-wse-viewer/public/sample.WSE \\
        --pm5 ../concept2-web-recorder/test/fixtures/pm5-fw175-*.jsonl

Writes, next to this script:

    cycling_revolutions.csv  every revolution of the Wattbike session:
                             start_s, end_s, power_w (the bike's own value)
    cycling_per_second.csv   second, power_w: instantaneous power (power_est)
                             averaged over each whole second, i.e. method A
    cycling_shape.csv        phase, power: the average shape of one revolution,
                             normalised to a mean of 1 (steady revolutions only)
    rowing_strokes_all.csv   every usable PM5 stroke: trace, interval, stroke,
                             start_s (catch), end_s (next catch), drive_time_s,
                             work_j, power_w (= work / (end - start))
    rowing_shapes.csv        the force curve of each of those strokes,
                             resampled to 50 points over the drive, mean 1

Instantaneous power is derived as in extract_crops.py. A rowing stroke is
usable when it has a complete force curve, its work is known (the PM5 reports
0 J for the first stroke of each piece) and it lasts 1.2 to 4 s (longer means
a pause, not a stroke).
"""

import argparse
import csv
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.dont_write_bytecode = True  # no __pycache__ in the published folder
sys.path.insert(0, str(HERE))
from extract_crops import pm5_strokes  # noqa: E402

SHAPE_POINTS = 50


def write(name, header, rows):
    path = HERE / name
    with path.open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow(header)
        w.writerows(rows)
    print(f"Wrote {path} ({len(rows)} rows)")


def cycling(wse_parser: Path, wse_path: Path):
    sys.path.insert(0, str(wse_parser))
    import wse

    act = wse.Activity.load_wse(wse_path)
    data = act.data.to_pydict()
    revs = [
        (t - d, t, p)
        for t, d, p in zip(data["time"], data["duration"], data["power"])
    ]
    write("cycling_revolutions.csv", ["start_s", "end_s", "power_w"],
          [[f"{s:.3f}", f"{e:.3f}", f"{p:.1f}"] for s, e, p in revs])

    force = act.force.to_pydict()
    t = np.asarray(force["time"], dtype=float)
    power = np.nan_to_num(np.asarray([np.nan if p is None else p for p in force["power_est"]], dtype=float))
    seconds = np.floor(t + 1e-6).astype(int)
    per_second = np.bincount(seconds, weights=power) / np.maximum(np.bincount(seconds), 1)
    write("cycling_per_second.csv", ["second", "power_w"],
          [[s, f"{p:.1f}"] for s, p in enumerate(per_second)])

    # Average shape of a steady revolution: 80-95 rpm, 150-300 W.
    rev = np.array([-1 if r is None else r for r in force["revolution"]])
    shapes = []
    for i, (start, end, p) in enumerate(revs):
        cadence = 60 / (end - start)
        if 80 <= cadence <= 95 and 150 <= p <= 300:
            samples = power[rev == i]
            if len(samples) >= 20 and samples.mean() > 0:
                x = np.linspace(0, 1, len(samples), endpoint=False)
                shapes.append(np.interp(np.linspace(0, 1, 100, endpoint=False), x, samples / samples.mean()))
    shape = np.mean(shapes, axis=0)
    shape /= shape.mean()
    write("cycling_shape.csv", ["phase", "power"],
          [[f"{i / 100:.2f}", f"{v:.4f}"] for i, v in enumerate(shape)])
    print(f"  cycling shape from {len(shapes)} revolutions")


def rowing(pm5_paths: list[Path]):
    strokes, shapes = [], []
    for path in pm5_paths:
        for i, interval in enumerate(pm5_strokes(path)):
            for s, nxt in zip(interval, interval[1:]):
                period = nxt["catch"] - s["catch"]
                curve = s.get("curve", [])
                if s["work"] <= 0 or s["drive_time"] <= 0 or len(curve) < 10 or not 1.2 <= period <= 4:
                    continue
                key = [path.stem, i, s["n"]]
                strokes.append(key + [f"{s['catch']:.2f}", f"{nxt['catch']:.2f}", f"{s['drive_time']:.2f}",
                                      f"{s['work']:.1f}", f"{s['work'] / period:.1f}"])
                f = np.asarray(curve, dtype=float)
                resampled = np.interp(np.linspace(0, 1, SHAPE_POINTS), np.linspace(0, 1, len(f)), f)
                shapes.append(key + [f"{v:.4f}" for v in resampled / resampled.mean()])
    write("rowing_strokes_all.csv",
          ["trace", "interval", "stroke", "start_s", "end_s", "drive_time_s", "work_j", "power_w"], strokes)
    write("rowing_shapes.csv", ["trace", "interval", "stroke"] + [f"p{i}" for i in range(SHAPE_POINTS)], shapes)


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("--wse-parser", type=Path, required=True, help="directory containing wse.py")
    parser.add_argument("--wse", type=Path, required=True, help="Wattbike .WSE file")
    parser.add_argument("--pm5", type=Path, nargs="+", required=True, help="PM5 Bluetooth traces (.jsonl)")
    args = parser.parse_args()
    cycling(args.wse_parser, args.wse)
    rowing(sorted(args.pm5))


if __name__ == "__main__":
    main()
