/**
 * Script to update imports after reorganizing the lib folder
 * Run with: node scripts/update-imports.js
 */

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

// Map of old imports to new imports
const importMap = {
  '@/lib/styles': '@/lib/utils/styles',
  '@/lib/utils': '@/lib/utils/general',
  '@/lib/auth-utils': '@/lib/utils/auth',
  '@/lib/git-utils': '@/lib/utils/git',
  '@/lib/types': '@/lib/types',
  '@/lib/data-service': '@/lib/api',
  '@/lib/client-utils': '@/lib/api',
  '@/lib/client-service': '@/lib/api',
  '@/lib/productData': '@/lib/api',
  '@/lib/shippingHelper': '@/lib/api',
  '@/lib/stats-service': '@/lib/api',
  '@/lib/storeHelper': '@/lib/api',
  '@/lib/server-service': '@/lib/api',
  '@/lib/api-utils': '@/lib/api',
};

// Function to find all TypeScript and JavaScript files
function findTsJsFiles(directory) {
  let results = [];
  const files = fs.readdirSync(directory, { withFileTypes: true });

  for (const file of files) {
    const fullPath = path.join(directory, file.name);
    
    // Skip node_modules and .next directories
    if (file.isDirectory()) {
      if (file.name !== 'node_modules' && file.name !== '.next' && file.name !== '.git') {
        results = results.concat(findTsJsFiles(fullPath));
      }
    } else if (file.name.endsWith('.ts') || file.name.endsWith('.tsx') || file.name.endsWith('.js') || file.name.endsWith('.jsx')) {
      results.push(fullPath);
    }
  }

  return results;
}

// Function to update imports in a file
function updateImportsInFile(filePath) {
  console.log(`Checking ${filePath}`);
  let fileContent = fs.readFileSync(filePath, 'utf8');
  let originalContent = fileContent;
  let hasChanges = false;

  // Check for each old import and replace with new import
  for (const [oldImport, newImport] of Object.entries(importMap)) {
    // Create regex to match import statements for this module
    // This handles different import formats:
    // import X from 'oldImport' 
    // import { X } from 'oldImport'
    // import * as X from 'oldImport'
    const importRegex = new RegExp(`import\\s+(?:.+?)\\s+from\\s+['"]${oldImport.replace('/', '\\/')}['"]`, 'g');
    
    if (importRegex.test(fileContent)) {
      fileContent = fileContent.replace(importRegex, (match) => {
        return match.replace(oldImport, newImport);
      });
      hasChanges = true;
    }
  }

  // If any changes were made, write the file
  if (hasChanges) {
    fs.writeFileSync(filePath, fileContent, 'utf8');
    console.log(`✅ Updated imports in ${filePath}`);
    return true;
  }
  
  return false;
}

// Main function to update all imports
function updateAllImports() {
  console.log('🔎 Finding TypeScript and JavaScript files...');
  const projectRoot = path.resolve(__dirname, '..');
  const files = findTsJsFiles(projectRoot);
  
  console.log(`Found ${files.length} files to check.`);
  console.log('🔄 Updating imports...');
  
  let updatedCount = 0;
  
  for (const file of files) {
    if (updateImportsInFile(file)) {
      updatedCount++;
    }
  }
  
  console.log(`\n✅ Import update complete!`);
  console.log(`- ${updatedCount} files were updated`);
  console.log(`- ${files.length - updatedCount} files had no changes needed`);
  
  // Run next build to check for any remaining errors
  console.log('\n🔍 Running TypeScript check to find any remaining issues...');
  try {
    execSync('npx tsc --noEmit', { stdio: 'inherit' });
    console.log('\n✅ TypeScript check passed!');
  } catch (error) {
    console.error('\n⚠️ TypeScript check found some issues. Please fix them manually.');
  }
}

// Run the script
updateAllImports(); 