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

export interface StyleSimilarity {
  productId: string;
  competitorProductId: string;
  similarityScore: number; // 0-1
  ourPrice: number;
  competitorPrice: number;
}

/**
 * [BIZ_OPS_159] SKU 视觉同质化导致的价格战预警 (Same Style War)
 * @description 核心逻辑：分析 SKU 视觉特征相似度，识别陷入“同质化价格战”的商品，预警毛利雪崩风险并建议差异化策略。
 */
export class StyleWarService {
  /**
   * 执行同质化竞争审计
   */
  static async analyzeCompetition(tenantId: string, similarities: StyleSimilarity[]): Promise<any> {
    logger.info(`[StyleWar] Analyzing visual competition for tenant: ${tenantId}`);

    try {
      const alerts = [];

      for (const sim of similarities) {
        // 1. 识别高度同质化商品 (Score > 0.9)
        if (sim.similarityScore > 0.9) {
          // 2. 识别价格战特征 (竞品价格低于我方 > 10%)
          const priceDiff = (sim.ourPrice - sim.competitorPrice) / sim.ourPrice;

          if (priceDiff > 0.10) {
            const reason = `SKU ${sim.productId} is in a 'Red Sea' visual competition with ${sim.competitorProductId} (Similarity: ${(sim.similarityScore * 100).toFixed(0)}%). ` +
              `Competitor is pricing ${(priceDiff * 100).toFixed(1)}% lower.`;

            const advice = `${reason} High risk of 'Price War' leading to margin collapse. ` +
              `Suggesting: 1. Update main image to highlight unique features; 2. Bundle with value-add accessories; 3. Avoid direct follow-down if margin < 20%.`;

            // 3. [UX_XAI_01] 记录决策证据链
            await DecisionExplainabilityEngine.logDecision({
              tenantId,
              module: 'COMPETITIVE_STRATEGY',
              resourceId: sim.productId,
              decisionType: 'PRICE_WAR_WARNING',
              causalChain: advice,
              factors: [
                { name: 'VisualSimilarity', value: sim.similarityScore, weight: 0.6, impact: 'NEGATIVE' },
                { name: 'PriceDisadvantage', value: priceDiff, weight: 0.4, impact: 'NEGATIVE' }
              ],
              traceId: `style-war-${Date.now()}`
            });

            alerts.push({
              productId: sim.productId,
              riskLevel: 'HIGH',
              advice
            });
          }
        }
      }

      return { success: true, count: alerts.length, alerts };
    } catch (err: any) {
      logger.error(`[StyleWar][FATAL] Analysis failed: ${err.message}`);
      throw {
        category: 'Logic Conflict',
        rootCause: 'Failed to cross-reference visual similarity with pricing data',
        mitigation: 'Verify similarity scores and competitor price feed'
      };
    }
  }
}
