import mysql.connector


# det_res -> detection result
def best(det_res):
    chars = ['®', '|', ' ', "'", '[', ']', ',', '\n', '\x0c', '/', '\\']
    for i in range(len(det_res)):
        for char in chars:
            det_res[i] = det_res[i].replace(char, '')

    for ele in det_res:
        if len(ele) == 1:
            det_res.remove(ele)

    while "" in det_res:
        det_res.remove("")

    print(det_res)

    db = mysql.connector.connect(host="localhost", user="root", database="wtb_db")
    cursor = db.cursor()

    cursor.execute('SELECT * FROM coffee')
    db_results = cursor.fetchall()

    score = []
    for i in range(len(db_results)):
        keywords = db_results[i][2].split(';')
        score.append(0)
        for res in det_res:
            print(f'\n=== {db_results[i][1]} ===')
            for keyword in keywords:
                if res.lower() in keyword.lower():
                    print(f'{res} -- {keyword}')
                    # dwa pierwsze to zawsze nazwa kawy, dlatego jest lepiej punktowana
                    if i < 2:
                        score[i] += 3
                    else:
                        score[i] += 1
        if score[i] != 0:
            if i != 0:
                score[i] = score[i]/i

        print(score[i])
        print("=======================")

    print(score)
    if score.index(max(score)) < 1:
        return 'Nie wykryto kawy w bazie danych'
    else:
        best_index = score.index(max(score))

    return f"""
        WYKRYTO: {db_results[best_index][1]}\n
        Opis: {db_results[best_index][3]}
        """
