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


import com.typesafe.config.ConfigObject;
import com.tzld.piaoquan.recommend.server.service.score.ScorerConfigInfo;
import com.tzld.piaoquan.recommend.server.service.score.model.Model;
import com.tzld.piaoquan.recommend.server.service.score.model.ModelManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;


public abstract class AbstractScorer4Recall {
    public static Logger LOGGER = LoggerFactory.getLogger(AbstractScorer4Recall.class);
    protected ScorerConfigInfo scorerConfigInfo;
    protected ModelManager modelManager = ModelManager.getInstance();

    public AbstractScorer4Recall(ScorerConfigInfo scorerConfigInfo) {
        this.scorerConfigInfo = scorerConfigInfo;
    }

    public abstract void loadModel();

    public boolean isEnable() {
        return !getScorerConfigInfo().getDisableSwitch();
    }


    public void doLoadModel(Class<? extends Model> modelClass) {

        String modelPath = scorerConfigInfo.getModelPath();
        if (StringUtils.isNotBlank(modelPath)) {
            try {
                // 使用 modelPath 作为 modelName 注册
                ConfigObject paramMap = scorerConfigInfo.getParamMap();
                modelManager.registerModel(modelPath, modelPath, modelClass,
                        paramMap == null ? Collections.emptyMap() : paramMap.unwrapped());
                LOGGER.info("register model success, model path [{}], model class [{}]", modelPath, modelClass);
            } catch (ModelManager.ModelRegisterException e) {
                LOGGER.error("register model fail [{}]:[{}]", modelPath, e);
            } catch (IOException e) {
                LOGGER.error("register model fail [{}]:[{}]", modelPath, e);
            }
        } else {
            LOGGER.error("modelpath is null, for model class [{}]", modelClass);
        }
    }

    public Model getModel() {
        if (StringUtils.isBlank(scorerConfigInfo.getModelPath())) {
            return null;
        }
        return modelManager.getModel(scorerConfigInfo.getModelPath());
    }

    public ScorerConfigInfo getScorerConfigInfo() {
        return scorerConfigInfo;
    }

    public abstract List<Pair<Long, Double>> recall(Map<String, String> params);

}
