// Deterministic benchmark input generator, shared by browsers, workers and Node.
//
// Every case is rendered from the original source JPEG bytes, and the resulting RGBA
// bytes are identical in every conforming JavaScript engine. To guarantee that:
//  - JPEGs are decoded by the vendored pure-JS jpeg-js decoder (integer IDCT), never by
//    the browser, whose decoders differ between engines and versions;
//  - pixel math uses only IEEE-754 + - * / (exact by spec; engines may not fuse them),
//    Math.floor/ceil/round/abs/min/max and integer operations. Math.sin/exp/sqrt etc. are
//    implementation-approximated in ECMAScript, so the few transcendental values needed
//    come from the fixed series and literal constants below;
//  - evaluation order is fixed, and Float32Array intermediates round identically everywhere.
// Each manifest case stores the expected RGBA SHA-256; consumers verify it after rendering.
import decodeJpeg from './jpeg-js-0.4.4.mjs';

export const GENERATOR_ID='retail-generator-1';

const PI=3.141592653589793,LN2=0.6931471805599453;
// exp(x) by range reduction and a fixed-length Taylor series.
function exp(x){const k=Math.round(x/LN2),r=x-k*LN2;let term=1,sum=1;for(let n=1;n<=24;n++){term=term*r/n;sum+=term}if(k>0)for(let i=0;i<k;i++)sum*=2;else for(let i=0;i<-k;i++)sum/=2;return sum}
// sin(pi*x) by exact reduction to [0, 0.5] and a fixed-length Taylor series.
function sinPi(x){let r=x-2*Math.floor(x/2),sign=1;if(r>=1){r-=1;sign=-1}if(r>.5)r=1-r;const t=PI*r,t2=t*t;let term=t,sum=t;for(let n=1;n<=12;n++){term=-term*t2/((2*n)*(2*n+1));sum+=term}return sign*sum}
// Rotation angles are restricted to multiples of 15 degrees with literal [cos, sin] values.
const TRIG={15:[0.9659258262890683,0.25881904510252074],30:[0.8660254037844386,0.5],45:[0.7071067811865476,0.7071067811865476],60:[0.5,0.8660254037844386],75:[0.25881904510252074,0.9659258262890683]};

const byte=v=>v<=0?0:v>=255?255:Math.round(v);
const blank=(width,height)=>({width,height,data:new Uint8ClampedArray(width*height*4).fill(255)});

export function decode(bytes){const img=decodeJpeg(bytes instanceof Uint8Array?bytes:new Uint8Array(bytes),{useTArray:true,formatAsRGBA:true,maxResolutionInMP:100,maxMemoryUsageInMB:1024});return{width:img.width,height:img.height,data:new Uint8ClampedArray(img.data.buffer,img.data.byteOffset,img.data.length)}}

// Exact pixel re-indexing: out(x, y) <- in(f(x, y)).
const remaps={
 rot90cw:(W,H)=>[H,W,(x,y)=>[y,H-1-x]],
 rot180:(W,H)=>[W,H,(x,y)=>[W-1-x,H-1-y]],
 rot270cw:(W,H)=>[H,W,(x,y)=>[W-1-y,x]],
 flipH:(W,H)=>[W,H,(x,y)=>[W-1-x,y]],
 flipV:(W,H)=>[W,H,(x,y)=>[x,H-1-y]],
 transpose:(W,H)=>[H,W,(x,y)=>[y,x]],
 transverse:(W,H)=>[H,W,(x,y)=>[W-1-y,H-1-x]]};
function remap(img,kind){const[w,h,f]=remaps[kind](img.width,img.height),out=new Uint8ClampedArray(w*h*4),S=img.data,W=img.width;for(let y=0;y<h;y++)for(let x=0;x<w;x++){const[sx,sy]=f(x,y),p=(sy*W+sx)*4,o=(y*w+x)*4;out[o]=S[p];out[o+1]=S[p+1];out[o+2]=S[p+2];out[o+3]=255}return{width:w,height:h,data:out}}
const exifRemap={2:'flipH',3:'rot180',4:'flipV',5:'transpose',6:'rot90cw',7:'transverse',8:'rot270cw'};
// EXIF orientation first (as Pillow's exif_transpose), then the dataset's quarter-turn alignment.
export function orient(img,{exifOrientation=1,alignmentClockwiseDegrees=0}){let out=exifRemap[exifOrientation]?remap(img,exifRemap[exifOrientation]):img;if(alignmentClockwiseDegrees===90)out=remap(out,'rot90cw');else if(alignmentClockwiseDegrees!==0)throw Error('Unsupported alignment '+alignmentClockwiseDegrees);return out}

