#!/usr/bin/env python3

import sys
import subprocess
import logging

import coloredlogs

coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s")
log = logging.getLogger()


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]

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,
    "-b:v",
    str(video_br_bi),
    "-b:a",
    str(audio_br_bi),
    out_file,
]

subprocess.run(cmd, check=True)