package rank

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

	"gitlab.alibaba-inc.com/pai_biz_arch/pairec-experiment/client_golang/common"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec-experiment/client_golang/model"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/abtest"
	"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/utils"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/utils/ast"
)

var rankService *RankService

func init() {
	rankService = NewRankService()
}

type RankService struct {
	rankInters map[string][]IRank
}

func NewRankService() *RankService {
	rank := RankService{
		rankInters: make(map[string][]IRank, 0),
	}

	return &rank
}

func DefaultRankService() *RankService {
	return rankService
}

func RegisterRank(sceneName string, ranks ...IRank) {
	DefaultRankService().AddRanks(sceneName, ranks...)
}

func (r *RankService) AddRanks(sceneName string, ranks ...IRank) {
	var rankInters []IRank
	if preRanks, ok := r.rankInters[sceneName]; ok {
		rankInters = preRanks
	}

	for _, rank := range ranks {
		rankInters = append(rankInters, rank)
	}

	r.rankInters[sceneName] = rankInters
}

func (r *RankService) GetRanks(sceneName string, context *context.RecommendContext) (ret []IRank) {
	// first find experiment info
	if context.ExperimentResult != nil {
		rankconf := context.ExperimentResult.GetExperimentParams().Get("coldStartRankConf", "")
		if rankconf != "" {
			var rankConfig recconf.ColdStartRankConfig
			d, _ := json.Marshal(rankconf)
			if err := json.Unmarshal(d, &rankConfig); err == nil {
				rank := NewColdStartRank(rankConfig.RecallName, rankConfig.AlgoName)
				ret = append(ret, rank)
				// when rank is not ColdStartRank, add it
				if ranks, exist := r.rankInters[sceneName]; exist {
					for _, rank := range ranks {
						if _, ok := rank.(*ColdStartRank); !ok {
							ret = append(ret, rank)

						}
					}
				}
				return
			}
		}
	}

	if ranks, ok := r.rankInters[sceneName]; ok {
		ret = ranks
	}

	return
}

type boostFunc func(score float64, user *module.User, item *module.Item, context *context.RecommendContext) float64

var boostScoreFunc boostFunc

func SetBoostFunc(bf boostFunc) {
	boostScoreFunc = bf
}

