# -*- coding: utf-8 -*-
"""Re-check the leaderboard's 159s / 50.2km/h segment window if it's anchored
near the very start of the clip (right after the title card) instead of the
previously-matched 55s->214s window, per rider's correction that timing
starts essentially at video open."""
import json
import sys
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")
win = json.loads(Path(r"C:\ai\AUTOMOVIE\window_data.json").read_text(encoding="utf-8"))["records"]
pts = [(r["vt"], r["dist_m"]) for r in win if r.get("dist_m") is not None]
by_vt = {round(r["vt"]): r for r in win}

SEG_SEC = 159
TARGET_KMH = 50.2

def window_stats(a, b):
    da = by_vt.get(a, {}).get("dist_m")
    db = by_vt.get(b, {}).get("dist_m")
    if da is None or db is None:
        return None
    dur = b - a
    dist = db - da
    return dist, dist/dur*3.6

for label, a in [("title card end (~7s)", 7), ("video absolute start (0s)", 0)]:
    b = a + SEG_SEC
    r = window_stats(a, b)
    if r:
        dist, kmh = r
        print(f"{label}: {a}->{b}s  dist={dist:.0f}m  avg={kmh:.2f} km/h  (target {TARGET_KMH})")

print("\n--- best-matching 159s window anywhere (for reference, previously found) ---")
best = []
for i, (vt, d) in enumerate(pts):
    for j in range(i, len(pts)):
        if pts[j][0] - vt >= SEG_SEC:
            dur = pts[j][0] - vt
            dist = pts[j][1] - d
            kmh = dist / dur * 3.6
            best.append((abs(kmh - TARGET_KMH), vt, pts[j][0], dist, kmh))
            break
best.sort()
for err, a, b, dist, kmh in best[:3]:
    print(f"  t={a:.0f}->{b:.0f}s  {dist:.0f}m  {kmh:.2f} km/h  (err {err:.2f})")

print("\n--- speed profile, first 60s (to see how fast he's actually going at the very start) ---")
for t in range(0, 61, 5):
    r = by_vt.get(t)
    if r:
        print(f"  t={t:3d}s  {r.get('spd_kmh',0):5.1f} km/h  HR {r.get('hr',0):3.0f}  {r.get('pwr',0):4.0f} W")
