
import string, csv, sys, time, platform
import os, types
from termcolor import colored
import json
import KCALLMCore
import base64
import io
import time

verbose = 0

STRING_NOT_AVAIL = ""
UNKNOWN_VALUE = "N/A"
FLOAT_NOT_AVAIL = -1.0
INTEGER_NOT_AVAIL = -1


# Track error
ALL_ERRORS = {}
SOURCE_CONTEXT = ""

class bcolors:

    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def getVerbose():

    return verbose


def TRACE_ROLLBACK():
    
    print("-----------------------------------------")
    print("            A REMETTRE")
    print("-----------------------------------------")
    
    return


def TRACE_CONTEXT(context):

    global SOURCE_CONTEXT
    global ALL_ERRORS

    try:
        bid = ALL_ERRORS['ALL']
    except:
        ALL_ERRORS['ALL'] = {}

    try:
        bid = ALL_ERRORS[context]
    except:
        ALL_ERRORS[context] = {}
        
    SOURCE_CONTEXT = context
    
    return


def TRACE(mess):

    if verbose == 1:
        print(mess)

    return


def TRACE_ERR(errMess):

    #print(f"{bcolors.WARNING}ERROR: " + errMess + "{bcolors.ENDC}")
    # add os.system('color') at the beginning of your pgm
    print(colored("ERROR: " + errMess, 'red'))
    #print("ERROR: " + errMess)

    return


def TRACE_VALID(mess):

    print(colored("VALIDATION: " + mess, 'green'))

    return


def TRACE_ERR_DATA(data):

    print(colored(data, 'red'))

    return

def TRACE_HEADER(mess):

    print()
    print("==========================================================================================")
    print("==========================================================================================")
    print(mess)
    print("==========================================================================================")
    print("==========================================================================================")

    return


def displayExecutionTime(timeInSec):

    stop = int(time.time())
    nbs = int(stop - timeInSec)
    nbh = int(nbs / 3600)
    snbh = str(nbh)
    if len(snbh) == 1:
        snbh = '0' + snbh
    nbmn = int((nbs - nbh * 3600) / 60)
    snbmn = str(nbmn)
    if len(snbmn) == 1:
        snbmn = '0' + snbmn
    nbs = nbs - nbmn * 60 - nbh * 3600
    snbs = str(nbs)
    if len(snbs) == 1:
        snbs = '0' + snbs
    print('Execution time: ' + snbh + "h" + snbmn + "mn" + snbs + "s")

    return


def encodeImage(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def decodeImage(encoded_string, output_path):
    image_data = base64.b64decode(encoded_string)
    with open(output_path, "wb") as image_file:
        image_file.write(image_data)

def PRINT_ERROR_REPORT(totalCount):

    print()
    print("Error report:")
    print("-------------")

    # Max error message length
    global ALL_ERRORS

    # Loop on sources
    for source in ALL_ERRORS:
        
        nbc = 0
        for e in ALL_ERRORS[source]:
            if len(e) > nbc:
                nbc = len(e)
        nbc += 3
        
        #printErrorReport("Number of empty issues", nbItemIssues, nbItems)
        for title in ALL_ERRORS[source]:
            val = ALL_ERRORS[source][title]
            if totalCount == 0:
                print("{:<" + str(nbc) + "}    {}".format(title, val) )
            else:
                purc = float(val / totalCount * 100.0)
                ftext = "{:<11} {:<" + str(nbc) + "} {:<6} {:.1f}%"
                print(ftext.format(source, title, val, purc) )

    return


def buildEvent(mess, imagePath, image64, comment, test, llm, origin):
    
    event = {"queryStringParameters": {"speech": mess,
                                       "image64": image64,
                                       "imagePath": imagePath,
                                       "comment": comment,
                                       "test": test,
                                       "appid": "INTERNAL-TEST",
                                       "device": "iPhone12Pro",
                                       "version": "V15.0.0" ,
                                       "age": 50,
                                       "gender": "Female",
                                       "longitude": 180.0,
                                       "latitude": 90.0,
                                       "llmid": llm,
                                       "origin": origin}}
    
    return event

def ERROR_INCREMENT(txt):

    global ALL_ERRORS
    global SOURCE_CONTEXT

    source = SOURCE_CONTEXT 
    if source == '':
        source = 'ALL'

    try:
        ierr = ALL_ERRORS[source][txt]
    except KeyError:
        ALL_ERRORS[source][txt] = 0
    ALL_ERRORS[source][txt] += 1

    return


def RESET_ERROR_STACK():

    global ALL_ERRORS
    ALL_ERRORS = []
    SOURCE_CONTEXT = ''

    return


def ignorePrefix(prefix, jj):

    sjj = json.dumps(jj)
    sjj = sjj.replace(prefix, '')
    j = json.loads(sjj)
    return j


