"""Read local media roles with an existing ffprobe, without model inference."""

import argparse
import json
import math
import shutil
import subprocess
from pathlib import Path


def positive(value):
    try:
        number = float(value)
        return number if math.isfinite(number) and number > 0 else None
    except (TypeError, ValueError):
        return None


def inspect(path, binary):
    if not Path(path).is_file():
        raise ValueError("A local input file is missing")
    local_path = str(Path(path).resolve())
    result = subprocess.run(
        [
            binary,
            "-v",
            "error",
            "-protocol_whitelist",
            "file",
            "-show_streams",
            "-show_format",
            "-of",
            "json",
            "-i",
            local_path,
        ],
        capture_output=True,
        text=True,
        timeout=10,
        check=False,
    )
    if result.returncode:
        raise ValueError("ffprobe could not read a local input")
    data = json.loads(result.stdout)
    streams = data.get("streams", [])
    visual = next((s for s in streams if s.get("codec_type") == "video"), {})
    duration = positive(visual.get("duration")) or positive(data.get("format", {}).get("duration"))
    return {
        "width": positive(visual.get("width")),
        "height": positive(visual.get("height")),
        "duration_seconds": duration,
        "frames": positive(visual.get("nb_frames")),
        "has_audio": any(s.get("codec_type") == "audio" for s in streams),
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", required=True)
    parser.add_argument("--driver", required=True)
    parser.add_argument("--mode", choices=["motion", "speech"], required=True)
    args = parser.parse_args()
    report = {
        "scope": "media_roles_only",
        "unverified": [
            "face detection",
            "crop quality",
            "model compatibility",
            "lip sync",
            "inference",
        ],
    }
    try:
        binary = shutil.which("ffprobe")
        if not binary:
            raise ValueError("An existing ffprobe installation is required")
        source = inspect(args.source, binary)
        driver = inspect(args.driver, binary)
        report.update(source=source, driver=driver, mode=args.mode)
        if not source["width"] or not source["height"]:
            raise ValueError("Source has no readable visual dimensions")
        if args.mode == "speech" and not driver["has_audio"]:
            raise ValueError("Speech driver has no audio stream")
        if args.mode == "motion" and not (
            driver["width"]
            and driver["height"]
            and driver["duration_seconds"]
            and driver["frames"]
            and driver["frames"] > 1
        ):
            raise ValueError(
                "Motion driver needs video dimensions duration and multiple known frames"
            )
        report["media_roles_match"] = True
    except (ValueError, OSError, subprocess.TimeoutExpired):
        report["media_roles_match"] = False
        report["error"] = (
            "Input roles could not be verified; inspect local files and ffprobe availability"
        )
    print(json.dumps(report, indent=2))
    return 0 if report["media_roles_match"] else 2


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