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

// 基础路径
const SERVER_DIR = path.join(__dirname, '..', '..');

// 所有目录列表
const ALL_DIRS = [
  'ai', 'analytics', 'auth', 'business', 'compliance', 'core',
  'customer', 'finance', 'infra', 'integration', 'inventory',
  'logistics', 'marketing', 'monitoring', 'order', 'platform',
  'product', 'security', 'settlement', 'sovereignty', 'supplier',
  'telemetry', 'tenant', 'utils', 'webhook', 'adapters', '__tests__'
];

// 服务分类映射
const SERVICE_CATEGORIES = {};

// 扫描services目录，构建服务-目录映射
const scanServicesDir = () => {
  const servicesDir = path.join(SERVER_DIR, 'src', 'services');
  const items = fs.readdirSync(servicesDir);
  
  items.forEach(item => {
    const itemPath = path.join(servicesDir, item);
    if (fs.statSync(itemPath).isDirectory()) {
      const files = fs.readdirSync(itemPath);
      files.forEach(file => {
        if (file.endsWith('.ts') && !file.endsWith('.d.ts')) {
          const serviceName = file.replace('.ts', '');
          SERVICE_CATEGORIES[serviceName] = item.toLowerCase();
        }
      });
    }
  });
};

// 修复单个文件的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 匹配从services根目录导入服务的情况
    // 例如: import { XxxService } from '../../services/XxxService'
    // 应该改为: import { XxxService } from '../../services/category/XxxService'
    
    const importRegex = /from\s+['"](\.\.\/)+(services\/)([A-Z][a-zA-Z]+Service)['"]/g;
    const matches = [...content.matchAll(importRegex)];
    
    matches.forEach(match => {
      const serviceName = match[3];
      const category = SERVICE_CATEGORIES[serviceName];
      
      if (category) {
        const oldImport = match[0];
        const newImport = `from '${match[1]}services/${category}/${serviceName}'`;
        
        if (oldImport !== newImport) {
          content = content.replace(oldImport, newImport);
          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) => {
  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);
    }
  });
};

// 主函数
const main = () => {
  console.log('Scanning services directory...');
  scanServicesDir();
  
  console.log('\nFixing import paths...');
  fixImportsRecursive(SERVER_DIR);
  
  console.log('\nDone!');
};

main();
