#!/usr/bin/env node
import { lstatSync, writeFileSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { deflateSync } from 'node:zlib';

function crc32(buffer) {
  let value = 0xffffffff;
  for (const byte of buffer) {
    value ^= byte;
    for (let bit = 0; bit < 8; bit += 1) {
      value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0);
    }
  }
  return (value ^ 0xffffffff) >>> 0;
}

function chunk(type, data) {
  const typeBuffer = Buffer.from(type);
  const length = Buffer.alloc(4);
  length.writeUInt32BE(data.length);
  const checksum = Buffer.alloc(4);
  checksum.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])));
  return Buffer.concat([length, typeBuffer, data, checksum]);
}

function fixture(seed, width = 512, height = 512) {
  const header = Buffer.alloc(13);
  header.writeUInt32BE(width, 0);
  header.writeUInt32BE(height, 4);
  header[8] = 8;
  header[9] = 2;
  const rows = [];
  for (let y = 0; y < height; y += 1) {
    const row = Buffer.alloc(1 + width * 3);
    for (let x = 0; x < width; x += 1) {
      row[1 + x * 3] = (x + seed * 53) % 256;
      row[2 + x * 3] = (y + seed * 97) % 256;
      row[3 + x * 3] = (x + y + seed * 131) % 256;
    }
    rows.push(row);
  }
  return Buffer.concat([
    Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
    chunk('IHDR', header),
    chunk('IDAT', deflateSync(Buffer.concat(rows))),
    chunk('IEND', Buffer.alloc(0))
  ]);
}

const outputDirectory = resolve(process.argv[2] ?? '');
const info = lstatSync(outputDirectory);
if (!info.isDirectory() || info.isSymbolicLink()) {
  throw new Error('output directory must be a real directory');
}
for (let index = 1; index <= 3; index += 1) {
  writeFileSync(
    join(outputDirectory, `production-acceptance-reference-${index}.png`),
    fixture(index),
    { mode: 0o600, flag: 'wx' }
  );
}
process.stdout.write('acceptance_reference_images=PASS count=3 dimensions=512x512\n');
