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

const originalCsvPath = "translations.csv";
const oldCsvPath = "translations-old.csv";

// Create a map to store translations from translations-clean.csv
const translationsMap = new Map();

// Define the column to match and the column to copy
const columnToMatch = "Key";
const columnToCopy = "Italian (Italy), it_IT";

// Read old.csv
fs.createReadStream(oldCsvPath)
  .pipe(csv())
  .on("data", (row) => {
    translationsMap.set(row[columnToMatch], row[columnToCopy]);
  })
  .on("end", () => {
    const records = [];
    let headers = [];
    // Read new.csv
    fs.createReadStream(originalCsvPath)
      .pipe(csv())
      .on("headers", (row) => {
        headers = row;
      })
      .on("data", (row) => {
        // Check if the Key exists in translationsMap
        if (translationsMap.has(row[columnToMatch])) {
          // If yes, copy the value to the respective column
          row[columnToCopy] = translationsMap.get(row[columnToMatch]);
        }
        // Push the modified row to records
        records.push(row);
      })
      .on("end", () => {
        // Write the filtered rows to a new CSV file with double quotes around each value
        const headerRow = headers
          .map((value) => `"${value.replace(/"/g, '""')}"`)
          .join(",");
        const rows = records.map((row) =>
          Object.values(row)
            .map((value) => `"${value.replace(/"/g, '""')}"`)
            .join(",")
        );
        const outputContent = [headerRow, ...rows].join("\n");
        fs.writeFileSync(originalCsvPath, outputContent, "utf8");
        console.log("New CSV file created successfully!");
      });
  });
