import db from '../../config/database';
import { logger } from '../../utils/logger';

// Imports for domain initializations
import { SummaryAggregationService } from '../../domains/Analytics/SummaryAggregationService';
import { BillingService } from '../../domains/Billing/BillingService';
import { AdOptimizerService } from '../../domains/Finance/AdOptimizerService';
import { BillingEngine } from '../../domains/Finance/BillingEngine';
import { CACThresholdService } from '../../domains/Finance/CACThresholdService';
import { CampaignHealthService } from '../../domains/Finance/CampaignHealthService';
import { CashflowPredictor } from '../../domains/Finance/CashflowPredictor';
import { ClaimFraudService } from '../../domains/Finance/ClaimFraudService';
import { CommissionService } from '../../domains/Finance/CommissionService';
import { ComplianceAIGuard } from '../../domains/Finance/ComplianceAIGuard';
import { CreditMonitorService } from '../../domains/Finance/CreditMonitorService';
import { CurrencyRiskService } from '../../domains/Finance/CurrencyRiskService';
import { DynamicShippingService } from '../../domains/Finance/DynamicShippingService';
import { ExpenseService } from '../../domains/Finance/ExpenseService';
import { FinancialAuditService } from '../../domains/Finance/FinancialAuditService';
import { FinancialPlanner } from '../../domains/Finance/FinancialPlanner';
import { GlobalBalanceSheet } from '../../domains/Finance/GlobalBalanceSheet';
import { InventoryValueService } from '../../domains/Finance/InventoryValueService';
import { InvoicingService } from '../../domains/Finance/InvoicingService';
import { LegalTaxService } from '../../domains/Finance/LegalTaxService';
import { MarginProtector } from '../../domains/Finance/MarginProtector';
import { MaterialRiskService } from '../../domains/Finance/MaterialRiskService';
import { MultiAssetSettlementService } from '../../domains/Finance/MultiAssetSettlementService';
import { OrderProfitService } from '../../domains/Finance/OrderProfitService';
import { PaymentRiskService } from '../../domains/Finance/PaymentRiskService';
import { PaymentTermsService } from '../../domains/Finance/PaymentTermsService';
import { PayoutCycleService } from '../../domains/Finance/PayoutCycleService';
import { PayoutOptimizer } from '../../domains/Finance/PayoutOptimizer';
import { PricingAuditService } from '../../domains/Finance/PricingAuditService';
import { RebateService } from '../../domains/Finance/RebateService';
import { ReconciliationService } from '../../domains/Finance/ReconciliationService';
import { RefundAuditService } from '../../domains/Finance/RefundAuditService';
import { RefundRiskService } from '../../domains/Finance/RefundRiskService';
import { RemitPathService } from '../../domains/Finance/RemitPathService';
import { SavingTrackerService } from '../../domains/Finance/SavingTrackerService';
import { SKUEfficiencyService } from '../../domains/Finance/SKUEfficiencyService';
import { SovereignCreditPoolService } from '../../domains/Finance/SovereignCreditPoolService';
import { StockAuditService } from '../../domains/Finance/StockAuditService';
import { TaxComplianceService } from '../../domains/Finance/TaxComplianceService';
import { TaxFilingAdvisor } from '../../domains/Finance/TaxFilingAdvisor';
import { TaxPlanningService } from '../../domains/Finance/TaxPlanningService';
import { TenantHealthService } from '../../domains/Finance/TenantHealthService';
import { TrueROASService } from '../../domains/Finance/TrueROASService';
import { TurnoverWatchdog } from '../../domains/Finance/TurnoverWatchdog';
import { VendorCreditService } from '../../domains/Finance/VendorCreditService';
import { WarrantyService } from '../../domains/Finance/WarrantyService';

import { CongestionFailoverService } from '../../domains/Logistics/CongestionFailoverService';
import { FreightAuditService } from '../../domains/Logistics/FreightAuditService';
import { GlobalFulfillmentService } from '../../domains/Logistics/GlobalFulfillmentService';
import { LastMileAIService } from '../../domains/Logistics/LastMileAIService';
import { LastMileOptimizerService } from '../../domains/Logistics/LastMileOptimizerService';
import { LogisticTelemetryService } from '../../domains/Logistics/LogisticTelemetryService';
import { SupplierScoringService } from '../../domains/Logistics/SupplierScoringService';

import { GreenSupplyChainService } from '../../domains/Trade/GreenSupplyChainService';
import { InventoryForecastService } from '../../domains/Trade/InventoryForecastService';
import { SovereignCrisisService } from '../../domains/Trade/SovereignCrisisService';
import { TradeComplianceService } from '../../domains/Trade/TradeComplianceService';

