const fs = require('fs');
const path = require('path');
const packageJson = require('../package.json');
const nilePackageJson = require('../../nile/package.json');

const version = packageJson.version;
const nileVersion = nilePackageJson.version;
const distDir = path.join(__dirname, '../dist');

function replaceVersionInFile(filePath) {
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    
    if (content.includes('__NILE_ELEMENTS_VERSION__') || content.includes('__NILE_VERSION__')) {
      let updatedContent = content;
      updatedContent = updatedContent.replace(/__NILE_ELEMENTS_VERSION__/g, version);
      updatedContent = updatedContent.replace(/__NILE_VERSION__/g, nileVersion);
      fs.writeFileSync(filePath, updatedContent, 'utf8');
    }
  } catch (error) {
    process.exit(1);
  }
}

function processDirectory(dir) {
  if (!fs.existsSync(dir)) {
    return;
  }
  
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      processDirectory(filePath);
    } else if (file.endsWith('.js') || file.endsWith('.js.map')) {
      replaceVersionInFile(filePath);
    }
  });
}

processDirectory(distDir);