// Catmull-Rom bicubic (a = -0.5) sampling at pixel-center coordinates; outside the source is white.
function cubic(t,w){const t2=t*t,t3=t2*t;w[0]=-.5*t3+t2-.5*t;w[1]=1.5*t3-2.5*t2+1;w[2]=-1.5*t3+2*t2+.5*t;w[3]=.5*t3-.5*t2}
function warp(src,width,height,map){const{width:W,height:H,data:S}=src,out=new Uint8ClampedArray(width*height*4),wx=new Float64Array(4),wy=new Float64Array(4),m=new Float64Array(2);
 for(let y=0;y<height;y++)for(let x=0;x<width;x++){map(x+.5,y+.5,m);const fx=m[0]-.5,fy=m[1]-.5,o=(y*width+x)*4;out[o+3]=255;
  if(!(fx>-2&&fy>-2&&fx<W+1&&fy<H+1)){out[o]=out[o+1]=out[o+2]=255;continue}
  const ix=Math.floor(fx),iy=Math.floor(fy);cubic(fx-ix,wx);cubic(fy-iy,wy);let r=0,g=0,b=0;
  for(let j=0;j<4;j++){const sy=iy-1+j,rowIn=sy>=0&&sy<H,base=sy*W;for(let i=0;i<4;i++){const sx=ix-1+i,w=wx[i]*wy[j];if(rowIn&&sx>=0&&sx<W){const p=(base+sx)*4;r+=w*S[p];g+=w*S[p+1];b+=w*S[p+2]}else{r+=w*255;g+=w*255;b+=w*255}}}
  out[o]=byte(r);out[o+1]=byte(g);out[o+2]=byte(b)}
 return{width,height,data:out}}

// Clockwise rotation on an expanded white canvas that keeps the complete image.
export function rotate(img,angle){if(angle===0)return img;if(angle===90)return remap(img,'rot90cw');const t=TRIG[angle];if(!t)throw Error('Unsupported angle '+angle);const[c,s]=t,W=img.width,H=img.height,w=Math.ceil(W*c+H*s),h=Math.ceil(W*s+H*c),cx=w/2,cy=h/2,sx=W/2,sy=H/2;
 return warp(img,w,h,(x,y,m)=>{const dx=x-cx,dy=y-cy;m[0]=dx*c+dy*s+sx;m[1]=-dx*s+dy*c+sy})}

// Projective trapezoid: the top (side 0) or bottom (side 1) edge narrows by inset*width per side.
function solve(A,b){const n=b.length;for(let col=0;col<n;col++){let piv=col;for(let r=col+1;r<n;r++)if(Math.abs(A[r][col])>Math.abs(A[piv][col]))piv=r;[A[col],A[piv]]=[A[piv],A[col]];[b[col],b[piv]]=[b[piv],b[col]];for(let r=col+1;r<n;r++){const f=A[r][col]/A[col][col];for(let k=col;k<n;k++)A[r][k]-=f*A[col][k];b[r]-=f*b[col]}}const x=new Array(n);for(let r=n-1;r>=0;r--){let s=b[r];for(let k=r+1;k<n;k++)s-=A[r][k]*x[k];x[r]=s/A[r][r]}return x}
export function perspective(img,side,insetFraction){const w=img.width,h=img.height,inset=insetFraction*w,dst=side===0?[[inset,0],[w-inset,0],[w,h],[0,h]]:[[0,0],[w,0],[w-inset,h],[inset,h]],src=[[0,0],[w,0],[w,h],[0,h]],A=[],b=[];
 for(let i=0;i<4;i++){const[x,y]=dst[i],[u,v]=src[i];A.push([x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]);b.push(u,v)}
 const[a0,a1,a2,a3,a4,a5,a6,a7]=solve(A,b);return warp(img,w,h,(x,y,m)=>{const d=a6*x+a7*y+1;m[0]=(a0*x+a1*y+a2)/d;m[1]=(a3*x+a4*y+a5)/d})}

// Separable Gaussian blur, sigma in source pixels, 3-sigma kernel, edge pixels extended.
export function gaussianBlur(img,sigma){const r=Math.ceil(3*sigma),n=2*r+1,k=new Float64Array(n);let total=0;for(let i=0;i<n;i++){const d=i-r;k[i]=exp(-(d*d)/(2*sigma*sigma));total+=k[i]}for(let i=0;i<n;i++)k[i]/=total;
 const{width:W,height:H,data:S}=img,tmp=new Float32Array(W*H*3),out=new Uint8ClampedArray(W*H*4);
 for(let y=0;y<H;y++)for(let x=0;x<W;x++){let a=0,b=0,c=0;for(let i=0;i<n;i++){let sx=x+i-r;sx=sx<0?0:sx>=W?W-1:sx;const p=(y*W+sx)*4,w=k[i];a+=w*S[p];b+=w*S[p+1];c+=w*S[p+2]}const t=(y*W+x)*3;tmp[t]=a;tmp[t+1]=b;tmp[t+2]=c}
 for(let y=0;y<H;y++)for(let x=0;x<W;x++){let a=0,b=0,c=0;for(let i=0;i<n;i++){let sy=y+i-r;sy=sy<0?0:sy>=H?H-1:sy;const p=(sy*W+x)*3,w=k[i];a+=w*tmp[p];b+=w*tmp[p+1];c+=w*tmp[p+2]}const o=(y*W+x)*4;out[o]=byte(a);out[o+1]=byte(b);out[o+2]=byte(c);out[o+3]=255}
 return{width:W,height:H,data:out}}

