/**
 * Script to help clean up deprecated files in the codebase
 * Run with: node scripts/cleanup-deprecated-files.js
 */

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

// List of files that are now deprecated and can be removed/archived
const DEPRECATED_FILES = [
  // API Client files that are now merged into api-client.ts
  'lib/client-utils.ts',
  'lib/client-service.ts',
  'lib/data-service.ts',
  
  // Service files that are now in the services directory
  'lib/productData.ts',
  'lib/shippingHelper.ts',
  'lib/stats-service.ts',
  'lib/storeHelper.ts',
  
  // Server API files now in server-api.ts
  'lib/server-service.ts',
  
  // Files that may contain functionality already migrated
  'lib/api-utils.ts',
];

// Create backup directory if it doesn't exist
const BACKUP_DIR = path.join(__dirname, '../lib/deprecated-backup');
if (!fs.existsSync(BACKUP_DIR)) {
  fs.mkdirSync(BACKUP_DIR, { recursive: true });
  console.log(`Created backup directory: ${BACKUP_DIR}`);
}

// Process each deprecated file
function processDeprecatedFiles() {
  console.log('Analyzing deprecated files...\n');
  
  const results = {
    safe: [],
    notFound: [],
    mayNeedMigration: []
  };
  
  DEPRECATED_FILES.forEach(filePath => {
    const fullPath = path.join(__dirname, '..', filePath);
    
    if (!fs.existsSync(fullPath)) {
      results.notFound.push(filePath);
      return;
    }
    
    // Check if this file is safe to remove (has been migrated)
    const isSafeToRemove = checkIfSafeToRemove(filePath);
    
    if (isSafeToRemove) {
      results.safe.push(filePath);
    } else {
      results.mayNeedMigration.push(filePath);
    }
  });
  
  return results;
}

// Check if a file's functionality has been migrated
function checkIfSafeToRemove(filePath) {
  // Simple heuristic - files that we're confident have been fully migrated
  const definitelyMigrated = [
    'lib/client-utils.ts',
    'lib/client-service.ts',
    'lib/data-service.ts',
    'lib/productData.ts',
    'lib/shippingHelper.ts',
    'lib/stats-service.ts',
    'lib/server-service.ts',
  ];
  
  return definitelyMigrated.includes(filePath);
}

// Create a backup of a file before removing it
function backupFile(filePath) {
  const fullPath = path.join(__dirname, '..', filePath);
  const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
  
  try {
    const content = fs.readFileSync(fullPath, 'utf8');
    fs.writeFileSync(backupPath, content);
    console.log(`✅ Backed up: ${filePath} to ${path.basename(backupPath)}`);
    return true;
  } catch (error) {
    console.error(`❌ Failed to backup ${filePath}:`, error.message);
    return false;
  }
}

// Remove a file from the codebase
function removeFile(filePath) {
  const fullPath = path.join(__dirname, '..', filePath);
  
  try {
    fs.unlinkSync(fullPath);
    console.log(`🗑️  Removed: ${filePath}`);
    return true;
  } catch (error) {
    console.error(`❌ Failed to remove ${filePath}:`, error.message);
    return false;
  }
}

// Main execution function
function main() {
  const results = processDeprecatedFiles();
  
  console.log('\n=== ANALYSIS RESULTS ===\n');
  
  if (results.notFound.length > 0) {
    console.log('📂 Files not found:');
    results.notFound.forEach(f => console.log(`  - ${f}`));
    console.log('');
  }
  
  if (results.mayNeedMigration.length > 0) {
    console.log('⚠️  Files that may need migration:');
    results.mayNeedMigration.forEach(f => console.log(`  - ${f}`));
    console.log('\nCheck these files manually to ensure all functionality has been migrated.\n');
  }
  
  if (results.safe.length > 0) {
    console.log('✅ Files safe to remove (already migrated):');
    results.safe.forEach(f => console.log(`  - ${f}`));
    
    console.log('\nWhat would you like to do with these files?');
    console.log('1. Back up and remove now');
    console.log('2. Just back up');
    console.log('3. Do nothing for now');
    
    // In a real script, you'd get user input here
    // For now, just demonstrate with a backup
    console.log('\nDemo mode: backing up files...\n');
    
    results.safe.forEach(filePath => {
      if (backupFile(filePath)) {
        console.log(`To remove ${filePath}, run: rm "${path.join(__dirname, '..', filePath)}"`);
      }
    });
  }
  
  console.log('\n=== MANUAL CLEANUP INSTRUCTIONS ===\n');
  console.log('After verifying imports have been updated with find-deprecated-imports.js:');
  console.log('1. Remove the backed up files using the commands above');
  console.log('2. Check any remaining files in the lib/ directory to see if they should be organized');
  console.log('3. Update imports in files using the main API module');
}

// Run the script
main(); 