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;
    
    // 修复从services子目录导入的错误相对路径
    // 例如: import X from './finance/FXHedgingService' 应该改为 import X from '../finance/FXHedgingService'
    
    const wrongPatterns = [
      { regex: /from\s+['"]\.\/finance\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../finance/$1'" },
      { regex: /from\s+['"]\.\/settlement\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../settlement/$1'" },
      { regex: /from\s+['"]\.\/core\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from './$1'" },
      { regex: /from\s+['"]\.\/security\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../security/$1'" },
      { regex: /from\s+['"]\.\/inventory\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../inventory/$1'" },
      { regex: /from\s+['"]\.\/product\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../product/$1'" },
      { regex: /from\s+['"]\.\/order\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../order/$1'" },
      { regex: /from\s+['"]\.\/logistics\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../logistics/$1'" },
      { regex: /from\s+['"]\.\/platform\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../platform/$1'" },
      { regex: /from\s+['"]\.\/supplier\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../supplier/$1'" },
      { regex: /from\s+['"]\.\/customer\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../customer/$1'" },
      { regex: /from\s+['"]\.\/marketing\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../marketing/$1'" },
      { regex: /from\s+['"]\.\/ai\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../ai/$1'" },
      { regex: /from\s+['"]\.\/analytics\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../analytics/$1'" },
      { regex: /from\s+['"]\.\/auth\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../auth/$1'" },
      { regex: /from\s+['"]\.\/business\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../business/$1'" },
      { regex: /from\s+['"]\.\/compliance\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../compliance/$1'" },
      { regex: /from\s+['"]\.\/integration\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../integration/$1'" },
      { regex: /from\s+['"]\.\/monitoring\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../monitoring/$1'" },
      { regex: /from\s+['"]\.\/sovereignty\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../sovereignty/$1'" },
      { regex: /from\s+['"]\.\/tenant\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../tenant/$1'" },
      { regex: /from\s+['"]\.\/utils\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../utils/$1'" },
      { regex: /from\s+['"]\.\/webhook\/([A-Z][a-zA-Z]+Service)['"]/g, replacement: "from '../webhook/$1'" }
    ];
    
    wrongPatterns.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 remaining import paths...\n');
  fixImportsRecursive(SERVER_DIR, serviceMapping);
  
  console.log('\nDone!');
};

main();
