"""Compare one generated Robot 36 WAV with two MP3-to-PCM round trips.

Usage: python reproduce-mp3-roundtrip.py ROBOT36.wav OPEN_SSTV_REPO NEW_OUTPUT_DIR
Requires FFmpeg with libmp3lame, plus Open-SSTV 0.6.18 and its dependencies.
"""
import hashlib
import json
import os
from pathlib import Path
import shutil
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()
expected = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
if source_hash != expected:
    raise ValueError("Use the unchanged practice WAV")
version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
if version != "0.6.18":
    raise ValueError("Use Open-SSTV 0.6.18")
base = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
subprocess.run(["git", "diff", "--exit-code", base, "--", "src"], cwd=repo, check=True)
output.mkdir()
shutil.copyfile(source, output / "control.wav")
ffmpeg = ["ffmpeg", "-nostdin", "-v", "error"]
cases = []
reference = None
for label, bitrate in [("control", None), ("mp3-32k", "32k"), ("mp3-128k", "128k")]:
    audio = f"{label}.wav"
    png = f"{label}.png"
    encode = decode = None
    if bitrate is not None:
        encoded = f"{label}.mp3"
        encode = ffmpeg + ["-i", "control.wav", "-c:a", "libmp3lame", "-b:a", bitrate, "-ar", "48000", encoded]
        decode = ffmpeg + ["-i", encoded, "-c:a", "pcm_s16le", audio]
        for command in (encode, decode):
            subprocess.run(command, cwd=output, check=True, timeout=60)
    with wave.open(str(output / audio), "rb") as wav:
        fmt = [wav.getnchannels(), wav.getsampwidth(), wav.getframerate(), wav.getnframes()]
    if fmt != [1, 2, 48000, 1839120]:
        raise ValueError(f"{label}: unexpected PCM format or duration {fmt}")
    command = [sys.executable, "-m", "open_sstv.cli.decode", audio, "-o", png]
    result = subprocess.run(command, cwd=output, env={**os.environ, "PYTHONPATH": str(repo / "src")},
                            capture_output=True, text=True, timeout=180)
    log = result.stdout + result.stderr
    (output / f"{label}.log").write_text(log)
    image_hash = dimensions = error = same = None
    if (output / png).is_file():
        with Image.open(output / png) as image:
            dimensions = list(image.size)
            pixels = np.asarray(image.convert("RGB"), dtype=np.int16)
        image_hash = hashlib.sha256((output / png).read_bytes()).hexdigest()
        if bitrate is None:
            reference = pixels
        if reference is not None and reference.shape == pixels.shape:
            error = round(float(np.abs(pixels - reference).mean()), 3)
            same = bool(np.array_equal(pixels, reference))
    cases.append({"case": label, "mp3_bitrate": bitrate, "encode": encode, "return_to_pcm": decode,
                  "pcm_format_channels_bytes_rate_frames": fmt,
                  "wav_sha256": hashlib.sha256((output / audio).read_bytes()).hexdigest(),
                  "mp3_sha256": hashlib.sha256((output / encoded).read_bytes()).hexdigest() if bitrate else None,
                  "decode_command": ["python", *command[1:]], "decode_exit": result.returncode,
                  "decoder_output": log, "image_sha256": image_hash, "size_px": dimensions,
                  "average_absolute_rgb_difference_0_to_255": error, "pixel_identical_to_control": same})
report = {"scope": "Generated file replay in Open-SSTV. No RF signal, microphone, voice processing or SSTV Signal Desk app test.",
          "source_sha256": source_hash, "decoder_source_base": base,
          "decoder_checkout": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip(),
          "decoder_version": version, "python": sys.version.split()[0], "numpy": np.__version__,
          "ffmpeg": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0], "cases": cases}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
if cases[0]["decode_exit"] != 0 or cases[0]["size_px"] != [320, 240]:
    raise RuntimeError("The unchanged control did not decode")
