package com.tzld.piaoquan.recommend.server.service.score4recall.strategy;

import com.tzld.piaoquan.recommend.server.service.score.ScorerConfigInfo;
import com.tzld.piaoquan.recommend.server.service.score4recall.AbstractScorer4Recall;
import com.tzld.piaoquan.recommend.server.service.score4recall.model4recall.Model4RecallKeyValue;
import com.tzld.piaoquan.recommend.server.service.score4recall.model4recall.Model4RecallTomson;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.math3.distribution.BetaDistribution;

import java.util.*;


public class FlowPoolScorer extends AbstractScorer4Recall {

    public FlowPoolScorer(ScorerConfigInfo configInfo) {
        super(configInfo);
    }
    @Override
    public void loadModel() {
        doLoadModel(Model4RecallTomson.class);
    }

    @Override
    public List<Pair<Long, Double>> recall(Map<String, String> params){
        Map<String, String> randomSubset = new HashMap<>();
        if (params.size() > 3000){
            // 将键转换为列表
            List<String> keys = new ArrayList<>(params.keySet());
            // 打乱键列表
            Collections.shuffle(keys);
            // 限制要取出的键的数量为4000，或者如果键的数量少于4000，则取所有键
            int maxKeysToTake = Math.min(keys.size(), 3000);
            // 从打乱后的键列表中取出前10000个键，并获取对应的值
            for (int i = 0; i < maxKeysToTake; i++) {
                String key = keys.get(i);
                randomSubset.put(key, params.get(key));
            }
        }else{
            randomSubset = params;
        }
        // todo zhangbo 这里要写实现汤姆森采样的具体功能
        Model4RecallTomson model = (Model4RecallTomson) this.getModel();
        Map<Long, Pair<Double, Double>> maps = model.kv;
        List<Pair<Long, Double>> id2BetaScore = new ArrayList<>();
        BetaDistribution betaSample;
        for (Map.Entry<String, String> entry: randomSubset.entrySet()){
            String id = entry.getKey();
            Long idLong = Long.valueOf(id);
            Pair<Double, Double> betas = maps.getOrDefault(idLong, Pair.of(0.0, 0.0));
            betaSample = new BetaDistribution(betas.getLeft(), betas.getRight());
            id2BetaScore.add(Pair.of(idLong, betaSample.sample()));
        }
        id2BetaScore.sort(Comparator.comparingDouble(o -> -o.getRight()));
        return id2BetaScore.subList(0, Math.min(60, id2BetaScore.size()));
    }

    public static void main(String[] args) {
        BetaDistribution betaSample;
        betaSample = new BetaDistribution(0.0, 0.0);
        System.out.println(betaSample.sample());
    }

}