import db from '../../config/database';
import { logger } from '../../utils/logger';
import { PricingService, ProfitSnapshot } from '../../services/PricingService';
import { WebhookService } from '../../core/integrations/WebhookService';

export enum ArbitrageStatus {
  PENDING = 'PENDING',
  APPROVED = 'APPROVED',
  REJECTED = 'REJECTED',
  EXECUTED = 'EXECUTED',
  PUBLISHED = 'PUBLISHED',
  RECONCILED = 'RECONCILED'
}

export interface ArbitrageRecord {
  id: number;
  tenantId: string;
  sourceUrl: string;
  targetPlatform: string;
  status: ArbitrageStatus;
  initialProfitRate: number;
  initialRoi: number;
  salesCount: number;
  conversionRate: number;
}

/**
 * [BIZ_ARB_02] 套利闭环回流系统 (Arbitrage Feedback Loop)
 * @description 从选品建议进化为真实收益驱动的持续优化系统
 */
export class ArbitrageFeedbackService {
  private static readonly TABLE_NAME = 'cf_arbitrage_records';

  /**
   * 闭环链路：销量回流与策略迭代
   */
  static async handleSalesFeedback(recordId: number, sales: number, conversion: number): Promise<void> {
    logger.info(`[Arbitrage] Received feedback for ID ${recordId}: Sales=${sales}, Conv=${(conversion * 100).toFixed(2)}%`);
    
    // 1. 获取当前记录
    const record = await db(this.TABLE_NAME).where({ id: recordId }).first();
    if (!record) {
      logger.error(`[Arbitrage] Record not found: ${recordId}`);
      return;
    }

    // 2. 更新销量与转化率
    await db(this.TABLE_NAME).where({ id: recordId }).update({
      sales_count: sales,
      conversion_rate: conversion,
      updated_at: new Date()
    });

    // 3. 识别异常并输出策略建议
    const analysis = this.analyzePerformance(record, sales, conversion);
    if (analysis.isAnomaly) {
      logger.warn(`[Arbitrage] Anomaly detected for record ${recordId}: ${analysis.advice}`);
      
      // 触发 Webhook 或通知租户
      await WebhookService.trigger({
        tenantId: record.tenant_id,
        eventType: 'TASK_FAILED', // 借用作为策略提醒
        payload: {
          type: 'STRATEGY_ADVICE',
          recordId,
          anomalyType: analysis.type,
          advice: analysis.advice
        },
        traceId: `feedback-${Date.now()}`,
        timestamp: Date.now()
      });
    }
  }

  /**
   * 异常识别逻辑
   */
  private static analyzePerformance(record: any, sales: number, conversion: number): { 
    isAnomaly: boolean; 
    type?: 'HIGH_MARGIN_LOW_CONV' | 'HIGH_CONV_LOW_MARGIN'; 
    advice?: string 
  } {
    const profitRate = record.initial_profit_rate;

    // 1. 高毛利低转化 (High margin, low conversion)
    if (profitRate > 0.35 && conversion < 0.01 && sales < 5) {
      return {
        isAnomaly: true,
        type: 'HIGH_MARGIN_LOW_CONV',
        advice: '利润率极高但转化极差。建议降价 5-10% 以刺激动销。'
      };
    }

    // 2. 高转化低毛利 (High conversion, low margin)
    if (conversion > 0.05 && profitRate < 0.15) {
      return {
        isAnomaly: true,
        type: 'HIGH_CONV_LOW_MARGIN',
        advice: '转化率极高但利润空间薄。建议提价 3-5% 以榨取更多净利。'
      };
    }

    return { isAnomaly: false };
  }

  /**
   * 状态流转控制
   */
  static async updateStatus(recordId: number, nextStatus: ArbitrageStatus): Promise<void> {
    logger.info(`[Arbitrage] Status update for ${recordId}: -> ${nextStatus}`);
    await db(this.TABLE_NAME).where({ id: recordId }).update({
      status: nextStatus,
      updated_at: new Date()
    });
  }
}
