"""Compare a generated Robot 36 WAV with repeatable baseband noise.

Usage: python reproduce-robot36-noise.py robot36.wav OPEN_SSTV_CHECKOUT NEW_OUTPUT_DIR
Requires NumPy, Pillow and the dependencies of Open-SSTV 0.6.18.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tomllib
import wave

import numpy as np
from PIL import Image


def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def rms(samples):
    return np.sqrt(np.mean(samples ** 2))


source, repo, output = (Path(value).resolve() for value in sys.argv[1:])
baseline = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
expected_fixture = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
if version != "0.6.18" or sha256(source) != expected_fixture:
    raise ValueError("Use the published Robot 36 fixture and Open-SSTV 0.6.18 source.")
subprocess.run(["git", "diff", "--exit-code", baseline, "--", "src"], cwd=repo, check=True)
with wave.open(str(source), "rb") as wav:
    params = wav.getparams()
    if (params.nchannels, params.sampwidth, params.framerate) != (1, 2, 48000):
        raise ValueError("Expected a 48 kHz mono signed 16-bit WAV.")
    samples = np.frombuffer(wav.readframes(params.nframes), dtype="<i2").astype(np.float64)

seed = 20261125
low_hz, high_hz = 1000, 3000
start_s, stop_s = 2, 34
active = slice(start_s * params.framerate, stop_s * params.framerate)
signal_rms = rms(samples[active])
spectrum = np.fft.rfft(np.random.default_rng(seed).standard_normal(samples.size))
frequencies = np.fft.rfftfreq(samples.size, 1 / params.framerate)
spectrum[(frequencies < low_hz) | (frequencies > high_hz)] = 0
noise = np.fft.irfft(spectrum, n=samples.size)
noise /= rms(noise[active])

output.mkdir()
control = output / "clean.wav"
control.write_bytes(source.read_bytes())
inputs = [(control, None, None)]
for target_db in (18, 9, 3):
    noisy = output / f"noise-{target_db}db.wav"
    mixed = np.rint(samples + noise * signal_rms / 10 ** (target_db / 20))
    if mixed.min() < -32768 or mixed.max() > 32767:
        raise ValueError(f"The {target_db} dB mix clips.")
    measured_db = 20 * np.log10(signal_rms / rms(mixed[active] - samples[active]))
    with wave.open(str(noisy), "wb") as wav:
        wav.setparams(params)
        wav.writeframes(mixed.astype("<i2").tobytes())
    inputs.append((noisy, target_db, round(float(measured_db), 5)))

results = []
reference = None
for wav, target_db, measured_db in inputs:
    png = wav.with_suffix(".png")
    args = ["-m", "open_sstv.cli.decode", wav.name, "-o", png.name]
    run = subprocess.run([sys.executable, *args], cwd=output, env={**os.environ, "PYTHONPATH": str(repo / "src")},
                         timeout=90, capture_output=True, text=True)
    transcript = (run.stdout + run.stderr).strip()
    wav.with_suffix(".log").write_text(transcript + "\n")
    frame_size = image_sha = rgb_sha = difference = None
    if run.returncode == 0 and png.is_file():
        with Image.open(png) as image:
            frame_size = list(image.size)
            rgb = np.array(image.convert("RGB"), dtype=np.int16)
        image_sha = sha256(png)
        rgb_sha = hashlib.sha256(rgb.astype(np.uint8).tobytes()).hexdigest()
        if target_db is None:
            if frame_size != [320, 240] or "mode=robot_36" not in transcript:
                raise ValueError("The clean control did not decode as expected.")
            reference = rgb
        if reference is not None and rgb.shape == reference.shape:
            difference = round(float(np.mean(np.abs(rgb - reference))), 6)
    results.append({"input": wav.name, "wav_sha256": sha256(wav), "target_audio_snr_db": target_db,
                    "measured_pcm_snr_db": measured_db, "clipped_samples": 0, "decode_command": ["python", *args],
                    "decoder_exit": run.returncode, "decoder_output": transcript, "image_size_px": frame_size,
                    "png_sha256": image_sha, "decoded_rgb_sha256": rgb_sha, "mean_absolute_rgb_difference": difference})
if reference is None:
    raise ValueError("The clean WAV produced no image.")
report = {
    "scope": "Generated Robot 36 fixture plus synthesized band-limited noise. Offline file/CLI experiment only.",
    "fixture": "https://sstv.org.uk/samples/first-decode/robot36.wav",
    "fixture_sha256": expected_fixture,
    "decoder_source_baseline": baseline,
    "decoder_version": version,
    "numpy_version": np.__version__,
    "pcm": "48 kHz, mono, 16-bit",
    "noise": {"rng_seed": seed, "passband_hz": [low_hz, high_hz], "rms_window_seconds": [start_s, stop_s],
              "applied_to": "entire file with the same noise realization in each mix"},
    "results": results,
}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps([{k: item[k] for k in ("input", "decoder_exit", "image_size_px", "mean_absolute_rgb_difference",
                                       "measured_pcm_snr_db")} for item in results], indent=2))
