"""Prepare the V8 effects bed and carry the professor's walk through the kitchen cut."""
import argparse
import hashlib
import json
from pathlib import Path
import runpy
import subprocess

import numpy as np

HERE = Path(__file__).resolve().parent
OLD = runpy.run_path(str(HERE.parent / "scene-one-v8/sound-mix.py"))
decode, gain, RATE = OLD["decode"], OLD["gain"], OLD["RATE"]
FPS = 24
SPF = RATE // FPS


def read(name):
    return json.loads((HERE/name).read_text())


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


def stems(receipt, edit):
    """Reproduce the outgoing V8 stem and the single replacement field-recording passage."""
    saved = receipt["walk"]
    source = verified(saved)
    previous = json.loads(verified(receipt["previousWalk"]).read_text())["walk"]
    old = next(c for c in previous["cues"] if c["id"] == receipt["previousWalk"]["id"])
    old_stem = OLD["walking"](source,old) * gain(edit["sound"]["masterGainDb"])
    old_in = (receipt["picture"]["shotStarts"][old["shot"]]+old["frame"]) * SPF
    first, last = saved["sourceSeconds"]
    filters = (f"atrim=start={first}:end={last},highpass=f={saved['highpassHz']},"
               f"lowpass=f={saved['lowpassHz']},atempo={saved['tempo']}")
    mono = decode(source,1,filters).ravel().copy()
    n = len(mono)
    fade = min(round(.06 * RATE), n//2)
    mono[:fade] *= np.linspace(0,1,fade)
    mono[-fade:] *= np.linspace(1,0,fade)
    sample_frames = saved["startFrame"] + np.arange(n)/SPF
    levels = gain(np.interp(sample_frames, saved["envelopeFrames"], saved["gainDb"]))
    pan = np.interp(sample_frames, saved["envelopeFrames"], saved["pan"])
    return old_in, old_stem, saved["startFrame"]*SPF, OLD["stereo"](mono*levels,pan)


def dialogue_span(edit, exchange):
    speech = edit["dialogue"]
    start = 0
    for shot in edit["shots"]:
        if shot["id"] == "speaker":
            break
        start += shot["frames"]
    else:
        raise ValueError("Missing speaking shot")
    clip = decode(verified(exchange)) * gain(speech["gainDb"])
    return start * SPF + speech["audioDelaySamples"], clip


def render(keep_english=False):
    receipt = read("walk-receipt.json")
    edit = read("../scene-one-v8/edit.json")
    base = decode(verified(receipt["base"])).copy()
    old_in, old, new_in, new = stems(receipt,edit)
    base[old_in:old_in+len(old)] -= old
    base[new_in:new_in+len(new)] += new
    if not keep_english:
        # Remove only the documented English stem. Check that the room beneath
        # it matches the archived room recording before using the clean bed.
        exchange = receipt["dialogueExchange"]
        first, clip = dialogue_span(edit,exchange)
        room = decode(verified(exchange["room"])) * gain(edit["sound"]["room"]["gainDb"] + edit["sound"]["masterGainDb"])
        end = first + len(clip)
        clean = room[np.arange(first,end) % len(room)]
        if np.max(abs(base[first:end] - clip - clean)) > 1e-5:
            raise ValueError("The identified English stem does not isolate the documented room")
        base[first:end] = clean
    return base


def write_flac(output, samples):
    if not np.isfinite(samples).all() or np.max(abs(samples)) >= 1:
        raise ValueError("Invalid samples in the effects bed")
    pcm = np.rint(samples * 2**23).astype("<i4").view(np.uint8).reshape(-1,4)[:,:3]
    subprocess.run(["ffmpeg","-v","error","-y","-f","s24le","-ar",str(RATE),"-ac","2",
                    "-i","pipe:0","-map_metadata","-1","-compression_level","8",output],
                   input=pcm.tobytes(),check=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--english-comparison",type=Path,metavar="OUTPUT.flac",
                        help="Render the alternate with V8's original dialogue for comparison")
    args = parser.parse_args()
    write_flac(args.english_comparison or HERE/"walk-bed.flac", render(bool(args.english_comparison)))
