# -*- coding: utf-8 -*-
"""Can we derive a usable gradient (坡度) signal from the FIT data we already
have? Gradient isn't a recorded field — it must come from altitude deltas
over distance deltas, and barometric altitude is noisy, so the question is
whether smoothing produces numbers a rider would agree with."""
import json
import sys
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")

win = json.loads(Path(r"C:\ai\AUTOMOVIE\app\projects\20260802_183358\window.json")
                 .read_text(encoding="utf-8"))
pts = [(r["vt"], r["dist_m"], r["alt_m"]) for r in win
       if r.get("dist_m") is not None and r.get("alt_m") is not None]
print(f"可用資料點: {len(pts)}")


def gradient_at(i, span_m=25.0):
    """Slope over a lookback window of ~span_m metres, not per-second —
    per-second baro noise would swing wildly."""
    t, d, a = pts[i]
    j = i
    while j > 0 and d - pts[j][1] < span_m:
        j -= 1
    dd = d - pts[j][1]
    da = a - pts[j][2]
    return (da / dd * 100) if dd > 5 else 0.0


print("\nvt(s)  高度(m)  25m平滑坡度   [畫面上DJI顯示過的參考值: 0~6度]")
for i in range(0, len(pts), 15):
    t, d, a = pts[i]
    g = gradient_at(i)
    bar = "#" * min(20, int(abs(g) * 4))
    print(f"{t:6.0f}  {a:7.1f}  {g:+6.1f}%  {bar}")

grads = [gradient_at(i) for i in range(len(pts))]
print(f"\n範圍 {min(grads):+.1f}% ~ {max(grads):+.1f}%  "
      f"(橋面應 ±3% 內，超出太多代表雜訊需再平滑)")