import { CustomerService } from '../../domains/Customer/CustomerService';

import { KOLService } from '../../domains/Marketing/KOLService';
import { MarketingCalendarService } from '../../domains/Marketing/MarketingCalendarService';
import { SocialPulseService } from '../../domains/Marketing/SocialPulseService';
import { AutoRedTeamingService } from '../../services/AutoRedTeamingService';
import { CreditLimitService } from '../../services/CreditLimitService';
import { DisputeResolverService } from '../../services/DisputeResolverService';
import { ExperimentService } from '../../services/ExperimentService';
import { FinanceService } from '../../services/FinanceService';
import { FXHedgingService } from '../../services/FXHedgingService';
import { InventoryService } from '../../services/InventoryService';
import { LogisticsInsuranceService } from '../../services/LogisticsInsuranceService';
import { LogisticsIntelligenceService } from '../../services/LogisticsIntelligenceService';
import { LogisticTTLService } from '../../services/LogisticTTLService';
import { ProductService } from '../../services/ProductService';
import { ReplenishmentService } from '../../services/ReplenishmentService';
import { SelfHealingService } from '../../services/SelfHealingService';
import { SKUMappingService } from '../../services/SKUMappingService';
import { SupplierService } from '../../services/SupplierService';
import { TaxReportService } from '../../services/TaxReportService';
import { UnifiedTaskService } from '../../services/UnifiedTaskService';
import { AgentSelfAwarenessService } from '../ai/AgentSelfAwarenessService';
import { AGILegalComplianceService } from '../ai/AGILegalComplianceService';
import { AGIStrategyEvolutionService } from '../ai/AGIStrategyEvolutionService';
import { AutoCircuitBreakerService } from '../ai/AutoCircuitBreakerService';
import { FederatedNodeService } from '../ai/FederatedNodeService';
import { InfinityComputeService } from '../ai/InfinityComputeService';
import { ResourceReservationService } from '../ai/ResourceReservationService';
import { SandboxROIAdvisor } from '../ai/SandboxROIAdvisor';
import { SovereignReputationV2Service } from '../ai/SovereignReputationV2Service';
import { TXSentinelService } from '../pipeline/TXSentinelService';
import { AutonomousSandboxService } from '../sandbox/AutonomousSandboxService';
import { ApprovalService } from '../security/approvals/ApprovalService';
import { PrivateAuditService } from '../security/PrivateAuditService';
import { SecurityProfilingService } from '../security/SecurityProfilingService';
import { AutoDiagnosticsService } from '../telemetry/AutoDiagnosticsService';
import { TracingTopoService } from '../telemetry/TracingTopoService';

import { DisputeArbitrationService } from '../../domains/Customer/DisputeArbitrationService';
import { GlobalDisputeRouter } from '../../domains/Customer/GlobalDisputeRouter';
import { CrossNodeSettlementService } from '../../domains/Finance/CrossNodeSettlementService';
import { DIDSettlementService } from '../../domains/Finance/DIDSettlementService';
import { MultiCurrencyHedgingReconService } from '../../domains/Finance/MultiCurrencyHedgingReconService';
import { NodeLiquidityForecastService } from '../../domains/Finance/NodeLiquidityForecastService';
import { SovereignPrivateLCService } from '../../domains/Finance/SovereignPrivateLCService';
import { TradeInsuranceService } from '../../domains/Finance/TradeInsuranceService';
import { CarbonCreditTradingService } from '../../domains/Logistics/CarbonCreditTradingService';
import { CourierCreditService } from '../../domains/Logistics/CourierCreditService';
import { CrowdsourcedLogisticsService } from '../../domains/Logistics/CrowdsourcedLogisticsService';
import { DynamicRoutingFailoverService } from '../../domains/Logistics/DynamicRoutingFailoverService';
import { IntermodalFailoverService } from '../../domains/Logistics/IntermodalFailoverService';
import { ArbitrageAGIService } from '../../domains/Marketing/ArbitrageAGIService';
import { MembershipLTVService } from '../../domains/Marketing/MembershipLTVService';
import { MultiTouchAttributionService } from '../../domains/Marketing/MultiTouchAttributionService';
import { AgingInventoryService } from '../../domains/Trade/AgingInventoryService';
import { CarbonPledgeService } from '../../domains/Trade/CarbonPledgeService';
import { ComplianceCertificateService } from '../../domains/Trade/ComplianceCertificateService';
import { InventoryRLOptimizerService } from '../../domains/Trade/InventoryRLOptimizerService';
import { SupplierCapacityWatchService } from '../../domains/Trade/SupplierCapacityWatchService';
import { AgentSwarmService } from '../../services/AgentSwarmService';
import { AutonomousWarehousingService } from '../../services/AutonomousWarehousingService';
import { BondedWarehouseService } from '../../services/BondedWarehouseService';
import { ChannelStatusService } from '../../services/ChannelStatusService';
import { DisputeAdvisorService } from '../../services/DisputeAdvisorService';
import { DynamicPricingService } from '../../services/DynamicPricingService';
import { FraudSharedService } from '../../services/FraudSharedService';
import { FreightAuditor } from '../../services/FreightAuditor';
import { OmniStockService } from '../../services/OmniStockService';
import { PriorityTicketService } from '../../services/PriorityTicketService';
import { ProductHealthService } from '../../services/ProductHealthService';
import { StockPlannerService } from '../../services/StockPlannerService';
import { SupplyChainService } from '../../services/SupplyChainService';
import { TaxRoutingOptimizerService } from '../../services/TaxRoutingOptimizerService';
import { PredictiveHealthService } from '../../services/telemetry/PredictiveHealthService';
import { TrackingFraudDetector } from '../../services/TrackingFraudDetector';
import { WMSAdvisor } from '../../services/WMSAdvisor';
import { DecisionExplainabilityEngine } from '../ai/DecisionExplainabilityEngine';
import { FeatureToggleService } from '../governance/FeatureToggleService';
import { S3QuotaManager } from '../governance/S3QuotaManager';
import { HomomorphicService } from '../security/HomomorphicService';
import { HomomorphicSumService } from '../security/HomomorphicSumService';
import { DBShardingService } from './DBShardingService';

