import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { crc32 } from 'node:zlib';
import { PNG } from 'pngjs';

// Сигнатура и заголовок IHDR в переданный буфер длиной ≥ 33 (размер читается только из него).
export function fakePngBytes(b: Buffer, width: number, height: number) {
  Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0);
  b.writeUInt32BE(13, 8);
  b.write('IHDR', 12, 'ascii');
  b.writeUInt32BE(width, 16);
  b.writeUInt32BE(height, 20);
}

// Минимальный «PNG»: сигнатура + заголовок IHDR.
export function fakePng(path: string, width: number, height: number) {
  mkdirSync(dirname(path), { recursive: true });
  const b = Buffer.alloc(33);
  fakePngBytes(b, width, height);
  writeFileSync(path, b);
}
// Все детали pool мини-каталога (тела 1–3, глаза 1–2, одежда {1: 3, 2: 2}, причёска {1: 4}, аксессуар {1: 3}).
export const POOL_FILES = [
  'gen/Body_01.png', 'gen/Body_02.png', 'gen/Body_03.png', 'gen/Eyes_01.png', 'gen/Eyes_02.png',
  'gen/Outfit_01_01.png', 'gen/Outfit_01_02.png', 'gen/Outfit_01_03.png', 'gen/Outfit_02_01.png', 'gen/Outfit_02_02.png',
  'gen/Hairstyle_01_01.png', 'gen/Hairstyle_01_02.png', 'gen/Hairstyle_01_03.png', 'gen/Hairstyle_01_04.png',
  'gen/Accessory_01_Ladybug_01.png', 'gen/Accessory_01_Ladybug_02.png', 'gen/Accessory_01_Ladybug_03.png',
];

// Каталог ассетов мини-каталога: лист test/sheet.png sheetW×sheetH и все детали pool, кроме skip.
export function fakeAssets(sheetW: number, sheetH: number, skip: string[] = []) {
  const dir = mkdtempSync(join(tmpdir(), 'po-atlas-'));
  fakePng(join(dir, 'test/sheet.png'), sheetW, sheetH);
  for (const f of POOL_FILES) if (!skip.includes(f)) fakePng(join(dir, f), 896, 656);
  return dir;
}

// Настоящий PNG w×h, собранный в памяти (PNG не коммитятся); цвет пикселя — px(x, y) в RGBA.
export function realPng(w: number, h: number, px: (x: number, y: number) => [number, number, number, number] = () => [255, 0, 0, 255]): Buffer {
  const p = new PNG({ width: w, height: h });
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) p.data.set(px(x, y), (y * w + x) * 4);
  return PNG.sync.write(p);
}

// Тот же PNG с чанком type сразу после IHDR (сигнатура 8 байт + IHDR 25 байт) — например, gAMA, который браузер учёл бы.
export function withChunk(png: Buffer, type: string, data: Buffer): Buffer {
  const len = Buffer.alloc(4);
  len.writeUInt32BE(data.length);
  const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
  const crc = Buffer.alloc(4);
  crc.writeUInt32BE(crc32(body));
  return Buffer.concat([png.subarray(0, 33), len, body, crc, png.subarray(33)]);
}
