# -*- coding: utf-8 -*-
"""Spike: one AI call with 6 consecutive frames — does temporal context fix
the failure mode single stills had (direction flip-flops, no sense of who is
passing whom)?

Test window: t=64..69, deliberately chosen because per-frame analysis
previously flip-flopped 左/右 here.
"""
import json
import subprocess
import sys
import time
from pathlib import Path

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

FRAMES_DIR = Path(r"C:\ai\AUTOMOVIE\app\projects\20260802_183358\frames\i1")
# f_%04d.jpg is 1-based: t=64 -> f_0065.jpg
ts = list(range(64, 70))
paths = [FRAMES_DIR / f"f_{t+1:04d}.jpg" for t in ts]
for p in paths:
    assert p.exists(), p

meta = json.loads(Path(r"C:\ai\AUTOMOVIE\app\projects\20260802_183358\project.json")
                  .read_text(encoding="utf-8"))
print("=== 對照組：單張分析當時產出的說明（已清除超車描述前的原始快取已不在，"
      "現況為清理後版本）===")
for f in meta["frames"]:
    if f["t"] in ts:
        print(f"  t={f['t']}s  {f['scene']}")

img_list = "\n".join(f"第{i+1}張(t={t}s): {p}" for i, (t, p) in
                     enumerate(zip(ts, paths)))
prompt = (
    "這是自行車比賽第一人稱行車紀錄的連續畫面，每秒一張、共6張、時間連續"
    f"（影片第64~69秒）。請依序看完6張後，用2~3句繁體中文描述這6秒內"
    "「發生了什麼動態」：我方相對於前方騎士的距離變化、有沒有人的相對位置"
    "明顯改變（誰從哪一側往前移動）、集團隊形變化。"
    "重點是跨張比較的『變化』，不是單張的靜態描述。只回描述文字。\n"
    f"{img_list}"
)

cmd = ["agy", "-p", prompt, "--dangerously-skip-permissions"]
print("\n=== 連拍組：6 張一次丟給 agy ===")
t0 = time.time()
r = subprocess.run(cmd, capture_output=True, text=True,
                   encoding="utf-8", errors="replace", timeout=300)
dt = time.time() - t0
print(f"(耗時 {dt:.1f}s, returncode={r.returncode})")
print(r.stdout.strip() or r.stderr[-500:])
