#!/usr/bin/env python3
"""Compare audio files on disk with size = kbps x 1000 x seconds / 8.

Usage:
  python3 size-check.py --kbps 96 episode.mp3 [more files ...]
  python3 size-check.py --kbps 96 --list paths.txt   (one path per line; Windows line breaks are fine)
  python3 size-check.py episode.mp3                  (no --kbps: uses the audio stream's bitrate)

--kbps is the bitrate you chose at export. Without it the script reads the audio stream's bit_rate, never
ffprobe's format bit_rate (file size / duration, which counts cover art as "bitrate"). The comparison
only means something for constant-bitrate (CBR) MP3: a VBR or AAC file has no fixed size to compare with,
and its stream bitrate is its own average. Embedded pictures and other non-audio streams are listed.
Needs ffprobe (part of FFmpeg) on the PATH. MB = 1,000,000 bytes, MiB = 1,048,576 bytes.
"""
import json, os, subprocess, sys


def probe(path):
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,codec_name,bit_rate",
         "-of", "json", path],
        capture_output=True, text=True,
    )
    if out.returncode != 0:
        return None
    data = json.loads(out.stdout or "{}")
    streams = data.get("streams", [])
    audio = [s for s in streams if s.get("codec_type") == "audio"]
    try:
        dur = float(data["format"]["duration"])
    except (KeyError, ValueError):
        return None
    if not audio:
        return None
    try:
        br = int(audio[0]["bit_rate"])
    except (KeyError, ValueError):
        br = None
    others = [f'{s.get("codec_type")}/{s.get("codec_name")}' for s in streams if s.get("codec_type") != "audio"]
    return dur, br, audio[0].get("codec_name", "?"), others


def is_vbr_mp3(path):
    # LAME writes an "Info" header in CBR files and a "Xing" header in VBR files, near the start of the audio.
    with open(path, "rb") as f:
        head = f.read(1 << 16)
    return b"Xing" in head and b"Info" not in head


def check(path, kbps_arg):
    if not os.path.isfile(path):
        return f"{path} | missing file"
    size = os.path.getsize(path)
    if size == 0:
        return f"{path} | empty file (0 bytes)"
    got = probe(path)
    if got is None:
        return f"{path} | not readable as audio by ffprobe"
    dur, br, codec, others = got
    if kbps_arg is not None:
        kbps, src = kbps_arg, "export"
    elif br is not None:
        kbps, src = round(br / 1000), "stream"
    else:
        return f"{path} | no audio bitrate in the file: run again with --kbps"
    formula = kbps * 1000 * dur / 8
    diff = size - formula
    extra = " | non-audio streams: " + ", ".join(others) if others else ""
    if codec != "mp3":
        note = f" | {codec}: not CBR MP3, size depends on the audio"
    elif is_vbr_mp3(path):
        note = " | VBR MP3: size depends on the audio"
    else:
        note = ""
    return (f"{path} | {size} bytes = {size/1e6:.1f} MB = {size/1048576:.1f} MiB | {dur:.2f} s | "
            f"{kbps} kbps ({src}) | formula {formula:.0f} | diff {diff:+.0f} bytes ({diff/formula*100:+.3f}%)"
            f"{extra}{note}")


def main(argv):
    kbps = None
    if len(argv) >= 2 and argv[0] == "--kbps":
        try:
            kbps = int(argv[1])
        except ValueError:
            kbps = 0
        if kbps <= 0:
            print("--kbps needs a whole number above 0, for example --kbps 96"); return 2
        argv = argv[2:]
    if not argv:
        print(__doc__.strip()); return 2
    if argv[0] == "--list":
        if len(argv) < 2 or not os.path.isfile(argv[1]):
            print("list file not found"); return 1
        with open(argv[1], encoding="utf-8-sig", newline="") as f:
            paths = [line.strip("\r\n ") for line in f.read().splitlines()]
        paths = [p for p in paths if p]
        if not paths:
            print("list file is empty"); return 1
    else:
        paths = argv
    print("file | bytes | duration | bitrate | formula bytes | difference")
    for p in paths:
        print(check(p, kbps))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
