from langchain.chat_models import ChatOpenAI
from api_key import *
from output_parser import CharacterMappingParser
from encoding_method import caesar_encrypt
from langchain.prompts.chat import SystemMessagePromptTemplate, ChatPromptTemplate
from langchain import LLMChain
from langchain.llms import OpenAI
from utlis import alphabet_position, get_prompt
from data_creator import CharacterMappingDataCreator
from prompt_template_class import CharacterMappingGenerator
from tqdm import tqdm
import argparse
from utlis import str2bool
import random
import numpy as np
from utlis import load_llama, get_prompt, B_INST, E_INST
from langchain.prompts import PromptTemplate

parser = argparse.ArgumentParser()
parser.add_argument("--num_examples", type=int, default=200)
parser.add_argument("--model_name", type=str, default="text-davinci-003")
parser.add_argument("--few_shot", type=str2bool, default=True)
parser.add_argument("--cot", type=str2bool, default=False)
parser.add_argument("--multiple_run", type=str2bool, default=False)
args = parser.parse_args()
print(args)
# 0.5 0.2 0.2 False False
# 1.0 0.4333 0.4 True False
#0.8667 0.2667 0.2667 True True
num_examples = args.num_examples
output_parser = CharacterMappingParser()
meta_validation_acc = []
meta_full_acc = []
meta_average_acc = []
if "gpt-3.5" in args.model_name or "gpt-4" in args.model_name:
    llm = ChatOpenAI(model=args.model_name, openai_api_key=openai.api_key, temperature=0)
elif "llama" in args.model_name:
    args.model_name = "meta-llama/Llama-2-13b-chat-hf"
    llm = load_llama(args.model_name)
else:
    llm = OpenAI(model=args.model_name, openai_api_key=openai.api_key, temperature=0)
seed_list = [714, 123] if args.multiple_run == True else [714]
for seed in seed_list:
    random.seed(seed)
    data_creator = CharacterMappingDataCreator(dataset="app_reviews", num_examples=num_examples)
    mapping_prompt = CharacterMappingGenerator()
    data_sample, fewshot_sample = data_creator.create()
    mapping_table = data_creator.generatele_mapping_table(shift=3, reveal=26)
    few_shot = data_creator.random_rule_noise(mapping_table, [x[0] for x in fewshot_sample], determinstic=True)
    all_data = data_creator.random_rule_noise(mapping_table, [x[0] for x in data_sample])
    result = []
    prediction = []
    data_sample = []
    fewshot_sample = []
    for idx, example in enumerate(all_data):
        all_data[idx].append(caesar_encrypt(example[1], 3))
    for shot in few_shot:
        shot.append(caesar_encrypt(shot[1], 3))
        fewshot_sample.append(shot)
    validation_correct_count = 0
    explanation_count = 0
    explanation_correct_count = 0
    full_explanation_count = 0
    full_correct_count = 0
    acc_list = []
    all_prompt = mapping_prompt.rule_error_rectifying_template(mapping_table, fewshot_sample, data_creator,
                                                               chain_of_thought=args.cot,
                                                               few_shot=args.few_shot)
    chat_prompt = ChatPromptTemplate.from_messages(all_prompt)
    if "gpt" in args.model_name or "davincii" in args.model_name:
        chain = LLMChain(llm=llm, prompt=chat_prompt)
    else:
        system = ""
        system += chat_prompt.messages[0].format().content
        instruction = ""
        example_idx = 0
        if len(chat_prompt.messages) > 2:
            for message in chat_prompt.messages[1:-1]:
                if message.additional_kwargs["name"] == "example_user":
                    if example_idx == 0:
                        instruction += message.format().content + " " + E_INST + " "
                    else:
                        instruction += "<s>" + B_INST + " " +message.format().content + " " +E_INST + " "
                    example_idx += 1
                elif message.additional_kwargs["name"] == "example_assistant":
                    instruction += message.format().content + " " + "</s>\\"+ "\n"
        system += "Additionally, please just output the answer with provided format and don't add any other explanation."
        instruction += chat_prompt.messages[-1].format(Original="{Original}", Altered="{Altered}", Rules="{Rules}").content
        template = get_prompt(instruction, system)
        prompt = PromptTemplate(template=template, input_variables=["Original", "Altered", "Rules"])
        chain = LLMChain(prompt=prompt, llm=llm)
    for wrong_rule, ori, wrong_rule_indic, alt in tqdm(all_data):
        output = chain.run(Original=ori, Altered=alt, Rules=data_creator.mappingtable2text(wrong_rule))
        print(output)
        predicts, results = output_parser.parse_error_correction(output)
        local_correct_count = 0
        if wrong_rule_indic == True:
            explanation_count += 2
            full_explanation_count += 1
        if predicts == "Yes" and wrong_rule_indic == False:
            validation_correct_count += 1
        elif predicts == "No" and wrong_rule_indic == True:
            validation_correct_count += 1
            mis_matched_count = len(set([(x["Original"], x["Altered"]) for x in wrong_rule]) - set([(x["Original"], x["Altered"]) for x in mapping_table]))
            for result in results:
                fixed_ori, fixed_alt = result[0], result[1]
                if fixed_ori.isalpha() == True:
                    if mapping_table[alphabet_position(fixed_ori)]["Altered"] == fixed_alt.upper() and \
                            wrong_rule[alphabet_position(fixed_ori)]["Altered"] !=  \
                            mapping_table[alphabet_position(fixed_ori)]["Altered"]:
                        local_correct_count += 1
                        explanation_correct_count += 1
                    wrong_rule[alphabet_position(fixed_ori)]["Altered"] = fixed_alt.upper()
            acc_list.append([local_correct_count / mis_matched_count, output])
        if wrong_rule == mapping_table and wrong_rule_indic == True:
            full_correct_count += 1
    print(f"Validation Accuracy: {validation_correct_count / num_examples}")
    print(f"Average Partial Accuracy: {explanation_correct_count / explanation_count}")
    print(f"Full Explanation Accuracy: {full_correct_count / full_explanation_count}")
    print(f"---------------")
    meta_validation_acc.append(validation_correct_count / num_examples)
    meta_average_acc.append(explanation_correct_count / explanation_count)
    meta_full_acc.append(full_correct_count / full_explanation_count)
for idx, validation_acc, average_acc, full_acc in zip(seed_list, meta_validation_acc, meta_average_acc, meta_full_acc):
    print(f"Validation Accuracy: {validation_acc}")
    print(f"Explanation Accuracy: {average_acc}")
    print(f"Full Explanation Accuracy: {full_acc}")
    print(f"------Seed {idx}------")
print(f"Meta Validation Accuracy: {sum(meta_validation_acc) / len(meta_validation_acc)}")
print(f"STD of Validation Accuracy: {np.std(meta_validation_acc)}")
print(f"Meta Average Partial Accuracy: {sum(meta_average_acc) / len(meta_average_acc)}")
print(f"STD of Average Partial Accuracy: {np.std(meta_average_acc)}")
print(f"Meta Full Explanation Accuracy: {sum(meta_full_acc) / len(meta_full_acc)}")
print(f"STD of Full Explanation Accuracy: {np.std(meta_full_acc)}")



