const fs = require("fs");
const glob = require("glob");
const csv = require("csv-parser");

// Define the directory where you want to perform the replacement
const directoryPath = "./src"; // Update this with your source directory

const originalCsvPath = "translations.csv";

let headers = [];
let parsedKeys = [];
let dataKeys = [];

// Read translations.csv and get the headers
fs.createReadStream(originalCsvPath)
  .pipe(csv())
  .on("headers", (row) => {
    headers = row;
  })
  .on("data", (row) => {
    dataKeys.push(row.Key);
  });

// Function to convert a string to Camel Case
function toCamelCase(input) {
  return input
    .split(/[^a-zA-Z0-9]+/)
    .map((word, index) => {
      if (index === 0) {
        // Keep the first word as is
        return word.toLowerCase();
      } else {
        // Capitalize the first character of each word
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
      }
    })
    .join("");
}

// Function to replace the pattern in a file
function replacePatternInFile(filePath) {
  let content = fs.readFileSync(filePath, "utf8");
  const languages = headers
    .slice(1, headers.length - 1)
    .map(() => `""`)
    .join(",");

  const parseValue = (value) => {
    let keys = [];
    let parseValue = value.replace("//", "").trim();
    const indexOfSpliter = parseValue.indexOf("::");

    if (indexOfSpliter !== -1) {
      const parts = parseValue.split("::");
      keys.push(parts[0]);
      parseValue = parts[1];
    }

    let identifier = parseValue;

    const words = parseValue.split(" ");
    if (words.length > 2) {
      identifier = words.slice(0, 2).join(" ") + " " + words[words.length - 1];
    }

    keys.push(toCamelCase(identifier));

    return {
      key: keys.join("."),
      value: parseValue,
    };
  };

  const patternDoubleQuotes = /"(.*?)"/g;
  content = content.replace(patternDoubleQuotes, (match, result) => {
    if (result.startsWith("//")) {
      const { key, value } = parseValue(result);
      const replacement = `"${key}"`;
      // console.log(`Replaced: ${match} => ${replacement}`);
      if (!parsedKeys.includes(key)) {
        console.log(`${key},"${value}",${languages}`);
      }
      return replacement;
    }
    return match;
  });

  const patternSingleQuotes = /'(.*?)'/g;
  content = content.replace(patternSingleQuotes, (match, result) => {
    if (result.startsWith("//")) {
      const { key, value } = parseValue(result);
      const replacement = `'${key}'`;
      // console.log(`Replaced: ${match} => ${replacement}`);
      if (!parsedKeys.includes(key)) {
        console.log(`${key},"${value}",${languages}`);
      }
      return replacement;
    }
    return match;
  });

  fs.writeFileSync(filePath, content, "utf8");
}

// Function to replace the pattern in all matching files
function replacePatternInFiles(directoryPath) {
  glob(`${directoryPath}/**/*.{vue,js}`, (err, files) => {
    if (err) {
      console.error("Error reading files:", err);
      return;
    }
    files.forEach((file) => {
      replacePatternInFile(file);
    });
  });
}

// Start the replacement process
replacePatternInFiles(directoryPath);
