"""Verify lossless Robot 36 audio sharing with the published generated fixture.

Usage: python reproduce-flac-roundtrip.py robot36.wav OPEN_SSTV_CHECKOUT NEW_OUTPUT_DIR
Requires FFmpeg, Pillow and the dependencies of Open-SSTV 0.6.18.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tomllib
import wave

from PIL import Image

source, repo, output = (Path(value).resolve() for value in sys.argv[1:])
baseline = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
expected_fixture = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"


def digest(data):
    return hashlib.sha256(data).hexdigest()


def pcm(path):
    with wave.open(str(path), "rb") as file:
        format_fields = (file.getnchannels(), file.getsampwidth(), file.getframerate(), file.getnframes())
        return format_fields, file.readframes(file.getnframes())


version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
if version != "0.6.18" or digest(source.read_bytes()) != expected_fixture:
    raise ValueError("Use the published Robot 36 fixture and Open-SSTV 0.6.18 source.")
subprocess.run(["git", "diff", "--exit-code", baseline, "--", "src"], cwd=repo, check=True)
output.mkdir()
control = output / "control.wav"
control.write_bytes(source.read_bytes())
commands = [
    ["ffmpeg", "-nostdin", "-v", "error", "-i", "control.wav", "-map", "0:a:0", "-c:a", "flac", "share.flac"],
    ["ffmpeg", "-nostdin", "-v", "error", "-i", "share.flac", "-map", "0:a:0", "-c:a", "pcm_s16le", "restored.wav"],
]
for command in commands:
    subprocess.run(command, cwd=output, timeout=30, check=True)
restored = output / "restored.wav"
format_fields, samples = pcm(control)
if (format_fields, samples) != pcm(restored):
    raise ValueError("The round trip changed the PCM samples or their format.")
results = []
for wav in (control, restored):
    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)
    wav.with_suffix(".log").write_text(run.stdout + run.stderr)
    run.check_returncode()
    with Image.open(png) as image:
        size = image.size
        rgb_sha = digest(image.convert("RGB").tobytes())
    results.append({"input": wav.name, "wav_sha256": digest(wav.read_bytes()), "wav_bytes": wav.stat().st_size,
                    "decode_command": ["python", *args], "decoder_exit": run.returncode,
                    "image_size_px": size, "decoded_rgb_sha256": rgb_sha, "png_sha256": digest(png.read_bytes())})
if results[0]["decoded_rgb_sha256"] != results[1]["decoded_rgb_sha256"] or results[0]["image_size_px"] != (320, 240):
    raise ValueError("The restored WAV produced different decoded pixels or an unexpected size.")
flac = output / "share.flac"
report = {"scope": "Generated Robot 36 fixture, offline file conversion and CLI-only WAV decode; no iOS, direct FLAC import or RF test.",
          "source_url": "https://sstv.org.uk/samples/first-decode/robot36.wav", "source_baseline": baseline,
          "decoder_version": version, "ffmpeg_version": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0],
          "conversion_commands": commands, "pcm": {"channels": format_fields[0], "bits": format_fields[1] * 8,
          "sample_rate_hz": format_fields[2], "samples_per_channel": format_fields[3], "sha256_both": digest(samples), "identical": True},
          "flac": {"bytes": flac.stat().st_size, "sha256": digest(flac.read_bytes())}, "wav_decodes": results,
          "decoded_pixels_identical": True}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"wav_bytes": results[0]["wav_bytes"], "flac_bytes": flac.stat().st_size, "pcm": report["pcm"], "pixel_match": True}))
