import { validateImage } from './image.js';
import { normalizeToWebp } from './normalize.js';
import { encodePng } from './png.js';

const DEMO_COUNT = 18;

export async function seedDemoMemes(store) {
  const total = store.count();
  const existing = store.list({ page: 1, pageSize: Math.max(DEMO_COUNT, total) }).memes;
  const isDemoOnlyStore = existing.length === total && existing.every((meme) => meme.demo);
  if (total > 0 && !isDemoOnlyStore) return;

  const existingNames = new Set(existing.map((meme) => meme.originalName));

  for (let index = 0; index < DEMO_COUNT; index += 1) {
    const originalName = `protocol-sample-${String(index + 1).padStart(2, '0')}.png`;
    if (existingNames.has(originalName)) continue;

    const width = 960;
    const height = 960;
    const buffer = encodePng(width, height, pixelFactory(index));
    const image = validateImage(buffer, {
      maxBytes: 5 * 1024 * 1024,
      maxWidth: 6000,
      maxHeight: 6000,
      maxPixels: 20_000_000
    });
    const normalized = await normalizeToWebp(buffer);
    const createdAt = new Date(Date.now() - index * 17 * 60 * 1000).toISOString();
    await store.save({
      buffer: normalized.buffer,
      image: normalized.image,
      originalName,
      originalMime: image.mime,
      createdAt,
      demo: true
    });
  }
}

function pixelFactory(seed) {
  return (x, y, width, height) => {
    const nx = x / width;
    const ny = y / height;
    const grid = x % (32 + seed * 3) < 1 || y % (29 + seed * 2) < 1;
    const diagonal = Math.abs(((x + y + seed * 37) % 180) - 90) < 2;
    const ring = Math.abs(Math.hypot(nx - 0.5, ny - 0.5) - (0.18 + (seed % 4) * 0.05)) < 0.006;
    const scan = y % 7 === 0;
    const pulse = (Math.sin((x * (seed + 3) + y * 2) / 42) + 1) / 2;
    const green = grid || diagonal || ring ? 230 : Math.round(18 + pulse * 52);
    const blue = ring || (seed % 3 === 1 && diagonal) ? 210 : Math.round(18 + pulse * 30);
    const red = scan ? 22 : Math.round(4 + pulse * 14);
    return [red, green, blue, 255];
  };
}
