"""Locate the 2:39 / 50.2 km-h '里嶺大橋' Strava segment inside the video timeline."""
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]

SEG_SEC = 159        # 2:39
SEG_KMH = 50.2       # leaderboard avg speed
SEG_M = SEG_KMH / 3.6 * SEG_SEC

print(f"target: {SEG_SEC}s  {SEG_KMH} km/h  -> {SEG_M:.0f} m\n")

best = []
for i, (vt, d) in enumerate(pts):
    # find point ~SEG_SEC later
    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 - SEG_KMH), vt, pts[j][0], dist, kmh))
            break

best.sort()
print("best-matching 159s windows (by avg speed closeness):")
for err, a, b, dist, kmh in best[:5]:
    print(f"  video t={a:6.1f} → {b:6.1f}s   {dist:6.0f} m   {kmh:5.2f} km/h   (err {err:.2f})")

# also: fastest 159s window anywhere in the clip
fastest = max(best, key=lambda x: x[4])
print(f"\nfastest 159s window: t={fastest[1]:.0f} → {fastest[2]:.0f}s  {fastest[4]:.2f} km/h")
