import db from '../config/database';
import { logger } from '../utils/logger';
import { AIService } from './AIService';
import { FeatureGovernanceService } from '../core/governance/FeatureGovernanceService';

/**
 * [BIZ_ECO_05] 全球自治仓储节点调度协议 (AutonomousWarehousingService)
 * @description 在自治生态系统中，基于 AGI 实时调度全球各主权国家的仓储节点，实现最优路径、成本与合规性的动态平衡。
 */
export class AutonomousWarehousingService {
  private static readonly WAREHOUSING_TABLE = 'cf_autonomous_warehousing';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.WAREHOUSING_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.WAREHOUSING_TABLE} table...`);
      await db.schema.createTable(this.WAREHOUSING_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('warehouse_id', 64).notNullable(); // 仓储节点 ID
        table.string('region_code', 16).notNullable(); // 地区编码 (e.g., 'SEA', 'EU', 'NA')
        table.string('node_status', 32).defaultTo('ACTIVE'); // ACTIVE, OVERLOADED, MAINTENANCE
        table.json('capacity_stats'); // { total_m3, used_m3, remaining_m3 }
        table.decimal('base_storage_fee', 10, 2); // 基础仓储费
        table.json('fulfillment_capabilities'); // { packing, cross_docking, last_mile_integration }
        table.string('trace_id', 128);
        table.timestamps(true, true);
        table.index(['region_code', 'node_status']);
      });
      logger.info(`✅ Table ${this.WAREHOUSING_TABLE} created`);
    }
  }

  /**
   * 调度最优仓储节点
   * @param tenantId 租户 ID
   * @param orderDetails 订单详情
   * @param targetRegion 目标地区
   * @param traceId 调用链 ID
   */
  static async scheduleWarehousingNode(
    tenantId: string,
    orderDetails: any,
    targetRegion: string,
    traceId: string
  ): Promise<string | null> {
    // 1. 功能开关检查
    if (!(await FeatureGovernanceService.isEnabled('BIZ_ECO_AUTONOMOUS_WAREHOUSING', tenantId))) {
      logger.warn(`[AutonomousWarehousing] Service disabled for tenant ${tenantId} | traceId: ${traceId}`);
      return null;
    }

    logger.info(`[AutonomousWarehousing] Scheduling warehouse node for tenant ${tenantId} to ${targetRegion} | traceId: ${traceId}`);

    // 2. 获取目标地区所有活跃节点
    const nodes = await db(this.WAREHOUSING_TABLE)
      .where({
        region_code: targetRegion,
        node_status: 'ACTIVE'
      });

    if (nodes.length === 0) {
      logger.error(`[AutonomousWarehousing] No active nodes found in region ${targetRegion} | traceId: ${traceId}`);
      return null;
    }

    // 3. 调用 AGI 驱动的“调度决策引擎”
    // 基于订单特征、节点剩余容量、基础费用、履约能力进行多维度博弈
    const prompt = `Schedule best warehouse node in region ${targetRegion} for order details: ${JSON.stringify(orderDetails)} among nodes: ${JSON.stringify(nodes)}`;
    const decision = await AIService.generateStrategy(prompt, traceId);

    // 4. 解析 AGI 决策结果 (模拟解析逻辑)
    // 假设 AGI 返回一个 ID，如果解析失败则选择评分最高的节点
    const selectedNodeId = decision.includes('NODE_') 
      ? decision.match(/NODE_[a-zA-Z0-9]+/)?.[0] 
      : nodes[0].warehouse_id;

    if (selectedNodeId) {
      logger.info(`[AutonomousWarehousing] AGI scheduled Node ${selectedNodeId} for tenant ${tenantId} | traceId: ${traceId}`);
      
      // 5. 更新节点容量 (模拟扣减)
      await this.updateNodeCapacity(selectedNodeId, orderDetails.volume_m3 || 0.1, traceId);
    }

    return selectedNodeId || null;
  }

  /**
   * 更新节点容量 (模拟 AGI 实时动态扣减)
   */
  private static async updateNodeCapacity(warehouseId: string, volume: number, traceId: string) {
    const node = await db(this.WAREHOUSING_TABLE).where({ warehouse_id: warehouseId }).first();
    if (node) {
      const stats = JSON.parse(node.capacity_stats);
      stats.used_m3 += volume;
      stats.remaining_m3 -= volume;
      
      await db(this.WAREHOUSING_TABLE)
        .where({ warehouse_id: warehouseId })
        .update({
          capacity_stats: JSON.stringify(stats),
          updated_at: new Date()
        });
      
      logger.info(`[AutonomousWarehousing] Node ${warehouseId} capacity updated | volume: ${volume} | traceId: ${traceId}`);
    }
  }

  /**
   * 注册新仓储节点到自治生态系统
   */
  static async registerWarehouse(nodeData: any, traceId: string) {
    await db(this.WAREHOUSING_TABLE)
      .insert({
        ...nodeData,
        trace_id: traceId,
        created_at: new Date(),
        updated_at: new Date()
      });
    
    logger.info(`[AutonomousWarehousing] New warehouse node ${nodeData.warehouse_id} registered | traceId: ${traceId}`);
  }
}
