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

/**
 * [BIZ_OPS_154] 供应商产能饱和度间接推测建议 (Capacity)
 * @description 核心逻辑：分析供应商近期的交期偏移量 (LeadTime Drift)，间接推测其产能是否饱和（如从 3 天变为 5 天），并提前建议调整分流策略。
 */
export class LeadTimeDriftService {
  /**
   * 预测交期风险并建议调整 (BIZ_OPS_154)
   */
  static async predictLeadTimeRisk(tenantId: string, supplierId: string): Promise<any> {
    logger.info(`[LeadTimeDrift] Analyzing drift for Supplier: ${supplierId}, Tenant: ${tenantId}`);

    try {
      // 1. 获取近 30 天平均交期趋势 (模拟)
      const historicalLeadTime = 3.2; // 3.2 天
      const recentLeadTime = 5.5; // 5.5 天
      const drift = recentLeadTime - historicalLeadTime;

      // 2. 识别饱和风险：如果交期延长超过 50% 或 > 2天
      if (drift > 2 || drift / historicalLeadTime > 0.5) {
        const advice = `SUPPLIER CAPACITY SATURATION RISK: Lead time drifted from ${historicalLeadTime}d to ${recentLeadTime}d (Drift: +${drift.toFixed(1)}d). ` +
          `Suggesting immediate traffic diversion to alternative suppliers for urgent orders.`;

        // 记录决策
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'SUPPLY_CHAIN_CAPACITY',
          resourceId: supplierId,
          decisionType: 'CAPACITY_DRIFT_WARNING',
          causalChain: advice,
          factors: [
            { name: 'DriftDays', value: drift, weight: 0.7, impact: 'NEGATIVE' },
            { name: 'HistoricalLeadTime', value: historicalLeadTime, weight: 0.3, impact: 'NEUTRAL' }
          ],
          traceId: 'leadtime-drift-' + Date.now()
        });

        return { success: true, drift, riskLevel: 'HIGH', advice, status: 'PENDING_REVIEW' };
      }

      return { success: true, drift, message: 'Lead time is stable' };
    } catch (err: any) {
      logger.error(`[LeadTimeDrift][WARN] Prediction failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
