"""Measure real audio crossings: master -> lossy/lossless encode -> decode.

Claim tested per crossing: "true peak stays at or below -1.0 dBTP after this encode".
Oracle: ffmpeg's ebur128 filter (ITU-R BS.1770 loudness, 4x-oversampled true peak),
run on the pre-encode master and on the decoded encode. Neither the claim checker nor
the predictor wrote the oracle.

Writes audio_crossings.json. Deterministic inputs; every file is SHA-256 hashed.
"""
from __future__ import annotations

import hashlib
import json
import re
import subprocess
from pathlib import Path

import numpy as np
from scipy.io import wavfile

SR, DUR, LIMIT = 48000, 8.0, -1.0
WORK = Path("work_audio")
WORK.mkdir(exist_ok=True)

CODECS = [  # (label, ffmpeg args, extension)
    ("MP3 128k", ["-c:a", "libmp3lame", "-b:a", "128k"], "mp3"),
    ("MP3 320k", ["-c:a", "libmp3lame", "-b:a", "320k"], "mp3"),
    ("AAC 128k", ["-c:a", "aac", "-b:a", "128k"], "m4a"),
    ("AAC 256k", ["-c:a", "aac", "-b:a", "256k"], "m4a"),
    ("Opus 96k", ["-c:a", "libopus", "-b:a", "96k"], "opus"),
    ("Opus 160k", ["-c:a", "libopus", "-b:a", "160k"], "opus"),
    ("Vorbis q3", ["-c:a", "libvorbis", "-q:a", "3"], "ogg"),
    ("Vorbis q6", ["-c:a", "libvorbis", "-q:a", "6"], "ogg"),
    ("FLAC", ["-c:a", "flac", "-sample_fmt", "s32"], "flac"),
]
PEAKS = [-4.0, -3.0, -2.0, -1.5, -1.2, -1.0, -0.5]


def signals() -> dict[str, np.ndarray]:
    t = np.arange(int(SR * DUR)) / SR
    r = np.random.default_rng(20261021)
    sig = {}
    sig["Sine 997 Hz"] = np.sin(2 * np.pi * 997 * t)
    saw = 2 * ((110 * t) % 1) - 1
    sig["Bright sawtooth"] = saw + 0.5 * (2 * ((220.5 * t) % 1) - 1)
    white = r.normal(size=t.size)
    pink = np.fft.irfft(np.fft.rfft(white) / np.sqrt(np.maximum(np.arange(t.size // 2 + 1), 1)), t.size)
    sig["Pink noise"] = pink
    clicks = np.zeros_like(t)
    for k in range(0, t.size, SR // 4):
        n = np.arange(min(4000, t.size - k))
        clicks[k:k + n.size] += np.exp(-n / 300) * np.sin(2 * np.pi * 180 * n / SR) + 0.6 * np.exp(-n / 40) * r.normal(size=n.size)
    sig["Drum transients"] = clicks
    sig["Chord pad"] = sum(np.sin(2 * np.pi * f * t + p) for f, p in [(220, 0), (277.18, 1), (329.63, 2), (440, .5)])
    hats = np.zeros_like(t)
    for k in range(0, t.size, SR // 8):
        n = np.arange(min(1500, t.size - k))
        hats[k:k + n.size] += np.exp(-n / 150) * np.diff(r.normal(size=n.size + 1))
    sig["Bass and hats"] = np.sin(2 * np.pi * 55 * t) + 0.4 * np.sin(2 * np.pi * 110 * t) + 0.8 * hats
    out = {}
    for name, x in sig.items():
        right = np.roll(x, 37)  # small inter-channel offset so stereo is not mono
        out[name] = np.stack([x, right], 1)
    return out


def sha(p: Path) -> str:
    return hashlib.sha256(p.read_bytes()).hexdigest()


def ebur128(p: Path) -> tuple[float, float]:
    res = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(p), "-filter_complex",
                          "ebur128=peak=true", "-f", "null", "-"], capture_output=True, text=True, check=True)
    summ = res.stderr[res.stderr.rfind("Summary:"):]
    i = float(re.search(r"I:\s+(-?[\d.]+|-inf) LUFS", summ).group(1))
    tp = float(re.search(r"True peak:\s+Peak:\s+(-?[\d.]+|-inf) dBFS", summ, re.S).group(1))
    return i, tp


def main():
    version = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True).stdout.splitlines()[0]
    records = []
    for name, x in signals().items():
        x = x / np.max(np.abs(x))
        for pk in PEAKS:
            master = WORK / f"{name.replace(' ', '_')}_{pk:+.1f}.wav"
            wavfile.write(master, SR, (x * 10 ** (pk / 20)).astype(np.float32))
            pre_i, pre_tp = ebur128(master)
            for label, args, ext in CODECS:
                enc = master.with_name(master.stem + "_" + label.replace(" ", "_") + "." + ext)
                subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(master), *args, str(enc)], check=True)
                post_i, post_tp = ebur128(enc)
                records.append({
                    "id": f"A-{len(records) + 1:03d}", "substrate": "audio", "signal": name, "codec": label,
                    "sample_peak_dbfs": pk, "pre_true_peak_dbtp": pre_tp, "post_true_peak_dbtp": post_tp,
                    "pre_lufs": pre_i, "post_lufs": post_i, "limit_dbtp": LIMIT,
                    "holds": post_tp <= LIMIT, "overshoot_db": round(max(0.0, post_tp - LIMIT), 2),
                    "master_sha256": sha(master), "encoded_sha256": sha(enc),
                })
        print(name, "done")
    meta = {"oracle": "ffmpeg ebur128 filter (ITU-R BS.1770 integrated loudness, 4x-oversampled true peak)",
            "ffmpeg": version, "claim": f"post-encode true peak <= {LIMIT} dBTP", "sample_rate": SR, "seconds": DUR,
            "script_sha256": sha(Path(__file__))}
    Path("audio_crossings.json").write_text(json.dumps({"meta": meta, "records": records}, indent=1))
    n = len(records); h = sum(r["holds"] for r in records)
    print(f"{n} crossings, {h} hold, {n - h} fail")


if __name__ == "__main__":
    main()
