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

function removeComments(content, ext) {
  if (ext === '.css') {
    return content.replace(/\/\*[\s\S]*?\*\//g, '');
  } else if (['.js', '.jsx'].includes(ext)) {
    // This regex handles most JS comments but be careful with strings
    // A more robust way would be using a parser, but let's try this first
    return content
      .replace(/\/\*[\s\S]*?\*\//g, '') // Multi-line
      .replace(/(^|[^:])\/\/.*/g, '$1'); // Single-line (avoiding http://)
  }
  return content;
}

function processDirectory(dir) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      if (!['node_modules', '.git', 'dist', 'build'].includes(file)) {
        processDirectory(filePath);
      }
    } else {
      const ext = path.extname(file);
      if (['.js', '.jsx', '.css'].includes(ext)) {
        console.log(`Processing ${filePath}...`);
        let content = fs.readFileSync(filePath, 'utf8');
        let newContent = removeComments(content, ext);
        
        // Remove excessive empty lines
        newContent = newContent.replace(/\n\s*\n\s*\n/g, '\n\n');
        
        fs.writeFileSync(filePath, newContent, 'utf8');
      }
    }
  });
}

const targetDirs = [
  path.resolve(process.cwd(), 'src'),
  path.resolve(process.cwd(), '../../Backend2/src')
];

targetDirs.forEach(dir => {
  if (fs.existsSync(dir)) {
    console.log(`Cleaning comments in ${dir}...`);
    processDirectory(dir);
  } else {
    console.log(`Directory not found: ${dir}`);
  }
});

console.log('Cleanup complete!');
