#!/usr/bin/env python3
"""Check a video podcast export against YouTube and Spotify targets (koldflux.com, 2026-12-01).
Needs ffprobe (part of FFmpeg) on your PATH. Reads size, length, resolution and frame rate of your export (a short
test export works; we suggest 1-5 minutes) and prints its real total bitrate, MB per minute, GB per hour and the size of
the full episode (--minutes, default 60), in decimal GB (1,000,000,000 bytes) and in the "GB" Windows shows (GiB).
It then compares the bitrate with YouTube's recommended SDR video bitrate for that resolution (the shorter side, so a
vertical 1080x1920 file counts as 1080p) and frame rate plus 384 kbps stereo audio (for 4K the top of YouTube's range,
45,000 or 68,000 kbps, so a 35,000 kbps 4K file shows as about 78%), and the full episode with Spotify's "less than 10 GB" recommendation and 60 GB limit and
YouTube's 256 GB limit (platform figures read on 2026-12-01).
Usage: python3 episode-size.py [--minutes 75] export.mp4 [more files]"""
import argparse, os, shutil, subprocess, sys

# YouTube recommended SDR video bitrates in kbps: shorter side -> (24-30 fps, 48-60 fps); 4K is a range, top end used here.
YT = {720: (5000, 7500), 1080: (8000, 12000), 1440: (16000, 24000), 2160: (45000, 68000)}

def probe(path):
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,avg_frame_rate,bit_rate",
                        "-of", "default=nw=1", path], capture_output=True, text=True)
    if r.returncode != 0:
        return None, (r.stderr.strip().splitlines() or ["ffprobe could not read the file"])[-1]
    info = {"streams_bps": 0}
    for line in r.stdout.splitlines():
        k, _, v = line.partition("=")
        if k == "bit_rate" and v.isdigit():
            info["streams_bps"] += int(v)
        elif k == "codec_type" and v == "video":
            info["video"] = True
        elif k in ("width", "height", "avg_frame_rate") and "video" in info and k not in info:
            info[k] = v
        elif k == "duration":
            info[k] = v
    return info, ""

def last_packet_time(path):
    """End time in seconds of the last packet that can really be read. Catches a cut-off copy whose header (MP4, MOV)
    or duration tag (MKV, WebM) still describes the full length."""
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "packet=pts_time,duration_time", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    end = 0.0
    for line in r.stdout.splitlines():
        try:
            nums = [float(x) for x in line.split(",")[:2] if x not in ("", "N/A")]
        except ValueError:
            continue
        if nums:
            end = max(end, sum(nums))
    return end

def fps(rate):
    n, _, d = (rate or "0/1").partition("/")
    try:
        return float(n) / float(d or 1)
    except (ValueError, ZeroDivisionError):
        return 0.0

def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--minutes", type=float, default=60, help="length of the full episode in minutes (default 60)")
    ap.add_argument("files", nargs="+")
    a = ap.parse_args()
    if a.minutes <= 0:
        print("--minutes must be more than 0"); sys.exit(1)
    if not shutil.which("ffprobe"):
        print("ffprobe not found: install FFmpeg (it includes ffprobe) and make sure ffprobe is on your PATH"); sys.exit(1)
    bad = 0
    for f in a.files:
        f = f.rstrip("\r")  # a name pasted from a Windows text file can end in a carriage return
        if not os.path.isfile(f) or os.path.getsize(f) == 0:
            print(f"{f}: missing or empty"); bad = 1; continue
        info, err = probe(f)
        if info is None:
            print(f"{f}: not readable ({err})"); bad = 1; continue
        try:
            dur = float(info.get("duration", ""))
        except ValueError:
            dur = 0.0
        if dur <= 0:
            print(f"{f}: length unknown (the export may be unfinished); export again and let it complete"); bad = 1; continue
        size = os.path.getsize(f)
        expect = info["streams_bps"] * dur / 8
        if expect and size < 0.9 * expect:
            print(f"{f}: truncated or incomplete copy ({size:,} bytes, the header describes about {expect:,.0f}); "
                  "measure the original export"); bad = 1; continue
        end = last_packet_time(f)
        if end < 0.9 * dur:
            print(f"{f}: truncated or incomplete copy (the header says {dur:.1f} s, data ends at {end:.1f} s); "
                  "measure the original export"); bad = 1; continue
        kbps = size * 8 / dur / 1000
        full = size / dur * a.minutes * 60
        print(f"{f}: {size:,} bytes in {dur:.1f} s = {kbps:,.0f} kbps, {size / dur * 60 / 1e6:.1f} MB/min, "
              f"{size / dur * 3600 / 1e9:.2f} GB/h")
        print(f"  {a.minutes:g} min episode: {full / 1e9:.2f} GB ({full / 2**30:.2f} GB as Windows shows it)")
        if "video" not in info:
            print("  no video stream: audio-only file, platform video targets skipped")
        else:
            h = min(int(info.get("width", "0") or 0), int(info.get("height", "0") or 0))
            r = fps(info.get("avg_frame_rate"))
            row = min(YT, key=lambda k: abs(k - h))
            target = YT[row][1 if r > 31 else 0] + 384
            print(f"  YouTube {row}p at {r:.0f} fps: recommended about {target:,} kbps with stereo audio"
                  + (" (top of its 4K range)" if row == 2160 else "") + f"; your file is {kbps / target * 100:.0f}% of that")
        print("  Spotify: " + ("under the 10 GB recommendation" if full < 10e9 else
                               "over the 10 GB recommendation, still accepted up to 60 GB" if full <= 60e9 else
                               "over the 60 GB limit: lower the bitrate or split the episode")
              + "; YouTube: " + ("under the 256 GB limit" if full <= 256e9 else "over the 256 GB limit"))
        if dur < 60:
            print(f"  note: only {dur:.1f} s; a short stretch may not be typical of the whole episode, we suggest 1-5 minutes")
    sys.exit(bad)

if __name__ == "__main__":
    main()
