import db from '../config/database';
import { AuditService } from './AuditService';
import { AIService } from './AIService';
import { CrawlerService } from './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 scanResults = await Promise.all(
      platforms.map(p => AIService.scanPlatformForIPInfringement(p, product.title, product.images))
    );

    for (const result of scanResults.flat()) {
      // 3. 风险判定逻辑 (Risk Score > 0.8)
      if (result.riskScore > 0.8) {
        await db.transaction(async (trx) => {
          // 4. 持久化侵权记录
          const [id] = await trx('cf_ip_sentinel').insert({
            tenant_id: tenantId,
            product_id: productId,
            platform: result.platform,
            risk_score: result.riskScore,
            risk_type: result.type,
            matched_source_url: result.url,
            status: 'ACTIVE'
          });

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

          // 审计记录
          await AuditService.log({
            tenant_id: tenantId,
            action: 'IP_SENTINEL_ALERT',
            target_type: 'IP_SENTINEL',
            target_id: id.toString(),
            trace_id: traceId,
            new_data: JSON.stringify({ platform: result.platform, riskScore: result.riskScore }),
            metadata: JSON.stringify({ url: result.url })
          });
        });
      }
    }
  }

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