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

const SERVER_DIR = path.join(__dirname, '..', '..');
const SERVICES_DIR = __dirname;

// 获取所有服务文件及其所在目录的映射
const getServiceMapping = () => {
  const mapping = {};
  
  const scanDir = (dirPath, basePath = '') => {
    const items = fs.readdirSync(dirPath);
    
    items.forEach(item => {
      const itemPath = path.join(dirPath, item);
      const stat = fs.statSync(itemPath);
      
      if (stat.isDirectory() && !item.startsWith('__')) {
        scanDir(itemPath, path.join(basePath, item));
      } else if (stat.isFile() && item.endsWith('.ts') && !item.endsWith('.d.ts')) {
        const serviceName = item.replace('.ts', '');
        mapping[serviceName] = basePath;
      }
    });
  };
  
  scanDir(SERVICES_DIR);
  return mapping;
};

// 修复单个文件的导入路径
const fixImportsInFile = (filePath, serviceMapping) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 获取文件相对于src目录的深度
    const relativeToSrc = path.relative(path.join(SERVER_DIR, 'src'), filePath);
    const depth = relativeToSrc.split(path.sep).length - 1;
    
    // 修复从services目录导入的错误路径
    // 例如: import X from '../services/ai/AIService' 应该改为 import X from '../../services/ai/AIService'
    
    const wrongPatterns = [
      // 修复从core目录导入的错误路径
      { regex: /from\s+['"]\.\.\/services\/core\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: (match, p1) => {
        const prefix = '../'.repeat(depth);
        return `from '${prefix}services/core/${p1}'`;
      }},
      // 修复从ai目录导入的错误路径
      { regex: /from\s+['"]\.\.\/services\/ai\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: (match, p1) => {
        const prefix = '../'.repeat(depth);
        return `from '${prefix}services/ai/${p1}'`;
      }},
      // 修复从其他目录导入的错误路径
      { regex: /from\s+['"]\.\.\/services\/([a-z]+)\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: (match, p1, p2) => {
        const prefix = '../'.repeat(depth);
        return `from '${prefix}services/${p1}/${p2}'`;
      }}
    ];
    
    wrongPatterns.forEach(({ regex, replacement }) => {
      if (regex.test(content)) {
        content = content.replace(regex, replacement);
        changed = true;
      }
    });
    
    // 修复从当前目录导入的错误路径
    // 例如: import X from './finance/FXHedgingService' 应该改为 import X from '../finance/FXHedgingService'
    const currentDirPatterns = [
      { regex: /from\s+['"]\.\/([a-z]+)\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../$1/$2'" }
    ];
    
    currentDirPatterns.forEach(({ regex, replacement }) => {
      if (regex.test(content)) {
        content = content.replace(regex, replacement);
        changed = true;
      }
    });
    
    if (changed) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`Fixed: ${path.relative(SERVER_DIR, filePath)}`);
    }
  } catch (error) {
    console.error(`Error fixing ${filePath}: ${error.message}`);
  }
};

// 递归遍历目录
const fixImportsRecursive = (dirPath, serviceMapping) => {
  const items = fs.readdirSync(dirPath);
  
  items.forEach(item => {
    const itemPath = path.join(dirPath, item);
    const stat = fs.statSync(itemPath);
    
    if (stat.isDirectory() && !item.startsWith('__') && item !== 'node_modules') {
      fixImportsRecursive(itemPath, serviceMapping);
    } else if (stat.isFile() && item.endsWith('.ts') && !item.endsWith('.d.ts')) {
      fixImportsInFile(itemPath, serviceMapping);
    }
  });
};

// 主函数
const main = () => {
  console.log('Building service mapping...');
  const serviceMapping = getServiceMapping();
  
  console.log('\nFixing all import paths...\n');
  fixImportsRecursive(SERVER_DIR, serviceMapping);
  
  console.log('\nDone!');
};

main();