// Separable Lanczos-3 resampling (Pillow's convolution layout), for down- and upscaling.
function lanczos(x){if(x===0)return 1;if(x<=-3||x>=3)return 0;return 3*sinPi(x)*sinPi(x/3)/(PI*PI*x*x)}
function coefficients(inSize,outSize){const scale=inSize/outSize,fs=scale>1?scale:1,support=3*fs,taps=Math.ceil(support)*2+1,start=new Int32Array(outSize),count=new Int32Array(outSize),w=new Float64Array(outSize*taps);
 for(let i=0;i<outSize;i++){const center=(i+.5)*scale;let lo=Math.floor(center-support+.5),hi=Math.floor(center+support+.5);if(lo<0)lo=0;if(hi>inSize)hi=inSize;let total=0;for(let x=lo;x<hi;x++){const v=lanczos((x-center+.5)/fs);w[i*taps+x-lo]=v;total+=v}if(total!==0)for(let x=lo;x<hi;x++)w[i*taps+x-lo]/=total;start[i]=lo;count[i]=hi-lo}
 return{start,count,w,taps}}
export function resize(img,width,height){const{width:W,height:H,data:S}=img,cx=coefficients(W,width),cy=coefficients(H,height),tmp=new Float32Array(width*H*3),out=new Uint8ClampedArray(width*height*4);
 for(let y=0;y<H;y++)for(let x=0;x<width;x++){const lo=cx.start[x],n=cx.count[x],base=x*cx.taps;let a=0,b=0,c=0;for(let i=0;i<n;i++){const p=(y*W+lo+i)*4,w=cx.w[base+i];a+=w*S[p];b+=w*S[p+1];c+=w*S[p+2]}const t=(y*width+x)*3;tmp[t]=a;tmp[t+1]=b;tmp[t+2]=c}
 for(let y=0;y<height;y++){const lo=cy.start[y],n=cy.count[y],base=y*cy.taps;for(let x=0;x<width;x++){let a=0,b=0,c=0;for(let i=0;i<n;i++){const p=((lo+i)*width+x)*3,w=cy.w[base+i];a+=w*tmp[p];b+=w*tmp[p+1];c+=w*tmp[p+2]}const o=(y*width+x)*4;out[o]=byte(a);out[o+1]=byte(b);out[o+2]=byte(c);out[o+3]=255}}
 return{width,height,data:out}}

// Smooth multiplicative illumination; gains never exceed 1, so nothing clips to white.
export function lighting(img,mode){const{width:W,height:H,data:S}=img,out=new Uint8ClampedArray(S.length);
 for(let y=0;y<H;y++)for(let x=0;x<W;x++){let g;if(mode==='horizontal shadow')g=.35+.65*x/(W-1);else if(mode==='vertical shadow')g=1-.65*y/(H-1);else if(mode==='vignette'){const u=-1+2*x/(W-1),v=-1+2*y/(H-1),d=(u*u+v*v)/2;g=1-.6*(d<1?d:1)}else throw Error('Unknown lighting '+mode);
  const o=(y*W+x)*4;out[o]=byte(S[o]*g);out[o+1]=byte(S[o+1]*g);out[o+2]=byte(S[o+2]*g);out[o+3]=255}
 return{width:W,height:H,data:out}}

