#!/usr/bin/env nix-shell
#! nix-shell -i python3 --pure
#! nix-shell -p python3 ffmpeg

# Compress a video to make it fit under a certain size.
# Usage: videoQuota SIZE SRC DST
# SIZE: destination video size in bytes
# SRC: source video file
# DST: destination video file
# Example: videoQuota 20971520 source.mov dest.mp4
# To make a ~20 MiB MP4 of a MOV video

import subprocess
import sys


def duration_file(path: str) -> float:
    cmd = [
        "ffprobe",
        "-v",
        "error",
        "-show_entries",
        "format=duration",
        "-of",
        "default=noprint_wrappers=1:nokey=1",
        path,
    ]
    run = subprocess.run(cmd, stdout=subprocess.PIPE, check=True)
    ret = run.stdout.decode().strip()
    return float(ret)


# Constants
audio_br_bi = 128000

# TODO Arguments if you feel like it
quota_by = int(sys.argv[1])
in_file = sys.argv[2]
out_file = sys.argv[3]
filters = sys.argv[4:]

quota_bi = quota_by * 8
duration = duration_file(in_file)
tot_br_bi = quota_bi / duration
video_br_bi = int(tot_br_bi - audio_br_bi)
assert video_br_bi > 0, "Not even enough space for audio"

cmd = (
    [
        "ffmpeg",
        "-i",
        in_file,
    ]
    + filters
    + [
        "-b:v",
        str(video_br_bi),
        "-b:a",
        str(audio_br_bi),
        out_file,
    ]
)

print(" ".join(cmd))
subprocess.run(cmd, check=True)