"""Distinguish a playback-rate error from a constant audio frequency offset.

Usage: python reproduce-timing-offset-check.py ORIGINAL.wav OPEN_SSTV_REPO NEW_OUTPUT_DIR
Requires NumPy, SciPy, Pillow and the pinned Open-SSTV dependencies.
"""
from hashlib import sha256
from pathlib import Path
import json
import os
import subprocess
import sys
import tomllib
import wave

import numpy as np
import scipy
from scipy.signal import hilbert, resample_poly
from PIL import Image

source, repo, output = (Path(p).resolve() for p in sys.argv[1:])
base = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
expected = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
assert sha256(source.read_bytes()).hexdigest() == expected
subprocess.run(["git", "diff", "--exit-code", base, "--", "src"], cwd=repo, check=True)
output.mkdir(exist_ok=False)
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").astype(float)

# Keep every WAV labelled 48 kHz. The deliberately compressed copy therefore
# plays about 1% faster; inverse conversion uses its known experimental ratio.
faster = resample_poly(samples, 100, 101)
restored = resample_poly(faster, 101, 100)[:len(samples)]
# A 1% speed change raises the 1,900 Hz leader by 19 Hz. Compare a
# constant 19 Hz shift that leaves the frame count and scan timing intact.
phase = np.exp(2j * np.pi * 19 * np.arange(len(samples)) / params.framerate)
shifted = np.real(hilbert(samples) * phase)
report = {
    "experiment": "Playback-rate error versus constant frequency shift, 2026-11-12",
    "scope": "Controlled generated file replay in Open-SSTV CLI. No radio, microphone, physical clock measurement or SSTV app test.",
    "source_sha256": expected,
    "decoder_source_base": 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__, "scipy": scipy.__version__,
    "WAV_header_rate_hz": 48000,
    "new_upstream_submission": False, "cases": [],
}
control = None
for name, signal, ratio, offset in [
    ("original", samples, [1, 1], 0),
    ("faster-101-100", faster, [100, 101], 0),
    ("shifted-plus19hz", shifted, [1, 1], 19),
    ("known-ratio-restored", restored, [101, 100], 0),
]:
    pcm = np.clip(np.rint(signal), -32768, 32767).astype("<i2")
    wav_path, image_path = output / f"{name}.wav", output / f"{name}.png"
    with wave.open(str(wav_path), "wb") as wav:
        wav.setparams(params)
        wav.writeframes(pcm.tobytes())
    args = [sys.executable, "-m", "open_sstv.cli.decode", str(wav_path), "-o", str(image_path)]
    decoded = subprocess.run(args, cwd=repo, env={**os.environ, "PYTHONPATH": str(repo / "src")},
                             capture_output=True, text=True, timeout=180)
    log = (decoded.stdout + decoded.stderr).replace(str(output), "OUTPUT").replace(str(repo), "OPEN_SSTV_REPO")
    (output / f"{name}.log").write_text(log)
    dimensions, mae = None, None
    if image_path.exists():
        with Image.open(image_path) as image:
            pixels = np.asarray(image.convert("RGB"), dtype=np.int16)
        dimensions = [pixels.shape[1], pixels.shape[0]]
        if name == "original": control = pixels
        if control is not None and pixels.shape == control.shape:
            mae = float(np.abs(pixels - control).mean())
    start = int(np.flatnonzero(np.abs(pcm) > 100)[0])
    tone = pcm[start:start + int(params.framerate * 0.15)]
    # Zero-padding interpolates the FFT peak grid to 0.5 Hz.
    n_fft = params.framerate * 2
    spectrum = np.abs(np.fft.rfft(tone * np.hanning(len(tone)), n=n_fft))
    leader_peak = float(np.argmax(spectrum) * params.framerate / n_fft)
    row = {
        "name": name, "sample_conversion_up_down": ratio, "frames": len(pcm),
        "constant_shift_hz": offset, "leading_tone_peak_hz": leader_peak,
        "duration_seconds": len(pcm) / params.framerate,
        "input_sha256": sha256(wav_path.read_bytes()).hexdigest(),
        "exit_code": decoded.returncode, "decoded_dimensions": dimensions,
        "image_mae_rgb_0_255_vs_original_decode": mae,
        "decoder_output": log,
        "decode_command": ["python", "-m", "open_sstv.cli.decode", wav_path.name, "-o", image_path.name],
    }
    report["cases"].append(row)
    (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps(row), flush=True)
assert report["cases"][0]["exit_code"] == 0 and report["cases"][0]["decoded_dimensions"] == [320, 240]
assert len(faster) < len(samples) and len(restored) == len(shifted) == len(samples)
assert sha256(source.read_bytes()).hexdigest() == expected
