import db from '../../config/database';
import { logger } from '../../utils/logger';
import { SummaryAggregationService } from '../Analytics/SummaryAggregationService';
import { AdOpsService } from './AdOpsService';

/**
 * [BIZ_MKT_25] TikTok Shop 与 GMV MAX 广告数据对齐服务
 * @description 解决 TikTok Shop 后台订单数据与 GMV MAX 广告报表数据不一致（漂移）的问题。
 * 通过本地对齐逻辑，为 AI Agent 提供准确的归因分析数据。
 */
export class TikTokDriftAlignmentService {
  /**
   * [AGI_DATA_ALIGN] 对齐 TikTok 数据并识别漂移
   */
  static async alignTikTokData(tenantId: string, days: number = 7) {
    logger.info(`[TikTokAlignment] Starting data alignment for tenant: ${tenantId} over last ${days} days`);

    const endDate = new Date().toISOString().split('T')[0];
    const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

    // 1. 获取 Shop 端的真实销售数据 (Source of Truth for Cash)
    const shopSummary = await SummaryAggregationService.getSummary(tenantId, 'DAILY', startDate, endDate);
    const tiktokShopData = shopSummary.filter(s => s.platform === 'TIKTOK');
    const totalShopRevenue = tiktokShopData.reduce((sum, s) => sum + Number(s.total_revenue), 0);

    // 2. 获取 Ads 端的广告报表数据 (Platform Reported GMV)
    const campaigns = await AdOpsService.getCampaigns(tenantId, 'TIKTOK');
    // 假设 GMV MAX 广告计划名称包含 'GMV_MAX'
    const gmvMaxCampaigns = campaigns.filter(c => c.name.includes('GMV_MAX'));
    
    // 注意：这里的 roas * spent = reported_gmv
    const reportedAdGmv = gmvMaxCampaigns.reduce((sum, c) => sum + (Number(c.roas) * Number(c.spent)), 0);

    // 3. 计算漂移 (Drift)
    // Drift = (Reported GMV - Actual Shop Revenue) / Actual Shop Revenue
    const driftValue = totalShopRevenue > 0 ? (reportedAdGmv - totalShopRevenue) : 0;
    const driftRate = totalShopRevenue > 0 ? (driftValue / totalShopRevenue) : 0;

    logger.warn(`[TikTokAlignment] Drift detected for ${tenantId}: Reported $${reportedAdGmv.toFixed(2)} vs Actual $${totalShopRevenue.toFixed(2)}. Drift Rate: ${(driftRate * 100).toFixed(2)}%`);

    // 4. 本地对齐 (Local Alignment)
    // 如果漂移超过阈值 (如 15%)，AI Agent 在决策时应采用对齐后的 ROAS
    const alignedRoas = reportedAdGmv > 0 ? (totalShopRevenue / gmvMaxCampaigns.reduce((sum, c) => sum + Number(c.spent), 0)) : 0;

    return {
      tenantId,
      timeframe: { startDate, endDate },
      shopRevenue: totalShopRevenue,
      adReportedGmv: reportedAdGmv,
      drift: {
        value: driftValue,
        rate: driftRate,
        isSignificant: Math.abs(driftRate) > 0.15 // 超过 15% 视为显著漂移
      },
      alignment: {
        originalRoas: gmvMaxCampaigns.length > 0 ? gmvMaxCampaigns[0].roas : 0,
        trueRoas: alignedRoas,
        recommendation: driftRate > 0.15 ? 'OVER_REPORTED_BY_PLATFORM' : (driftRate < -0.15 ? 'UNDER_REPORTED_BY_PLATFORM' : 'STABLE')
      }
    };
  }

  /**
   * 为 AI Agent 生成对齐后的分析上下文
   */
  static async getAlignedAIContext(tenantId: string) {
    const alignment = await this.alignTikTokData(tenantId);
    
    return {
      platform: 'TIKTOK',
      status: alignment.drift.isSignificant ? 'DRIFT_DETECTED' : 'ALIGNED',
      metrics: {
        realRevenue: alignment.shopRevenue,
        adGmv: alignment.adReportedGmv,
        trueRoas: alignment.alignment.trueRoas
      },
      insight: `TikTok Shop 数据对齐完成。检测到 ${(alignment.drift.rate * 100).toFixed(2)}% 的数据漂移。AI 决策应以 True ROAS (${alignment.alignment.trueRoas.toFixed(2)}) 为准，而非平台报表的 ROAS。`
    };
  }
}
