import db from '../../config/database';
import { AuditService } from '../core/AuditService';
import { AIService } from '../ai/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({
      productTitle: product.title,
      productDescription: product.description || '',
      productImages: product.images || []
    });
    const riskScore = analysis.riskLevel === 'high' ? 0.9 : analysis.riskLevel === 'medium' ? 0.5 : 0.1;
    const matchedKeywords = analysis.detectedIssues;
    const similarImages = analysis.recommendations;

    // 3. 判定结果
    const status = analysis.hasInfringement ? '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({
        tenantId: tenantId,
        action: 'IP_INFRINGEMENT_BLOCKED',
        module: 'COMPLIANCE',
        resourceType: 'PRODUCT',
        resourceId: productId,
        traceId: traceId,
        userId: 'system',
        result: 'success',
        source: 'console',
        afterSnapshot: { riskScore, matchedKeywords },
        metadata: { 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');
  }
}
