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

const SERVICES_DIR = __dirname;

// 需要修复的目录映射
const dirMappings = [
  { from: 'AI', to: 'ai' },
  { from: 'Analytics', to: 'analytics' },
  { from: 'Core', to: 'core' },
  { from: 'Logistics', to: 'logistics' },
  { from: 'Product', to: 'product' },
  { from: 'Business', to: 'business' },
  { from: 'Infra', to: 'infra' }
];

console.log('Starting final directory rename process...\n');

dirMappings.forEach(({ from, to }) => {
  const fromPath = path.join(SERVICES_DIR, from);
  const toPath = path.join(SERVICES_DIR, to);
  
  // 使用PowerShell的Get-Item检查实际文件名
  try {
    const actualName = execSync(
      `powershell.exe -Command "(Get-Item '${fromPath}').Name"`,
      { encoding: 'utf8' }
    ).trim();
    
    console.log(`Actual directory name: ${actualName}`);
    
    if (actualName === from) {
      // 需要重命名
      const tempName = `${from}_RENAME_TEMP`;
      const tempPath = path.join(SERVICES_DIR, tempName);
      
      try {
        // 步骤1: 重命名为临时名称
        console.log(`  Step 1: ${from} -> ${tempName}`);
        fs.renameSync(fromPath, tempPath);
        
        // 步骤2: 重命名为小写名称
        console.log(`  Step 2: ${tempName} -> ${to}`);
        fs.renameSync(tempPath, toPath);
        
        console.log(`  ✓ Success: ${from} -> ${to}\n`);
      } catch (error) {
        console.error(`  ✗ Failed: ${error.message}\n`);
      }
    } else if (actualName === to) {
      console.log(`  ✓ Already lowercase: ${to}\n`);
    } else {
      console.log(`  ? Unexpected name: ${actualName}\n`);
    }
  } catch (error) {
    console.error(`  ✗ Error checking ${from}: ${error.message}\n`);
  }
});

console.log('Done!');
