"""Parse the ride FIT file into a clean per-second timeline + summary."""
import json
import sys
from datetime import timezone, timedelta
from pathlib import Path

import fitparse

FIT = Path(r"C:\ai\AUTOMOVIE\濕背約騎-里嶺_-美濃-茂林_里嶺.fit")
TW = timezone(timedelta(hours=8))

fit = fitparse.FitFile(str(FIT))

records = []
for msg in fit.get_messages("record"):
    d = {f.name: f.value for f in msg}
    ts = d.get("timestamp")
    if ts is None:
        continue
    records.append(
        {
            "t": ts.replace(tzinfo=timezone.utc).astimezone(TW).isoformat(),
            "lat": (d["position_lat"] * 180 / 2**31) if d.get("position_lat") else None,
            "lon": (d["position_long"] * 180 / 2**31) if d.get("position_long") else None,
            "dist_m": d.get("distance"),
            "spd_kmh": round(d["speed"] * 3.6, 1) if d.get("speed") is not None else None,
            "alt_m": d.get("enhanced_altitude", d.get("altitude")),
            "hr": d.get("heart_rate"),
            "cad": d.get("cadence"),
            "pwr": d.get("power"),
            "temp": d.get("temperature"),
        }
    )

sessions = []
for msg in fit.get_messages("session"):
    d = {f.name: f.value for f in msg}
    sessions.append({k: (v.isoformat() if hasattr(v, "isoformat") else v) for k, v in d.items()})

laps = []
for msg in fit.get_messages("lap"):
    d = {f.name: f.value for f in msg}
    laps.append({k: (v.isoformat() if hasattr(v, "isoformat") else v) for k, v in d.items()})

out = {"records": records, "sessions": sessions, "laps": laps}
Path(r"C:\ai\AUTOMOVIE\ride_data.json").write_text(
    json.dumps(out, ensure_ascii=False, default=str), encoding="utf-8"
)

# --- summary to stdout ---
sys.stdout.reconfigure(encoding="utf-8")
print(f"records: {len(records)}  laps: {len(laps)}  sessions: {len(sessions)}")
if records:
    print(f"start: {records[0]['t']}")
    print(f"end  : {records[-1]['t']}")
    print(f"dist : {(records[-1]['dist_m'] or 0)/1000:.2f} km")


def stat(key):
    vals = [r[key] for r in records if r.get(key) is not None]
    if not vals:
        return f"{key}: (none)"
    return f"{key}: avg {sum(vals)/len(vals):.1f}  max {max(vals):.1f}  n={len(vals)}"


for k in ("spd_kmh", "hr", "cad", "pwr", "alt_m", "temp"):
    print(stat(k))

if sessions:
    s = sessions[0]
    print("\n--- session ---")
    for k in (
        "start_time", "total_elapsed_time", "total_timer_time", "total_distance",
        "total_ascent", "total_descent", "avg_speed", "max_speed", "avg_heart_rate",
        "max_heart_rate", "avg_power", "max_power", "normalized_power", "total_calories",
        "avg_cadence", "sport",
    ):
        if k in s:
            print(f"  {k}: {s[k]}")
