"""Conform the selected Professor performance and replace the V13 dialogue. Requires NumPy and FFmpeg."""
import hashlib
import json
import os
import subprocess
from pathlib import Path

import numpy as np


HERE = Path(__file__).resolve().parent
V9 = HERE.parent / "scene-one-v9"
V13 = HERE.parent / "scene-one-v13"
RATE = 48000
SCALE = 2**23
TRIM = 5376  # 112 ms before the first word in the casting recording.
TEMPO = ("atrim=start_sample=5376,asetpts=PTS-STARTPTS,asetnsamples=n=240:p=1,"
         "asendcmd=c='0.615 atempo tempo 0.64',atempo=0.815,afade=t=in:ss=0:ns=192")


def record(path):
    with path.open("rb") as stream:
        return {"file": os.path.relpath(path, HERE), "sha256": hashlib.file_digest(stream, "sha256").hexdigest()}


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


def levels(samples):
    cmd = ["ffmpeg", "-nostats", "-f", "f32le", "-ar", str(RATE), "-ac", "2", "-i", "-",
           "-af", "loudnorm=I=-23:TP=-1:LRA=7:print_format=json", "-f", "null", "-"]
    log = subprocess.run(cmd, input=samples.astype("<f4").tobytes(), capture_output=True, check=True).stderr.decode()
    result = json.loads(log[log.rindex("{"):log.rindex("}") + 1])
    return float(result["input_i"]), float(result["input_tp"])


def pcm24(samples):
    return np.rint(samples * SCALE).astype("<i4")


def write_pcm(path, samples):
    if np.max(samples) >= SCALE or np.min(samples) < -SCALE:
        raise ValueError("24-bit audio would clip")
    packed = samples.astype("<i4").view(np.uint8).reshape(-1, 4)[:, :3].tobytes()
    codec = ["-compression_level", "8"] if path.suffix == ".flac" else ["-c:a", "pcm_s24le"]
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "s24le", "-ac", "2", "-ar", str(RATE),
                    "-i", "-", "-map_metadata", "-1", *codec, path], input=packed, check=True)


def main():
    raw = HERE / "line-raw.wav"
    casting = HERE.parent / "voices/professor-v1/reference.wav"
    original = decode(raw, channels=1)
    if len(original) != 62400 or not np.array_equal(original, decode(casting, channels=1)[:62400]):
        raise ValueError("The selected line must be the exact first 62,400 samples of approved voice B")

    voice_info = V9 / "voice-mix.json"
    old = json.loads(voice_info.read_text())
    previous = V13 / "mix.flac"
    room = V9 / old["effectsBed"]
    old_line = V9 / old["source"]
    trim_info = V13 / "trim-receipt.json"
    first, last = json.loads(trim_info.read_text())["soundAudit"]["removedStereoSampleFrames"]
    source_start = old["timelineStartSample"]
    source_end = old["timelineEndSampleExclusive"]
    start, end = source_start - (last - first), source_end - (last - first)
    bed = decode(room)[source_start:source_end]
    baseline = pcm24(decode(previous))
    legacy = decode(old_line) * 10 ** (old["gainDb"] / 20)
    if not np.array_equal(pcm24(bed + legacy), baseline[start:end]):
        raise ValueError("Archived effects bed and old dialogue must reproduce every original 24-bit sample")

    fitted = decode(raw, TEMPO)
    level, _ = levels(fitted)
    gain_db = round(old["polishMixedIntegratedLufs"] - level, 2)
    stem = pcm24(fitted * 10 ** (gain_db / 20))
    if len(stem) > end - start:
        raise ValueError("Replacement runs past the old dialogue window")
    dialogue, output = HERE / "dialogue.wav", HERE / "mix.flac"
    write_pcm(dialogue, stem)
    master = baseline.copy()
    master[start:end] = pcm24(bed)
    master[start:start + len(stem)] += stem
    write_pcm(output, master)

    # Verify the delivered files, including the bed under the entire new line.
    check = pcm24(decode(output))
    clean = check[start:end].copy()
    clean[:len(stem)] -= pcm24(decode(dialogue))
    if not (np.array_equal(check, master) and np.array_equal(clean, pcm24(bed))):
        raise ValueError("Printed audio differs from the archive bed plus the new dialogue")
    before = int(np.count_nonzero(check[:start] != baseline[:start]))
    after = int(np.count_nonzero(check[end:] != baseline[end:]))
    if before or after:
        raise ValueError("Audio outside the dialogue changed")
    mixed_level, peak = levels(decode(dialogue))
    master_lufs, master_peak = levels(decode(output))
    receipt = {
        "parentEdition": "yesterdays-pnl-v13", "voiceId": "professor-v1", "language": "pl",
        "line": old["line"], "credits": 0, "raw": record(raw), "dialogue": record(dialogue),
        "output": record(output), "inputs": [record(p) for p in (casting, previous, room, old_line, voice_info, trim_info)],
        "sampleRate": RATE, "channels": 2, "bitDepth": 24, "totalSampleFrames": len(check),
        "timelineStartSample": start, "timelineEndSampleExclusive": start + len(stem),
        "replacedSampleRange": [start, end],
        "conform": {"sourceTrimSamples": TRIM, "ffmpegFilter": TEMPO,
                    "method": "Remove the casting pre-roll. Use continuous pitch-preserving overlap-add at 0.815×, then 0.64× through the closing word. Fade in the first four milliseconds before articulation."},
        "loudness": {"gainDb": gain_db, "targetLufs": old["polishMixedIntegratedLufs"],
                     "dialogueLufs": mixed_level, "dialogueTruePeakDbtp": peak,
                     "mixLufs": master_lufs, "mixTruePeakDbtp": master_peak},
        "sync": {"fps": 24, "subtitleFrames": [178, 217],
                 "picture": "Retain the existing Polish picture. Check the end of nam around frame 187, closed lips on the p around 197 and the rounded release after 204.",
                 "audioLandmarks": "From line start, the first word becomes audible at 0.01 s, the nam vowel at 0.21 s and its closure around 0.40 s. The p closes around 0.77–0.82 s. The final rounded vowel starts around 1.12 s and decays around 1.34 s."},
        "pcmAudit": {"oldDialogueReconstructionMaxErrorLsb": 0, "recoveredBedMaxErrorLsb": 0,
                     "changedChannelSamplesBefore": before, "changedChannelSamplesAfter": after,
                     "identicalOutsideWindowSampleFrames": len(check) - (end - start)}
    }
    (HERE / "mix-receipt.json").write_text(json.dumps(receipt, indent=2, ensure_ascii=False) + "\n")


if __name__ == "__main__":
    main()
