"""Convert local ffprobe frame JSON into media presentation milliseconds.

Run ffprobe separately as documented in the guide then pass its local JSON file.
Only the chosen video stream should be included in that JSON.
"""
import json
import math
import sys
from pathlib import Path


def convert(path):
    raw = Path(path)
    if raw.stat().st_size > 8 * 1024 * 1024:
        raise ValueError("Keep the input under eight MB")
    frames = json.loads(raw.read_text())["frames"]
    if not 3 <= len(frames) <= 10000:
        raise ValueError("Use three to 10000 video frames")
    times = [float(frame["best_effort_timestamp_time"]) for frame in frames]
    if any(not math.isfinite(t) for t in times):
        raise ValueError("Every frame needs a finite presentation timestamp")
    if any(b < a for a, b in zip(times, times[1:])):
        raise ValueError("Out of order timestamps need investigation not sorting")
    rebased = [(t - times[0]) * 1000 for t in times]
    if not 0 < rebased[-1] <= 600000:
        raise ValueError("Use a positive span no longer than ten minutes")
    return "timestamp_ms\n" + "\n".join(f"{t:.6f}" for t in rebased) + "\n"


if __name__ == "__main__":
    try:
        if len(sys.argv) != 2:
            raise ValueError("Pass one local ffprobe JSON filename")
        output = convert(sys.argv[1])
    except (ValueError, KeyError, TypeError, OSError) as error:
        sys.exit(f"Could not convert frame timestamps: {error}")
    print(output, end="")
