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

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

// 定义目录名映射（大写 -> 小写）
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'
};

// 修复文件中的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 修复目录大小写的导入
    Object.entries(DIR_CASE_MAP).forEach(([oldName, newName]) => {
      // 直接替换字符串，避免正则表达式的复杂性
      const replacements = [
        [`from '../${oldName}/`, `from '../${newName}/`],
        [`from '../../${oldName}/`, `from '../../${newName}/`],
        [`from '../../../${oldName}/`, `from '../../../${newName}/`],
        [`from '../../../../${oldName}/`, `from '../../../../${newName}/`],
        [`from './${oldName}/`, `from './${newName}/`],
        [`require('../${oldName}/`, `require('../${newName}/`],
        [`require('../../${oldName}/`, `require('../../${newName}/`],
        [`require('./${oldName}/`, `require('./${newName}/`],
        [`from "../${oldName}/`, `from "../${newName}/`],
        [`from "../../${oldName}/`, `from "../../${newName}/`],
        [`from "../../../${oldName}/`, `from "../../../${newName}/`],
        [`from "../../../../${oldName}/`, `from "../../../../${newName}/`],
        [`from "./${oldName}/`, `from "./${newName}/`],
        [`require("../${oldName}/`, `require("../${newName}/`],
        [`require("../../${oldName}/`, `require("../../${newName}/`],
        [`require("./${oldName}/`, `require("./${newName}/`]
      ];
      
      replacements.forEach(([oldStr, newStr]) => {
        if (content.includes(oldStr)) {
          content = content.replace(new RegExp(oldStr, 'g'), 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('.d.ts')) {
      fixImportsInFile(itemPath);
    }
  });
};

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

// 运行主函数
main();
