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

export interface SourcingComparison {
  productId: string;
  currentPrice: number;
  cheapest1688Price: number;
  potentialSavings: number;
  matchConfidence: number;
  supplierName: string;
  imageUrl: string;
}

/**
 * [BIZ_OPS_131] 1688 图片搜索相似款比价建议 (Image Search)
 * @description 核心逻辑：利用 1688 图片搜索 API 获取相似款最低价，算出“每单可省多少钱”并生成降本建议。
 */
export class VisualSourcingService {
  private static readonly AUDIT_TABLE = 'cf_sourcing_audit';

  /**
   * 生成降本比价报告并创建建议 (BIZ_OPS_131)
   */
  static async generateCostReductionReport(tenantId: string, productId: string): Promise<any> {
    logger.info(`[VisualSourcing] Generating cost reduction report for Product: ${productId}, Tenant: ${tenantId}`);

    try {
      // 1. 获取当前商品信息
      const product = await db('cf_product').where({ id: productId, tenant_id: tenantId }).first();
      if (!product) throw new Error('Product not found or access denied');

      const currentPrice = product.purchase_price || 0;
      const imageUrl = product.main_image || '';

      if (!imageUrl) {
        logger.warn(`[VisualSourcing] No image found for product ${productId}. Skipping.`);
        return { success: false, reason: 'No image found for visual search' };
      }

      // 2. 模拟 1688 图片搜索 (调用 SupplyChainService 的模拟方法)
      const visualResults = await SupplyChainService.visualSourcing(imageUrl);
      const suppliers = visualResults.suppliers || [];

      if (suppliers.length === 0) {
        return { success: false, reason: 'No matching suppliers found on 1688' };
      }

      // 3. 找出最低价供应源
      const cheapest = suppliers.reduce((prev: any, curr: any) => (prev.price < curr.price ? prev : curr));
      const potentialSavings = currentPrice - cheapest.price;

      // 4. 务实逻辑：仅在能省钱 (savings > 0) 且匹配度高 (> 0.9) 时生成建议
      if (potentialSavings > 0 && cheapest.matchConfidence > 0.9) {
        const reason = `Cheaper source found on 1688: ${cheapest.name}. Potential savings: ${potentialSavings.toFixed(2)} per unit.`;
        
        // 5. 插入 cf_sourcing_audit 表作为待审核建议
        const [suggestionId] = await db(this.AUDIT_TABLE).insert({
          tenant_id: tenantId,
          product_id: productId,
          supplier_id: '1688_' + cheapest.name, // 模拟 1688 供应商 ID
          supplier_name: cheapest.name,
          price: cheapest.price,
          delivery_days: 3, // 模拟
          trust_score: 95.0, // 模拟
          reason: reason,
          status: 'PENDING_REVIEW',
          created_at: new Date()
        });

        logger.info(`[VisualSourcing] Suggestion Generated (ID: ${suggestionId}): Savings=${potentialSavings.toFixed(2)}`);

        // 6. [UX_XAI_01] 记录决策证据链
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'SOURCING_COST_REDUCTION',
          resourceId: String(suggestionId),
          decisionType: 'COST_REDUCTION_SUGGESTION',
          causalChain: reason,
          factors: [
            { name: 'CurrentPrice', value: currentPrice, weight: 0.4, impact: 'NEGATIVE' },
            { name: '1688LowestPrice', value: cheapest.price, weight: 0.4, impact: 'POSITIVE' },
            { name: 'MatchConfidence', value: cheapest.matchConfidence, weight: 0.2, impact: 'POSITIVE' }
          ],
          traceId: 'visual-sourcing-' + Date.now()
        });

        return { 
          success: true, 
          suggestionId, 
          potentialSavings, 
          newPrice: cheapest.price, 
          supplier: cheapest.name,
          status: 'PENDING_REVIEW' 
        };
      }

      return { success: true, message: 'Current source is optimal or no high-confidence matches found' };
    } catch (err: any) {
      logger.error(`[VisualSourcing][WARN] Report generation failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
