"""Move the opening CRT relay to frame 35 in the lossless stereo mix. Requires NumPy and FFmpeg."""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile

import numpy as np

ROOT = Path(__file__).resolve().parent
INPUTS = {
    'mix': ('../scene-one-v10/mix.flac', 'b7fcff6963118fe11b4d4c120f026969821c92cc7e67293a927e2b4db622221c'),
    'room': ('../yesterday/room.mp3', '5e60130853775fcd53306c95d686a15d17ddae36357dd10061c63ff98698bf57'),
}
RATE, FPS = 48000, 24
OLD, NEW = 48, 35
SAMPLES = RATE // FPS
# The recorded relay generator used 200 ms of contact and up to 52 ms of reflections.
LENGTH = round(0.252 * RATE)


def digest(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def ffmpeg(*args, data=None):
    return subprocess.run(['ffmpeg','-nostdin','-v','error','-y',*map(str,args)],
                          input=data,stdout=subprocess.PIPE,check=True).stdout


def pcm24(path):
    return np.frombuffer(ffmpeg('-i',path,'-map','0:a:0','-f','s32le','-'),'<i4').reshape(-1,2) >> 8


def render():
    inputs = {key: ROOT/value[0] for key,value in INPUTS.items()}
    for key,path in inputs.items():
        if digest(path) != INPUTS[key][1]:
            raise ValueError(f'Unexpected source checksum for {key}')
    previous = pcm24(inputs['mix'])
    old, new = OLD*SAMPLES, NEW*SAMPLES
    before, after = slice(old,old+LENGTH), slice(new,new+LENGTH)
    # Reproduce the earlier stereo mixer's two float32 gains and 24-bit rounding.
    # Begin at room sample zero so the resampler and its startup delay agree.
    stop = old+LENGTH+2*SAMPLES
    room = np.frombuffer(ffmpeg('-i',inputs['room'],'-af',f'aresample={RATE},atrim=end_sample={stop}',
                                '-ac',2,'-ar',RATE,'-f','f32le','-'),'<f4').reshape(-1,2)
    room = np.rint(room * (10**(-7/20)) * (10**(1/20)) * (2**23-1)).astype('<i4')
    if not (np.array_equal(previous[new:old],room[new:old]) and
            np.array_equal(previous[old+LENGTH:stop],room[old+LENGTH:stop])):
        raise ValueError('The isolated room differs from the opening bed.')
    relay = previous[before] - room[before]
    active = np.flatnonzero(np.any(relay,axis=1))
    if not len(active) or active[0] == 0 or active[-1] == LENGTH-1:
        raise ValueError('Relay extraction does not include its quiet boundaries.')
    mix = previous.copy()
    mix[before] = room[before]
    mix[after] += relay
    if mix.min() < -2**23 or mix.max() >= 2**23:
        raise ValueError('The edited sound exceeds 24-bit range.')
    target = ROOT/'mix.flac'
    with tempfile.TemporaryDirectory(dir=ROOT) as folder:
        temp = Path(folder)/target.name
        packed = mix.astype('<i4').reshape(-1).view(np.uint8).reshape(-1,4)[:,:3]
        ffmpeg('-f','s24le','-ar',RATE,'-ac',2,'-i','pipe:0','-map_metadata','-1',
               '-compression_level',8,temp,data=packed.tobytes())
        printed = pcm24(temp)
        if not np.array_equal(printed,mix):
            raise ValueError('The FLAC round trip changed the mixed samples.')
        temp.replace(target)
    changed = np.any(printed != previous, axis=1)
    if not np.array_equal(np.flatnonzero(changed),np.r_[new+active,old+active]):
        raise ValueError('Unexpected change outside the two placements.')
    return {
        'sampleRate':RATE, 'channels':2, 'bits':24, 'fps':FPS, 'oldFrame':OLD, 'newFrame':NEW,
        'inputs':{key:{'file':name,'sha256':sha} for key,(name,sha) in INPUTS.items()},
        'oldSampleRange':[old,old+LENGTH], 'newSampleRange':[new,new+LENGTH],
        'sampleRangeConvention':'Stereo sample frames, zero-based; end exclusive.',
        'activeContactOffsets':[int(active[0]),int(active[-1])+1],
        'method':'Reconstruct the continuous apartment bed at its original -7 dB mix gain and +1 dB mastering gain. Subtract it from the old relay window, return the old position to the bed, and add the exact stereo difference at the new screen wake.',
        'restoredBedMaxErrorLsb':int(np.abs(printed[before]-room[before]).max()),
        'translatedContactMaxErrorLsb':int(np.abs((printed[after]-room[after])-relay).max()),
        'samplesPerChannel':len(printed), 'changedSamplesPerChannel':int(changed.sum()),
        'unchangedSamplesPerChannel':int((~changed).sum()), 'changesOutsideCueWindows':0,
        'output':{'file':target.name,'sha256':digest(target)}
    }


if __name__ == '__main__':
    (ROOT/'relay-receipt.json').write_text(json.dumps(render(),indent=2)+'\n')
