import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';

export interface PricingProfile {
  userId?: string;
  region: string;
  deviceType: 'MOBILE' | 'DESKTOP';
  historicalPurchasePower: number; // 0-1
}

/**
 * [BIZ_MKT_30] 智能动态调价与套利保护 (Dynamic Pricing & Arbitrage Protection)
 * @description 核心逻辑：在 V2 (套利基准) 基础上，引入实时竞品监控、用户画像与利润红线。
 * 系统在毫秒级内完成：1. 竞品价格爬取反馈；2. 用户购买力分层；3. 利润红线校验与套利空间保护。
 */
export class DynamicPricingV3Service {
  /**
   * [BIZ_MKT_30] 核心调价算法 (Main Pricing Algorithm)
   */
  static async calculateBestPrice(params: {
    productId: string;
    costPrice: number;
    basePrice: number;
    competitorPrices: number[];
    profile: PricingProfile;
    tenantId: string;
  }): Promise<{
    finalPrice: number;
    strategyUsed: string;
    margin: number;
  }> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_MKT_DYNAMIC_PRICING_V3', params.tenantId))) {
      return { finalPrice: params.basePrice, strategyUsed: 'DEFAULT', margin: 0.25 };
    }

    const { costPrice, basePrice, competitorPrices, profile } = params;
    
    // 1. 竞品对齐策略 (Competitor Alignment)
    const minCompetitor = Math.min(...competitorPrices);
    let targetPrice = minCompetitor * 0.99; // 略低于对手 1% 以保持竞争力

    // 2. 购买力分层策略 (Purchase Power Tiering)
    if (profile.historicalPurchasePower > 0.8) {
      targetPrice *= 1.03; // 高购买力用户适当溢价
    }

    // 3. 套利红线与利润保护 (Arbitrage Guardrail - BIZ_MKT_30)
    // 根据 B2C 利润红线 (20%) 强制校验
    const minMargin = 0.20; 
    const minAllowedPrice = costPrice / (1 - minMargin);
    
    let finalPrice = Math.max(targetPrice, minAllowedPrice);
    let strategy = finalPrice === minAllowedPrice ? 'PROFIT_GUARD_ENFORCED' : 'COMPETITIVE_AUTO';

    // 4. 套利空间保护 (防止价格波动过大触发平台风控)
    if (finalPrice > basePrice * 1.5) {
      finalPrice = basePrice * 1.5;
      strategy = 'ANTI_GOUGING_PROTECTION';
    }

    const margin = (finalPrice - costPrice) / finalPrice;

    logger.info(`[DynamicPricing] Product ${params.productId}: ${finalPrice.toFixed(2)} (${strategy}), Margin: ${(margin * 100).toFixed(2)}%`);

    return { finalPrice, strategyUsed: strategy, margin };
  }

  /**
   * [BIZ_MKT_30] 实时竞品价格监控 (Simulated)
   */
  static async monitorCompetitors(productId: string): Promise<number[]> {
    // 实际应调用爬虫服务 (RLCrawlerService) 实时获取各平台价格
    logger.debug(`[DynamicPricing] Monitoring competitors for product: ${productId}`);
    return [45.0, 48.5, 42.0, 46.8]; // Mock prices
  }

  /**
   * 执行并记录调价操作
   */
  static async applyDynamicPrice(params: {
    productId: string;
    tenantId: string;
    newPrice: number;
    reason: string;
  }): Promise<void> {
    await db('cf_product').where({ id: params.productId }).update({
      price: params.newPrice,
      updated_at: new Date()
    });

    // 记录调价日志 (用于 XAI 因果叙述)
    await db('cf_price_history').insert({
      product_id: params.productId,
      tenant_id: params.tenantId,
      old_price: 0, // 实际应查询旧价格
      new_price: params.newPrice,
      change_reason: params.reason,
      created_at: new Date()
    });
  }
}
