import { describe, it, expect } from 'vitest';
import { PNG } from 'pngjs';
import { comparePngBuffers } from '../visualDiff.js';

function solidPng(width: number, height: number, r: number, g: number, b: number): Buffer {
  const png = new PNG({ width, height });
  for (let y = 0; y < height; y += 1) {
    for (let x = 0; x < width; x += 1) {
      const idx = (width * y + x) << 2;
      png.data[idx] = r;
      png.data[idx + 1] = g;
      png.data[idx + 2] = b;
      png.data[idx + 3] = 255;
    }
  }
  return PNG.sync.write(png);
}

describe('comparePngBuffers', () => {
  it('reports 0% mismatch for identical images', () => {
    const a = solidPng(4, 4, 10, 20, 30);
    const b = solidPng(4, 4, 10, 20, 30);
    const result = comparePngBuffers(a, b);
    expect(result.mismatchedPixels).toBe(0);
    expect(result.mismatchPercent).toBe(0);
  });

  it('reports mismatch for different images', () => {
    const a = solidPng(4, 4, 0, 0, 0);
    const b = solidPng(4, 4, 255, 255, 255);
    const result = comparePngBuffers(a, b);
    expect(result.mismatchedPixels).toBeGreaterThan(0);
    expect(result.mismatchPercent).toBeGreaterThan(0);
  });

  it('throws when dimensions differ', () => {
    const a = solidPng(2, 2, 0, 0, 0);
    const b = solidPng(3, 3, 0, 0, 0);
    expect(() => comparePngBuffers(a, b)).toThrow(/dimensions differ/);
  });
});
