#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Optional Operavue synthetic-media verification v1.0. Python 3.9+.

Requires installed ffmpeg with libx264 encoding, ffprobe, and the timestamp
inspector. Installs nothing, downloads nothing, and uses no existing recordings.
All evidence is retained in a new output directory. Exit 0 means these synthetic
checks passed; exit 1 means verification failed; exit 2 means invalid invocation.
This does not validate cameras, exposure clocks, synchronization, clinical use,
or attached-artwork exclusion. It does not establish performance on other builds.

MIT License
Copyright (c) 2026 Operavue

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import argparse
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys

VERSION = "1.0"
TOLERANCE = Fraction(1, 1000000)
LIMITS = ("Synthetic generated media only; no camera, exposure-clock, synchronization, "
          "clinical-suitability, or attached-artwork-exclusion validation. "
          "Results apply to the recorded tool builds and fixtures, not all media.")


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def write_json(path, value):
    with path.open("x", encoding="utf-8") as handle:
        json.dump(value, handle, indent=2)
        handle.write("\n")


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--output", type=Path, required=True, help="Fresh, nonexisting evidence directory")
    parser.add_argument("--inspector", type=Path, default=Path(__file__).with_name("audit-video-timestamps.py"))
    parser.add_argument("--ffmpeg", default="ffmpeg")
    parser.add_argument("--ffprobe", default="ffprobe")
    args = parser.parse_args()
    ffmpeg, ffprobe = shutil.which(args.ffmpeg), shutil.which(args.ffprobe)
    if not ffmpeg or not ffprobe or not args.inspector.is_file():
        parser.error("Installed ffmpeg, ffprobe, and an existing inspector script are required; nothing is installed automatically.")
    output, inspector = args.output.absolute(), args.inspector.resolve()
    try:
        output.mkdir(parents=True, exist_ok=False)
    except OSError as error:
        parser.error("--output must be a new, writable directory: " + str(error))
    commands, cases = [], []
    summary = {"verification_version": VERSION, "status": "failed", "scope": LIMITS,
               "inspector_sha256": hashlib.sha256(inspector.read_bytes()).hexdigest(), "cases": cases}
    expected = {"timestamp_tolerance_seconds": "0.000001", "max_gap_ms": "50",
                "regular": {"frames": 60, "compared_pairs": 59, "stream_index": 0,
                            "timestamp_rule": "n/30, n = 0..59", "gap_candidates": 0, "inspector_exit": 0},
                "shifted": {"frames": 60, "compared_pairs": 59, "stream_index": 0,
                            "timestamp_rule": "n/30 + (1/10 if n >= 30 else 0), n = 0..59",
                            "gap_candidates": 1, "gap_pair": [29, 30],
                            "gap_seconds_exact": "2/15", "gap_ms_approximate": "133.333333", "inspector_exit": 1},
                "multistream": {"selected_stream_index": 1, "selected_frames": 60,
                                "other_video_stream_index": 2, "other_video_frames": 12, "inspector_exit": 0},
                "invalid": {"ffprobe_exit": "nonzero", "error_log": "nonempty", "inspector": "skipped"}}
    write_json(output / "expected-observations.json", expected)

    def run(label, argv, clean=True):
        record = {"label": label, "argv": [str(value) for value in argv],
                  "stdout": label + ".stdout", "stderr": label + ".stderr"}
        commands.append(record)
        with (output / record["stdout"]).open("xb") as stdout, (output / record["stderr"]).open("xb") as stderr:
            try:
                completed = subprocess.run(record["argv"], stdout=stdout, stderr=stderr,
                                           stdin=subprocess.DEVNULL, timeout=120, check=False)
                record["exit_code"] = completed.returncode
            except (OSError, subprocess.TimeoutExpired) as error:
                record["execution_error"] = str(error)
                raise RuntimeError(label + " could not complete; see commands.json") from error
        if clean:
            require(record["exit_code"] == 0 and (output / record["stderr"]).stat().st_size == 0,
                    label + " failed or logged errors; partial output is not accepted")
        return record

    def read_stdout(record):
        return json.loads((output / record["stdout"]).read_text(encoding="utf-8"))

    def generate(name, rate, frames, shifted=False):
        # Both the finite source and frame limit bound generation; no output-duration truncation.
        pattern = "testsrc" if name == "secondary" else "testsrc2"
        source = "{}=size=160x120:rate={}:duration={}".format(pattern, rate, frames // rate)
        timing = r"settb=1/30000,setpts=PTS+if(gte(N\,30)\,3000\,0)" if shifted else "settb=1/30000"
        run(name + "-encode", [ffmpeg, "-nostdin", "-v", "error", "-n", "-f", "lavfi", "-i", source,
            "-frames:v", str(frames), "-vf", timing, "-c:v", "libx264", "-crf", "0", "-pix_fmt", "yuv420p",
            "-enc_time_base", "1/30000", "-video_track_timescale", "30000", "-fps_mode", "passthrough", output / (name + ".mp4")])

    def inspect(name, shifted=False, stream=0):
        media = output / (name + ".mp4")
        diagnostic = run(name + "-streams", [ffprobe, "-v", "error", "-protocol_whitelist", "file",
            "-count_frames", "-show_streams", "-show_format", "-of", "json", "-i", media])
        # This is the published export recipe, unchanged except for the synthetic input path.
        exported = run(name + "-frames", [ffprobe, "-v", "error", "-protocol_whitelist", "file",
            "-select_streams", "V:0", "-show_frames", "-show_entries",
            "frame=media_type,stream_index,best_effort_timestamp_time", "-show_optional_fields", "always", "-of", "json", "-i", media])
        frames = read_stdout(exported)["frames"]
        require(len(frames) == 60, name + ": decoded frame count differs from 60")
        for index, frame in enumerate(frames):
            wanted = Fraction(index, 30) + (Fraction(1, 10) if shifted and index >= 30 else 0)
            require(frame.get("media_type") == "video" and frame.get("stream_index") == stream,
                    name + ": incorrect selected stream metadata")
            require(abs(Fraction(frame["best_effort_timestamp_time"]) - wanted) <= TOLERANCE,
                    name + ": unexpected timestamp at frame " + str(index))
        audited = run(name + "-report", [sys.executable, inspector, output / exported["stdout"], "--max-gap-ms", "50"], clean=False)
        require(audited["exit_code"] == (1 if shifted else 0) and (output / audited["stderr"]).stat().st_size == 0,
                name + ": unexpected inspector exit or error log")
        report = read_stdout(audited)
        counts = report["counts"]
        require(all(counts[key] == value for key, value in {"frames": 60, "valid_timestamps": 60,
                "compared_pairs": 59, "adjacent_pairs": 59, "skipped_pairs": 0, "missing_timestamps": 0,
                "invalid_timestamps": 0, "duplicate_intervals": 0, "backward_intervals": 0,
                "gap_candidates": int(shifted), "issues_total": int(shifted)}.items()), name + ": unexpected findings/counts")
        require(report["stream_metadata"] == {"observed_indices": [stream], "frames_with_stream_index": 60,
                "frames_with_media_type": 60}, name + ": incomplete report stream identity")
        require(report["status"] == ("timestamp_findings" if shifted else "no_timestamp_findings"), name + ": incorrect status")
        if shifted:
            issue = report["issue_preview"][0]
            require(issue["type"] == "gap_candidate" and issue["previous_frame_index"] == 29 and issue["frame_index"] == 30,
                    "shifted: gap is not at the known 29/30 boundary")
            require(abs(Fraction(issue["interval_ms"]) / 1000 - Fraction(2, 15)) <= 2 * TOLERANCE,
                    "shifted: gap interval does not match 133.333 ms")
        hashes = output / (name + "-decoded.framehash")
        run(name + "-hash", [ffmpeg, "-nostdin", "-v", "error", "-n", "-protocol_whitelist", "file", "-i", media,
            "-map", "0:V:0", "-c:v", "rawvideo", "-pix_fmt", "yuv420p", "-fps_mode", "passthrough",
            "-enc_time_base", "demux", "-f", "framehash", "-hash", "sha256", hashes])
        pixel_hashes = [line.split(",")[-1].strip() for line in hashes.read_text().splitlines() if line and not line.startswith("#")]
        require(len(pixel_hashes) == 60, name + ": decoded hash sequence does not contain 60 frames")
        cases.append({"name": name, "status": "passed", "frames": 60, "selected_stream_index": stream,
                      "gap_candidates": int(shifted), "inspector_exit": audited["exit_code"]})
        return pixel_hashes, read_stdout(diagnostic)["streams"]

    try:
        for tool, path in (("ffmpeg", ffmpeg), ("ffprobe", ffprobe)):
            record = run(tool + "-version", [path, "-version"])
            summary[tool + "_version"] = (output / record["stdout"]).read_text().splitlines()[0]
        generate("regular", 30, 60)
        generate("shifted", 30, 60, shifted=True)
        regular_hashes, _ = inspect("regular")
        shifted_hashes, _ = inspect("shifted", shifted=True)
        require(regular_hashes == shifted_hashes, "Decoded ordered pixel hashes differ between regular and shifted fixtures")
        summary["regular_shifted_ordered_pixel_hashes_equal"] = True
        generate("secondary", 12, 12)
        run("multistream-mux", [ffmpeg, "-nostdin", "-v", "error", "-n", "-f", "lavfi", "-i",
            "anullsrc=r=48000:cl=mono:d=2", "-protocol_whitelist", "file", "-i", output / "regular.mp4",
            "-protocol_whitelist", "file", "-i", output / "secondary.mp4", "-map", "0:a:0", "-map", "1:v:0",
            "-map", "2:v:0", "-c:a", "aac", "-c:v", "copy", output / "multistream.mp4"])
        multi_hashes, streams = inspect("multistream", stream=1)
        require([(item["index"], item["codec_type"]) for item in streams] == [(0, "audio"), (1, "video"), (2, "video")],
                "multistream: actual audio/video stream ordering differs")
        require(int(streams[1]["nb_read_frames"]) == 60 and int(streams[2]["nb_read_frames"]) == 12,
                "multistream: independent decoded stream counts differ")
        require(multi_hashes == regular_hashes, "Selected multistream video pixels differ from regular fixture")
        (output / "invalid.mp4").write_text("Deliberately invalid synthetic text, not media.\n", encoding="utf-8")
        invalid = run("invalid-frames", [ffprobe, "-v", "error", "-protocol_whitelist", "file", "-select_streams", "V:0",
            "-show_frames", "-show_entries", "frame=media_type,stream_index,best_effort_timestamp_time",
            "-show_optional_fields", "always", "-of", "json", "-i", output / "invalid.mp4"], clean=False)
        require(invalid["exit_code"] != 0 and (output / invalid["stderr"]).stat().st_size > 0,
                "Invalid synthetic media did not fail with a logged FFprobe error")
        cases.append({"name": "invalid", "status": "passed", "ffprobe_exit": invalid["exit_code"], "inspector": "skipped"})
        summary["status"] = "passed"
    except (OSError, ValueError, KeyError, IndexError, TypeError, RuntimeError) as error:
        summary["error"] = str(error)
    finally:
        write_json(output / "commands.json", commands)
        write_json(output / "summary.json", summary)
    print("Evidence directory: " + str(output))
    print(json.dumps(summary, indent=2))
    return 0 if summary["status"] == "passed" else 1


if __name__ == "__main__":
    sys.exit(main())
