import fs from "fs";
import path from "path";

const generateIconsList = (iconsDir, jsonFilePath, prefix) => {
  const toPascalCase = (str) => str.replace(/(^\w|[-_]\w)/g, clearAndUpper);

  function clearAndUpper(text) {
    return text.replace(/[-_]/, "").toUpperCase();
  }

  const generateIconInfo = (fileName) => {
    const baseName = path.basename(fileName, path.extname(fileName));
    const pascalName = prefix + toPascalCase(baseName);
    const words = baseName
      .split(/[-_]/)
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1));

    return {
      name: pascalName,
      description: "",
      aliases: [],
      usage: [],
      tags: [prefix, ...words],
    };
  };

  const updateIconData = (existingData, newIconInfo) => {
    const existingIconData = existingData[newIconInfo.name] || {};

    return {
      name: existingIconData.name || newIconInfo.name,
      description: existingIconData.description || "",
      aliases: existingIconData.aliases || newIconInfo.aliases,
      usage: existingIconData.usage || newIconInfo.usage,
      tags: updateTags(existingIconData.tags || [], newIconInfo.tags),
    };
  };

  const updateTags = (existingTags, newTags) => {
    newTags.forEach((tag) => {
      if (!existingTags.includes(tag)) {
        existingTags.push(tag);
      }
    });
    return existingTags;
  };

  fs.readFile(jsonFilePath, "utf8", (err, data) => {
    const existingData = err ? {} : JSON.parse(data);

    fs.readdir(iconsDir, (err, files) => {
      if (err) {
        console.error("Error reading directory:", err);
        return;
      }

      files.forEach((file) => {
        const newIconInfo = generateIconInfo(file);
        existingData[newIconInfo.name] = updateIconData(
          existingData,
          newIconInfo
        );
      });

      fs.writeFile(
        jsonFilePath,
        JSON.stringify(existingData, null, 2),
        "utf8",
        (err) => {
          if (err) {
            console.error("Error writing JSON file:", err);
          } else {
            console.log(`JSON data saved to ${jsonFilePath}`);
          }
        }
      );
    });
  });
};

// Uso del script con los parámetros deseados
const iconsDir = "./src/svgs/rx"; // Ruta a la carpeta de íconos
const jsonFilePath = "./jsons/IconsList/RadixIconsList.json"; // Ruta al archivo JSON de salida
const prefix = "Rx"; // Prefijo para los nombres de los iconos

generateIconsList(iconsDir, jsonFilePath, prefix);
