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

// 服务目录
const SERVICES_DIR = __dirname;

// 所有可能的目录名（大写和小写）
const DIRECTORIES = [
  'ai', 'AI',
  'analytics', 'Analytics',
  'auth', 'Auth',
  'business', 'Business',
  'compliance', 'Compliance',
  'core', 'Core',
  'customer', 'Customer',
  'finance', 'Finance',
  'infra', 'Infra',
  'integration', 'Integration',
  'inventory', 'Inventory',
  'logistics', 'Logistics',
  'marketing', 'Marketing',
  'monitoring', 'Monitoring',
  'order', 'Order',
  'platform', 'Platform',
  'product', 'Product',
  'security', 'Security',
  'settlement', 'Settlement',
  'sovereignty', 'Sovereignty',
  'webhook', 'Webhook'
];

// 修复单个文件的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 遍历所有目录名，替换导入路径中的大写目录名为小写
    for (let i = 0; i < DIRECTORIES.length; i += 2) {
      const lowercaseDir = DIRECTORIES[i];
      const uppercaseDir = DIRECTORIES[i + 1];
      
      // 匹配导入语句中的目录路径
      const importRegex = new RegExp(`from\s+['"]\.*/${uppercaseDir}/['"]`, 'g');
      const newImport = `from './${lowercaseDir}/'`;
      
      if (importRegex.test(content)) {
        content = content.replace(importRegex, newImport);
        changed = true;
      }
      
      // 匹配相对路径中的目录路径
      const relativePathRegex = new RegExp(`\.*/${uppercaseDir}/`, 'g');
      const newRelativePath = `./${lowercaseDir}/`;
      
      if (relativePathRegex.test(content)) {
        content = content.replace(relativePathRegex, newRelativePath);
        changed = true;
      }
    }
    
    if (changed) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`Fixed imports in: ${filePath}`);
    }
  } catch (error) {
    console.error(`Error fixing imports in ${filePath}: ${error.message}`);
  }
};

// 递归遍历目录，修复所有TypeScript文件的导入路径
const fixImportsRecursive = (dirPath) => {
  const items = fs.readdirSync(dirPath);
  
  items.forEach(item => {
    const itemPath = path.join(dirPath, item);
    const stat = fs.statSync(itemPath);
    
    if (stat.isDirectory() && item !== '__tests__' && item !== 'node_modules') {
      fixImportsRecursive(itemPath);
    } else if (stat.isFile() && item.endsWith('.ts')) {
      fixImportsInFile(itemPath);
    }
  });
};

// 运行修复
const runFixImports = () => {
  console.log('Starting import path fix...');
  fixImportsRecursive(SERVICES_DIR);
  console.log('\nImport path fix completed!');
};

// 运行修复
runFixImports();
