const fs = require('fs');
const path = require('path');

const inputFolderPath = '/path/to/image/folder/'; // Replace this with the actual path to your image folder
const outputFolderPath = '/path/to/output/folder/'; // Replace this with the path to your desired output folder
const imageFileExtension = '.jpg'; // Change the extension if your images have a different extension

// Function to pad numbers with leading zeros
function padNumberWithZeros(num, width) {
  const numString = num.toString();
  return numString.length >= width ? numString : new Array(width - numString.length + 1).join('0') + numString;
}

// Function to rename image files with sequential numbers
function renameImageFiles() {
  fs.readdir(inputFolderPath, (err, files) => {
    if (err) {
      console.error('Error reading directory:', err);
      return;
    }

    const renamedFiles = new Set(); // Keep track of renamed filenames

    let counter = 1;
    let renamedCount = 0;

    function renameNext() {
      if (counter > files.length) {
        console.log(`Successfully renamed ${renamedCount} files.`);
        return;
      }

      const file = files[counter - 1];
      if (path.extname(file) === imageFileExtension) {
        const newFileName = padNumberWithZeros(counter, 2) + imageFileExtension;

        // Check if the new filename is already taken
        if (renamedFiles.has(newFileName)) {
          // If taken, find the next available number for the filename
          let suffix = 1;
          while (renamedFiles.has(`${padNumberWithZeros(counter + suffix, 2)}${imageFileExtension}`)) {
            suffix++;
          }
          const uniqueFileName = `${padNumberWithZeros(counter + suffix, 2)}${imageFileExtension}`;
          renamedFiles.add(uniqueFileName);

          const oldFilePath = path.join(inputFolderPath, file);
          const newFilePath = path.join(outputFolderPath, uniqueFileName);

          fs.rename(oldFilePath, newFilePath, (err) => {
            if (err) {
              console.error(`Error renaming ${file}:`, err);
            } else {
              console.log(`Renamed ${file} to ${uniqueFileName}`);
              renamedCount++;
              counter++;
              setTimeout(renameNext, 1000); // Continue with the next file after a 1-second delay
            }
          });
        } else {
          renamedFiles.add(newFileName);

          const oldFilePath = path.join(inputFolderPath, file);
          const newFilePath = path.join(outputFolderPath, newFileName);

          fs.rename(oldFilePath, newFilePath, (err) => {
            if (err) {
              console.error(`Error renaming ${file}:`, err);
            } else {
              console.log(`Renamed ${file} to ${newFileName}`);
              renamedCount++;
              counter++;
              setTimeout(renameNext, 1000); // Continue with the next file after a 1-second delay
            }
          });
        }
      } else {
        counter++;
        renameNext();
      }
    }

    renameNext();
  });
}

renameImageFiles();