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

// 服务目录
const SERVICES_DIR = __dirname;

// 目录映射（旧路径 -> 新路径）
const DIRECTORY_MAPPINGS = {
  'AI': 'ai',
  'Analytics': 'analytics',
  'Core': 'core',
  'Logistics': 'logistics',
  'Business': 'business',
  'Infra': 'infra',
  'Auth': 'auth',
  'Compliance': 'compliance',
  'Finance': 'finance',
  'Inventory': 'inventory',
  'Marketing': 'marketing',
  'Order': 'order',
  'Product': 'Product', // 保持Product目录大小写不变
  'Logistics': 'logistics',
  'Supplier': 'supplier',
  'Customer': 'customer',
  'Platform': 'platform',
  'Analytics': 'analytics',
  'AI': 'ai',
  'Core': 'core',
  'Integration': 'integration',
  'Monitoring': 'monitoring',
  'Security': 'security',
  'Settlement': 'settlement',
  'Sovereignty': 'sovereignty',
  'Webhook': 'webhook'
};

// 修复单个文件的导入路径
const fixImportPathsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 遍历目录映射，替换导入路径
    Object.entries(DIRECTORY_MAPPINGS).forEach(([oldDir, newDir]) => {
      // 匹配导入语句中的目录路径
      const importRegex = new RegExp(`from\s+['"]\.*/${oldDir}/['"]`, 'g');
      const newImport = `from './${newDir}/'`;
      
      if (importRegex.test(content)) {
        content = content.replace(importRegex, newImport);
        changed = true;
      }
      
      // 匹配相对路径中的目录路径
      const relativePathRegex = new RegExp(`\.*/${oldDir}/`, 'g');
      const newRelativePath = `./${newDir}/`;
      
      if (relativePathRegex.test(content)) {
        content = content.replace(relativePathRegex, newRelativePath);
        changed = true;
      }
    });
    
    // 特殊处理：修复从services根目录导入的路径
    const servicesRootRegex = new RegExp(`from\s+['"]\.\./(\w+)Service['"]`, 'g');
    content = content.replace(servicesRootRegex, (match, serviceName) => {
      // 查找服务所属的目录
      let targetDir = 'core'; // 默认目录
      
      // 遍历目录，查找服务文件
      const directories = fs.readdirSync(SERVICES_DIR).filter(dir => {
        const dirPath = path.join(SERVICES_DIR, dir);
        return fs.statSync(dirPath).isDirectory();
      });
      
      for (const dir of directories) {
        const dirPath = path.join(SERVICES_DIR, dir);
        const files = fs.readdirSync(dirPath);
        if (files.includes(`${serviceName}Service.ts`)) {
          targetDir = dir;
          break;
        }
      }
      
      changed = true;
      return `from '../${targetDir}/${serviceName}Service'`;
    });
    
    if (changed) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`Fixed import paths in: ${filePath}`);
    }
  } catch (error) {
    console.error(`Error fixing import paths in ${filePath}: ${error.message}`);
  }
};

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

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

// 运行修复
fixImportPaths();
