"""Compare an intact SSTV WAV, cuts at its end, and padding after a cut.

Usage: python reproduce-short-recording.py ROBOT36.wav OPEN_SSTV_REPO NEW_OUTPUT_DIR
Use Python with Open-SSTV's dependencies and Pillow available.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tomllib
import wave

from PIL import Image, ImageChops

source, repo, output = (Path(arg).resolve() for arg in sys.argv[1:])
digest = lambda blob: hashlib.sha256(blob).hexdigest()
expected = "dbb64c8cb34d3599c5aa7c36144746039632832da554eefff324a9fc68ae0166"
if digest(source.read_bytes()) != expected:
    raise ValueError("Use the unchanged generated Robot 36 practice WAV")
version = tomllib.loads((repo / "pyproject.toml").read_text())["project"]["version"]
base = "f773bd4fcb9da0c68ab915e9a1fa2c024bfdcc98"
if version != "0.6.18":
    raise ValueError("Use Open-SSTV 0.6.18")
subprocess.run(["git", "diff", "--exit-code", base, "--", "src"], cwd=repo, check=True)
with wave.open(str(source), "rb") as wav:
    params = wav.getparams()
    if (params.nchannels, params.sampwidth, params.framerate) != (1, 2, 48000):
        raise ValueError("Expected mono 16-bit 48 kHz PCM")
    pcm = wav.readframes(params.nframes)

output.mkdir()
results = []
reference = None
for label, cut_seconds, pad in [
    ("control", 0, False),
    ("trim-quiet-tail", 0.4, False),
    ("cut-final-five-seconds", 5, False),
    ("cut-final-five-seconds-pad", 5, True),
]:
    cut_bytes = round(cut_seconds * params.framerate) * params.sampwidth
    audio = pcm[:len(pcm) - cut_bytes]
    removed = pcm[len(audio):]
    if pad:
        audio += bytes(cut_bytes)
    wav_path = output / f"{label}.wav"
    png = f"{label}.png"
    if label == "control":
        wav_path.write_bytes(source.read_bytes())
    else:
        with wave.open(str(wav_path), "wb") as wav:
            wav.setparams(params)
            wav.writeframes(audio)
    command = [sys.executable, "-m", "open_sstv.cli.decode", wav_path.name, "-o", png]
    run = subprocess.run(command, cwd=output, env={**os.environ, "PYTHONPATH": str(repo / "src")},
                         capture_output=True, text=True, timeout=180)
    log = run.stdout + run.stderr
    (output / f"{label}.log").write_text(log)
    image_path = output / png
    width_height = identical = changed_rows = png_hash = None
    if image_path.is_file():
        with Image.open(image_path) as image:
            rgb = image.convert("RGB")
        width_height = list(rgb.size)
        png_hash = digest(image_path.read_bytes())
        if label == "control":
            reference = rgb
        if reference is not None and reference.size == rgb.size:
            difference = ImageChops.difference(reference, rgb)
            rows = [y for y in range(rgb.height) if difference.crop((0, y, rgb.width, y + 1)).getbbox()]
            identical = not rows
            changed_rows = {"count": len(rows), "first_0based": rows[0] if rows else None,
                            "last_0based": rows[-1] if rows else None}
    results.append({"case": label, "cut_seconds": cut_seconds, "silence_padded": pad,
                    "removed_region_was_all_zero": not any(removed),
                    "pcm_frames": len(audio) // params.sampwidth,
                    "duration_seconds": len(audio) / params.sampwidth / params.framerate,
                    "wav_sha256": digest(wav_path.read_bytes()), "command": ["python", *command[1:]],
                    "exit": run.returncode, "decoder_output": log, "size_px": width_height,
                    "pixel_identical_to_control": identical, "changed_rows": changed_rows,
                    "png_sha256": png_hash})
report = {"scope": "Generated Robot 36 file replay with Open-SSTV CLI. No live RF, microphone, device, or SSTV Signal Desk app test.",
          "source_sha256": expected, "decoder_version": version, "decoder_source_base": base,
          "decoder_checkout": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip(),
          "python": sys.version.split()[0], "pcm_format": "48 kHz, 16-bit mono PCM", "cases": results}
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
if results[0]["exit"] != 0 or results[0]["size_px"] != [320, 240]:
    raise RuntimeError("Unchanged reference did not decode to 320 x 240")
