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

// 服务分类映射
const SERVICE_CATEGORIES = {
  // Auth 服务
  'AuthService': 'auth',
  'PermissionTestService': 'auth',
  'RBACService': 'auth',
  
  // Compliance 服务
  'CertificateDatabaseService': 'compliance',
  'CertificateService': 'compliance',
  'ComplianceService': 'compliance',
  
  // Finance 服务
  'FXHedgingService': 'finance',
  'FinanceReconciliationService': 'finance',
  'FinanceService': 'finance',
  
  // Inventory 服务
  'AgingInventoryService': 'inventory',
  'InventoryAgingService': 'inventory',
  'InventoryService': 'inventory',
  'InventorySyncAdapter': 'inventory',
  'OmniStockService': 'inventory',
  'ReplenishmentService': 'inventory',
  'SensibleStockService': 'inventory',
  'SlowMovingStockService': 'inventory',
  'StockPlannerService': 'inventory',
  
  // Marketing 服务
  'ABTestAnalysisService': 'marketing',
  'ABTestService': 'marketing',
  'AdMimicryService': 'marketing',
  'AdService': 'marketing',
  'BiddingStrategyService': 'marketing',
  'FestivalMarketingService': 'marketing',
  'MarketingCalendarService': 'marketing',
  'MarketingService': 'marketing',
  'MediaAssetService': 'marketing',
  'OmnichannelMarketingService': 'marketing',
  'PersonalizedPricingService': 'marketing',
  'PersonalizedRecommendService': 'marketing',
  'PixelFeedbackService': 'marketing',
  'StrategyRecommendationService': 'marketing',
  'StrategyService': 'marketing',
  
  // Order 服务
  'AfterSalesService': 'order',
  'DisputeAdvisorService': 'order',
  'DisputeClassifier': 'order',
  'DisputeResolverService': 'order',
  'OrderAggregationService': 'order',
  'OrderCentralService': 'order',
  'OrderFulfillmentService': 'order',
  'OrderProfitService': 'order',
  'OrderService': 'order',
  'ReturnAnalysisService': 'order',
  'ReturnEffectivenessService': 'order',
  'ReturnRateDatabaseService': 'order',
  'ReturnRateMonitorService': 'order',
  
  // Product 服务
  'MultiPlatformProductService': 'Product',
  'ProductCollectionService': 'Product',
  'ProductHealthService': 'Product',
  'ProductListingService': 'Product',
  'ProductScoringService': 'Product',
  'ProductSelectionService': 'Product',
  'ProductService': 'Product',
  'SKUMappingService': 'Product',
  
  // Logistics 服务
  'LogisticsService': 'logistics',
  'LastMileOptimizerService': 'logistics',
  'LogisticTTLService': 'logistics',
  'LogisticTelemetryService': 'logistics',
  'LogisticsInsuranceService': 'logistics',
  'LogisticsIntelligenceService': 'logistics',
  'FailoverLogisticsService': 'logistics',
  'SeaFreightAdvisor': 'logistics',
  'WMSAdvisor': 'logistics',
  
  // Supplier 服务
  'SupplierService': 'supplier',
  'SupplierRiskRadar': 'supplier',
  'SupplierRiskRadarService': 'supplier',
  'SupplierInquiryService': 'supplier',
  'SupplierBlacklistService': 'supplier',
  
  // Customer 服务
  'CustomerService': 'customer',
  'CustomerServiceAgent': 'customer',
  'UserService': 'customer',
  'UserAssetService': 'customer',
  'UserValueAnalysisService': 'customer',
  'MemberLevelService': 'customer',
  
  // Platform 服务
  'PlatformApiService': 'platform',
  'PlatformAccountService': 'platform',
  'PlatformFeeWatcher': 'platform',
  'IndependentSiteService': 'platform',
  'StoreService': 'platform',
  'StoreCreationService': 'platform',
  
  // Analytics 服务
  'AnalyticsService': 'analytics',
  'PredictiveAnalysis': 'analytics',
  'MerchantAnalysisService': 'analytics',
  'MerchantBehaviorAnalysisService': 'analytics',
  'MerchantDataStatisticsService': 'analytics',
  'ShopReportAggregationService': 'analytics',
  'TrueROASService': 'analytics',
  
  // AI 服务
  'AIService': 'ai',
  'AIDecisionService': 'ai',
  'AIDecisionSystem': 'ai',
  'AIDecisionLogService': 'ai',
  'AgentSwarmService': 'ai',
  'BlacklistAI': 'ai',
  'SentimentAIService': 'ai',
  'IntelligentRecommendation': 'ai',
  'B2BAIService': 'ai',
  'InfluencerBotService': 'ai',
  'NegotiationBotService': 'ai',
  
  // Core 服务
  'CoreServicePriorityService': 'core',
  'CoreBusinessService': 'core',
  'BullMQService': 'core',
  'BullMQDeadLetterService': 'core',
  'AsyncOperationService': 'core',
  'ContentGapService': 'core',
  'DatabaseOptimizationService': 'core',
  'DeployService': 'core',
  'DevOpsService': 'core',
  'EdgeSyncService': 'core',
  'ExperimentService': 'core',
  'FeatureActivationService': 'core',
  'InfrastructureService': 'core',
  'MessageProcessingService': 'core',
  'ProcurementAuditService': 'core',
  'QuotaCircuitBreakerService': 'core',
  'ReasoningPipelineService': 'core',
  'SelfHealingService': 'core',
  'SemanticLogService': 'core',
  'SmartPricingService': 'core',
  'TaskCenterService': 'core',
  'UnifiedTaskService': 'core',
  'UsageService': 'core',
  
  // Integration 服务
  'CrossBorderService': 'integration',
  'CrossBorderIntegrationService': 'integration',
  'CustomsDeclarationService': 'integration',
  'DataIsolationService': 'integration',
  'DataManagementService': 'integration',
  'GreenSupplyChainService': 'integration',
  'GreenSupplyService': 'integration',
  'LiveScriptService': 'integration',
  'ManufacturingCoordinationService': 'integration',
  'OmnichannelCommunicationService': 'integration',
  'PackingOptimizer': 'integration',
  'PathSimulatorService': 'integration',
  'PoolSourcingService': 'integration',
  'SupplyChainService': 'integration',
  'SyncService': 'integration',
  'TraceabilityService': 'integration',
  'TracingTopoService': 'integration',
  'UnifiedFulfillmentService': 'integration',
  
  // Monitoring 服务
  'MonitoringAlertService': 'monitoring',
  'GlobalCSMonitor': 'monitoring',
  'PRMonitorService': 'monitoring',
  'LeaderboardService': 'monitoring',
  'MerchantMonitorService': 'monitoring',
  'StuckTrackingService': 'monitoring',
  
  // Security 服务
  'AutoCircuitBreakerService': 'security',
  'ConfidentialSharingService': 'security',
  'CongestionFailoverService': 'security',
  'ContainerQuotaService': 'security',
  'DeadlockAdvisor': 'security',
  'TEEComputeService': 'security',
  'ZKPSovereignAdmissionService': 'security',
  
  // Settlement 服务
  'MerchantSettlementService': 'settlement',
  'TaxService': 'settlement',
  'TaxReportService': 'settlement',
  'TaxIncentivesService': 'settlement',
  'TaxBonusService': 'settlement',
  'PaymentRiskService': 'settlement',
  'PayoutAppealService': 'settlement',
  'MicroCreditService': 'settlement',
  'CreditLimitService': 'settlement',
  'LiquidityHedgingService': 'settlement',
  
  // Sovereignty 服务
  'SovereigntyGovernanceService': 'sovereignty',
  'SovereigntyIdentityService': 'sovereignty',
  'SovereigntyReputationService': 'sovereignty',
  'SovereigntyReputationV2Service': 'sovereignty',
  'SovereigntySettlementService': 'sovereignty',
  'SovereignCreditPoolService': 'sovereignty',
  'SovereignLedgerService': 'sovereignty',
  'SovereignLogisticsV2Service': 'sovereignty',
  'SovereignMediationService': 'sovereignty',
  'BrandSovereigntyService': 'sovereignty',
  'BlockchainTraceabilityService': 'sovereignty',
  
  // Webhook 服务
  'WebhookService': 'webhook'
};

