const fs = require('fs');

const pkSourceFilePath = 'data.json';
const pkDestinationFilePath = 'copy.json';

function pkCopyData() {
  fs.readFile(pkSourceFilePath, 'utf8', (err, data) => {
    if (err) {
      console.error('Error reading source file:', err);
    } else {
      try {
        const pkJsonData = JSON.parse(data);

        fs.readFile(pkDestinationFilePath, 'utf8', (err, existingData) => {
          if (err && err.code !== 'ENOENT') {
            console.error('Error reading destination file:', err);
            return;
          }

          let pkCopyJsonData = {};

          if (!err) {
            try {
              if (existingData.trim() !== '') {
                pkCopyJsonData = JSON.parse(existingData);
              }
            } catch (parseError) {
              console.error('Error parsing existing JSON data:', parseError);
            }
          }

          const pkHighestIndex = Object.keys(pkCopyJsonData).reduce((maxIndex, key) => {
            const index = parseInt(key.split('_')[1]);
            return index > maxIndex ? index : maxIndex;
          }, 0);

          for (const item of Object.values(pkJsonData)) {
            const pkNewIndex = pkHighestIndex + 1;
            pkCopyJsonData[`item_${pkNewIndex}`] = item;
          }

          fs.writeFile(pkDestinationFilePath, JSON.stringify(pkCopyJsonData, null, 2), 'utf8', (err) => {
            if (err) {
              console.error('Error writing destination file:', err);
            } else {
              console.log('Data copied successfully!');
            }
          });
        });
      } catch (error) {
        console.error('Error parsing JSON data from source file:', error);
      }
    }
  });
}

pkCopyData();

fs.watch(pkSourceFilePath, (event, filename) => {
  if (event === 'change') {
    console.log('Changes detected in data.json, updating copy.json...');
    pkCopyData();
  } else if (event === 'rename') {
    console.log('data.json was deleted. copy.json is not affected.');
  }
});