"""Original CC0 planar-RGB holdouts; native FFmpeg is a developer reader/fixture tool only."""
from pathlib import Path
import datetime, hashlib, json, subprocess
import numpy as np

out=Path('benchmarks/fixtures/video-rgb1');out.mkdir(exist_ok=False)
sha=lambda b:hashlib.sha256(b).hexdigest()
rows=[]
for name,bits,w,h,count,rate,alpha in [('sdr-gbr10',10,160,96,12,12,False),('sdr-gbr12',12,192,108,10,10,False),('sdr-gbra10',10,162,98,10,10,True)]:
    yy,xx=np.mgrid[:h,:w];maximum=(1<<bits)-1;frames=[]
    for n in range(count):
        rgb=np.stack([(xx/(w-1)+n/53)%1,(yy/(h-1)+n/71)%1,((xx*3+yy*5+n*11)%197)/196],axis=2)
        # Large interior patches give independent matrix/range controls beyond edge/codec noise.
        colors=[(0,0,0),(1,1,1),(.5,.5,.5),(1,0,0),(0,1,0),(0,0,1),(.8,.2,.4),(.15,.7,.35)]
        for i,c in enumerate(colors):
            x=i*w//8;rgb[4:30,x:x+w//8]=c
        samples=np.rint(rgb*maximum).astype('<u2')
        planes=[samples[:,:,1],samples[:,:,2],samples[:,:,0]]
        if alpha:
            a=np.rint(np.clip((xx+n*3)/(w-1),0,1)*maximum).astype('<u2');a[:,:w//4]=0;a[:,3*w//4:]=maximum
            planes.append(a)
        frames.append(b''.join(p.tobytes()for p in planes))
    raw=b''.join(frames);source=out/(name+'.raw');source.write_bytes(raw)
    pixel=('gbrap'if alpha else'gbrp')+str(bits)+'le';file=out/(name+'.mkv')
    cmd=['ffmpeg','-hide_banner','-v','error','-nostdin','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate',str(rate),'-i',str(source),'-c:v','ffv1','-level','3','-coder','1','-context','1','-slicecrc','1','-pix_fmt',pixel,'-color_range','pc','-colorspace','rgb','-color_primaries','bt709','-color_trc','iec61966-2-1','-fflags','+bitexact',str(file)]
    subprocess.run(cmd,check=True,capture_output=True)
    decoded=subprocess.check_output(['ffmpeg','-v','error','-xerror','-i',str(file),'-pix_fmt',pixel,'-f','rawvideo','-'])
    assert decoded==raw,'Native FFV1 fixture is not exact original samples'
    probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-show_streams','-show_format','-of','json',str(file)]))
    rows.append(dict(name=name,file=file.name,sha256=sha(file.read_bytes()),bytes=file.stat().st_size,pixelFormat=pixel,raw=source.name,rawSha256=sha(raw),width=w,height=h,frames=count,rate=rate,bits=bits,alpha=alpha,command=cmd,probe=probe,sourceIntent='Full-range planar GBR(A), BT.709 primaries, sRGB transfer; original channel samples are authoritative.'))
    if name=='sdr-gbr10':
        packed=out/'packed-bgr8-control.mkv'
        control=['ffmpeg','-v','error','-y','-i',str(file),'-c:v','ffv1','-level','3','-pix_fmt','bgr0','-color_range','pc','-colorspace','rgb','-color_primaries','bt709','-color_trc','iec61966-2-1',str(packed)]
        subprocess.run(control,check=True,capture_output=True)
        rows.append(dict(name='packed-bgr8-control',file=packed.name,sha256=sha(packed.read_bytes()),bytes=packed.stat().st_size,derivativeOf=name,originalCorpus=False,command=control))
(out/'manifest.json').write_text(json.dumps(dict(createdAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),license='CC0-1.0; original fixtures generated for Tabmorph, never user media',originalCorpora=3,packedControlDerivatives=1,producerSha256=sha(Path(__file__).read_bytes()),nativeVersion=subprocess.check_output(['ffmpeg','-version'],text=True).splitlines()[0],rows=rows),indent=2)+'\n')
print(dict(fixtures=len(rows),originalCorpora=3,packedControlDerivatives=1))
