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

/**
 * Script that removes \ufffd for all files in a specified directory and its subdirectories.
 */
const directoryPath = process.argv[2]; // Get the target directory from command-line arguments

function removeInvalidChars(filePath) {
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file ${filePath}:`, err);
      return;
    }
    const cleanedData = data.replace(/\ufffd/g, '');
    fs.writeFile(filePath, cleanedData, 'utf8', (err) => {
      if (err) {
        console.error(`Error writing file ${filePath}:`, err);
      } else {
        console.log(`Fixed file: ${filePath}`);
      }
    });
  });
}

function traverseDirectory(dir) {
  fs.readdir(dir, { withFileTypes: true }, (err, files) => {
    if (err) {
      console.error(`Error reading directory ${dir}:`, err);
      return;
    }
    files.forEach((file) => {
      const fullPath = path.join(dir, file.name);
      if (file.isDirectory()) {
        traverseDirectory(fullPath);
      } else if (file.isFile()) {
        removeInvalidChars(fullPath);
      }
    });
  });
}

traverseDirectory(directoryPath);