func (r *RankService) Rank(user *module.User, items []*module.Item, context *context.RecommendContext) {
	start := time.Now()
	if context.Debug {
		fmt.Println(user)
	}

	rankItems := items
	algoDataList := make([]IAlgoData, 0)
	scene := context.GetParameter("scene").(string)

	i := 0
	var customRanks []*customRank
	for _, rank := range r.GetRanks(scene, context) {
		customRank := newCustomRank(rank)
		customRanks = append(customRanks, customRank)
	}

	// 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
		}
	}

	batchCount := 100
	if rankConfig.BatchCount > 0 {
		batchCount = rankConfig.BatchCount
	}
	algoGenerator := CreateAlgoDataGenerator(rankConfig.Processor)

	var userFeatures map[string]interface{}

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

	var filter bool
	for _, item := range rankItems {
		filter = false
		if len(customRanks) > 0 {
			for _, rank := range customRanks {
				if rank.rankInter.Filter(user, item, context) {
					filter = true
					rank.appendFeature(userFeatures, item, context)
					break
				}
			}
		}

		if filter {
			continue
		}

		features := item.GetFeatures()
		algoGenerator.AddFeatures(item, features, userFeatures)
		i++
		if i%batchCount == 0 {
			algoData := algoGenerator.GeneratorAlgoData()
			algoDataList = append(algoDataList, algoData)
		}
	}

	if algoGenerator.HasFeatures() {
		algoData := algoGenerator.GeneratorAlgoData()
		algoDataList = append(algoDataList, algoData)
	}

	var rankWG sync.WaitGroup
	// invoke custom rank
	if len(customRanks) > 0 {
		for _, rank := range customRanks {
			rankWG.Add(1)
			go func(customRank *customRank) {
				defer rankWG.Done()
				customRank.rankInter.Rank(user, customRank.items, customRank.requestData, context)
			}(rank)
		}
	}

	if len(algoDataList) == 0 {
		if len(customRanks) > 0 {
			rankWG.Wait()
		}
		return
	}
	requestCh := make(chan IAlgoData, len(algoDataList))
	responseCh := make(chan IAlgoData, len(algoDataList))
	defer close(requestCh)
	defer close(responseCh)

	for _, data := range algoDataList {
		requestCh <- data
	}

	gCount := len(algoDataList)
	for i := 0; i < gCount; i++ {
		go func() {
			algoData := <-requestCh

			var wg sync.WaitGroup
			for _, algoName := range rankConfig.RankAlgoList {
				wg.Add(1)
				go func(algo string) {
					defer wg.Done()
					ret, err := algorithm.Run(algo, 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)
						}
					}

				}(algoName)

			}
			wg.Wait()
			responseCh <- algoData
		}()
	}

	for i := 0; i < gCount; i++ {
		algoData := <-responseCh
		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())
					}
				}
			}
		}

		if rankConfig.RankScore != "" {
			itemList := algoData.GetItems()
			for k, _ := range itemList {
				itemList[k].Score = ast.ExprSourceResult(rankConfig.RankScore, itemList[k])
				if boostScoreFunc != nil {
					itemList[k].Score = boostScoreFunc(itemList[k].Score, user, itemList[k], context)
				}
			}
		}
	}

	if len(customRanks) > 0 {
		rankWG.Wait()
	}

	go r.logRankResult(user, items, context)
	log.Info(fmt.Sprintf("requestId=%s\tmodule=rank\tcost=%d", context.RecommendId, utils.CostTime(start)))
}
func (r *RankService) logRankResult(user *module.User, items []*module.Item, context *context.RecommendContext) {

	if abtest.GetExperimentClient() != nil {
		scene := context.Param.GetParameter("scene").(string)
		currTime := time.Now().Unix()
		jobs := abtest.GetExperimentClient().GetSceneParams(scene).GetFeatureConsistencyJobs()

		for _, job := range jobs {
			if job.Status == common.Feature_Consistency_Job_State_RUNNING {
				if currTime >= job.StartTime && currTime <= job.EndTime {
					log.Info(fmt.Sprintf("requestId=%s\tevent=logRankResult\tname=%s", context.RecommendId, job.JobName))
					if job.FeatureBackflowQueueType == "datahub" {
						r.logRankResultToDatahub(user, items, context, job)
					}
				}
			}
		}
	}
}

func (r *RankService) logRankResultToDatahub(user *module.User, items []*module.Item, context *context.RecommendContext, job *model.FeatureConsistencyJob) {
	name := fmt.Sprintf("%s-%s-%s-%s-%s", job.FeatureBackflowQueueDatahubAccessId, job.FeatureBackflowQueueDatahubAccessKey, job.FeatureBackflowQueueDatahubEndpoint,
		job.FeatureBackflowQueueDatahubProject, job.FeatureBackflowQueueDatahubTopic)
	var dh *datahub.Datahub
	dh, err := datahub.GetDatahub(name)
	if err != nil {
		dh = datahub.NewDatahub(job.FeatureBackflowQueueDatahubAccessId, job.FeatureBackflowQueueDatahubAccessKey, job.FeatureBackflowQueueDatahubEndpoint,
			job.FeatureBackflowQueueDatahubProject, job.FeatureBackflowQueueDatahubTopic)
		err = dh.Init()
		datahub.RegisterDatahub(name, dh)
	}

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

	userFeatures := utils.ConvertFeatures(user.MakeUserFeatures2())
	userData, _ := json.Marshal(userFeatures)
	scene := context.Param.GetParameter("scene").(string)
	var data []map[string]interface{}
	i := 0
	for _, item := range items {
		messsage := make(map[string]interface{})
		messsage["request_id"] = context.RecommendId
		messsage["scene"] = scene
		messsage["request_time"] = time.Now().Unix()
		messsage["user_id"] = string(user.Id)
		messsage["item_id"] = string(item.Id)
		messsage["user_features"] = string(userData)
		j, _ := json.Marshal(utils.ConvertFeatures(item.GetFeatures()))
		messsage["item_features"] = string(j)
		j, _ = json.Marshal(item.GetAlgoScores())
		messsage["scores"] = string(j)
		data = append(data, messsage)
		i++
		if i%5 == 0 {
			dh.SendMessage(data)
			data = data[:0]
		}
	}
	if len(data) > 0 {
		dh.SendMessage(data)
	}
}
