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

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

// 修复单个文件的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 修复从services子目录导入其他services的相对路径
    // 例如: import X from '../config/database' 应该改为 import X from '../../config/database'
    
    // 获取文件相对于services目录的深度
    const relativeToServices = path.relative(SERVICES_DIR, filePath);
    const depth = relativeToServices.split(path.sep).length - 1;
    
    // 根据深度确定正确的相对路径前缀
    const correctPrefix = '../'.repeat(depth + 1);
    const wrongPrefix = '../'.repeat(depth);
    
    // 修复常见的错误导入模式
    const fixes = [
      { from: `from '${wrongPrefix}config/`, to: `from '${correctPrefix}config/` },
      { from: `from '${wrongPrefix}utils/`, to: `from '${correctPrefix}utils/` },
      { from: `from '${wrongPrefix}types/`, to: `from '${correctPrefix}types/` },
      { from: `from '${wrongPrefix}models/`, to: `from '${correctPrefix}models/` },
      { from: `from '${wrongPrefix}shared/`, to: `from '${correctPrefix}shared/` },
      { from: `from '${wrongPrefix}core/`, to: `from '${correctPrefix}core/` },
      { from: `require('${wrongPrefix}config/`, to: `require('${correctPrefix}config/` },
      { from: `require('${wrongPrefix}utils/`, to: `require('${correctPrefix}utils/` },
      { from: `require('${wrongPrefix}types/`, to: `require('${correctPrefix}types/` },
      { from: `require('${wrongPrefix}models/`, to: `require('${correctPrefix}models/` },
      { from: `require('${wrongPrefix}shared/`, to: `require('${correctPrefix}shared/` },
      { from: `require('${wrongPrefix}core/`, to: `require('${correctPrefix}core/` }
    ];
    
    fixes.forEach(({ from, to }) => {
      if (content.includes(from)) {
        content = content.split(from).join(to);
        changed = true;
      }
    });
    
    // 修复从services根目录导入其他服务的情况
    // 例如: import X from './ServiceName' 应该改为 import X from './category/ServiceName'
    const serviceImportPattern = /from\s+['"]\.\/([A-Z][a-zA-Z]+Service)['"]/g;
    const matches = [...content.matchAll(serviceImportPattern)];
    
    matches.forEach(match => {
      const serviceName = match[1];
      // 查找服务所在的目录
      let targetDir = null;
      const dirs = fs.readdirSync(SERVICES_DIR).filter(d => {
        const dPath = path.join(SERVICES_DIR, d);
        return fs.statSync(dPath).isDirectory() && !d.startsWith('__');
      });
      
      for (const dir of dirs) {
        const dirPath = path.join(SERVICES_DIR, dir);
        const files = fs.readdirSync(dirPath);
        if (files.includes(`${serviceName}.ts`)) {
          targetDir = dir;
          break;
        }
      }
      
      if (targetDir) {
        const oldImport = match[0];
        const newImport = `from './${targetDir}/${serviceName}'`;
        if (oldImport !== newImport) {
          content = content.replace(oldImport, newImport);
          changed = true;
        }
      }
    });
    
    if (changed) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`Fixed: ${path.relative(SRC_DIR, filePath)}`);
    }
  } catch (error) {
    console.error(`Error fixing ${filePath}: ${error.message}`);
  }
};

// 递归遍历目录
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.startsWith('__') && item !== 'node_modules') {
      fixImportsRecursive(itemPath);
    } else if (stat.isFile() && item.endsWith('.ts') && !item.endsWith('.d.ts')) {
      fixImportsInFile(itemPath);
    }
  });
};

// 运行修复
console.log('Fixing all service imports...\n');
fixImportsRecursive(SERVICES_DIR);
console.log('\nDone!');
