#!/usr/bin/env python3
"""Generated media fixtures and inspection; no third-party media or network IO."""
import argparse
import hashlib
import io
import json
import subprocess
import tempfile
from pathlib import Path

def run(args):
    return subprocess.run(args,check=True,capture_output=True,text=True).stdout

def tools():
    return {name:run([name,'-version']).splitlines()[0].split(' Copyright')[0] for name in ('ffmpeg','ffprobe')}

def image_source(version=1):
    from PIL import Image
    im=Image.new('RGB',(320,180))
    for y in range(180):
        for x in range(320):
            im.putpixel((x,y),((x*3+version*11)%256,(y*5+version*17)%256,((x//16+y//16)%2)*180+30))
    data=io.BytesIO();im.save(data,format='PNG',compress_level=9)
    return data.getvalue()

def _resize(data, width=160):
    from PIL import Image,ImageOps
    if width not in (80,160) or len(data)>2**20:
        raise ValueError('unsupported transform')
    with Image.open(io.BytesIO(data)) as im:
        if im.format not in ('PNG','JPEG') or im.width*im.height>320*180:
            raise ValueError('unsupported input')
        im.load()
        im=ImageOps.exif_transpose(im).convert('RGB')
        im.thumbnail((width,width),Image.Resampling.LANCZOS)
        out=io.BytesIO();im.save(out,format='JPEG',quality=70,optimize=False,progressive=False,subsampling=2)
        return out.getvalue(),im.size

def resize(data,width=160):
    from PIL import Image
    try:return _resize(data,width)
    except (OSError,SyntaxError,Image.DecompressionBombError) as exc:raise ValueError('invalid image bytes') from exc

def image_metadata(data):
    from PIL import Image
    resize(data,80)
    with Image.open(io.BytesIO(data)) as image:return image.format,image.size

def probe(path):
    info=json.loads(run(['ffprobe','-v','error','-protocol_whitelist','file','-count_frames','-select_streams','v:0',
                         '-show_entries','stream=codec_name,width,height,nb_read_frames,avg_frame_rate:format=duration,size',
                         '-of','json',str(path)]))
    stream=info['streams'][0]
    return {'codec':stream['codec_name'],'width':stream['width'],'height':stream['height'],
            'frames':int(stream['nb_read_frames']),'fps':stream['avg_frame_rate'],
            'duration':info['format']['duration'],'bytes':int(info['format']['size'])}

def source(directory):
    path=Path(directory)/'source.y4m'
    run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','lavfi','-i',
         'testsrc2=size=320x180:rate=12:duration=3','-frames:v','36','-pix_fmt','yuv420p',
         '-fflags','+bitexact','-flags:v','+bitexact',str(path)])
    return path

def encode(source_path,directory):
    directory=Path(directory); directory.mkdir(parents=True,exist_ok=True)
    outputs={}
    for name,width,height,crf in [('low',160,90,32),('high',320,180,24)]:
        path=directory/f'{name}.mp4'
        run(['ffmpeg','-hide_banner','-loglevel','error','-y','-i',str(source_path),
             '-vf',f'scale={width}:{height}:flags=lanczos','-an','-c:v','libx264','-preset','medium',
             '-crf',str(crf),'-threads','1','-g','12','-keyint_min','12','-sc_threshold','0',
             '-pix_fmt','yuv420p','-fflags','+bitexact','-flags:v','+bitexact','-map_metadata','-1',str(path)])
        outputs[name]=path
    return outputs

def hls(renditions,directory):
    directory=Path(directory);directory.mkdir(parents=True,exist_ok=True)
    result={}
    for name,source_path in renditions.items():
        target=directory/name;target.mkdir(exist_ok=True)
        run(['ffmpeg','-hide_banner','-loglevel','error','-y','-i',str(source_path),'-c','copy',
             '-f','hls','-hls_time','1','-hls_list_size','0','-hls_playlist_type','vod',
             '-hls_flags','independent_segments','-hls_segment_filename',str(target/'seg%d.ts'),str(target/'index.m3u8')])
        lines=(target/'index.m3u8').read_text().splitlines();segments=[];duration=None
        for line in lines:
            if line.startswith('#EXTINF:'):duration=float(line.split(':')[1].split(',')[0])
            elif line and not line.startswith('#'):
                if duration is None or not (target/line).is_file():raise ValueError('bad segment manifest')
                segments.append({'file':line,'duration':duration,'bytes':(target/line).stat().st_size})
                duration=None
        if len(segments)!=3 or sum(s['duration'] for s in segments)!=3:
            raise ValueError('unexpected fixture segment set')
        result[name]={'playlist':target/'index.m3u8','segments':segments}
    lines=['#EXTM3U','#EXT-X-VERSION:6']
    for name,width,height in [('low',160,90),('high',320,180)]:
        peak=max(int(s['bytes']*8/s['duration']) for s in result[name]['segments'])
        lines += [f'#EXT-X-STREAM-INF:BANDWIDTH={peak},RESOLUTION={width}x{height}',f'{name}/index.m3u8']
    (directory/'master.m3u8').write_text('\n'.join(lines)+'\n')
    return result

def summary(directory):
    src=source(directory);renditions=encode(src,Path(directory)/'renditions');segments=hls(renditions,Path(directory)/'hls')
    print(json.dumps({'tools':tools(),'source':probe(src),'renditions':{k:probe(v) for k,v in renditions.items()},
                      'segments':{k:v['segments'] for k,v in segments.items()}},indent=2))
    return src,renditions,segments

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['inspect']);args=parser.parse_args()
    with tempfile.TemporaryDirectory(prefix='fanout-m24-media-') as directory:summary(directory)
