"""Mix the exact Polish performance at its locked sync offset into the apartment effects bed.

First conform: python3 polish-mix.py selected.wav --at-sample 380000
Replay the archived decision: python3 polish-mix.py
"""
import argparse
import hashlib
import json
from pathlib import Path
import runpy
import subprocess

import numpy as np

HERE = Path(__file__).resolve().parent
TOOLS = runpy.run_path(str(HERE/"walk-mix.py"))
decode, gain, rate = TOOLS["decode"],TOOLS["gain"],TOOLS["RATE"]


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def loudness(samples):
    """FFmpeg's gated BS.1770 integrated loudness and true-peak reading."""
    result = subprocess.run(["ffmpeg","-nostats","-v","info","-f","f32le","-ar",str(rate),"-ac","2","-i","pipe:0",
        "-af","loudnorm=I=-23:TP=-1:LRA=7:print_format=json","-f","null","-"],
        input=samples.astype("<f4").tobytes(),capture_output=True,check=True)
    log = result.stderr.decode()
    record = json.loads(log[log.rindex("{"):log.rindex("}")+1])
    values = float(record["input_i"]),float(record["input_tp"])
    if not np.isfinite(values).all():
        raise ValueError("The selected speech is too short or silent for loudness matching")
    return values


def mix(source, offset, recorded=None):
    bed_path = HERE/"walk-bed.flac"
    source_path = (HERE/source).resolve()
    if source_path.parent != HERE or not source_path.is_file():
        raise ValueError("Place the selected performance beside this script and pass its filename")
    source = source_path.name
    if recorded and (digest(source_path)!=recorded["sourceSha256"] or digest(bed_path)!=recorded["effectsBedSha256"]):
        raise ValueError("The recorded voice or effects bed has changed")
    bed = decode(bed_path).copy()
    voice = decode(source_path)
    end = offset+len(voice)
    if offset < 0 or end > len(bed):
        raise ValueError("Voice range exceeds the film")
    old_edit = TOOLS["read"]("../scene-one-v8/edit.json")
    old = TOOLS["read"]("walk-receipt.json")["dialogueExchange"]
    old_start, reference = TOOLS["dialogue_span"](old_edit,old)
    target, _ = loudness(reference)
    spoken_level, peak = loudness(voice)
    desired = target - spoken_level
    # Reserve 1 dB true-peak headroom and the peak of simultaneous room.
    headroom = 20*np.log10(10**(-1/20) - np.max(abs(bed[offset:end])))
    applied = round(min(desired,headroom-peak),2)
    mixed_voice = voice*gain(applied)
    bed[offset:end] += mixed_voice
    out = HERE/"mix.flac"
    TOOLS["write_flac"](out,bed)
    guarded = decode(out)
    if guarded.shape != bed.shape or np.max(abs(guarded-bed))>1.5e-7:
        raise ValueError("Final FLAC differs from the computed mix")
    mixed_level, mixed_peak = loudness(mixed_voice)
    mix_level, mix_peak = loudness(guarded)
    receipt = {"language":"pl","line":"Jak nam wczoraj poszło?","source":source,"sourceSha256":digest(source_path),
        "effectsBed":bed_path.name,"effectsBedSha256":digest(bed_path),"sampleRate":rate,
        "timelineStartSample":offset,"timelineEndSampleExclusive":end,
        "referenceEnglish":old["file"],"referenceTimelineStartSample":old_start,
        "englishIntegratedLufs":target,"polishSourceIntegratedLufs":spoken_level,"gainDb":applied,
        "polishMixedIntegratedLufs":mixed_level,"polishMixedTruePeakDbtp":mixed_peak,
        "master":{"file":out.name,"sha256":digest(out),"durationSeconds":len(guarded)/rate,
                  "integratedLufs":mix_level,"truePeakDbtp":mix_peak},
        "method":"Decode each performance to the same stereo layout and sample rate. Match the Polish performance to the gated integrated loudness of the selected English line at its V8 playback gain. Preserve its timing, pauses and dynamics with one linear gain. Reserve room for the existing apartment bed."}
    (HERE/"voice-mix.json").write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+"\n")


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source",nargs="?")
    parser.add_argument("--at-sample",type=int)
    args=parser.parse_args()
    if args.source is None and args.at_sample is None:
        rec=TOOLS["read"]("voice-mix.json")
        mix(rec["source"],rec["timelineStartSample"],rec)
    elif args.source is not None and args.at_sample is not None:
        mix(args.source,args.at_sample)
    else:
        parser.error("Supply both the filename and --at-sample, or use no arguments to replay.")


if __name__=="__main__":
    main()
