from langchain.chat_models import ChatOpenAI
from api_key import *
from output_parser import CharacterMappingParser
from encoding_method import caesar_encrypt
from utlis import few_shot_rule_incorporation, alphabet_position
from langchain.prompts.chat import SystemMessagePromptTemplate, ChatPromptTemplate
from langchain import LLMChain
from langchain.llms import OpenAI
from data_creator import CharacterMappingDataCreator
from prompt_template_class import CharacterMappingGenerator
import argparse
from utlis import str2bool
from tqdm import tqdm
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=True)
args = parser.parse_args()
print(args)
#0.33 0.9 0.36
#0.37 0.24 0.
#
num_examples = args.num_examples
output_parser = CharacterMappingParser()
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)
meta_validation_acc = []
meta_average_acc = []
meta_full_acc = []
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()
    rules = data_creator.generatele_mapping_table(shift=3, reveal=26)
    few_shot = few_shot_rule_incorporation(rules, [x[0] for x in fewshot_sample], determinstic=True)
    all_data = few_shot_rule_incorporation(rules, [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[2], 3))
    for shot in few_shot:
        shot.append(caesar_encrypt(shot[2], 3))
        fewshot_sample.append(shot)

    validation_correct_count = 0
    matched_discover = 0
    total_discover = 0
    full_correct_count = 0
    full_explanation_count = 0
    whole_discover_count = 0
    acc_list = []
    all_prompt = mapping_prompt.rule_incorporating_template(rules, 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 "davinci" 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 incompelete_rule, added_char, ori, incompelete_rule_indic, alt in tqdm(all_data):
        output = chain.run(Original=ori, Altered=alt, Rules=data_creator.mappingtable2text(incompelete_rule))
        print(output)
        predicts, pred_rules = output_parser.parser_incorporating(output)
        whole_discover_count += len(added_char)
        pred_rules = list(set(pred_rules))
        if incompelete_rule_indic == True:
            full_explanation_count += 1
            total_discover += len(added_char)
        if incompelete_rule_indic == True and predicts == "Yes":
            validation_correct_count += 1
            added_ori = [rule[0].lower() for rule in pred_rules]
            local_correct = sum([char in added_ori for char in added_char])
            if local_correct == len(added_char):
                full_correct_count += 1
            matched_discover += local_correct
            acc_list.append([local_correct / len(added_char), predicts, added_char, added_ori])
        elif incompelete_rule_indic != True and predicts == "No":
            validation_correct_count += 1
    print(f"Validation Accuracy: {validation_correct_count / num_examples}")
    print(f"Averaged Accuracy: { matched_discover / total_discover}")
    print(f"Full Accuracy: {full_correct_count / full_explanation_count}")
    print(f"---------------")
    meta_validation_acc.append(validation_correct_count / num_examples)
    meta_average_acc.append(matched_discover / total_discover)
    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 Averaged Accuracy: {sum(meta_average_acc) / len(meta_average_acc)}")
print(f"STD of Averaged Accuracy: {np.std(meta_average_acc)}")
print(f"Meta Full Accuracy: {sum(meta_full_acc) / len(meta_full_acc)}")
print(f"STD of Full Accuracy: {np.std(meta_full_acc)}")