/**
 * [ARCH_CLEANUP] 遗留表初始化器 (Legacy Table Initializer)
 */
export class LegacyTableInitializer {
  static async init() {
    logger.info('[LegacyTableInitializer] Starting table initializations...');

    try {
      await FeatureToggleService.initTable();
      await DBShardingService.initTable();
      await S3QuotaManager.initTable();
      await DynamicPricingService.initTable();
      await SupplyChainService.initTable();
      await ChannelStatusService.initTable();
      await DecisionExplainabilityEngine.initTable();
      await DisputeAdvisorService.initTable();
      await TrackingFraudDetector.initTable();
      await PriorityTicketService.initTable();
      await StockPlannerService.initTable();
      await FraudSharedService.initTable();
      await OmniStockService.initTable();
      await FreightAuditor.initTable();
      await WMSAdvisor.initTable();
      await ProductHealthService.initTable();
      await ApprovalService.initTable();
      await PrivateAuditService.initTable();
      await InfinityComputeService.initTable();
      await AgentSelfAwarenessService.initTable();
      await AGILegalComplianceService.initTable();
      await SovereignReputationV2Service.initTable();
      await LogisticsIntelligenceService.initTable();
      await ResourceReservationService.initTable();
      await TXSentinelService.initTable();
      await TracingTopoService.initTable();
      await AutoDiagnosticsService.initTable();
      await AutoRedTeamingService.initTable();
      await CreditLimitService.initTable();
      await LogisticsInsuranceService.initTable();
      await TaxPlanningService.initTable();
      await LogisticTTLService.initTable();
      await ReplenishmentService.initTable();
      await DisputeResolverService.initTable();
      await ExperimentService.initTable();
      await TaxReportService.initTable();
      await FinanceReconService.initTable();
      await ReconciliationService.initTable();
      await InvoicingService.initTable();
      await SupplierScoringService.initTable();
      await LogisticTelemetryService.initTable();
      await SecurityProfilingService.initTable();
      await SelfHealingService.initTable();
      await BillingService.initTable();
      await ProductService.initTable();
      await InventoryService.initTable();
      await FinanceService.initTable();
      await SKUMappingService.initTable();
      await UnifiedTaskService.initTable();
      await SummaryAggregationService.initTable();
      await AGIStrategyEvolutionService.initTable();
      await FederatedNodeService.initTable();
      await AutonomousSandboxService.initTable();
      await SandboxROIAdvisor.initTable();
      await AutoCircuitBreakerService.initTable();
      await ReputationZKPService.initTable();
      await NetworkTopologyService.initTable();
      await AlertService.initTable();
      await SupplierService.initTable();
      await FXHedgingService.initTable();
      
      // Calibration Batch 1 Initializations
      await AgentSwarmService.initTable();
      await PredictiveHealthService.initTable();
      await WMSWaveService.initTable();
      await LogisticsTrackerService.initTable();
      await AgingInventoryService.initTable();
      await ArbitrageAGIService.initTable();
      await AutonomousWarehousingService.initTable();
      await BondedWarehouseService.initTable();
      await HomomorphicService.initTable();
      await HomomorphicSumService.initTable();
      
      // AI-3 New Services Initializations
      await OrderProfitService.initTable();
      await CurrencyRiskService.initTable();
      await PricingAuditService.initTable();
      await TrueROASService.initTable();
      await TaxComplianceService.initTable();
      await VendorCreditService.initTable();
      await CashflowPredictor.initTable();
      await BillingEngine.initTable();
      await SKUEfficiencyService.initTable();
      await PayoutCycleService.initTable();
      await InventoryValueService.initTable();
      await RefundRiskService.initTable();
      await PaymentTermsService.initTable();
      await RemitPathService.initTable();
      await StockAuditService.initTable();
      await AdOptimizerService.initTable();
      await TenantHealthService.initTable();
      await RebateService.initTable();
      await FinancialAuditService.initTable();
      await ExpenseService.initTable();
      await MaterialRiskService.initTable();
      await RefundAuditService.initTable();
      await CACThresholdService.initTable();
      await CommissionService.initTable();
      await TurnoverWatchdog.initTable();
      await WarrantyService.initTable();
      await TaxFilingAdvisor.initTable();
      await MarginProtector.initTable();
      await CreditMonitorService.initTable();
      await LegalTaxService.initTable();
      await PayoutOptimizer.initTable();
      await FinancialPlanner.initTable();
      await PaymentRiskService.initTable();
      await DynamicShippingService.initTable();
      await CampaignHealthService.initTable();
      await SavingTrackerService.initTable();
      await ClaimFraudService.initTable();
      await GlobalBalanceSheet.initTable();
      await ComplianceAIGuard.initTable();
      await MultiAssetSettlementService.initTable();
      await SovereignCreditPoolService.initTable();
      await LastMileAIService.initTable();
      await FreightAuditService.initTable();
      await GlobalFulfillmentService.initTable();
      await LastMileOptimizerService.initTable();
      await CongestionFailoverService.initTable();
      await InventoryForecastService.initTable();
      await SovereignCrisisService.initTable();
      await GreenSupplyChainService.initTable();
      await TradeComplianceService.initTable();
      await Customer360Service.initTable();
      await CustomerService.initTable();
      await KOLService.initTable();
      await MarketingCalendarService.initTable();
      await SocialPulseService.initTable();
      await MultiTouchAttributionService.initTable();
      await MembershipLTVService.initTable();
      await DIDSettlementService.initTable();
      await ReputationPerksService.initTable();
      await MultiCurrencyHedgingReconService.initTable();
      await NodeLiquidityForecastService.initTable();
      await CrossNodeSettlementService.initTable();
      await TaxRoutingOptimizerService.initTable();
      await SovereignPrivateLCService.initTable();
      await TradeInsuranceService.initTable();
      await DynamicRoutingFailoverService.initTable();
      await CrowdsourcedLogisticsService.initTable();
      await IntermodalFailoverService.initTable();
      await CarbonCreditTradingService.initTable();
      await CourierCreditService.initTable();
      await InventoryRLOptimizerService.initTable();
      await SupplierCapacityWatchService.initTable();
      await ComplianceCertificateService.initTable();
      await CarbonPledgeService.initTable();
      await NodeResourceQuotaService.initTable();
      await DisputeArbitrationService.initTable();
      await GlobalDisputeRouter.initTable();
      // await AIService.initTable(); // If exists
      
      // Some services don't have initTable yet, skipping them.
      
      // 1. [BIZ_MKT_01] 投放-库存联动
      const hasAdCampaignsTable = await db.schema.hasTable('cf_ad_campaigns');
      if (!hasAdCampaignsTable) {
        logger.info('📦 Creating cf_ad_campaigns table...');
        await db.schema.createTable('cf_ad_campaigns', (table) => {
          table.string('id', 64).primary();
          table.string('tenant_id', 64).notNullable();
          table.string('shop_id', 64).notNullable();
          table.string('product_id', 64).notNullable();
          table.string('platform', 32).notNullable();
          table.float('daily_budget').defaultTo(0);
          table.float('cpa_limit').defaultTo(0);
          table.string('status', 16).defaultTo('ACTIVE');
          table.timestamps(true, true);
          table.index(['tenant_id', 'product_id']);
        });
      }

      logger.info('[LegacyTableInitializer] Table initializations completed.');
    } catch (err: any) {
      logger.error(`[LegacyTableInitializer] Error during table initialization: ${err.message}`);
    }
  }
}
