/**
 * Script to organize the lib folder by moving files into appropriate directories
 * Run with: node scripts/organize-lib-folder.js
 */

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

// File organization plan
const ORGANIZATION_PLAN = {
  // Files to move to utils folder
  'utils': [
    { source: 'lib/utils.ts', destination: 'lib/utils/general.ts' },
    { source: 'lib/auth-utils.ts', destination: 'lib/utils/auth.ts' },
    { source: 'lib/git-utils.ts', destination: 'lib/utils/git.ts' },
    { source: 'lib/styles.ts', destination: 'lib/utils/styles.ts' }
  ],
  
  // Files to move to types folder
  'types': [
    { source: 'lib/types.ts', destination: 'lib/types/index.ts' }
  ],
  
  // Files to keep in lib root (core API files)
  'keep': [
    'lib/api.ts',
    'lib/api-client.ts',
    'lib/server-api.ts',
    'lib/README.md'
  ],
  
  // Files to remove (already migrated to services or consolidated)
  'remove': [
    'lib/client-utils.ts',
    'lib/client-service.ts',
    'lib/data-service.ts',
    'lib/productData.ts',
    'lib/shippingHelper.ts',
    'lib/stats-service.ts',
    'lib/storeHelper.ts',
    'lib/server-service.ts',
    'lib/api-utils.ts'
  ]
};

// Create backup directory
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}`);
}

// Make sure target directories exist
function createDirectories() {
  const directories = ['lib/utils', 'lib/types', 'lib/services'];
  
  directories.forEach(dir => {
    const fullPath = path.join(__dirname, '..', dir);
    if (!fs.existsSync(fullPath)) {
      fs.mkdirSync(fullPath, { recursive: true });
      console.log(`Created directory: ${dir}`);
    }
  });
}

// Backup a file before moving or removing it
function backupFile(filePath) {
  const fullPath = path.join(__dirname, '..', filePath);
  
  if (!fs.existsSync(fullPath)) {
    console.log(`⚠️  ${filePath} doesn't exist, skipping backup`);
    return false;
  }
  
  try {
    const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
    fs.copyFileSync(fullPath, backupPath);
    console.log(`✅ Backed up: ${filePath} to backup folder`);
    return true;
  } catch (error) {
    console.error(`❌ Failed to backup ${filePath}:`, error.message);
    return false;
  }
}

// Move a file to its new location
function moveFile(source, destination) {
  const sourcePath = path.join(__dirname, '..', source);
  const destPath = path.join(__dirname, '..', destination);
  
  if (!fs.existsSync(sourcePath)) {
    console.log(`⚠️  Source file ${source} doesn't exist, skipping`);
    return false;
  }
  
  try {
    // Ensure the destination directory exists
    const destDir = path.dirname(destPath);
    if (!fs.existsSync(destDir)) {
      fs.mkdirSync(destDir, { recursive: true });
    }
    
    // Read content from source
    const content = fs.readFileSync(sourcePath, 'utf8');
    
    // Write to destination
    fs.writeFileSync(destPath, content);
    console.log(`✅ Moved: ${source} → ${destination}`);
    
    // Remove the source file
    fs.unlinkSync(sourcePath);
    return true;
  } catch (error) {
    console.error(`❌ Error moving ${source} to ${destination}:`, error.message);
    return false;
  }
}

// Remove a file 
function removeFile(filePath) {
  const fullPath = path.join(__dirname, '..', filePath);
  
  if (!fs.existsSync(fullPath)) {
    console.log(`⚠️  ${filePath} doesn't exist, skipping removal`);
    return false;
  }
  
  try {
    fs.unlinkSync(fullPath);
    console.log(`🗑️  Removed: ${filePath}`);
    return true;
  } catch (error) {
    console.error(`❌ Failed to remove ${filePath}:`, error.message);
    return false;
  }
}

// Update imports in the utils/index.ts file
function updateUtilsIndex() {
  const indexPath = path.join(__dirname, '..', 'lib/utils/index.ts');
  
  try {
    const content = `/**
 * Main utilities index file
 * Re-exports all utility functions from their respective modules
 */

// Re-export general utils
export * from './general';

// Re-export auth utils
export * from './auth';

// Re-export git utils
export * from './git';

// Re-export style utils
export * from './styles';
`;
    
    fs.writeFileSync(indexPath, content);
    console.log(`✅ Updated lib/utils/index.ts with proper exports`);
    return true;
  } catch (error) {
    console.error(`❌ Failed to update utils index:`, error.message);
    return false;
  }
}

// Main function to organize files
function organizeLibFolder() {
  console.log('Starting lib folder organization...\n');
  
  // Create necessary directories
  createDirectories();
  
  // Stats to track progress
  const stats = {
    backed_up: 0,
    moved: 0,
    removed: 0,
    errors: 0
  };
  
  // First, back up all files we'll be modifying
  const allFiles = [
    ...ORGANIZATION_PLAN.utils.map(item => item.source),
    ...ORGANIZATION_PLAN.types.map(item => item.source),
    ...ORGANIZATION_PLAN.remove
  ];
  
  allFiles.forEach(file => {
    if (backupFile(file)) {
      stats.backed_up++;
    } else {
      stats.errors++;
    }
  });
  
  // Move files to utils folder
  ORGANIZATION_PLAN.utils.forEach(item => {
    if (moveFile(item.source, item.destination)) {
      stats.moved++;
    } else {
      stats.errors++;
    }
  });
  
  // Move files to types folder
  ORGANIZATION_PLAN.types.forEach(item => {
    if (moveFile(item.source, item.destination)) {
      stats.moved++;
    } else {
      stats.errors++;
    }
  });
  
  // Remove deprecated files
  ORGANIZATION_PLAN.remove.forEach(file => {
    if (removeFile(file)) {
      stats.removed++;
    } else {
      stats.errors++;
    }
  });
  
  // Update the utils index file
  updateUtilsIndex();
  
  // Summary
  console.log(`\nOrganization complete!`);
  console.log(`✅ ${stats.backed_up} files backed up`);
  console.log(`✅ ${stats.moved} files moved to appropriate folders`);
  console.log(`✅ ${stats.removed} deprecated files removed`);
  
  if (stats.errors > 0) {
    console.log(`❌ ${stats.errors} errors encountered (see above)`);
  }
  
  console.log(`\nBackups are located in: lib/deprecated-backup`);
  console.log(`You can delete this directory when you are confident the migration is complete.`);
}

// Show confirmation before proceeding
console.log(`
✨ Lib Folder Organization Tool ✨

This script will organize your lib folder as follows:

1. Move utility files to lib/utils/
   ${ORGANIZATION_PLAN.utils.map(f => `\n   - ${f.source} → ${f.destination}`).join('')}

2. Move type files to lib/types/
   ${ORGANIZATION_PLAN.types.map(f => `\n   - ${f.source} → ${f.destination}`).join('')}

3. Keep core API files in the lib root
   ${ORGANIZATION_PLAN.keep.map(f => `\n   - ${f}`).join('')}

4. Remove deprecated files
   ${ORGANIZATION_PLAN.remove.map(f => `\n   - ${f}`).join('')}

All files will be backed up to lib/deprecated-backup before any changes.

To proceed, edit this script and uncomment the organizeLibFolder() call at the bottom.
`);

// Uncomment this line to actually organize the folder
organizeLibFolder(); 