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

export interface Supplier {
  id: string;
  name: string;
  price: number;
  stock: number;
  deliveryDays: number;
  matchConfidence: number;
  trustScore: number; // [BIZ_SUP_20] 接入信用分
  isDirectFactory: boolean;
}

/**
 * [BIZ_SUP_15] 多源供应比价与路由优化 (Routing)
 * @description 核心逻辑：基于价格、库存、信用分 (TrustScore) 自动选择最优货源
 */
export class SupplyChainService {
  private static readonly AUDIT_TABLE = 'cf_sourcing_audit';

  /**
   * 初始化供应建议表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.AUDIT_TABLE);
    if (!hasTable) {
      await db.schema.createTable(this.AUDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('product_id', 64).index();
        table.string('supplier_id', 64);
        table.string('supplier_name', 255);
        table.decimal('price', 10, 2);
        table.integer('delivery_days');
        table.decimal('trust_score', 5, 2);
        table.string('reason', 255);
        table.string('status', 32).defaultTo('PENDING_REVIEW');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * [Visual Sourcing] 视觉溯源厂家 (核心入口)
   */
  static async traceSourceFactory(tenantId: string, productId: string, imageUrl: string): Promise<any> {
    logger.info(`[SupplyChain] Tracing source factory for image: ${imageUrl}`);

    try {
      // 1. 模拟视觉检索最优货源
      const topSuppliers = await db('cf_suppliers')
        .where({ isSourceFactory: true })
        .orderBy('rating_score', 'desc')
        .limit(5);

      // 2. 联动 BIZ_SUP_20: 获取每个供应商的 TrustScore 报告
      const detailedSuppliers = await Promise.all(topSuppliers.map(async (s: any) => {
        const trustReport = await SupplierService.getSupplierTrustReport(s.id);
        return {
          id: s.id,
          name: s.name,
          price: Number((Math.random() * 50 + 10).toFixed(2)), // 模拟实时价格
          stock: Math.floor(Math.random() * 1000),
          deliveryDays: s.avg_delivery_days,
          matchConfidence: Number((Math.random() * 0.2 + 0.8).toFixed(2)),
          trustScore: trustReport.trustScore,
          isDirectFactory: s.isSourceFactory
        };
      }));

      // 3. 执行路由算法：综合评分 = (1/价格 * 40%) + (信用分 * 40%) + (匹配度 * 20%)
      const routedSuppliers = detailedSuppliers.sort((a, b) => {
        const scoreA = (1 / a.price * 0.4) + (a.trustScore / 100 * 0.4) + (a.matchConfidence * 0.2);
        const scoreB = (1 / b.price * 0.4) + (b.trustScore / 100 * 0.4) + (b.matchConfidence * 0.2);
        return scoreB - scoreA;
      });

      const bestSupplier = routedSuppliers[0];
      const reason = `Selected ${bestSupplier.name} based on weighted price and TrustScore.`;

      // 4. 生成供应建议 (Suggestion-First)
      const [suggestionId] = await db(this.AUDIT_TABLE).insert({
        tenant_id: tenantId,
        product_id: productId,
        supplier_id: bestSupplier.id,
        supplier_name: bestSupplier.name,
        price: bestSupplier.price,
        delivery_days: bestSupplier.deliveryDays,
        trust_score: bestSupplier.trustScore,
        reason: reason,
        status: 'PENDING_REVIEW'
      });

      // [UX_XAI_01] 记录决策证据链
      await DecisionExplainabilityEngine.logDecision({
        tenantId,
        module: 'SOURCING',
        resourceId: String(suggestionId),
        decisionType: 'BEST_SUPPLIER_ROUTING',
        causalChain: reason,
        factors: [
          { name: 'Price', value: bestSupplier.price, weight: 0.4, impact: 'POSITIVE' },
          { name: 'TrustScore', value: bestSupplier.trustScore, weight: 0.4, impact: 'POSITIVE' },
          { name: 'MatchConfidence', value: bestSupplier.matchConfidence, weight: 0.2, impact: 'POSITIVE' }
        ],
        traceId: 'sourcing-' + Date.now()
      });

      return {
        suggestionId,
        originalImageUrl: imageUrl,
        extractedFeatures: 'VEC_' + Math.random().toString(36).substring(7).toUpperCase(),
        bestSupplier: bestSupplier,
        alternatives: routedSuppliers.slice(1),
        status: 'PENDING_REVIEW'
      };
    } catch (err: any) {
      // [CORE_DIAG_01] Agent 异常自省
      logger.error(`[SupplyChain][FATAL] Routing failed: ${err.message}`);
      throw {
        category: 'Logic Conflict',
        rootCause: 'Failed to aggregate TrustScore or Database timeout',
        mitigation: 'Fallback to default rating_score sorting'
      };
    }
  }

