"""Inspect the original unpacked input bundle with local ffprobe and no model imports."""

import bisect
import csv
import json
import math
import struct
import subprocess
import sys
from pathlib import Path

root = Path(sys.argv[1]).resolve()
with (root / "manifest.csv").open(newline="") as f:
    rows = list(csv.DictReader(f))
assert len(rows) == 1, "This original study has one recording"
row = rows[0]
video = (root / row["proxy_video"]).resolve()
cover = (root / row["first_frame"]).resolve()
assert video.is_relative_to(root) and cover.is_relative_to(root)
assert video.name == "recording.mp4"
prompts = json.loads((video.parent / "prompts.json").read_text())
probe = json.loads(
    subprocess.check_output(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "v:0",
            "-show_frames",
            "-show_entries",
            "stream=width,height,duration,avg_frame_rate:frame=best_effort_timestamp_time",
            "-of",
            "json",
            str(video),
        ]
    )
)
stream = probe["streams"][0]
width, height = stream["width"], stream["height"]
assert (width, height) == (1280, 704)
assert stream["avg_frame_rate"] == "24/1"
assert 4 * 1280 * height <= 5 * width * 704 <= 6 * 1280 * height
available = math.floor(float(stream["duration"]) * 24)
selected = 4 * ((available - 1) // 4) + 1
assert selected == 49
stamps = [float(x["best_effort_timestamp_time"]) for x in probe["frames"]]
stamps = [x - stamps[0] for x in stamps]
midpoints = [(a + b) / 2 for a, b in zip(stamps[:-1], stamps[1:], strict=True)]
indices = [bisect.bisect_left(midpoints, i / 24) for i in range(selected)]
assert indices == list(range(49))
assert all(abs(t - i / 24) < 0.000001 for i, t in enumerate(stamps))
raw = cover.read_bytes()
assert raw[:8] == b"\x89PNG\r\n\x1a\n"
assert struct.unpack(">II", raw[16:24]) == (width, height)
assert isinstance(prompts["staticPrompt"], str) and prompts["staticPrompt"].strip()
for event in prompts["dynamicPrompts"]:
    assert 0 <= event["startMs"] < event["endMs"] <= prompts["durationMs"]
    assert isinstance(event["text"], str) and event["text"].strip()
print(
    json.dumps(
        {
            "dimensions": [width, height],
            "fps": 24,
            "sourceFrames": len(stamps),
            "selectedFrames": selected,
            "referenceContextSamples": len(indices[::4]),
            "coverDimensionsMatch": True,
            "scope": "Independent media and sidecar inspection, not upstream runtime execution",
        },
        indent=2,
    )
)
