package com.tzld.piaoquan.ad.engine.commons.util;

import com.tzld.piaoquan.recommend.similarity.word2vec.Segment;
import com.tzld.piaoquan.recommend.similarity.word2vec.Word2Vec;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author dyp
 */
@Slf4j
public final class SimilarityUtils {

    private static Word2Vec vec = new Word2Vec();

    private static final AtomicBoolean modelLoaded = new AtomicBoolean(false);
    private static final AtomicBoolean init = new AtomicBoolean(false);

    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public static void init() {
        if (init.compareAndSet(false, true)) {
            Segment.getWords("1");
            scheduler.scheduleAtFixedRate(() -> {
                try {
                    long start = System.currentTimeMillis();
                    String endpoint = PropertiesUtil.getString("oss.endpoint");
                    String bucketName = "art-recommend";
                    String path = "similarity/word2vec/Google_word2vec_zhwiki210720_300d.bin";
                    String accessKeyId = "LTAIP6x1l3DXfSxm";
                    String accessKetSecret = "KbTaM9ars4OX3PMS6Xm7rtxGr1FLon";
                    Word2Vec temp = new Word2Vec();
                    temp.loadGoogleModelFromOss(endpoint, bucketName, path, accessKeyId, accessKetSecret);
                    vec = temp;
                    long end = System.currentTimeMillis();

                    if (modelLoaded.compareAndSet(false, true)) {
                        scheduler.shutdown();
                        log.info("Model loaded successfully cost {}. Scheduled tasks cancelled.", end - start);
                    }

                } catch (IOException e) {
                    log.error("loadGoogleModelFromOss error", e);
                }
            }, 0, 5, TimeUnit.MINUTES);
        }
    }

    /**
     * 原始方法，保持兼容
     */
    public static float word2VecSimilarity(String str1, String str2) {
        List<String> words1 = Segment.getWords(str1);
        List<String> words2 = Segment.getWords(str2);
        return vec.sentenceSimilarity(words1, words2);
    }

    /**
     * 优化版本：复用已分词的结果，避免重复分词
     * @param words1 已分词的词列表
     * @param words2 已分词的词列表
     * @return 相似度分数
     */
    public static float word2VecSimilarityWithWords(List<String> words1, List<String> words2) {
        if (words1 == null || words1.isEmpty() || words2 == null || words2.isEmpty()) {
            return 0.0f;
        }
        return vec.sentenceSimilarity(words1, words2);
    }

    /**
     * 优化版本：对一个文本与多个文本计算相似度，复用第一个文本的分词结果
     * @param str1 第一个文本
     * @param str2 第二个文本
     * @param str1Words 第一个文本已分词的结果（如果为null则现场分词）
     * @return 相似度分数
     */
    public static float word2VecSimilarityWithCache(String str1, String str2, List<String> str1Words) {
        List<String> words1 = (str1Words != null) ? str1Words : Segment.getWords(str1);
        List<String> words2 = Segment.getWords(str2);
        return vec.sentenceSimilarity(words1, words2);
    }

    /**
     * 分词方法，供外部缓存使用
     * @param text 待分词文本
     * @return 分词结果
     */
    public static List<String> segment(String text) {
        if (text == null || text.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return Segment.getWords(text);
    }

}