  /**
   * 批量批复供应建议
   */
  static async approveSuggestions(tenantId: string, suggestionIds: number[]) {
    logger.info(`[SupplyChain] Approving ${suggestionIds.length} suggestions for tenant ${tenantId}`);
    
    return await db.transaction(async (trx) => {
      const suggestions = await trx(this.AUDIT_TABLE)
        .whereIn('id', suggestionIds)
        .where({ tenant_id: tenantId, status: 'PENDING_REVIEW' });

      for (const s of suggestions) {
        // 更新商品主表的供应商信息
        await trx('cf_product')
          .where({ id: s.product_id })
          .update({
            supplier_id: s.supplier_id,
            purchase_price: s.price,
            updated_at: new Date()
          });

        // 更新建议状态
        await trx(this.AUDIT_TABLE)
          .where({ id: s.id })
          .update({ status: 'EXECUTED', updated_at: new Date() });
      }

      return suggestions.length;
    });
  }

  /**
   * [CORE_AI_50] 多模态 AGI 视觉寻源 (Visual Sourcing)
   * @description 集成 CLIP 视觉特征匹配与 1688 图片搜索，自动锁定源头工厂
   */
  static async visualSourcing(imageUrl: string) {
    logger.info(`[VisualSourcing] Initializing multi-modal search for: ${imageUrl}`);

    try {
      // 1. 模拟 CLIP 特征提取
      const featureVector = await this.extractVisualFeatures(imageUrl);

      // 2. 模拟 1688 图片搜索 API 调用
      const rawResults = await this.search1688ByImage(imageUrl);

      // 3. AGI 结果过滤与厂家评分逻辑
      const topSuppliers = rawResults
        .filter((res: any) => res.factoryRating > 4.0)
        .map((res: any) => ({
          name: res.supplierName,
          price: res.factoryPrice,
          location: res.region,
          matchConfidence: Number((Math.random() * 0.2 + 0.8).toFixed(2)), // 模拟匹配度
          isDirectFactory: res.isDirectFactory
        }));

      return {
        originalImageUrl: imageUrl,
        extractedFeatures: featureVector.substring(0, 32) + '...',
        suppliers: topSuppliers.sort((a: any, b: any) => b.matchConfidence - a.matchConfidence)
      };
    } catch (err: any) {
      logger.error(`[VisualSourcing] Failed: ${err.message}`);
      throw err;
    }
  }

  private static async extractVisualFeatures(imageUrl: string): Promise<string> {
    // 模拟 CLIP Embedding
    return `vec_${Buffer.from(imageUrl).toString('hex')}`;
  }

  private static async search1688ByImage(imageUrl: string): Promise<any[]> {
    // 模拟 1688 图片搜索原始结果
    return [
      { supplierName: 'Yiwu Smart Manufacturing Co.', factoryPrice: 12.5, region: 'Zhejiang', factoryRating: 4.8, isDirectFactory: true },
      { supplierName: 'Shenzhen Tech Wholesale', factoryPrice: 14.2, region: 'Guangdong', factoryRating: 4.5, isDirectFactory: false },
      { supplierName: 'Ningbo Global Trade Ltd.', factoryPrice: 11.8, region: 'Zhejiang', factoryRating: 4.2, isDirectFactory: true }
    ];
  }

  /**
   * [CORE_AI_50] 利润链路穿透分析 (Profit Chain Analysis)
   * @description 模拟从源头工厂到消费端的多级加价与利润核算
   */
  static async analyzeProfitChain(productId: number, consumerPrice: number) {
    try {
      const product = await db('cf_product').where({ id: productId }).first();
      if (!product) return null;

      const factoryPrice = product.originalPrice * 0.7; // 假设工厂价为原价 70%
      const logisticsCost = 5.0; // 假设固定物流成本
      const platformFee = consumerPrice * 0.15; // 假设平台佣金 15%

      const markupChain = [
        { role: 'FACTORY', price: factoryPrice },
        { role: 'WHOLESALER', price: product.originalPrice },
        { role: 'HUB_COST', price: product.originalPrice + logisticsCost },
        { role: 'CONSUMER', price: consumerPrice }
      ];

      const netProfit = consumerPrice - product.originalPrice - logisticsCost - platformFee;

      return {
        markupChain,
        profitAnalysis: {
          factoryToConsumerMarkup: ((consumerPrice - factoryPrice) / factoryPrice * 100).toFixed(2) + '%',
          estimatedNetProfit: netProfit.toFixed(2),
          roi: (netProfit / (product.originalPrice + logisticsCost) * 100).toFixed(2) + '%'
        }
      };
    } catch (error: any) {
      logger.error(`[SupplyChain] Profit analysis failed: ${error.message}`);
      return null;
    }
  }
}
