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

// 服务目录
const SERVICES_DIR = __dirname;

// 完整的文件分类映射
const FILE_CATEGORIES = {
  // AI 服务
  'AIDecisionLogService.ts': 'ai',
  'AIDecisionService.ts': 'ai',
  'AIDecisionSystem.ts': 'ai',
  'AIService.ts': 'ai',
  'AgentSwarmService.ts': 'ai',
  'B2BAIService.ts': 'ai',
  'BlacklistAI.ts': 'ai',
  'InfluencerBotService.ts': 'ai',
  'IntelligentRecommendation.ts': 'ai',
  'NegotiationBotService.ts': 'ai',
  'SentimentAIService.ts': 'ai',
  
  // Analytics 服务
  'AnalyticsService.ts': 'analytics',
  'MerchantAnalysisService.ts': 'analytics',
  'MerchantBehaviorAnalysisService.ts': 'analytics',
  'MerchantDataStatisticsService.ts': 'analytics',
  'PredictiveAnalysis.ts': 'analytics',
  'ShopReportAggregationService.ts': 'analytics',
  'TrueROASService.ts': 'analytics',
  
  // Core 服务
  'AsyncOperationService.ts': 'core',
  'BullMQDeadLetterService.ts': 'core',
  'BullMQService.ts': 'core',
  'ContentGapService.ts': 'core',
  'CoreBusinessService.ts': 'core',
  'CoreServicePriorityService.ts': 'core',
  'DatabaseOptimizationService.ts': 'core',
  'DeployService.ts': 'core',
  'DevOpsService.ts': 'core',
  'EdgeSyncService.ts': 'core',
  'ExperimentService.ts': 'core',
  'FeatureActivationService.ts': 'core',
  'InfrastructureService.ts': 'core',
  'MessageProcessingService.ts': 'core',
  'ProcurementAuditService.ts': 'core',
  'QuotaCircuitBreakerService.ts': 'core',
  'ReasoningPipelineService.ts': 'core',
  'SelfHealingService.ts': 'core',
  'SemanticLogService.ts': 'core',
  'SmartPricingService.ts': 'core',
  'TaskCenterService.ts': 'core',
  'UnifiedTaskService.ts': 'core',
  'UsageService.ts': 'core',
  
  // Logistics 服务
  'FailoverLogisticsService.ts': 'logistics',
  'LastMileOptimizerService.ts': 'logistics',
  'LogisticTTLService.ts': 'logistics',
  'LogisticTelemetryService.ts': 'logistics',
  'LogisticsInsuranceService.ts': 'logistics',
  'LogisticsIntelligenceService.ts': 'logistics',
  'LogisticsService.ts': 'logistics',
  'SeaFreightAdvisor.ts': 'logistics',
  'WMSAdvisor.ts': 'logistics',
  
  // Product 服务
  'MultiPlatformProductService.ts': 'product',
  'ProductCollectionService.ts': 'product',
  'ProductHealthService.ts': 'product',
  'ProductListingService.ts': 'product',
  'ProductScoringService.ts': 'product',
  'ProductSelectionService.ts': 'product',
  'ProductService.ts': 'product',
  'SKUMappingService.ts': 'product',
  
  // 根目录下的服务文件分类
  'ArbitrageDetectionService.ts': 'core',
  'ArbitrageService.ts': 'core',
  'AuditService.ts': 'core',
  'AutoDelistService.ts': 'core',
  'AutoDiagnosticsService.ts': 'core',
  'AutoExecutionConfigService.ts': 'core',
  'AutoListingService.ts': 'core',
  'AutoPilotScheduler.ts': 'core',
  'AutoPilotService.ts': 'core',
  'AutoRedTeamingService.ts': 'core',
  'AutoReturnQAService.ts': 'core',
  'AutonomousEcoService.ts': 'core',
  'AutonomousSandboxService.ts': 'core',
  'AutonomousSourcingService.ts': 'core',
  'AutonomousWarehousingService.ts': 'core',
  'B2BTradeService.ts': 'core',
  'BlacklistAnalysisService.ts': 'core',
  'BlacklistDatabaseService.ts': 'core',
  'BlacklistEffectivenessService.ts': 'core',
  'BlacklistService.ts': 'core',
  'BlacklistShareService.ts': 'core',
  'BondedWarehouseService.ts': 'core',
  'BusinessModelEvolutionService.ts': 'core',
  'CarbonCostGameService.ts': 'core',
  'CarbonNeutralPathService.ts': 'core',
  'ChannelStatusService.ts': 'core',
  'CollectionAdapterService.ts': 'core',
  'CommodityHedgingService.ts': 'core',
  'CompetitorPriceMonitor.ts': 'core',
  'CompetitorPriceService.ts': 'core',
  'CompetitorPulseService.ts': 'core',
  'CompetitorService.ts': 'core',
  'CostAttributionService.ts': 'core',
  'CostTemplateService.ts': 'core',
  'CrawlerService.ts': 'core',
  'DecentralizedArbitrationService.ts': 'core',
  'DynamicPricingService.ts': 'core',
  'DynamicRecompositionService.ts': 'core',
  'DynamicShippingService.ts': 'core',
  'EcoValueSharingService.ts': 'core',
  'ExceptionAutoFixService.ts': 'core',
  'ExchangeRateService.ts': 'finance',
  'FactoryMonitorService.ts': 'core',
  'FreightAuditor.ts': 'logistics',
  'FulfillmentConsensusService.ts': 'core',
  'GeopoliticalRiskHedgeService.ts': 'core',
  'HighValueQAService.ts': 'core',
  'HolidayRiskService.ts': 'core',
  'ImageFingerprintService.ts': 'core',
  'ImprovementSuggestionService.ts': 'core',
  'InventoryRLService.ts': 'inventory',
  'KOLOrchestratorService.ts': 'marketing',
  'LeadTimeDriftService.ts': 'logistics',
  'MerchantIntegrationTest.ts': 'core',
  'MerchantMetricsService.ts': 'analytics',
  'MerchantPerformanceTest.ts': 'core',
  'MerchantProductOrderService.ts': 'order',
  'MerchantService.ts': 'core',
  'NodeGovernanceV2Service.ts': 'core',
  'PointsService.ts': 'core',
  'PredictiveFXService.ts': 'finance',
  'PredictiveHealthService.ts': 'core',
  'PredictiveStagingService.ts': 'core',
  'PriceComparisonService.ts': 'core',
  'PricingAuditService.ts': 'core',
  'PricingDecisionService.ts': 'core',
  'PricingService.ts': 'core',
  'PriorityTicketService.ts': 'core',
  'PublishService.ts': 'core',
  'RLCrawlerService.ts': 'core',
  'RedTeamingService.ts': 'security',
  'ReportService.ts': 'core',
  'ReviewService.ts': 'core',
  'SLAScoringService.ts': 'core',
  'SocialTrendSourcingService.ts': 'core',
  'SovereignReputationV2Service.ts': 'sovereignty',
  'StyleWarService.ts': 'core',
  'TraceService.ts': 'core',
  'TrackingFraudDetector.ts': 'core',
  'TradeService.ts': 'core',
  'TrustEvolutionService.ts': 'core',
  'VaultService.ts': 'security',
  'VendorCreditService.ts': 'core',
  'VisionFactoryService.ts': 'core',
  'VisualSourcingService.ts': 'core',
  'WarehouseService.ts': 'inventory',
  'WinNodeService.ts': 'core',
  'WorkerProfilerService.ts': 'core',
  'reconciliationService.ts': 'finance'
};

