#!/usr/bin/env python3
import json
import re
import subprocess
import sys
from pathlib import Path


def media_path(argv):
    for item in reversed(argv[1:]):
        if not item.startswith("-"):
            return item
    return None


def run_ffmpeg(path):
    ffmpeg = Path(__file__).with_name("ffmpeg")
    proc = subprocess.run(
        [str(ffmpeg), "-hide_banner", "-i", str(path)],
        capture_output=True,
        text=True,
    )
    return (proc.stderr or "") + "\n" + (proc.stdout or "")


def parse_duration(text):
    m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", text)
    if not m:
        return 0.0
    h, mnt, sec = m.groups()
    return int(h) * 3600 + int(mnt) * 60 + float(sec)


def parse_video(text):
    stream = re.search(r"Video:.*?(\d{2,5})x(\d{2,5}).*?(?:(\d+(?:\.\d+)?)\s+fps)?", text)
    if not stream:
        return None
    width, height, fps = stream.groups()
    fps = fps or "30"
    if "." in fps:
        rate = f"{int(round(float(fps) * 1000))}/1000"
    else:
        rate = f"{fps}/1"
    return {
        "width": int(width),
        "height": int(height),
        "r_frame_rate": rate,
    }


def main():
    path = media_path(sys.argv)
    if not path:
        print("ffprobe wrapper: missing input path", file=sys.stderr)
        return 2

    text = run_ffmpeg(path)
    duration = parse_duration(text)

    if "csv=p=0" in sys.argv:
        print(f"{duration:.6f}")
        return 0

    if "json" in sys.argv:
        video = parse_video(text) or {"width": 0, "height": 0, "r_frame_rate": "0/1"}
        print(json.dumps({"streams": [video], "format": {"duration": f"{duration:.6f}"}}))
        return 0

    print(f"{duration:.6f}")
    return 0


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