#!/usr/bin/env python3

from dataset_cli import MESSAGE_SEPARATOR

import sys

sys.path.append("../../../utils")
sys.path.append("../../../sentiment-old")

from nlputils import SentimentAnalyzer
from typing import List, Tuple
import argparse

def parse_dataset_file(path: str) -> List[Tuple[str, float]]:
    result = []
    with open(path, "r") as f:
        tmp_str = []
        for line in f:
            if MESSAGE_SEPARATOR in line:
                continue
            if "VALUE=" in line:
                result.append(("\n".join(tmp_str), float(line.split("=")[-1])))
                tmp_str = []
                continue
            tmp_str.append(line)
    return result


def test(dataset: List[Tuple[str, float]], args=None) -> List[List[int]]:
    confusion_matrix = [[0 for i in range(3)] for j in range(3)]
    sent_anal = SentimentAnalyzer()
    if args and args.neg_emoji_score is not None:
        sent_anal.set_params([args.neg_emoji_score, args.neg_emotion_coeff, args.neg_raw_emotion_coeff,
            args.neutral_sentiment_threshold])
    for message, label in dataset:
        text_obj = []
        value, preprocessed = sent_anal.detect_from_message(message, "cs", debug=True, text_obj=text_obj)
        confusion_matrix[int(label)][int(value)] += 1
        print(MESSAGE_SEPARATOR)
        print(f"MESSAGE: {message}")
        if value == label:
            print(f"RESULT: {value} vs. EXPECTED RESULT: {label}")
        else:
            print(f"RESULT: {value} vs. EXPECTED RESULT: {label} - MISMATCH")
        print("============METADATA============")
        print(f"PREPROCESSED INPUT: {preprocessed}")
        print(f"EMOTION SCORES FOR TEXT:")
        text_obj[0].printEmotions()
        print("LONG printStatistics string:")
        for i, sentence in enumerate(text_obj[0].sentences):
            print(f"Sentence {i}:")
            sentence.printStatistics()
        print("=SENTIMENT PER WORD=")
        for i, sentence in enumerate(text_obj[0].sentences):
            for j, word in enumerate(sentence.words):
                print(f"Sentence {i} word {j}: {word.word}/{word.rawWord} - {word.emotion} {word.emotionLevel}")

        print(MESSAGE_SEPARATOR)
    return confusion_matrix


def draw_confusion_matrix(confusion_matrix: List[List[int]]) -> None:
    print("\t\t0\t1\t-1")
    print("Expect 0:\t{}".format('\t'.join(map(str, confusion_matrix[0]))))
    print("Expect 1:\t{}".format('\t'.join(map(str, confusion_matrix[1]))))
    print("Expect -1:\t{}".format('\t'.join(map(str, confusion_matrix[-1]))))
    accuracy = sum([confusion_matrix[i][i] for i in range(3)]) / sum([sum(i) for i in confusion_matrix])
    print(f"Overall accuracy: {accuracy}")


if __name__ == "__main__":
    dataset = parse_dataset_file("sentiment_test_set.txt")
    parser = argparse.ArgumentParser()
    parser.add_argument("--neg-emoji-score", type=float)
    parser.add_argument("--neg-emotion-coeff", type=float)
    parser.add_argument("--neg-raw-emotion-coeff", type=float)
    parser.add_argument("--neutral-sentiment-threshold", type=float)
    conf_matrix = test(dataset, parser.parse_args())
    draw_confusion_matrix(conf_matrix)
