"""Slice the FIT timeline to the video window and detect highlight moments.

Video sync (verified by OCR of the burned-in timestamp at 12 sample points):
    real_time = 2026-08-01 08:57:01 (+08:00) + video_seconds
"""
import json
import sys
from datetime import datetime, timezone, timedelta
from pathlib import Path

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

TW = timezone(timedelta(hours=8))
VIDEO_T0 = datetime(2026, 8, 1, 8, 57, 1, tzinfo=TW)
VIDEO_DUR = 220.203
TITLE_CARD_END = 7.0  # leaderboard screenshot covers the frame until here

data = json.loads(Path(r"C:\ai\AUTOMOVIE\ride_data.json").read_text(encoding="utf-8"))

win = []
for r in data["records"]:
    t = datetime.fromisoformat(r["t"])
    vt = (t - VIDEO_T0).total_seconds()
    if -5 <= vt <= VIDEO_DUR + 5:
        r = dict(r)
        r["vt"] = round(vt, 1)
        win.append(r)

print(f"window records: {len(win)}  (video 0..{VIDEO_DUR:.0f}s)")
if not win:
    sys.exit("NO OVERLAP - check sync")

print(f"first: vt={win[0]['vt']}  {win[0]['t']}")
print(f"last : vt={win[-1]['vt']}  {win[-1]['t']}")

d0 = win[0]["dist_m"] or 0
d1 = win[-1]["dist_m"] or 0
print(f"distance covered in window: {(d1 - d0)/1000:.2f} km")


def series(key):
    return [(r["vt"], r[key]) for r in win if r.get(key) is not None]


print("\n--- window stats ---")
for k, label, unit in [
    ("spd_kmh", "speed", "km/h"),
    ("hr", "HR", "bpm"),
    ("pwr", "power", "W"),
    ("cad", "cadence", "rpm"),
    ("alt_m", "alt", "m"),
]:
    s = series(k)
    if not s:
        continue
    vals = [v for _, v in s]
    mx = max(s, key=lambda x: x[1])
    print(
        f"{label:8s} avg {sum(vals)/len(vals):6.1f}  max {mx[1]:6.1f} {unit} @ video t={mx[0]:.0f}s"
    )

# --- highlight detection ---
print("\n--- highlights ---")
hi = []

# peak power bursts (>=400W sustained 3s)
run = []
for vt, p in series("pwr"):
    if p >= 400:
        run.append((vt, p))
    else:
        if len(run) >= 3:
            hi.append(("POWER", run[0][0], run[-1][0], f"{max(x[1] for x in run):.0f}W 爆發 {len(run)}秒"))
        run = []
if len(run) >= 3:
    hi.append(("POWER", run[0][0], run[-1][0], f"{max(x[1] for x in run):.0f}W 爆發 {len(run)}秒"))

# top speed moments (>=55 km/h)
run = []
for vt, s in series("spd_kmh"):
    if s >= 55:
        run.append((vt, s))
    else:
        if len(run) >= 3:
            hi.append(("SPEED", run[0][0], run[-1][0], f"破 {max(x[1] for x in run):.1f} km/h 持續 {len(run)}秒"))
        run = []
if len(run) >= 3:
    hi.append(("SPEED", run[0][0], run[-1][0], f"破 {max(x[1] for x in run):.1f} km/h 持續 {len(run)}秒"))

# HR zone 5 (>=178 assuming max ~185)
run = []
for vt, h in series("hr"):
    if h >= 178:
        run.append((vt, h))
    else:
        if len(run) >= 5:
            hi.append(("HR", run[0][0], run[-1][0], f"心率紅區 {max(x[1] for x in run):.0f} bpm 撐 {len(run)}秒"))
        run = []
if len(run) >= 5:
    hi.append(("HR", run[0][0], run[-1][0], f"心率紅區 {max(x[1] for x in run):.0f} bpm 撐 {len(run)}秒"))

for kind, a, b, desc in sorted(hi, key=lambda x: x[1]):
    print(f"  [{kind:6s}] t={a:6.0f} → {b:6.0f}s  {desc}")

# per-10s table for scripting
print("\n--- 10s timeline (video t / speed / HR / power / cad / alt) ---")
by_vt = {round(r["vt"]): r for r in win}
for vt in range(0, int(VIDEO_DUR) + 1, 10):
    r = by_vt.get(vt)
    if not r:
        continue
    print(
        f"  t={vt:3d}  {r['spd_kmh'] or 0:5.1f} km/h  {r['hr'] or 0:3.0f} bpm  "
        f"{r['pwr'] or 0:4.0f} W  {r['cad'] or 0:3.0f} rpm  {r['alt_m'] or 0:5.1f} m"
    )

Path(r"C:\ai\AUTOMOVIE\window_data.json").write_text(
    json.dumps({"records": win, "highlights": hi}, ensure_ascii=False), encoding="utf-8"
)
print("\nwrote window_data.json")
