import { logger } from '../../utils/logger';
import { AdOpsService } from '../Marketing/AdOpsService';
import { SummaryAggregationService } from './SummaryAggregationService';

/**
 * [BIZ_AI_10] AI 决策引擎数据服务 (AI Context Provider)
 * @description 为 LLM (AI Agent) 提供语义化的、跨域关联的分析数据。
 * 将散落在订单、广告、库存、物流中的原始数据转化为“洞察就绪”的上下文。
 */
export class AIEngineDataService {
  /**
   * 获取核心经营上下文 (Sales + Ads + Profit)
   * @description 供 AI 分析整体经营状况，识别利润黑洞或增长点
   */
  static async getBusinessInsightContext(tenantId: string, site: string, days: number = 30) {
    const endDate = new Date().toISOString().split('T')[0];
    const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

    logger.info(`[AIEngine] Fetching business insight context for ${tenantId} (${site}) over last ${days} days`);

    // 1. 获取聚合经营数据 (Revenue, Profit, OrderCount)
    const salesSummary = await SummaryAggregationService.getSummary(tenantId, 'DAILY', startDate, endDate);
    const siteFiltered = salesSummary.filter(s => s.site === site || !site);

    // 2. 获取广告数据 (Spent, ROAS, Conversions)
    const campaigns = await AdOpsService.getCampaigns(tenantId);
    const adStats = {
      totalSpent: campaigns.reduce((sum, c) => sum + Number(c.spent), 0),
      avgRoas: campaigns.length > 0 ? campaigns.reduce((sum, c) => sum + Number(c.roas), 0) / campaigns.length : 0,
      totalConversions: campaigns.reduce((sum, c) => sum + c.conversions, 0)
    };

    // 3. 获取物流时效数据 (从 LogisticTelemetryService 模拟)
    // TODO: 接入真实物流遥测数据
    const logisticsStats = {
      avgDeliveryDays: 5.2,
      delayRate: 0.08,
      topBottleneckRoute: 'CN-US-LAX'
    };

    // 4. 获取 TikTok 漂移对齐数据 (新加)
    const tiktokAlignment = await TikTokDriftAlignmentService.getAlignedAIContext(tenantId);

    // 5. 构建语义化输出
    return {
      timeframe: { startDate, endDate },
      performance: {
        totalRevenue: siteFiltered.reduce((sum, s) => sum + Number(s.total_revenue), 0),
        totalProfit: siteFiltered.reduce((sum, s) => sum + Number(s.net_profit), 0),
        orderCount: siteFiltered.reduce((sum, s) => sum + s.order_count, 0),
        margin: siteFiltered.length > 0 ? (siteFiltered.reduce((sum, s) => sum + Number(s.net_profit), 0) / siteFiltered.reduce((sum, s) => sum + Number(s.total_revenue), 0)) : 0
      },
      marketing: adStats,
      logistics: logisticsStats,
      tiktok: tiktokAlignment, // 注入对齐数据
      anomalies: this.detectBasicAnomalies(siteFiltered, campaigns, tiktokAlignment)
    };
  }

  /**
   * 异常检测逻辑 (初步)
   */
  private static detectBasicAnomalies(sales: any[], campaigns: any[], tiktok?: any) {
    const anomalies: string[] = [];
    
    // 1. 利润率预警
    const latestMargin = sales.length > 0 ? (sales[sales.length - 1].net_profit / sales[sales.length - 1].total_revenue) : 1;
    if (latestMargin < 0.15) {
      anomalies.push(`CRITICAL: Profit margin dropped to ${(latestMargin * 100).toFixed(2)}% (Below 15% threshold)`);
    }

    // 2. 广告效率预警
    const lowRoasCampaigns = campaigns.filter(c => c.roas < 1.2 && c.status === 'ACTIVE');
    if (lowRoasCampaigns.length > 0) {
      anomalies.push(`WARNING: ${lowRoasCampaigns.length} campaigns have ROAS below 1.2`);
    }

    // 3. TikTok 漂移检测
    if (tiktok && tiktok.status === 'DRIFT_DETECTED') {
      anomalies.push(`DRIFT: TikTok Shop and GMV MAX Ads data mismatch. ${tiktok.insight}`);
    }

    return anomalies;
  }

  /**
   * 为 AI Agent 生成 Prompt 友好型文本
   */
  static async generateAnalysisPrompt(tenantId: string, site: string) {
    const context = await this.getBusinessInsightContext(tenantId, site);
    
    return `
      ### Business Analysis Context for ${site} (Last 30 Days)
      
      **Performance Overview:**
      - Total Revenue: $${context.performance.totalRevenue.toLocaleString()}
      - Net Profit: $${context.performance.totalProfit.toLocaleString()}
      - Profit Margin: ${(context.performance.margin * 100).toFixed(2)}%
      - Total Orders: ${context.performance.orderCount}
      
      **Marketing Efficiency:**
      - Total Ad Spend: $${context.marketing.totalSpent.toLocaleString()}
      - Average ROAS: ${context.marketing.avgRoas.toFixed(2)}
      - Total Conversions: ${context.marketing.totalConversions}
      
      **Logistics Health:**
      - Avg Delivery Time: ${context.logistics.avgDeliveryDays} days
      - Delay Rate: ${(context.logistics.delayRate * 100).toFixed(2)}%
      
      **Detected Anomalies:**
      ${context.anomalies.map(a => `- ${a}`).join('\n')}
      
      **Instruction:** Please analyze the data above and provide 3 actionable strategies to improve profit margin while maintaining growth.
    `;
  }
}
