import { CrawlerService } from './CrawlerService';
import { ProductService } from './ProductService';
import { AuditService } from './AuditService';
import { logger } from '../utils/logger';
import { Product } from '../models/Product';

/**
 * [CORE_AI_11] AI 竞品动态监控引擎 (AI Competitor Pulse)
 * @description 实时感知竞品价格、库存与素材变更
 */
export class CompetitorPulseService {
  /**
   * [CORE_AI_11] 广告素材探测 (Ad Asset Probing)
   * @description 关联竞品在社交媒体的广告投放数据
   */
  static async probeAdAssets(productId: number): Promise<{
    hasAds: boolean;
    adPlatforms: string[];
    trend: 'increasing' | 'stable' | 'decreasing';
  }> {
    const product = await ProductService.getById('SYSTEM', productId);
    if (!product) throw new Error('Product not found');

    logger.info(`[Pulse] Probing ad assets for: ${product.title}`);

    // 实际业务中应调用专门的广告情报接口 (如 BigSpy, AdSpy API)
    // 模拟探测结果
    const platforms = ['Facebook', 'TikTok', 'Instagram'];
    const activeAds = Math.random() > 0.3; // 70% 概率有广告

    return {
      hasAds: activeAds,
      adPlatforms: activeAds ? platforms.slice(0, Math.floor(Math.random() * 3) + 1) : [],
      trend: activeAds ? (Math.random() > 0.5 ? 'increasing' : 'stable') : 'stable'
    };
  }

  /**
   * @description 对指定商品进行心跳检测，识别变化 (增强版：加入广告素材探测)
   */
  static async pulseCheck(productId: number): Promise<{
    hasChanged: boolean;
    changes?: string[];
    adInsight?: any;
  }> {
    try {
      // ... 现有对比逻辑 ...
      const baseResult = await this.performBaseCheck(productId);
      
      // 加入广告素材探测
      const adInsight = await this.probeAdAssets(productId);

      if (baseResult.hasChanged || adInsight.hasAds) {
        // 如果广告趋势增加，记入审计日志
        if (adInsight.trend === 'increasing') {
          await AuditService.logSystem({
            action: 'COMPETITOR_AD_SURGE',
            resourceType: 'product',
            resourceId: String(productId),
            metadata: { adInsight }
          });
        }
      }

      return { ...baseResult, adInsight };
    } catch (err: any) {
      logger.error(`[Pulse] Check failed for ID ${productId}: ${err.message}`);
      throw err;
    }
  }

  private static async performBaseCheck(productId: number) {
    const existingProduct = await ProductService.getById('SYSTEM', productId);
    if (!existingProduct || !existingProduct.detailUrl) {
      throw new Error('Product not found or detailUrl missing');
    }
    const crawler = new CrawlerService();
    const latestData = await crawler.crawl(existingProduct.detailUrl, false);
    const keysToWatch = ['price', 'title', 'images', 'skus'];
    const changes: string[] = [];
    const oldSnapshot: any = {};
    const newSnapshot: any = {};
    keysToWatch.forEach(key => {
      const oldValue = (existingProduct as any)[key];
      const newValue = (latestData as any)[key];
      if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
        changes.push(key);
        oldSnapshot[key] = oldValue;
        newSnapshot[key] = newValue;
      }
    });
    if (changes.length > 0) {
      await AuditService.logSystem({
        action: 'COMPETITOR_PULSE_CHANGE',
        resourceType: 'product',
        resourceId: String(productId),
        beforeSnapshot: oldSnapshot,
        afterSnapshot: newSnapshot,
        metadata: { source: 'PulseCheck' }
      });
      await ProductService.update('SYSTEM', productId, latestData);
      return { hasChanged: true, changes };
    }
    return { hasChanged: false };
  }

  /**
   * @description 批量执行监控任务 (可由定时任务触发)
   */
  static async runBatchPulse(limit: number = 10) {
    const products = await ProductService.getAll('SYSTEM');
    const candidates = products.slice(0, limit);

    for (const p of candidates) {
      if (p.id) {
        await this.pulseCheck(p.id).catch(() => {});
      }
    }
  }
}
