import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const data = JSON.parse(await fs.readFile(path.join(projectRoot, "app/quiz-data.json"), "utf8"));
const outputDir = path.join(projectRoot, "public/assets/thumbs");
const displayDir = path.join(projectRoot, "public/assets/display");
const ideologies = Object.values(data.ideologies);
const assetPath = (url) => url.split("?", 1)[0].replace(/^\//, "");

await fs.mkdir(outputDir, { recursive: true });
await fs.mkdir(displayDir, { recursive: true });

const workerCount = Math.min(8, ideologies.length);
let nextIndex = 0;

async function renderNext() {
  while (nextIndex < ideologies.length) {
    const index = nextIndex++;
    const ideology = ideologies[index];
    const source = path.join(projectRoot, "public", assetPath(ideology.flag));
    const destination = path.join(projectRoot, "public", assetPath(ideology.thumbnail));
    const displayDestination = path.join(projectRoot, "public", assetPath(ideology.image));
    await Promise.all([
      sharp(source, { density: 144 })
        .resize(360, 240, { fit: "cover", position: "centre" })
        .webp({ quality: 77, effort: 4 })
        .toFile(destination),
      sharp(source, { density: 192 })
        .resize(960, 640, { fit: "cover", position: "centre" })
        .webp({ quality: 84, effort: 4 })
        .toFile(displayDestination),
    ]);
  }
}

await Promise.all(Array.from({ length: workerCount }, () => renderNext()));
console.log(`Generated ${ideologies.length} thumbnail and display image pairs`);
