"""Read local source/mask container alignment with an existing ffprobe."""

import argparse
import json
import shutil
import subprocess
from fractions import Fraction
from pathlib import Path


def inspect(path, binary):
    local = Path(path)
    if not local.is_file():
        raise ValueError("Missing local file")
    result = subprocess.run(
        [
            binary,
            "-v",
            "error",
            "-protocol_whitelist",
            "file",
            "-count_frames",
            "-select_streams",
            "v:0",
            "-show_entries",
            "stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate",
            "-of",
            "json",
            "-i",
            str(local.resolve()),
        ],
        capture_output=True,
        text=True,
        timeout=30,
        check=False,
    )
    if result.returncode:
        raise ValueError("Unreadable local media")
    streams = json.loads(result.stdout).get("streams", [])
    if not streams:
        raise ValueError("No visual stream")
    stream = streams[0]
    values = {key: int(stream[key]) for key in ["width", "height", "nb_read_frames"]}
    rate = Fraction(stream["avg_frame_rate"])
    nominal = Fraction(stream["r_frame_rate"])
    if min(values.values()) <= 0 or values["nb_read_frames"] < 2 or rate <= 0 or nominal <= 0:
        raise ValueError("Unknown or invalid video metadata")
    return {**values, "average_fps": str(rate), "nominal_fps": str(nominal)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", required=True)
    parser.add_argument("--mask", required=True)
    args = parser.parse_args()
    report = {
        "scope": "container_alignment_only",
        "unverified": [
            "per-frame timestamps",
            "mask polarity",
            "mask pixels",
            "subject coverage",
            "conditioning pixels",
            "model compatibility",
            "inference",
        ],
    }
    try:
        binary = shutil.which("ffprobe")
        if not binary:
            raise ValueError("Existing ffprobe required")
        source, mask = inspect(args.source, binary), inspect(args.mask, binary)
        report.update(source=source, mask=mask)
        report["container_alignment_match"] = source == mask
    except (ValueError, KeyError, TypeError, OSError, subprocess.TimeoutExpired, ZeroDivisionError):
        report["container_alignment_match"] = False
        report["error"] = "Could not verify known video dimensions frame counts and rates"
    print(json.dumps(report, indent=2))
    return 0 if report["container_alignment_match"] else 2


if __name__ == "__main__":
    raise SystemExit(main())
