"""Render the workprint's quieter stereo mix from sample- and frame-indexed source cues."""

from pathlib import Path
import hashlib
import json
import runpy
import subprocess
import tempfile
import wave

import numpy as np

ROOT = Path(__file__).resolve().parent
RATE = 48000


def decode(path, channels=2, filters=None):
    command = ["ffmpeg", "-v", "error", "-i", str(path), "-vn"]
    if filters:
        command += ["-af", filters]
    command += ["-ar", str(RATE), "-ac", str(channels), "-f", "f32le", "-"]
    return np.frombuffer(subprocess.check_output(command), "<f4").reshape(-1, channels)


def gain(db):
    return 10 ** (db / 20)


def read_source(item):
    path = ROOT / item["file"]
    if hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
        raise ValueError(f"Source has changed: {item['file']}")
    return path


def render(edit, output):
    """Write stereo 24-bit PCM. The editor muxes this lossless signal with the selected picture."""
    receipt = json.loads((ROOT / "sound-receipt.json").read_text())
    at = {}
    total = 0
    for shot in edit["shots"]:
        at[shot["id"]] = total
        total += shot["frames"]
    stride, tail = divmod(RATE, edit["fps"])
    if tail:
        raise ValueError("Choose a frame rate with an integer number of samples per frame")
    length = total * stride
    spec = edit["sound"]
    room = spec["room"]
    if room["gainDb"] != receipt["room"]["gainDb"]:
        raise ValueError("The EDL room level differs from the sound decision")
    recorded_room = decode(ROOT / room["source"])
    mix = np.tile(recorded_room, (1 + (length - 1) // len(recorded_room), 1))[:length] * gain(room["gainDb"])
    fade = round(RATE * 0.08)
    mix[:fade] *= np.linspace(0, 1, fade)[:, None]
    fade = round(RATE * 0.6)
    mix[-fade:] *= np.linspace(1, 0, fade)[:, None]

    def place(clip, sample):
        if sample < 0 or sample + len(clip) > length:
            raise ValueError(f"Audio exceeds picture at sample {sample}")
        mix[sample:sample + len(clip)] += clip

    tap = spec["tap"]
    water = decode(ROOT / tap["source"])[:tap["frames"] * stride].copy()
    fade = round(RATE * 0.16)
    water[-fade:] *= np.linspace(1, 0, fade)[:, None]
    place(water * gain(tap["gainDb"]), (at[tap["shot"]] + tap["frame"]) * stride)

    contacts = runpy.run_path(str(ROOT.parent / "scene-one-v2/foley.py"))
    with tempfile.TemporaryDirectory() as scratch:
        contact_file = Path(scratch) / "contacts.wav"
        contacts["render"](edit, contact_file)
        mix += decode(contact_file)

    walker = read_source(receipt["walk"])
    for cue in receipt["walk"]["cues"]:
        a, b = cue["sourceSeconds"]
        filters = f"atrim=start={a}:end={b},highpass=f=50,lowpass=f=5800"
        direct = decode(walker, 1, filters).ravel()
        muffled = decode(walker, 1, filters + ",lowpass=f=1100").ravel()
        dur = len(direct)
        perspective = np.linspace(*cue["distance"], dur)
        take = (direct * (1 - perspective) + muffled * perspective) * gain(np.linspace(*cue["gainDb"], dur))
        fade = min(round(RATE * 0.03), dur // 2)
        take[:fade] *= np.linspace(0, 1, fade)
        take[-fade:] *= np.linspace(1, 0, fade)
        pan = (np.linspace(*cue["pan"], dur) + 1) * np.pi / 4
        place(np.column_stack((take * np.cos(pan), take * np.sin(pan))), (at[cue["shot"]] + cue["frame"]) * stride)

    if spec.get("sip"):
        item, cue = receipt["sip"], spec["sip"]
        a, b = item["sourceSeconds"]
        filters = (f"atrim=start={a}:end={b},asetpts=PTS-STARTPTS,highpass=f=105,lowpass=f=5900,"
                   f"afade=t=in:d=0.02,afade=t=out:st={b - a - .04:.4f}:d=0.04")
        source = decode(read_source(item), filters=filters)
        start = (at[cue["shot"]] + cue["frame"]) * stride - round((item["syncSourceSeconds"] - a) * RATE)
        place(source * gain(item["gainDb"]), start)

    dialogue = edit["dialogue"]
    place(decode(ROOT / dialogue["audio"]) * gain(dialogue["gainDb"] - spec["masterGainDb"]),
          at["speaker"] * stride + dialogue["audioDelaySamples"])
    mix *= gain(spec["masterGainDb"])
    if not np.isfinite(mix).all() or np.max(abs(mix)) >= 1:
        raise ValueError("Mix exceeds 24-bit PCM range")
    # Pack signed 24-bit little-endian samples. The high-order 4th byte contains sign extension.
    pcm = np.rint(mix * (2**23 - 1)).astype("<i4").view(np.uint8).reshape(-1, 4)[:, :3]
    with wave.open(str(output), "wb") as wav:
        wav.setparams((2, 3, RATE, length, "NONE", "not compressed"))
        wav.writeframes(pcm.tobytes())


if __name__ == "__main__":
    render(json.loads((ROOT / "edit.json").read_text()), ROOT / "mix.wav")
