"""Compare a narrow audio notch on clean and tone-contaminated Robot 36.

Usage: python reproduce-robot36-notch.py robot36.wav OPEN_SSTV_REPO NEW_RESULTS_DIR
Requires the Open-SSTV 0.6.18 environment and SciPy.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import wave

import numpy as np
from PIL import Image
from scipy import __version__ as scipy_version
from scipy.signal import iirnotch, sosfiltfilt, tf2sos


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


def rms(array):
    return np.sqrt(np.mean(np.square(array)))


source, repo, output = (Path(arg).resolve() for arg in sys.argv[1:])
source_hash = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
decoder_commit = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
if digest(source) != source_hash:
    raise ValueError("Use the public Robot 36 fixture identified by the recorded checksum.")
subprocess.run(["git", "diff", "--exit-code", decoder_commit, "--", "src"], cwd=repo, check=True)
with wave.open(str(source), "rb") as wav:
    params = wav.getparams()
    audio = np.frombuffer(wav.readframes(params.nframes), dtype="<i2").astype(np.float64)
if (params.nchannels, params.sampwidth, params.framerate) != (1, 2, 48000):
    raise ValueError("Expected 48 kHz mono 16-bit PCM.")

rate = params.framerate
window = slice(2 * rate, 34 * rate)
frequency, quality = 1800, 30
tone = np.sin(2 * np.pi * frequency * np.arange(audio.size) / rate)
tone *= rms(audio[window]) / (10 ** (9 / 20) * rms(tone[window]))
mixed = np.rint(audio + tone)
notch = tf2sos(*iirnotch(frequency, quality, fs=rate))
cases = {
    "clean": audio,
    "whistle": mixed,
    "clean-notched": sosfiltfilt(notch, audio),
    "whistle-notched": sosfiltfilt(notch, mixed),
}
output.mkdir()
results = {}
reference = None
for label, samples in cases.items():
    samples = np.rint(samples)
    if samples.min() < -32768 or samples.max() > 32767:
        raise ValueError(f"{label} exceeds the PCM range.")
    wav_path, png = (output / f"{label}.{ext}" for ext in ("wav", "png"))
    if label == "clean":
        wav_path.write_bytes(source.read_bytes())
    else:
        with wave.open(str(wav_path), "wb") as wav:
            wav.setparams(params)
            wav.writeframes(samples.astype("<i2").tobytes())
    args = ["-m", "open_sstv.cli.decode", wav_path.name, "-o", png.name]
    command = subprocess.run([sys.executable, *args], cwd=output, timeout=90,
                             env={**os.environ, "PYTHONPATH": str(repo / "src")},
                             capture_output=True, text=True)
    transcript = (command.stdout + command.stderr).strip()
    (output / f"{label}.log").write_text(transcript + "\n")
    result = {"wav_sha256": digest(wav_path), "command": ["python", *args], "exit": command.returncode,
              "output": transcript, "clipped_samples": 0, "image_size_px": None,
              "mean_absolute_rgb_difference_vs_clean": None}
    if command.returncode == 0 and png.is_file():
        with Image.open(png) as image:
            result["image_size_px"] = list(image.size)
            pixels = np.asarray(image.convert("RGB"), dtype=np.int16)
        if label == "clean":
            reference = pixels
        result["png_sha256"] = digest(png)
        if reference is not None and pixels.shape == reference.shape:
            result["mean_absolute_rgb_difference_vs_clean"] = round(float(np.abs(pixels - reference).mean()), 6)
    results[label] = result

report = {
    "scope": "Generated Robot 36 audio, controlled added tone and offline Open-SSTV decoding.",
    "fixture_url": "https://sstv.org.uk/samples/first-decode/robot36.wav",
    "fixture_sha256": source_hash, "decoder_commit": decoder_commit, "decoder_version": "0.6.18",
    "numpy_version": np.__version__, "scipy_version": scipy_version,
    "mix": {"tone_hz": frequency, "audio_to_tone_rms_db": 9, "gain_measurement_seconds": [2, 34]},
    "filter": {"type": "forward-backward second-order IIR notch", "center_hz": frequency,
               "single_pass_Q": quality, "renormalization": False},
    "results": results,
}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({key: [v["exit"], v["image_size_px"], v["mean_absolute_rgb_difference_vs_clean"]]
                  for key, v in results.items()}))