function inside(poly,x,y){let c=false;for(let i=0,j=poly.length-1;i<poly.length;j=i++){const[xi,yi]=poly[i],[xj,yj]=poly[j];if((yi>y)!==(yj>y)&&x<(xj-xi)*(y-yi)/(yj-yi)+xi)c=!c}return c}
const lum=(r,g,b)=>.2126*r+.7152*g+.0722*b;
function percentile(sorted,p){const pos=p/100*(sorted.length-1),lo=Math.floor(pos),hi=lo+1<sorted.length?lo+1:lo;return sorted[lo]+(sorted[hi]-sorted[lo])*(pos-lo)}
// Recolor dark, near-neutral ink inside a reviewed barcode polygon; everything else is unchanged.
export function inkRecolor(img,polygon,rgb){const{width:W,height:H,data:S}=img,out=new Uint8ClampedArray(S),mask=new Uint8Array(W*H);let n=0;
 for(let y=0;y<H;y++)for(let x=0;x<W;x++)if(inside(polygon,x+.5,y+.5)){mask[y*W+x]=1;n++}
 if(!n)throw Error('Empty recolor region');const values=new Float64Array(n);let i=0;for(let p=0;p<W*H;p++)if(mask[p])values[i++]=lum(S[p*4],S[p*4+1],S[p*4+2]);values.sort();
 const dark=percentile(values,15),light=percentile(values,85),threshold=(dark+light)/2,span=threshold-dark>1?threshold-dark:1;
 for(let p=0;p<W*H;p++){if(!mask[p])continue;const o=p*4,r=S[o],g=S[o+1],b=S[o+2],hi=r>g?(r>b?r:b):(g>b?g:b),lo=r<g?(r<b?r:b):(g<b?g:b);if(hi-lo>=45)continue;let a=(threshold-lum(r,g,b))/span;if(a<=0)continue;if(a>1)a=1;out[o]=byte(r*(1-a)+rgb[0]*a);out[o+1]=byte(g*(1-a)+rgb[1]*a);out[o+2]=byte(b*(1-a)+rgb[2]*a)}
 return{width:W,height:H,data:out,stats:{darkReference:dark,backgroundReference:light,inkThreshold:threshold}}}
export function tint(img,gains){const S=img.data,out=new Uint8ClampedArray(S.length);for(let o=0;o<S.length;o+=4){out[o]=byte(S[o]*gains[0]);out[o+1]=byte(S[o+1]*gains[1]);out[o+2]=byte(S[o+2]*gains[2]);out[o+3]=255}return{width:img.width,height:img.height,data:out}}
export function channelSwap(img,order){const idx=order.map(c=>'RGB'.indexOf(c)),S=img.data,out=new Uint8ClampedArray(S.length);for(let o=0;o<S.length;o+=4){out[o]=S[o+idx[0]];out[o+1]=S[o+idx[1]];out[o+2]=S[o+idx[2]];out[o+3]=255}return{width:img.width,height:img.height,data:out}}

// Paste a source rectangle [x0, y0, x1, y1) at (dx, dy), clipped to the canvas.
function paste(dst,src,[x0,y0,x1,y1],dx,dy){for(let y=y0;y<y1;y++){const ty=dy+y-y0;if(ty<0||ty>=dst.height)continue;for(let x=x0;x<x1;x++){const tx=dx+x-x0;if(tx<0||tx>=dst.width)continue;const p=(y*src.width+x)*4,o=(ty*dst.width+tx)*4;dst.data[o]=src.data[p];dst.data[o+1]=src.data[p+1];dst.data[o+2]=src.data[p+2]}}}
// Native-pixel collage: context crops first, protected barcode regions last so they stay intact.
export function collage(images,{width,height,placements}){const out=blank(width,height);
 placements.forEach((p,i)=>{const[b0,b1]=p.protectedSourceBox,[c0,c1]=p.contextSourceBox;paste(out,images[i],p.contextSourceBox,p.x-(b0-c0),p.y-(b1-c1))});
 placements.forEach((p,i)=>paste(out,images[i],p.protectedSourceBox,p.x,p.y));return out}

// Render one case. `loadSource(source)` resolves to the decoded, oriented RGBA source image.
export async function render(generator,loadSource){if(generator.id!==GENERATOR_ID)throw Error('Unsupported generator '+generator.id);
 const images=await Promise.all(generator.sources.map(loadSource)),img=images[0],p=generator.params||{};
 switch(generator.op){
  case 'rotate':return rotate(img,p.angle);
  case 'perspective':return perspective(img,p.side,p.insetFraction);
  case 'blur':return gaussianBlur(img,p.sigma);
  case 'resize':return resize(img,p.width,p.height);
  case 'lighting':return lighting(img,p.mode);
  case 'ink':return inkRecolor(img,p.polygon,p.rgb);
  case 'tint':return tint(img,p.gains);
  case 'channel-swap':return channelSwap(img,p.order);
  case 'collage':return collage(images,p);
  default:throw Error('Unknown generator op '+generator.op)}}

// Small cache so consecutive cases of one photo (e.g. its seven rotations) decode it once.
export function sourceLoader(fetchBytes,limit=2){const cache=new Map();return source=>{const key=JSON.stringify([source.id,source.exifOrientation,source.alignmentClockwiseDegrees]);if(!cache.has(key)){const pending=Promise.resolve(fetchBytes(source)).then(bytes=>orient(decode(bytes),source));pending.catch(()=>cache.get(key)===pending&&cache.delete(key));cache.set(key,pending);while(cache.size>limit)cache.delete(cache.keys().next().value)}else{const v=cache.get(key);cache.delete(key);cache.set(key,v)}return cache.get(key)}}
