"""Inspect a local input clip and a Clout review plan without loading Qwen Video Edit."""

import argparse
import json
import subprocess
from pathlib import Path

p = argparse.ArgumentParser(description=__doc__)
p.add_argument("video", type=Path)
p.add_argument("plan", type=Path)
a = p.parse_args()
plan = json.loads(a.plan.read_text())
raw = subprocess.check_output(
    [
        "ffprobe",
        "-v",
        "error",
        "-select_streams",
        "v:0",
        "-show_frames",
        "-show_streams",
        "-show_entries",
        "frame=best_effort_timestamp_time:stream=width,height,r_frame_rate,nb_frames",
        "-of",
        "json",
        str(a.video),
    ],
    text=True,
)
media = json.loads(raw)
frames = media["frames"]
assert len(frames) == plan["sourceFrames"]
size = plan["chunkSize"]
assert size in (45, 81)
count = min(plan["promptCount"], (len(frames) + size - 1) // size)
assert len(plan["chunks"]) == count
real_total = 0
for i, chunk in enumerate(plan["chunks"]):
    start = i * size
    real = min(size, len(frames) - start)
    assert chunk["firstSourceFrame"] == start
    assert chunk["lastSourceFrame"] == start + real - 1
    assert chunk["realFrames"] == real
    assert chunk["paddingFrames"] == size - real
    assert chunk["promptLine"] == i + 1
    assert chunk["outputFrames"] == size
    assert abs(chunk["outputStartSeconds"] - i * size / plan["outputFps"]) < 1e-9
    assert abs(chunk["outputEndSeconds"] - (i + 1) * size / plan["outputFps"]) < 1e-9
    real_total += real
assert plan["unprocessedFrames"] == len(frames) - real_total
assert plan["paddingFrames"] == count * size - real_total
assert plan["plannedOutputFrames"] == count * size
assert abs(plan["plannedOutputSeconds"] - count * size / plan["outputFps"]) < 1e-9
timestamps = [float(f["best_effort_timestamp_time"]) for f in frames]
assert all(abs(t - i / plan["sourceFps"]) < 1e-5 for i, t in enumerate(timestamps)), (
    "This study expects CFR timestamps"
)
print(
    json.dumps(
        {
            "sourceFrames": len(frames),
            "chunks": count,
            "paddingFrames": plan["paddingFrames"],
            "unprocessedFrames": plan["unprocessedFrames"],
            "plannedOutputSeconds": plan["plannedOutputSeconds"],
            "scope": "Independent input and review sheet inspection only, not model execution",
        },
        indent=2,
    )
)
