"""Finish the three approved Seedance Mini performances directly from their selected frames."""
import hashlib
import json
from pathlib import Path
import runpy
import subprocess
import tempfile

import numpy as np
from PIL import Image, ImageDraw, ImageFilter

ROOT = Path(__file__).resolve().parent
PROD = ROOT.parent
SIZE = (1920,1080)
FPS = 24
LANCZOS = Image.Resampling.LANCZOS
SOURCES = {'chair':'../scene-one-v2/chair.mp4','reaction':'../scene-one-v7/reaction.mp4',
           'sofa-reveal':'../scene-one-v7/sofa-reveal-finish.mp4'}
COUNTS = {'chair':80,'reaction':96,'sofa-reveal':216}


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


def decode(path, count, start=0):
    info=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_streams',
                                            '-of','json',path]))['streams'][0]
    if info['avg_frame_rate']!='24/1' or start+count > int(info['nb_frames']):
        raise ValueError(f'Source range exceeds the selected 24 fps take: {path.name}')
    width,height=info['width'],info['height']
    cmd=['ffmpeg','-v','error','-i',path,'-vf',f'trim=start_frame={start}:end_frame={start+count}',
         '-fps_mode','passthrough','-pix_fmt','rgb24','-f','rawvideo','-an','pipe:1']
    with subprocess.Popen(cmd,stdout=subprocess.PIPE) as pipe:
        for _ in range(count):
            raw=pipe.stdout.read(width*height*3)
            if len(raw)!=width*height*3:
                raise ValueError(f'Incomplete source: {path.name}')
            yield Image.frombytes('RGB',(width,height),raw)
        if pipe.wait():
            raise RuntimeError(f'Could not decode {path.name}')


def restore(source, crop):
    # A mild high-frequency pass on luma only. Limit the contribution to three
    # 8-bit steps; do not sharpen chroma or synthesize textures across frames.
    y,cb,cr=source.convert('YCbCr').split()
    coarse=np.asarray(y,dtype=np.int16)
    low=np.asarray(y.filter(ImageFilter.GaussianBlur(.75)),dtype=np.int16)
    gain=np.clip(np.rint(.24*(coarse-low)),-3,3)
    luma=Image.fromarray(np.uint8(np.clip(coarse+gain,0,255)))
    box=None
    if crop:
        height=source.width*9/16
        box=(0,(source.height-height)/2,source.width,(source.height+height)/2)
    return Image.merge('YCbCr',(luma,cb,cr)).resize(SIZE,LANCZOS,box=box).convert('RGB')


def wide_frames(shot, path, start, count, sharpen):
    desc=next(s for s in json.loads((PROD/'scene-one-v6/edit.json').read_text())['shots'] if s['id']==shot)
    crt=runpy.run_path(str(PROD/'scene-one-v6/crt.py'))
    reference=Image.open(PROD/'scene-one-v6'/desc['background']).convert('RGB').resize(SIZE,LANCZOS)
    matte=Image.new('L',SIZE)
    ImageDraw.Draw(matte).rounded_rectangle([round(c*1.5) for c in desc['movingRegion']],radius=42,fill=255)
    matte=matte.filter(ImageFilter.GaussianBlur(21))
    # The two static cameras in this scene each have one audited landmark set.
    if len(desc['glass'])!=1:
        raise ValueError('Expected one locked-camera screen alignment.')
    tl,tr,br,bl=np.asarray(desc['glass'][0][1],dtype=float)
    main=np.array([tl+[-6,-7],tr+[13,-8],br+[14,9],bl+[-6,12]])*1.5
    second=(np.array([(444,325),(510,317),(528,403),(460,416)])+(tl-[331,305]))*1.5
    tube=desc['tube']
    dark,ramp=tube.get('darkFrames',0),tube.get('lightRamp',0)
    screens={}
    for n,source in enumerate(decode(path,count,start)):
        image=restore(source,False) if sharpen else source.resize(SIZE,LANCZOS)
        opening=min(1,max(0,(n-dark+1)/ramp)) if ramp else 1
        message=None if n<dark else next((m['text'] for m in reversed(tube['messages']) if n>=m['at']),'')
        key=(message,opening)
        if key not in screens:
            scene=reference.copy()
            crt['composite'](scene,'primary',main,message,opening)
            crt['composite'](scene,'menu',second)
            screens[key]=scene
        yield Image.composite(image,screens[key],matte)


def main():
    rows=[]
    cursor=0
    for key,count in COUNTS.items():
        rows.append({'shot':key,'file':SOURCES[key],'sha256':digest(ROOT/SOURCES[key]),
                     'sourceFrames':[0,count],'reelFrames':[cursor,cursor+count]})
        cursor+=count
    with tempfile.TemporaryDirectory(dir=ROOT) as temp:
        folder=Path(temp)
        result=folder/'motion-hd.mp4'
        times=','.join(str(s['reelFrames'][0]/24) for s in rows)
        cmd=['ffmpeg','-v','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1920x1080','-framerate','24',
             '-i','pipe:0','-an','-c:v','libx264','-crf','13','-preset','medium','-threads','2','-pix_fmt','yuv420p',
             '-force_key_frames',times,'-movflags','+faststart',result]
        with subprocess.Popen(cmd,stdin=subprocess.PIPE) as encoder:
            for name,count in COUNTS.items():
                path=ROOT/SOURCES[name]
                if name=='chair':
                    frames=wide_frames(name,path,0,count,True)
                else:
                    frames=(restore(frame,True) for frame in decode(path,count))
                for image in frames:
                    encoder.stdin.write(image.tobytes())
            encoder.stdin.close()
            if encoder.wait():
                raise RuntimeError('Could not encode motion restoration.')
        report={'file':result.name,'sha256':digest(result),'size':SIZE,'fps':FPS,'frames':cursor,'shots':rows,
                'additionalSources':['../scene-one-v2/chair.png','../scene-one-v6/edit.json','../scene-one-v6/crt.py',
                    '../scene-one-v5/crt.py','../../sources/original/monitor-i-am-ready.png',
                    '../../sources/original/monitor-automation-options-day.png','../scene-one/switch.mp4','../yesterday/render.py'],
                'native':'All three performances decode at 864 × 496. The near-rocker repair in the closing take was completed before this finish.',
                'method':'A 0.75-pixel Gaussian estimate separates broad tone from edge detail. A 24% luma refinement is bounded to three 8-bit levels per native pixel. Chroma follows the measured source. Lanczos resampling at the approved aperture keeps the frame count, motion and focus pull. The chair uses the original 1672 × 941 room plate with the moving actor and original CRT timing.'}
        (folder/'motion-hd.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
        result.replace(ROOT/result.name)
        (folder/'motion-hd.json').replace(ROOT/'motion-hd.json')

if __name__=='__main__':
    main()