// 目录重命名映射（大写 -> 小写）
const DIR_RENAME_MAP = {
  'AI': 'ai',
  'Analytics': 'analytics',
  'Core': 'core',
  'Logistics': 'logistics',
  'Product': 'product'
};

// 确保目录存在
const ensureDir = (dirPath) => {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
    console.log(`Created directory: ${dirPath}`);
  }
};

// 移动文件
const moveFile = (source, target) => {
  try {
    fs.renameSync(source, target);
    console.log(`Moved: ${path.basename(source)} -> ${path.dirname(target)}`);
    return true;
  } catch (error) {
    console.error(`Error moving ${source}: ${error.message}`);
    return false;
  }
};

// 重命名目录（通过临时名称）
const renameDir = (oldPath, newPath) => {
  if (!fs.existsSync(oldPath)) {
    console.log(`Source directory does not exist: ${oldPath}`);
    return false;
  }
  
  if (fs.existsSync(newPath)) {
    console.log(`Target directory already exists: ${newPath}`);
    return false;
  }
  
  try {
    // 先重命名为临时名称
    const tempPath = `${oldPath}_temp_${Date.now()}`;
    fs.renameSync(oldPath, tempPath);
    console.log(`Renamed to temp: ${path.basename(oldPath)} -> ${path.basename(tempPath)}`);
    
    // 再重命名为目标名称
    fs.renameSync(tempPath, newPath);
    console.log(`Renamed to target: ${path.basename(tempPath)} -> ${path.basename(newPath)}`);
    return true;
  } catch (error) {
    console.error(`Error renaming directory ${oldPath}: ${error.message}`);
    return false;
  }
};

