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


import com.tzld.piaoquan.ad.engine.commons.score.model.Model;

import com.tzld.piaoquan.ad.engine.commons.score.model.ModelManager;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.AdRankItem;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.UserAdFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


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

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

    public 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 注册
                modelManager.registerModel(modelPath, modelPath, modelClass);
                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<AdRankItem> scoring(final ScoreParam param,
                                             final UserAdFeature userAdFeature,
                                             final List<AdRankItem> rankItems);

    public List<AdRankItem> scoring(final Map<String, String> sceneFeatureMap,
                                    final Map<String, String> userFeatureMap,
                                    List<AdRankItem> rankItems) {
        throw new NoSuchMethodError();
    }
}
