package service

import (
	"encoding/json"
	"fmt"
	"sync"
	"time"

	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/algorithm"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/algorithm/eas"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/algorithm/response"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/context"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/datasource/datahub"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/module"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/service/rank"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/utils"
)

type FeatureReplyService struct {
	RecommendService
}

func NewFeatureReplyService() *FeatureReplyService {
	service := FeatureReplyService{}
	return &service
}

func (r *FeatureReplyService) FeatureReply(userFeatures, itemFeatures string, context *context.RecommendContext) {
	userId := r.GetUID(context)
	user := module.NewUserWithContext(userId, context)
	userProperties := make(map[string]interface{}, 0)
	if userFeatures != "" {
		features := make(map[string]*utils.FeatureInfo, 0)
		if err := json.Unmarshal([]byte(userFeatures), &features); err != nil {
			log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureReply\terror=%v", context.RecommendId, err))
			return
		}

		for name, feature := range features {
			userProperties[name] = utils.GetValueByType(feature.Value, feature.Type)
		}
	}

	user.Properties = userProperties
	itemProperties := make(map[string]interface{}, 0)
	if itemFeatures != "" {
		features := make(map[string]*utils.FeatureInfo, 0)
		if err := json.Unmarshal([]byte(itemFeatures), &features); err != nil {
			log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureReply\terror=%v", context.RecommendId, err))
			return
		}

		for name, feature := range features {
			itemProperties[name] = utils.GetValueByType(feature.Value, feature.Type)
		}
	}

	item := module.NewItemWithProperty(context.GetParameter("item_id").(string), itemProperties)

	r.rank(user, []*module.Item{item}, context)
}

func (r *FeatureReplyService) rank(user *module.User, items []*module.Item, context *context.RecommendContext) {
	start := time.Now()

	rankItems := items
	scene := context.GetParameter("scene").(string)

	// find rank config
	var rankConfig recconf.RankConfig
	found := false
	if context.ExperimentResult != nil {
		rankconf := context.ExperimentResult.GetExperimentParams().Get("rankconf", "")
		if rankconf != "" {
			d, _ := json.Marshal(rankconf)
			if err := json.Unmarshal(d, &rankConfig); err == nil {
				found = true
			}
		}
	}
	if !found {
		if rankConfigs, ok := recconf.Config.RankConf[scene]; ok {
			rankConfig = rankConfigs
		}
	}

	algoGenerator := rank.CreateAlgoDataGenerator(rankConfig.Processor)

	var userFeatures map[string]interface{}

	if rankConfig.Processor == eas.Eas_Processor_EASYREC {
		userFeatures = user.MakeUserFeatures2()
	} else {
		userFeatures = user.MakeUserFeatures()
	}

	for _, item := range rankItems {
		features := item.GetFeatures()
		algoGenerator.AddFeatures(item, features, userFeatures)
	}

	var algoData rank.IAlgoData
	if algoGenerator.HasFeatures() {
		algoData = algoGenerator.GeneratorAlgoDataDebug()
	}

	var wg sync.WaitGroup
	for _, algoName := range rankConfig.RankAlgoList {
		wg.Add(1)
		go func(algo string) {
			defer wg.Done()

			newAlgoName := algo + "_feature_reply"
			found := false
			var processor string
			for _, config := range context.Config.AlgoConfs {
				if config.Name == newAlgoName {
					found = true
					processor = config.EasConf.Processor
					break
				}
			}
			if !found {
				var algoConfig recconf.AlgoConfig
				for _, config := range context.Config.AlgoConfs {
					if config.Name == algo {
						algoConfig = config
						processor = config.EasConf.Processor
						// change algoname  and  response function name
						algoConfig.Name = newAlgoName
						if algoConfig.EasConf.ResponseFuncName != "" {
							algoConfig.EasConf.ResponseFuncName += "Debug"
						}
						algorithm.AddAlgo(algoConfig)
						break
					}
				}
			}
			// run 返回原始的值，然后处理返回数据// 注册配置
			ret, err := algorithm.Run(newAlgoName, algoData.GetFeatures())
			if err != nil {
				log.Error(fmt.Sprintf("requestId=%s\terror=run algorithm error(%v)", context.RecommendId, err))
				algoData.SetError(err)
			} else {
				if result, ok := ret.([]response.AlgoResponse); ok {
					algoData.SetAlgoResult(algo, result)
					if processor == eas.Eas_Processor_EASYREC {
						itemList := algoData.GetItems()
						for j := 0; j < len(result) && j < len(itemList); j++ {
							response, _ := (result[j]).(*eas.EasyrecResponse)
							itemList[j].AddProperty("raw_features", response.RawFeatures)
							itemList[j].AddProperty("generate_features", response.GenerateFeatures)
							itemList[j].AddProperty("context_features", response.ContextFeatures)

						}
					}
				}
			}

		}(algoName)

	}

	wg.Wait()
	if algoData.Error() == nil && algoData.GetAlgoResult() != nil {
		for name, algoResult := range algoData.GetAlgoResult() {
			itemList := algoData.GetItems()
			for j := 0; j < len(algoResult) && j < len(itemList); j++ {
				if algoResult[j].GetModuleType() {
					arr_score := algoResult[j].GetScoreMap()
					for k, v := range arr_score {
						itemList[j].AddAlgoScore(name+"_"+k, v)
					}
				} else {
					itemList[j].AddAlgoScore(name, algoResult[j].GetScore())
				}
			}
		}
		go r.logFeatureReplyResult(user, items, context)
	}

	log.Info(fmt.Sprintf("requestId=%s\tmodule=rank\tcost=%d", context.RecommendId, utils.CostTime(start)))
}

func (r *FeatureReplyService) logFeatureReplyResult(user *module.User, items []*module.Item, context *context.RecommendContext) {
	datasourceType := context.GetParameter("datasource_type").(string)
	if datasourceType == "datahub" {
		r.logReatureReplyResultToDatahub(user, items, context)
	}
}
func (r *FeatureReplyService) logReatureReplyResultToDatahub(user *module.User, items []*module.Item, context *context.RecommendContext) {
	accessId := context.GetParameter("access_id").(string)
	accessKey := context.GetParameter("access_key").(string)
	endpoint := context.GetParameter("endpoint").(string)
	project := context.GetParameter("project").(string)
	topic := context.GetParameter("topic").(string)

	name := fmt.Sprintf("%s-%s-%s-%s-%s", accessId, accessKey, endpoint, project, topic)

	var dh *datahub.Datahub
	dh, err := datahub.GetDatahub(name)
	if err != nil {
		dh = datahub.NewDatahub(accessId, accessKey, endpoint, project, topic)
		err = dh.Init()
		datahub.RegisterDatahub(name, dh)
	}

	if dh == nil {
		log.Error(fmt.Sprintf("requestId=%s\tevent=logFeatureReplyResultToDatahub\tmsg=create datahub error\terror=%v", context.RecommendId, err))
		return
	}

	scene := context.Param.GetParameter("scene").(string)
	var data []map[string]interface{}
	for _, item := range items {
		message := make(map[string]interface{})
		message["request_id"] = context.RecommendId
		message["request_time"] = time.Now().Unix()
		message["scene"] = scene
		message["user_id"] = string(user.Id)
		message["item_id"] = string(item.Id)
		message["raw_features"] = item.StringProperty("raw_features")
		message["generate_features"] = item.StringProperty("generate_features")
		message["context_features"] = item.StringProperty("context_features")
		// j, _ := json.Marshal(item.GetAlgoScores())
		// message["scores"] = string(j)
		data = append(data, message)
	}
	dh.SendMessage(data)
}
