#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// Helper function to fix unused variables in a file
function fixUnusedVariablesInFile(filePath, unusedVars) {
  console.log(`\nProcessing file: ${filePath}`);
  console.log(`  Found unused variables: ${unusedVars.join(', ')}`);

  // Read the file
  const content = fs.readFileSync(filePath, 'utf8');
  const lines = content.split('\n');
  let fileFixed = false;
  let fixedCount = 0;

  // Process each line
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    
    // For each unused variable
    for (const varName of unusedVars) {
      if (line.includes(varName)) {
        // Check for imports or destructured variables
        if (line.includes('import') || (line.includes('{') && line.includes('}'))) {
          // Handle imports/destructuring
          const newLine = line.replace(
            new RegExp(`\\b${varName}\\b`, 'g'),
            `_${varName}`
          );
          
          if (newLine !== line) {
            lines[i] = newLine;
            fileFixed = true;
            fixedCount++;
            console.log(`    - Fixed: ${varName} → _${varName}`);
          }
        } 
        // Handle other variable declarations
        else {
          const newLine = line.replace(
            new RegExp(`\\b${varName}\\b`, 'g'),
            `_${varName}`
          );
          
          if (newLine !== line) {
            lines[i] = newLine;
            fileFixed = true;
            fixedCount++;
            console.log(`    - Fixed: ${varName} → _${varName}`);
          }
        }
      }
    }
  }

  // Write the updated content back to the file if changes were made
  if (fileFixed) {
    fs.writeFileSync(filePath, lines.join('\n'), 'utf8');
    console.log(`  Successfully fixed ${fixedCount} unused variables`);
    return fixedCount;
  } else {
    console.log(`  No changes made to file`);
    return 0;
  }
}

// Main execution
try {
  console.log('Running ESLint to find all unused variables...');
  const lintOutput = execSync('npx next lint', { encoding: 'utf8' });
  
  // Parse the lint output to find files with unused variables
  const fileWarnings = new Map();
  
  // Create regex to match lines like "./components/ui/chart.tsx"
  const fileLineRegex = /^\.\/([^\s]+)\s/;
  
  // Create regex to match unused variable warnings
  const unusedVarRegex = /.*['"](.*?)['"].*(?:never used|is defined but never used)/;
  
  let currentFile = null;
  
  // Parse the lint output line by line
  const lines = lintOutput.split('\n');
  for (const line of lines) {
    // Check if this is a file path line
    const fileMatch = line.match(fileLineRegex);
    if (fileMatch) {
      currentFile = fileMatch[1];
      fileWarnings.set(currentFile, []);
      continue;
    }
    
    // If we have a current file and this line is a warning for unused variables
    if (currentFile && line.includes('no-unused-vars')) {
      const varMatch = line.match(unusedVarRegex);
      if (varMatch && varMatch[1]) {
        fileWarnings.get(currentFile).push(varMatch[1]);
      }
    }
  }
  
  // Filter out files with no unused variables
  for (const [file, vars] of fileWarnings.entries()) {
    if (vars.length === 0) {
      fileWarnings.delete(file);
    }
  }
  
  console.log(`\nFound ${fileWarnings.size} files with unused variables.`);
  
  // Fix each file
  let totalFixedCount = 0;
  
  for (const [file, unusedVars] of fileWarnings.entries()) {
    const filePath = file;
    
    if (fs.existsSync(filePath)) {
      const fixedCount = fixUnusedVariablesInFile(filePath, unusedVars);
      totalFixedCount += fixedCount;
    } else {
      console.log(`\nSkipping file ${filePath} - not found`);
    }
  }
  
  console.log(`\nCompleted! Fixed ${totalFixedCount} unused variable issues across ${fileWarnings.size} files.`);
  
} catch (error) {
  console.error('Error running the script:', error.message);
  console.error('Stack trace:', error.stack);
  process.exit(1);
} 