"""Revise the marked sounds against the exact lossless V7 print."""
import hashlib
import json
from pathlib import Path
import random
import runpy
import wave

import numpy as np

HERE = Path(__file__).resolve().parent
AUDIO = runpy.run_path(str(HERE.parent / "scene-one-v7/sound-mix.py"))
decode, gain, RATE = AUDIO["decode"], AUDIO["gain"], AUDIO["RATE"]


def verified(item):
    path = HERE / item["file"]
    if hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
        raise ValueError(f"Changed sound source: {item['file']}")
    return path


def stereo(mono, pan):
    angle = (pan + 1) * np.pi / 4
    return np.column_stack((mono * np.cos(angle), mono * np.sin(angle)))


def walking(source, cue):
    start, end = cue["sourceSeconds"]
    filters = f"atrim=start={start}:end={end},highpass=f=50,lowpass=f=5800"
    clear = decode(source, 1, filters).ravel()
    distant = decode(source, 1, filters + ",lowpass=f=1100").ravel()
    n = len(clear)
    distance = np.linspace(*cue["distance"], n)
    steps = (clear * (1 - distance) + distant * distance) * gain(np.linspace(*cue["gainDb"], n))
    fade = min(round(RATE * 0.03), n // 2)
    steps[:fade] *= np.linspace(0, 1, fade)
    steps[-fade:] *= np.linspace(1, 0, fade)
    return stereo(steps, np.linspace(*cue["pan"], n))


def key_sound(source, item, cue):
    a, b = item["sourceSeconds"]
    # Filter before trimming so the alignment stays in original source coordinates.
    clip = decode(source, 1, f"highpass=f=80,lowpass=f={cue['lowpassHz']},atrim=start={a}:end={b}").ravel().copy()
    clip[-480:] *= np.linspace(1, 0, 480)
    offset = round((item["syncSourceSeconds"] - a) * RATE)
    return stereo(clip * gain(cue["gainDb"]), cue["pan"]), offset


def render(edit, output):
    receipt = json.loads((HERE / "sound-receipt.json").read_text())
    spec = edit["sound"]
    starts = {}
    total = 0
    for shot in edit["shots"]:
        starts[shot["id"]] = total
        total += shot["frames"]
    stride, remainder = divmod(RATE, edit["fps"])
    mix = decode(verified(receipt["base"])).copy()
    if remainder or len(mix) != total * stride:
        raise ValueError("The V7 sound revision requires the original shot lengths and sample rate")

    room = decode(HERE / spec["room"]["source"]) * gain(spec["room"]["gainDb"] + spec["masterGainDb"])
    for region in receipt["roomWindows"]:
        a, b = ((starts[region["shot"]] + f) * stride for f in region["frames"])
        mix[a:b] = room[np.arange(a, b) % len(room)]

    def place(sample, sound):
        if sample < 0 or sample + len(sound) > len(mix):
            raise ValueError("Sound outside the picture")
        mix[sample:sample + len(sound)] += sound

    switch = receipt["switch"]
    make_contact = runpy.run_path(str(HERE / switch["source"]))["contact"]
    dry = np.array(make_contact("rocker", random.Random(switch["seed"]))) * gain(switch["gainDb"])
    place((starts[switch["shot"]] + switch["frame"]) * stride, stereo(dry, switch["pan"]))

    keyboard = receipt["keyboard"]
    keys = verified(keyboard)
    for cue in keyboard["cues"]:
        hit, pre = key_sound(keys, keyboard, cue)
        place((starts[keyboard["shot"]] + cue["frame"]) * stride - pre, hit)

    walk = receipt["walk"]
    old = json.loads((HERE / walk["previousCues"]).read_text())["walk"]
    source = verified(walk)
    for multiplier, cues in ((-1, old["cues"]), (1, walk["cues"])):
        for cue in cues:
            place((starts[cue["shot"]] + cue["frame"]) * stride,
                  walking(source, cue) * (multiplier * gain(spec["masterGainDb"])))

    if not np.isfinite(mix).all() or np.max(abs(mix)) >= 1:
        raise ValueError("Sound exceeds PCM range")
    # FFmpeg decodes signed 24-bit PCM as signed sample / 2**23.
    pcm = np.rint(mix * 2**23).astype("<i4").view(np.uint8).reshape(-1, 4)[:, :3]
    with wave.open(str(output), "wb") as out:
        out.setparams((2, 3, RATE, len(mix), "NONE", "not compressed"))
        out.writeframes(pcm.tobytes())


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