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

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

// 定义目录名映射（大写 -> 小写）
const DIR_CASE_MAP = {
  'AI': 'ai',
  'Analytics': 'analytics',
  'Auth': 'auth',
  'Compliance': 'compliance',
  'Core': 'core',
  'Customer': 'customer',
  'Finance': 'finance',
  'Integration': 'integration',
  'Inventory': 'inventory',
  'Logistics': 'logistics',
  'Marketing': 'marketing',
  'Monitoring': 'monitoring',
  'Order': 'order',
  'Platform': 'platform',
  'Product': 'product',
  'Security': 'security',
  'Supplier': 'supplier',
  'Telemetry': 'telemetry',
  'Tenant': 'tenant',
  'Utils': 'utils',
  'Webhook': 'webhook',
  'Domains': 'domains',
  'Strategy': 'strategy'
};

// 修复文件中的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 修复目录大小写的导入
    Object.entries(DIR_CASE_MAP).forEach(([oldName, newName]) => {
      // 构建所有可能的导入模式
      const patterns = [
        // from 语句，使用单引号
        `from '../${oldName}/`,
        `from '../../${oldName}/`,
        `from '../../../${oldName}/`,
        `from '../../../../${oldName}/`,
        `from './${oldName}/`,
        // from 语句，使用双引号
        `from "../${oldName}/`,
        `from "../../${oldName}/`,
        `from "../../../${oldName}/`,
        `from "../../../../${oldName}/`,
        `from "./${oldName}/`,
        // require 语句，使用单引号
        `require('../${oldName}/`,
        `require('../../${oldName}/`,
        `require('./${oldName}/`,
        // require 语句，使用双引号
        `require("../${oldName}/`,
        `require("../../${oldName}/`,
        `require("./${oldName}/`
      ];
      
      patterns.forEach(pattern => {
        if (content.includes(pattern)) {
          const replacement = pattern.replace(oldName, newName);
          content = content.split(pattern).join(replacement);
          changed = true;
        }
      });
    });
    
    // 修复常见的导入路径错误
    const pathFixes = [
      // 修复从product目录导入core服务的路径
      [`from '../core/`, `from '../core/`],
      [`from "../core/`, `from "../core/`],
      [`require('../core/`, `require('../core/`],
      [`require("../core/`, `require("../core/`],
      // 修复从security目录导入core服务的路径
      [`from '../core/`, `from '../core/`],
      [`from "../core/`, `from "../core/`],
      [`require('../core/`, `require('../core/`],
      [`require("../core/`, `require("../core/`],
      // 修复从settlement目录导入core服务的路径
      [`from '../core/`, `from '../core/`],
      [`from "../core/`, `from "../core/`],
      [`require('../core/`, `require('../core/`],
      [`require("../core/`, `require("../core/`],
      // 修复从sovereignty目录导入core服务的路径
      [`from '../core/`, `from '../core/`],
      [`from "../core/`, `from "../core/`],
      [`require('../core/`, `require('../core/`],
      [`require("../core/`, `require("../core/`],
      // 修复从utils目录导入core服务的路径
      [`from '../core/`, `from '../core/`],
      [`from "../core/`, `from "../core/`],
      [`require('../core/`, `require('../core/`],
      [`require("../core/`, `require("../core/`],
      // 修复从services根目录导入服务的路径
      [`from '../product/ProductService'`, `from '../product/ProductService'`],
      [`from "../product/ProductService"`, `from "../product/ProductService"`],
      [`require('../product/ProductService'`, `require('../product/ProductService'`],
      [`require("../product/ProductService"`, `require("../product/ProductService"`]
    ];
    
    pathFixes.forEach(([oldStr, newStr]) => {
      if (content.includes(oldStr)) {
        content = content.split(oldStr).join(newStr);
        changed = true;
      }
    });
    
    if (changed) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`Fixed imports in: ${filePath}`);
    }
  } catch (error) {
    console.error(`Error fixing imports in ${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('.js')) && !item.endsWith('.d.ts')) {
      fixImportsInFile(itemPath);
    }
  });
};

// 主函数
const main = () => {
  console.log('=== Fixing Imports Comprehensive ===\n');
  
  // 修复所有TypeScript和JavaScript文件中的导入路径
  fixImportsRecursive(SRC_DIR);
  
  console.log('\n=== Fixing Imports Comprehensive Completed ===');
};

// 运行主函数
main();