// 修复文件中的导入路径
const fixImportsInFile = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;
    
    // 修复大写目录名的导入
    Object.entries(DIR_RENAME_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;
        }
      });
    });
    
    // 修复从services根目录导入其他服务的路径
    // 例如：import { Service } from './ServiceName' -> import { Service } from './category/ServiceName'
    const rootImportPattern = /from\s+['"]\.\/([A-Z][a-zA-Z]+Service)['"]/g;
    const matches = [...content.matchAll(rootImportPattern)];
    
    matches.forEach(match => {
      const serviceName = match[1];
      const category = FILE_CATEGORIES[serviceName + '.ts'];
      if (category) {
        const oldImport = match[0];
        const newImport = `from './${category}/${serviceName}'`;
        content = content.replace(oldImport, newImport);
        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 runMigration = () => {
  console.log('=== Starting Complete Migration ===\n');
  
  // 步骤1: 重命名大写目录为小写
  console.log('Step 1: Renaming directories to lowercase...');
  Object.entries(DIR_RENAME_MAP).forEach(([oldName, newName]) => {
    const oldPath = path.join(SERVICES_DIR, oldName);
    const newPath = path.join(SERVICES_DIR, newName);
    renameDir(oldPath, newPath);
  });
  console.log('');
  
  // 步骤2: 移动根目录下的服务文件到对应分类目录
  console.log('Step 2: Moving service files to categorized directories...');
  const rootFiles = fs.readdirSync(SERVICES_DIR);
  let movedCount = 0;
  let skippedCount = 0;
  
  rootFiles.forEach(file => {
    const filePath = path.join(SERVICES_DIR, file);
    const stat = fs.statSync(filePath);
    
    // 只处理TypeScript文件，跳过目录和脚本文件
    if (!stat.isFile() || !file.endsWith('.ts') || file.endsWith('.d.ts')) {
      skippedCount++;
      return;
    }
    
    // 跳过迁移脚本文件
    if (file.includes('migrate') || file.includes('fix') || file.includes('normalize')) {
      skippedCount++;
      return;
    }
    
    const category = FILE_CATEGORIES[file];
    if (category) {
      const targetDir = path.join(SERVICES_DIR, category);
      ensureDir(targetDir);
      
      const targetPath = path.join(targetDir, file);
      if (moveFile(filePath, targetPath)) {
        movedCount++;
      }
    } else {
      console.log(`No category found for: ${file}`);
      skippedCount++;
    }
  });
  
  console.log(`\nMoved ${movedCount} files, skipped ${skippedCount} files\n`);
  
  // 步骤3: 修复所有文件中的导入路径
  console.log('Step 3: Fixing import paths in all files...');
  fixImportsRecursive(SERVICES_DIR);
  console.log('');
  
  console.log('=== Migration Completed ===');
};

// 运行迁移
runMigration();
