import KCALLMPrompt
import KCALLMConst
import KCALLMEngine
import KCALLMCore
import KCALLMNutritionUtilities
import KCALLMTrace

import os
import json

from numpy import dot
from numpy.linalg import norm


def searchClosestEntity(sig, sigs):

    eRefNorm =norm(sig)
    idx = 0
    idxRef = -1
    distRef = 0
    for s in sigs:
        eFood = sigs[idx]
        dist = dot(eRef, eFood) / (eRefNorm * norm(eFood))
        if dist > distRef:
            distRef = dist
            idxRef = idx
        idx += 1
    
    print(distRef)

    return idxRef


# List des foods
foods = ["lait","eau", "eau petillante", "yaourt", "Perrier", "ketchup", "pomme", "coca", "orangina", "blanquette de veau", "blanquette de poulet"]
sigs = []
sigs = KCALLMEngine.generateEmbedding(foods, KCALLMCore.MODEL_MISTRAL_ONLINE)

# Reference food
food = "Boisson avec des bulles"
eRefTab = KCALLMEngine.generateEmbedding(food, KCALLMCore.MODEL_MISTRAL_ONLINE)
eRef = eRefTab[0]

# Search
idx = searchClosestEntity(eRef, sigs)
print()
# print("---> Le plus proche de '" + text[0] + " , " + text[1] + "' est '" + foods[idxRef][0] + " , " +  foods[idxRef][1]  + "'")
print("---> Le plus proche de '" + food + "' est '" + foods[idx] + "'")


##
##mapper = {}
##mapper['name'] = []
##intent = KCALLMConst.INTENT_TEXT_TO_ACTIVITY
##portraitRobot = ''
##s = KCALLMPrompt.getPreprompt(mapper, intent, portraitRobot)

#-------------------------------------------------------------------
#
#                         TEST INTENT
#
#-------------------------------------------------------------------
## Intentify the list of intents
#text = "J'ai bu un Coca et j'ai fait du ménage"
#listIntents = KCALLMConst.getIntentList()
#model = KCALLMCore.getDefaultModel()
# image64 = ''
#intents = KCALLMEngine.getIntentsFromPrompt(listIntents, text, image64, model)
#print(intents)


#-------------------------------------------------------------------
#
#                         TEST BEST SOLUTION
#
#-------------------------------------------------------------------
# dataLocation = os.path.join("__deriveddata__", "DerivedObjects", "Data")
# dbPath = os.path.join(dataLocation, "KcalMeDB_fr.sl3")
# dbEmbeddingPath = os.path.join(dataLocation, "embeddingDB.sl3")
# pictoPath = os.path.join(dataLocation, "PictoMatcherNetNG_fr.json")
# jVoca = {}
# with open(pictoPath, 'r', encoding='utf-8') as f:
#     jVoca = json.load(f)
# f.close()
# #jresult = {'response': [{'name': 'saucisses', 'quantity': 'trois', 'cooking': '', 'brand': '', 'company': '', 'type': 'nourriture', 'time': 'déjeuner', 'event': 'declaration'}, ], 'cost': 0.0}
# jresult = {'response': [{'name': 'saucisses', 'quantity': 'trois', 'cooking': '', 'brand': '', 'company': '', 'type': 'nourriture', 'time': 'déjeuner', 'event': 'declaration'}, {'name': 'petits pois', 'quantity': '', 'cooking': '', 'brand': '', 'company': '', 'type': 'nourriture', 'time': 'déjeuner', 'event': 'declaration'}, {'name': 'banane', 'quantity': 'une', 'cooking': '', 'brand': '', 'company': '', 'type': 'nourriture', 'time': 'déjeuner', 'event': 'declaration'}], 'cost': 0.0}
# sols = KCALLMNutritionUtilities.getBestSolutions(jresult["response"], dbPath, dbEmbeddingPath, jVoca)
# print(sols)

# #-------------------------------------------------------------------
# #
# #                         TEST PORTRAIT ROBOT
# #
# #-------------------------------------------------------------------
# dataLocation = os.path.join("__deriveddata__", "DerivedObjects", "Data")
# pictosPath = os.path.join("__deriveddata__", "DerivedObjects", "FoodPictos")
# dbPath = os.path.join(dataLocation, "KcalMeDB_fr.sl3")
# #jeresults = [{'name': 'Orange', 'normName': ' orange ', 'comment': 'pulpe, crue', 'normComment': ' pulpe crue ', 'rank': 19789, 'id': 'CIQ#a84ec3c1b9bc46c10b639fa15eeef5f4', 'quantity': 'une', 'quantityLem': '1', 'pack': ['ORA.w200'], 'type': 'fruit', 'gtin': '', 'gtinRef': '', 'brand': '', 'time': '', 'event': 'unknown', 'serving': 'ORA-100', 'posiNormName': 0}]
# jeresults = [{'name': 'Orange', 'normName': ' orange ', 'comment': 'pulpe, crue', 'normComment': ' pulpe crue ', 'rank': 19789, 'id': 'CIQ#a84ec3c1b9bc46c10b639fa15eeef5f4', 'quantity': 'une', 'quantityLem': '1', 'pack': ['ORA.w200'], 'type': 'fruit', 'gtin': '', 'gtinRef': '', 'brand': '', 'time': 'petit-déjeuner', 'event': 'declaration', 'serving': 'ORA-100', 'posiNormName': 0}]
# sols = KCALLMNutritionUtilities.extractPortraitRobots(jeresults, dbPath, pictosPath)
# print(sols)


# #-------------------------------------------------------------------
# #
# #                         TEST SPLIT
# #
# #-------------------------------------------------------------------
#text = "J'ai bu un Coca et j'ai fait du ménage, après j'ai mangé un sandwish au jambon. Quel est l'age de napoleon?"
# itext = "Tout compte fait ce midi j'ai mangé un pavé de saumon accompagné d'une pomme de terre \
# et un demi verre de vin blanc en dessert la tarte au pomme était excellente j'ai également pris un yaourt nature danone au fait \
# aujourd'hui j'ai marché 30 minutes et j'ai couru deux heures dans le parc voisin"
# itext = "Ce matin j'ai mangé deux Vache Qui Rit j'ai mangé également un quignon de pain et bu un grand verre de lait \
#     pour aller ensuite courir dans le parc d'à côté 30 miniutes"
# model = KCALLMCore.getDefaultModel()
# prompts = KCALLMEngine.splitPrompt(itext, model)

# # Read sport grounding
# mapper = {}
# mapper['type'] = []
# portraitRobot = ''
# text = prompts["foodSentence"]
# image64 = ""
# effectiveIntent = KCALLMConst.INTENT_TEXT_TO_FOOD

# # First step for food question: identify the foods
# prompt = KCALLMPrompt.getPreprompt(text, mapper, effectiveIntent, portraitRobot)
    
# # Run query
# jresult = KCALLMEngine.runLLM(prompt, image64, model)

# KCALLMTrace.TRACE("")
# KCALLMTrace.TRACE("--------------------------------- LLM result -----------------------------------")
# KCALLMTrace.TRACE(jresult)
# KCALLMTrace.TRACE("--------------------------------------------------------------------------------")

#-------------------------------------------------------------------
#
#                         MODEL LIST
#
#-------------------------------------------------------------------
# mdls = KCALLMEngine.getMistralModelList()
# print(mdls)

