import { ImageFingerprintService } from '../../services/ImageFingerprintService';
import { AIService } from '../../services/AIService';
import { logger } from '../../utils/logger';
import { TurboGateway } from '../gateway/TurboGateway';
import crypto from 'crypto';

/**
 * [CORE_AI_15] 视觉/语义指纹解析中心 (AI-Native Fingerprint Engine)
 * @description 融合图像 pHash 与文本 Embedding，实现跨平台商品的精准匹配与去重
 */
export class FingerprintEngine {
  /**
   * 生成复合指纹
   */
  static async generateCompositeFingerprint(data: {
    title: string;
    description?: string;
    mainImage: string;
  }): Promise<{
    phash: string;
    semanticHash: string;
    vectorEmbedding: number[];
  }> {
    try {
      // 1. 生成视觉指纹 (pHash)
      const phash = await ImageFingerprintService.generateHashFromUrl(data.mainImage);

      // 2. 生成语义向量 (Embedding) - 增加缓存逻辑以优化成本
      const textToEmbed = `${data.title} ${data.description || ''}`.substring(0, 1000);
      const textHash = crypto.createHash('md5').update(textToEmbed).digest('hex');
      const cacheKey = `embedding:${textHash}`;

      let vectorEmbedding = await TurboGateway.getL2(cacheKey);
      if (!vectorEmbedding) {
        logger.info(`[FingerprintEngine] Embedding Cache Miss for text: ${textHash}`);
        vectorEmbedding = await AIService.generateEmbedding(textToEmbed);
        await TurboGateway.setL2(cacheKey, vectorEmbedding, 86400 * 7); // 缓存 7 天
      } else {
        logger.info(`[FingerprintEngine] Embedding Cache Hit: ${textHash}`);
      }

      // 3. 生成语义哈希 (SimHash) - 简化版用于快速检索
      const semanticHash = this.generateSimHash(textToEmbed);

      return {
        phash,
        semanticHash,
        vectorEmbedding
      };
    } catch (err: any) {
      logger.error(`[FingerprintEngine] Failed to generate composite fingerprint: ${err.message}`);
      throw err;
    }
  }

  /**
   * 计算余弦相似度 (Cosine Similarity)
   */
  static cosineSimilarity(vecA: number[], vecB: number[]): number {
    if (vecA.length !== vecB.length) return 0;
    let dotProduct = 0;
    let normA = 0;
    let normB = 0;
    for (let i = 0; i < vecA.length; i++) {
      dotProduct += vecA[i] * vecB[i];
      normA += vecA[i] * vecA[i];
      normB += vecB[i] * vecB[i];
    }
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
  }

  /**
   * 简化版 SimHash 实现
   */
  private static generateSimHash(text: string): string {
    // 这是一个极简版实现，生产环境建议使用专门的库
    const words = text.toLowerCase().split(/\s+/);
    const v = new Array(64).fill(0);
    
    for (const word of words) {
      const hash = this.stringToHash64(word);
      for (let i = 0; i < 64; i++) {
        if ((hash >> BigInt(i)) & BigInt(1)) {
          v[i]++;
        } else {
          v[i]--;
        }
      }
    }

    let fingerprint = BigInt(0);
    for (let i = 0; i < 64; i++) {
      if (v[i] > 0) {
        fingerprint |= (BigInt(1) << BigInt(i));
      }
    }

    return fingerprint.toString(16).padStart(16, '0');
  }

  private static stringToHash64(str: string): bigint {
    let hash = BigInt(0);
    for (let i = 0; i < str.length; i++) {
      hash = (hash * BigInt(31) + BigInt(str.charCodeAt(i))) & BigInt('0xFFFFFFFFFFFFFFFF');
    }
    return hash;
  }
}
