"""Compare a brief silence with excised samples in a generated Robot 36 WAV.

Usage: python reproduce-audio-dropout.py ROBOT36.wav OPEN_SSTV_REPO NEW_OUTPUT_DIR
Use Open-SSTV 0.6.18 with its dependencies, plus NumPy and Pillow.
"""
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

source, repo, output = (Path(arg).resolve() for arg in sys.argv[1:])
source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
assert source_hash == "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
decoder_base = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
subprocess.run(["git", "diff", "--exit-code", decoder_base, "--", "src"], cwd=repo, check=True)
with wave.open(str(source)) as wav:
    params = wav.getparams()
    assert (params.nchannels, params.sampwidth, params.framerate) == (1, 2, 48000)
    samples = np.frombuffer(wav.readframes(params.nframes), dtype="<i2")
output.mkdir()
start = 12 * params.framerate
stop = start + 3 * params.framerate // 10
silenced = samples.copy()
silenced[start:stop] = 0
excised = np.concatenate((samples[:start], samples[stop:]))
cases = []
control = None
for label, signal in [("control", samples), ("silence", silenced), ("excised", excised)]:
    audio_path = output / f"{label}.wav"
    image_path = output / f"{label}.png"
    with wave.open(str(audio_path), "wb") as wav:
        wav.setparams(params)
        wav.writeframes(signal.tobytes())
    command = [sys.executable, "-m", "open_sstv.cli.decode", str(audio_path), "-o", str(image_path)]
    result = subprocess.run(command, cwd=repo, env={**os.environ, "PYTHONPATH": str(repo / "src")},
                            capture_output=True, text=True, timeout=180)
    log = (result.stdout + result.stderr).replace(str(output), "OUTPUT")
    (output / f"{label}.log").write_text(log)
    dimensions = None
    band_mae = None
    if image_path.exists():
        with Image.open(image_path) as image:
            pixels = np.asarray(image.convert("RGB"), dtype=np.int16)
        dimensions = list(pixels.shape[1::-1])
        if label == "control":
            control = pixels
        if control is not None and pixels.shape == control.shape:
            delta = np.abs(pixels - control)
            band_mae = {name: round(float(delta[lo:hi].mean()), 3)
                        for name, lo, hi in [("rows_0_to_59", 0, 60),
                                             ("rows_60_to_99", 60, 100),
                                             ("rows_100_to_239", 100, 240)]}
    cases.append({
        "case": label, "frames": len(signal), "duration_seconds": len(signal) / params.framerate,
        "audio_sha256": hashlib.sha256(audio_path.read_bytes()).hexdigest(),
        "image_sha256": hashlib.sha256(image_path.read_bytes()).hexdigest() if image_path.exists() else None,
        "command": ["python", "-m", "open_sstv.cli.decode", audio_path.name, "-o", image_path.name],
        "return_code": result.returncode, "decoder_output": log, "size_px": dimensions,
        "mean_absolute_rgb_difference_by_row_range": band_mae,
    })
report = {
    "scope": "Generated 48 kHz mono PCM file replay. No microphone, receiver, RF signal or SSTV app test.",
    "source_sha256": source_hash, "decoder_source_base": decoder_base,
    "decoder_checkout": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip(),
    "decoder_version": tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"],
    "python": sys.version.split()[0], "numpy": np.__version__,
    "interval_seconds": [12.0, 12.3], "cases": cases,
}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
assert cases[0]["return_code"] == 0 and cases[0]["size_px"] == [320, 240]
