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

/**
 * [BIZ_AUTO_14] 自动化知识产权 (IP) 侵权预审
 * 负责在商品上架前，利用 AI 自动比对商标库、版权图库，识别潜在侵权风险
 */
export class IPCheckService {
  /**
   * 执行侵权预审
   */
  static async performIPCheck(
    tenantId: string, 
    productId: string, 
    traceId: string
  ): Promise<'CLEAR' | 'BLOCKED'> {
    // 1. 获取商品信息 (标题、关键词、图片)
    const product = await db('cf_product').where({ productId }).first();
    if (!product) return 'CLEAR';

    // 2. 文本与图片比对 (模拟调用 AI 服务)
    const analysis = await AIService.checkIPInfringement(product.title, product.images);
    const riskScore = analysis.riskScore; // 0-1
    const matchedKeywords = analysis.matchedKeywords;
    const similarImages = analysis.similarImages;

    // 3. 判定结果
    const status = riskScore > 0.7 ? 'BLOCKED' : 'CLEAR';

    // 4. 持久化记录
    const [id] = await db('cf_ip_check').insert({
      tenant_id: tenantId,
      product_id: productId,
      risk_score: riskScore,
      matched_keywords: matchedKeywords.join(', '),
      similar_images: JSON.stringify(similarImages),
      status
    });

    // 5. 触发合规拦截 (如果风险过高)
    if (status === 'BLOCKED') {
      await AuditService.log({
        tenant_id: tenantId,
        action: 'IP_INFRINGEMENT_BLOCKED',
        target_type: 'PRODUCT',
        target_id: productId,
        trace_id: traceId,
        new_data: JSON.stringify({ riskScore, matchedKeywords }),
        metadata: JSON.stringify({ reason: 'Potential IP Infringement detected' })
      });

      // 自动下架或禁止发布
      await db('cf_sync_status')
        .where({ platformProductId: productId })
        .update({ status: 'failed', updated_at: db.fn.now() });
    }

    return status;
  }

  /**
   * 获取租户所有高风险 IP 检查记录
   */
  static async getHighRiskChecks(tenantId: string) {
    return await db('cf_ip_check')
      .where({ tenant_id: tenantId, status: 'BLOCKED' })
      .orderBy('risk_score', 'desc');
  }
}
