"""Compare a generated Robot 36 WAV with filtered and peak-matched copies.

Usage: python reproduce-low-pass-gain.py ROBOT36.wav OPEN_SSTV_REPO NEW_OUTPUT_DIR
Requires FFmpeg, numpy, Pillow and the Open-SSTV CLI dependencies.
"""
import hashlib
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import tomllib
import wave

import numpy as np
from PIL import Image

source, repo, output = (Path(value).resolve() for value in sys.argv[1:])
baseline = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
profile = (1, 2, 48000, 1839120)


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


def read_pcm(path):
    with wave.open(str(path), "rb") as audio:
        observed = (audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getnframes())
        if observed != profile:
            raise ValueError(f"Unexpected WAV format for {path.name}: {observed}")
        return np.frombuffer(audio.readframes(profile[-1]), dtype="<i2").astype(np.int32)


expected_hash = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
if digest(source) != expected_hash:
    raise ValueError("Use the published generated Robot 36 fixture.")
version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
if version != "0.6.18":
    raise ValueError("Use Open-SSTV 0.6.18.")
subprocess.run(["git", "diff", "--exit-code", baseline, "--", "src"], cwd=repo, check=True)
output.mkdir()
control, filtered, matched = (output / f"{label}.wav" for label in ("control", "lowpass-1800", "lowpass-1800-peak-matched"))
control.write_bytes(source.read_bytes())
ffmpeg = ["ffmpeg", "-nostdin", "-v", "error", "-i", str(source), "-af",
          "lowpass=f=1800:p=2,lowpass=f=1800:p=2", "-c:a", "pcm_s16le", filtered.name]
subprocess.run(ffmpeg, cwd=output, timeout=30, check=True)
control_peak = np.abs(read_pcm(control)).max()
filtered_pcm = read_pcm(filtered)
filtered_peak = np.abs(filtered_pcm).max()
gain = control_peak / filtered_peak
matched_samples = np.rint(filtered_pcm * gain)
if matched_samples.min() < -32768 or matched_samples.max() > 32767:
    raise ValueError("Peak matching would clip.")
with wave.open(str(matched), "wb") as wav:
    wav.setparams((*profile, "NONE", "not compressed"))
    wav.writeframes(matched_samples.astype("<i2").tobytes())

cases = []
reference = None
env = {**os.environ, "PYTHONPATH": str(repo / "src")}
for path in (control, filtered, matched):
    image_path = path.with_suffix(".png")
    command = [sys.executable, "-m", "open_sstv.cli.decode", path.name, "-o", image_path.name]
    result = subprocess.run(command, cwd=output, env=env, capture_output=True, text=True, timeout=90)
    path.with_suffix(".log").write_text(result.stdout + result.stderr)
    if result.returncode != 0:
        raise RuntimeError(f"{path.name} did not decode. See its log.")
    with Image.open(image_path) as image:
        rgb = np.asarray(image.convert("RGB"), dtype=np.int16)
    if reference is None:
        reference = rgb
    if rgb.shape != (240, 320, 3):
        raise ValueError(f"Expected a 320 × 240 picture from {path.name}.")
    delta = np.abs(rgb - reference)
    cases.append({"case": path.stem, "peak_pcm": int(np.abs(read_pcm(path)).max()), "wav_sha256": digest(path),
                  "decoder_exit": result.returncode, "decode_command": ["python", *command[1:]],
                  "png_sha256": digest(image_path), "decoded_size_px": [320, 240],
                  "changed_pixels": int(np.any(delta, axis=2).sum()),
                  "mean_absolute_rgb_difference_0_to_255": round(float(delta.mean()), 3)})
record = {"scope": "One generated Robot 36 WAV decoded offline; no radio, microphone, hardware or app measurement.",
          "source_url": "https://sstv.org.uk/samples/first-decode/robot36.wav", "source_sha256": expected_hash,
          "decoder_version": version, "decoder_source_baseline": baseline, "filter_command": ffmpeg,
          "ffmpeg": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0],
          "pcm_format": "48 kHz 16-bit mono; all variants have the same sample count",
          "applied_peak_match_gain_db": round(20 * math.log10(gain), 3),
          "cases": cases}
(output / "report.json").write_text(json.dumps(record, indent=2) + "\n")
print(json.dumps({"gain_db": record["applied_peak_match_gain_db"], "results": [(x["case"], x["peak_pcm"], x["changed_pixels"], x["mean_absolute_rgb_difference_0_to_255"]) for x in cases]}))
