"""Compare two tones added to the same generated Robot 36 recording.

Usage: python reproduce-robot36-tone.py robot36.wav OPEN_SSTV_CHECKOUT NEW_RESULTS_DIR
Requires NumPy, Pillow and the Open-SSTV 0.6.18 dependencies.
"""
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 float(np.sqrt(np.mean(samples ** 2)))


source, repo, output = map(lambda p: Path(p).resolve(), sys.argv[1:])
baseline = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
source_hash = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
decoder_version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
if sha256(source) != source_hash or decoder_version != "0.6.18":
    raise ValueError("Use the published fixture and the pinned decoder.")
subprocess.run(["git", "diff", "--exit-code", baseline, "--", "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 16-bit mono PCM.")

rate = params.framerate
t = np.arange(audio.size) / rate
active = slice(2 * rate, 34 * rate)
signal_rms = rms(audio[active])
target_db = 9
output.mkdir()
control = output / "clean.wav"
control.write_bytes(source.read_bytes())
inputs = [(control, None, None)]
for hz in (60, 1800):
    tone = np.sin(2 * np.pi * hz * t)
    delta = tone * (signal_rms / 10 ** (target_db / 20) / rms(tone[active]))
    mixed = np.rint(audio + delta)
    if mixed.min() < -32768 or mixed.max() > 32767:
        raise ValueError(f"The {hz} Hz mix clips.")
    measured_db = round(20 * np.log10(signal_rms / rms((mixed - audio)[active])), 5)
    path = output / f"tone-{hz}hz.wav"
    with wave.open(str(path), "wb") as wav:
        wav.setparams(params)
        wav.writeframes(mixed.astype("<i2").tobytes())
    inputs.append((path, hz, measured_db))

results = []
reference = None
for wav, hz, 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")
    size = rgb_hash = image_hash = difference = None
    if run.returncode == 0 and png.is_file():
        with Image.open(png) as image:
            size = list(image.size)
            pixels = np.asarray(image.convert("RGB"), dtype=np.uint8)
        image_hash = sha256(png)
        rgb_hash = hashlib.sha256(pixels.tobytes()).hexdigest()
        if hz is None:
            if size != [320, 240] or "mode=robot_36" not in transcript:
                raise ValueError("The clean WAV did not decode as expected.")
            reference = pixels.astype(np.int16)
        if reference is not None and pixels.shape == reference.shape:
            difference = round(float(np.mean(np.abs(pixels.astype(np.int16) - reference))), 6)
    results.append({
        "wav": wav.name, "wav_sha256": sha256(wav), "added_tone_hz": hz, "measured_signal_to_tone_db": measured_db,
        "clipped_samples": 0, "command": ["python", *args], "exit_code": run.returncode, "decoder_output": transcript,
        "image_size_px": size, "png_sha256": image_hash, "decoded_rgb_sha256": rgb_hash,
        "mean_absolute_rgb_difference_vs_clean": difference,
    })
if reference is None:
    raise ValueError("The clean WAV produced no image.")
report = {
    "scope": "Generated practice WAV and synthetic single-frequency tones. Offline file replay only; no RF, device, or SSTV app.",
    "fixture": "https://sstv.org.uk/samples/first-decode/robot36.wav", "fixture_sha256": source_hash,
    "decoder_version": decoder_version, "decoder_source_baseline": baseline, "numpy_version": np.__version__,
    "pcm": "48 kHz mono signed 16-bit, matching sample counts", "target_signal_to_tone_db": target_db,
    "measurement_window_seconds": [2, 34], "tone": "Continuous, zero initial phase, unchanged source, no post-mix normalization",
    "results": results,
}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(results, indent=2))
