import { access, readdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

const DATA_DIRECTORY = "website/public/data";

function formatTitle(value) {
  return String(value || "")
    .replace(/\.json$/i, "")
    .replace(/[_-]+/g, " ")
    .replace(/\b\p{L}/gu, (letter) => letter.toUpperCase());
}

async function generateListIndex(directory) {
  const entries = await readdir(directory, { withFileTypes: true });
  const files = entries
    .filter((entry) => entry.isFile() && entry.name.endsWith(".json") && entry.name !== "index.json")
    .map((entry) => entry.name)
    .sort((a, b) => a.localeCompare(b, "fr"));

  const lists = await Promise.all(files.map(async (file) => {
    const payload = JSON.parse(await readFile(path.join(directory, file), "utf8"));
    const id = file.replace(/\.json$/i, "");
    return {
      id,
      title: payload.titre || formatTitle(id),
      file
    };
  }));

await writeFile(path.join(directory, "index.json"), `${JSON.stringify({ lists }, null, 2)}\n`);
}

async function findListDirectories() {
  const entries = await readdir(DATA_DIRECTORY, { withFileTypes: true });
  const directories = await Promise.all(entries
    .filter((entry) => entry.isDirectory())
    .map(async (entry) => {
      const listDirectory = path.join(DATA_DIRECTORY, entry.name, "lists");
      try {
        await access(listDirectory);
        return listDirectory;
      } catch {
        return null;
      }
    }));

  return directories.filter(Boolean);
}

const listDirectories = await findListDirectories();
await Promise.all(listDirectories.map(generateListIndex));
