import os
import json
import argparse
import time

import KCALLMTrace as KCATrace
import KCALLMMain
import KCALLMUtilities


# Read arguments
parserArg = argparse.ArgumentParser()
parserArg.add_argument('-i', help='input query spec')
parserArg.add_argument('-o', help='output query')
args = parserArg.parse_args()

inputPath = ''
outputPath = ''

if args.i == None:
    print("Define -i argument for input spec")
    exit(0)
elif args.o == None:
    print("Define -o argument with output result")
    exit(0)
else:
    inputPath = args.i
    outputPath = args.o

KCATrace.TRACE("Input path: " + inputPath)
KCATrace.TRACE("Output path: " + outputPath)

# Read voca
inputData = {}
with open(inputPath, 'r', encoding='utf-8') as f:
    inputData = json.load(f)
f.close()

# Query
jresult = None

# Read prompt
speech = ""
comment = ""
llmid = ""
image64 = ""
origin = ""
imagePath = ""
try:
    with open(inputPath, 'r') as file:
        jdata = json.load(file)
        speech = jdata["speech"]
        imagePath = jdata["imagePath"]
        llmid = jdata["llmid"]
        origin = jdata["origin"]
except:
    print("WARNING/ No prompt in input")
    speech = ""

# Case image
if imagePath != '':
    comment = "Search by upload"
    speech = ''
    image64 = KCALLMUtilities.encodeImage(imagePath)

    
# Retrieve
event = KCALLMUtilities.buildEvent(speech, imagePath, image64, comment, 0, llmid, origin)

# Go
omess = KCALLMMain.runEvent(event)


# Save output
with open(outputPath, "w") as outfile:
    json.dump(omess, outfile)
    
exit(0)

