#!/usr/bin/env python3
"""Measure the test encodes of the video podcast file size guide (Koldflux, 2026-12-01).

Usage: python3 measure.py <output folder>
Reads every .mp4 with ffprobe and prints, per file: duration, size, video and audio stream bitrates, GB per hour
(size / duration x 3600 / 1,000,000,000) and, for files made at a target bitrate, the formula
(video kbps + audio kbps) x 1,000 x 3,600 / 8 / 1,000,000,000 and the difference in percent.
Control with a known answer: a two-pass or CBR file must land within 2% of the formula, and the 300 s file must give
the same bytes per second as the 60 s file within 2%. If a control fails, the script says CONTROL-FAIL.
"""
import json
import os
import re
import subprocess
import sys

if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]):
    sys.exit("usage: measure.py <output folder>")
folder = sys.argv[1]


def probe(path):
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration,size:stream=codec_type,bit_rate",
                        "-of", "json", path], capture_output=True, text=True)
    if r.returncode != 0:
        raise SystemExit(f"ffprobe failed on {path}: {r.stderr.strip()}")
    j = json.loads(r.stdout)
    st = {s["codec_type"]: int(s.get("bit_rate", 0)) for s in j["streams"]}
    return float(j["format"]["duration"]), int(j["format"]["size"]), st.get("video", 0), st.get("audio", 0)


rows, fails = {}, []
print("file | duration s | bytes | video kbps | audio kbps | GB/h measured | target v+a kbps | GB/h formula | diff %")
for name in sorted(os.listdir(folder)):
    if not name.endswith(".mp4"):
        continue
    d, size, vb, ab = probe(os.path.join(folder, name))
    gbh = size / d * 3600 / 1e9
    m = re.search(r"-(?:yt|sp)(\d+)(?:cbr)?-a(\d+)", name)
    line = f"{name} | {d:.3f} | {size} | {vb / 1000:.0f} | {ab / 1000:.0f} | {gbh:.3f}"
    if m:
        target = int(m.group(1)) + int(m.group(2))
        formula = target * 1000 * 3600 / 8 / 1e9
        diff = (gbh / formula - 1) * 100
        line += f" | {target} | {formula:.3f} | {diff:+.2f}"
        if abs(diff) > 2:
            fails.append(f"{name} {diff:+.2f}% from the formula")
    else:
        line += " | quality target (CRF), no formula | - | -"
    rows[name] = (d, size, vb, ab, gbh)
    print(line)

print()
print("derived:")
def r(n):
    return rows[n]
a, b = r("c1080-yt8000-a384.mp4"), r("c1080-yt8000-a384-300s.mp4")
bps60, bps300 = a[1] / a[0], b[1] / b[0]
lc = (bps300 / bps60 - 1) * 100
print(f"length control: 60 s file {bps60:.0f} bytes/s, 300 s file {bps300:.0f} bytes/s, difference {lc:+.2f}%")
if abs(lc) > 2:
    fails.append(f"length control {lc:+.2f}%")
au = r("c1080-yt8000-a384.mp4")[1] - r("c1080-yt8000-a128.mp4")[1]
print(f"audio 384 vs 128 kbps at 8000 kbps video: +{au} bytes per 60 s = {au / 60 * 3600 / 1e9:.3f} GB/h "
      f"(formula 256 kbps = {256 * 1000 * 3600 / 8 / 1e9:.3f} GB/h)")
for res, yt in (("c1080", "c1080-yt8000-a384.mp4"), ("k2160", "k2160-yt35000-a384.mp4")):
    for q in (18, 23):
        n = f"{res}-crf{q}-a384.mp4"
        print(f"{n}: {r(n)[4]:.3f} GB/h = {r(n)[4] / r(yt)[4] * 100:.1f}% of {yt} ({r(yt)[4]:.3f} GB/h); "
              f"video stream {r(n)[2] / 1000:.0f} kbps")
for q in (18, 23):
    k4, k1 = r(f"k2160-crf{q}-a384.mp4"), r(f"k1080-crf{q}-a384.mp4")
    print(f"same 4K footage at CRF {q}: 2160p {k4[4]:.3f} GB/h vs 1080p {k1[4]:.3f} GB/h, ratio {k4[4] / k1[4]:.2f}")
print()
print("CONTROL-FAIL: " + "; ".join(fails) if fails else "CONTROLS-OK (every target-bitrate file within 2% of the formula, length control within 2%)")
