import db from '../../config/database';
import { AuditService } from '../core/AuditService';
import { AIService } from '../ai/AIService';
import { CrawlerService } from '../core/CrawlerService';

/**
 * [BIZ_AUTO_17] 自动化 IP 侵权全网扫描与预警 (IP Sentinel)
 * 负责在全球各大电商平台 (Amazon/TikTok/Shopee) 自动扫描潜在的 IP 侵权（盗图、仿冒、商标冒用）并预警
 */
export class IPSentinelService {
  /**
   * 执行全网 IP 扫描
   */
  static async scanGlobalIP(tenantId: string, productId: string, traceId: string): Promise<void> {
    // 1. 获取本产品指纹信息 (模拟调用 ImageFingerprintService)
    const product = await db('cf_product').where({ productId }).first();
    if (!product) return;

    // 2. 模拟全网爬虫扫描 (多平台并发)
    const platforms = ['Amazon', 'TikTok', 'Shopee', 'Lazada'];
    const scanPromises = platforms.map(p => 
      AIService.scanPlatformForIPInfringement({
        platform: p,
        brandName: product.title,
        productKeywords: [product.title],
        scanDepth: 'shallow'
      })
    );
    const scanResults = await Promise.all(scanPromises);

    for (const scanResult of scanResults) {
      // 3. 风险判定逻辑 (检查潜在侵权)
      for (const infringement of scanResult.potentialInfringements) {
        if (infringement.matchScore > 0.8) {
          await db.transaction(async (trx) => {
            // 4. 持久化侵权记录
            const [id] = await trx('cf_ip_sentinel').insert({
              tenant_id: tenantId,
              product_id: productId,
              platform: scanResult.platform || 'Unknown',
              risk_score: infringement.matchScore,
              risk_type: infringement.riskLevel,
              matched_source_url: `https://platform.com/product/${infringement.productId}`,
              status: 'ACTIVE'
            });

            // 5. 联动风险雷达 (Risk Radar) 进行预警
            await trx('cf_risk_radar').insert({
              tenant_id: tenantId,
              product_id: productId,
              type: 'IP_INFRINGEMENT',
              severity: 'HIGH',
              message: `Potential infringement detected: ${infringement.productTitle}`,
              status: 'ACTIVE'
            });

            // 审计记录
            await AuditService.log({
              tenantId: tenantId,
              action: 'IP_SENTINEL_ALERT',
              module: 'COMPLIANCE',
              resourceType: 'IP_SENTINEL',
              resourceId: id.toString(),
              traceId: traceId,
              userId: 'system',
              result: 'success',
              source: 'console',
              afterSnapshot: { platform: scanResult.platform, riskScore: infringement.matchScore },
              metadata: { url: `https://platform.com/product/${infringement.productId}` }
            });
          });
        }
      }
    }
  }

  /**
   * 获取租户所有活动中的 IP 预警
   */
  static async getActiveAlerts(tenantId: string) {
    return await db('cf_ip_sentinel')
      .where({ tenant_id: tenantId, status: 'ACTIVE' })
      .orderBy('risk_score', 'desc');
  }
}
