import db from '../config/database';
import { DecisionExplainabilityEngine } from '../core/ai/DecisionExplainabilityEngine';
import { logger } from '../utils/logger';
import { SupplierService } from './SupplierService';

/**
 * [BIZ_OPS_138] 供应商 TrustScore 关联采购成功率 (Trust)
 * @description 核心逻辑：分析 TrustScore 与历史采购订单成功率（CONCLUDED vs FAILED）的关联性，动态调整采购路由权重。
 */
export class TrustEvolutionService {
  /**
   * 计算 TrustScore 与成功率的关联性并生成权重建议 (BIZ_OPS_138)
   */
  static async calculateSuccessCorrelation(tenantId: string, supplierId: string): Promise<any> {
    logger.info(`[TrustEvolution] Analyzing success correlation for Supplier: ${supplierId}`);

    try {
      // 1. 获取供应商当前 TrustScore
      const score = await SupplierService.calculateSupplierScore(supplierId);

      // 2. 获取历史订单成功率
      const orders = await db('cf_orders')
        .where({ supplier_id: supplierId, tenant_id: tenantId })
        .limit(100);

      const concludedCount = orders.filter(o => o.status === 'CONCLUDED').length;
      const totalCount = orders.length || 1;
      const successRate = concludedCount / totalCount;

      // 3. 关联性分析 (模拟逻辑)
      // 如果 TrustScore 高但成功率低，说明当前权重模型失效，建议增加 "Real-time fulfillment" 权重
      let weightAdjustment = 0;
      let advice = 'TrustScore is well-aligned with fulfillment success.';

      if (score > 80 && successRate < 0.6) {
        weightAdjustment = 0.15;
        advice = `Correlation gap detected: High TrustScore (${score.toFixed(1)}) but low success rate (${(successRate * 100).toFixed(1)}%). ` +
          `Suggesting 15% weight increase for 'Historical Success Rate' in routing.`;
      }

      if (weightAdjustment > 0) {
        // 4. [UX_XAI_01] 记录决策证据链
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'SOURCING_ROUTING_WEIGHTS',
          resourceId: supplierId,
          decisionType: 'WEIGHT_ADJUSTMENT_SUGGESTION',
          causalChain: advice,
          factors: [
            { name: 'TrustScore', value: score, weight: 0.5, impact: 'POSITIVE' },
            { name: 'HistoricalSuccessRate', value: successRate, weight: 0.5, impact: 'NEGATIVE' }
          ],
          traceId: 'trust-evolution-' + Date.now()
        });

        return { success: true, weightAdjustment, advice, status: 'PENDING_REVIEW' };
      }

      return { success: true, advice, status: 'OPTIMAL' };
    } catch (err: any) {
      logger.error(`[TrustEvolution][WARN] Correlation analysis failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