// 服务目录
const SERVICES_DIR = __dirname;

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

// 迁移服务文件
const migrateServices = () => {
  console.log('Starting service migration...');
  
  // 确保所有目标目录存在
  const targetDirs = ['auth', 'compliance', 'finance', 'inventory', 'marketing', 'order', 'Product', 'logistics', 'supplier', 'customer', 'platform', 'analytics', 'ai', 'core', 'integration', 'monitoring', 'security', 'settlement', 'sovereignty', 'webhook'];
  targetDirs.forEach(dir => {
    ensureDirectoryExists(path.join(SERVICES_DIR, dir));
  });
  
  // 读取当前目录下的文件
  const files = fs.readdirSync(SERVICES_DIR);
  const migratedFiles = [];
  const skippedFiles = [];
  
  files.forEach(file => {
    const filePath = path.join(SERVICES_DIR, file);
    
    // 跳过目录和非TypeScript文件
    if (fs.statSync(filePath).isDirectory() || !file.endsWith('.ts')) {
      skippedFiles.push(file);
      return;
    }
    
    // 提取服务名（去掉Service.ts后缀）
    let serviceName = file.replace('.ts', '');
    
    // 查找分类
    let category = SERVICE_CATEGORIES[serviceName];
    
    // 如果没有找到分类，尝试去掉Service后缀再查找
    if (!category && serviceName.endsWith('Service')) {
      const shortName = serviceName.replace('Service', '');
      category = SERVICE_CATEGORIES[shortName];
    }
    
    if (category) {
      const targetPath = path.join(SERVICES_DIR, category, file);
      
      // 移动文件
      fs.renameSync(filePath, targetPath);
      migratedFiles.push({ file, category, targetPath });
      console.log(`Migrated ${file} to ${category}/`);
    } else {
      skippedFiles.push(file);
      console.log(`Skipped ${file} - no category found`);
    }
  });
  
  // 生成迁移报告
  console.log('\n=== Migration Report ===');
  console.log(`Total files: ${files.length}`);
  console.log(`Migrated files: ${migratedFiles.length}`);
  console.log(`Skipped files: ${skippedFiles.length}`);
  
  if (migratedFiles.length > 0) {
    console.log('\nMigrated files:');
    migratedFiles.forEach(item => {
      console.log(`- ${item.file} -> ${item.category}/`);
    });
  }
  
  if (skippedFiles.length > 0) {
    console.log('\nSkipped files:');
    skippedFiles.forEach(file => {
      console.log(`- ${file}`);
    });
  }
  
  console.log('\nMigration completed!');
};

// 运行迁移
migrateServices();
