from encoding_method import colors
from tqdm import tqdm
from prompt_template_class import OrderingGenerator
from langchain.prompts.chat import SystemMessagePromptTemplate, ChatPromptTemplate, PromptTemplate
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
from api_key import *
from output_parser import OrderingOutputParser
from data_creator import OrderingDataCreator
import argparse
from utlis import str2bool, load_llama
import random
import numpy as np
from utlis import load_llama, get_prompt
from langchain.prompts import PromptTemplate
from utlis import load_llama, get_prompt, B_INST, E_INST

parser = argparse.ArgumentParser()
parser.add_argument("--num_examples", type=int, default=10)
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.52 0.57 False False
#0.6 0.662 True True
#0.64 0.814 True False
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)
parser = OrderingOutputParser()
meta_full_acc = []
meta_average_acc = []
parser = OrderingOutputParser()
meta_full_acc = []
meta_average_acc = []
seed_list = [714, 123] if args.multiple_run == True else [714]
for seed in seed_list:
    random.seed(seed)
    ordering_creator = OrderingDataCreator(colors[:20])
    prioritys, examples, unsorted_example, explanations = ordering_creator.create_normal(num_examples=args.num_examples,
                                                                                  repeat=True,
                                                                                  repeat_num=5,
                                                                                  missing=True,
                                                                                  missing_num=5)
    few_shot_prioritys, prioritys = prioritys[:5], prioritys[5:]
    few_shot_examples, examples = examples[:5], examples[5:]
    few_shot_unsorted_examples, unsorted_examples = unsorted_example[:5], unsorted_example[5:]
    few_shot_explanations, explanations = explanations[:5], explanations[5:]

    prompt_generator = OrderingGenerator()

    acc_list = []
    full_correct = 0
    all_prompt = prompt_generator.ordering_instruction(few_shot_examples, few_shot_unsorted_examples, few_shot_prioritys,
                                                       model_name=args.model_name, 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(colors=str(colors[:20])).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(color_preference="{color_preference}",
                                                       UnOrderedLists="{UnOrderedLists}",
                                                       ).content
        template = get_prompt(instruction, system)
        prompt = PromptTemplate(template=template,
                                input_variables=["color_preference", "UnOrderedLists"])
        chain = LLMChain(prompt=prompt, llm=llm)
    for priority, example, unsorted_example, explanation in tqdm(zip(prioritys, examples, unsorted_examples, explanations)):
        sorted_rules = sorted(priority.items(), key=lambda x: x[1])
        color_preference = ""
        for color_rank in sorted_rules:
            color_preference += f"Rank {str(color_rank[1])}: {color_rank[0]}\n"
        example_text = str(unsorted_example[0])
        if "gpt" in args.model_name or "davinci" in args.model_name:
            output = chain.run(colors=str(colors[:20]), color_preference=color_preference, UnOrderedLists=example_text)
        else:
            output = chain.run(color_preference=color_preference, UnOrderedLists=example_text)
        print(output)
        sorted_prio = parser.parse_instruction(output)
        sorted_result = sorted(unsorted_example[0], key=priority.get)
        partial_count = 0
        for pred, gold in zip(sorted_prio, sorted_result):
            if pred == gold:
                partial_count += 1
        partial_acc = partial_count/len(unsorted_example[0])
        if partial_acc == 1:
            full_correct += 1
        acc_list.append([partial_acc, sorted_prio, priority])
    print(f"Full Accuracy: {full_correct/len(prioritys)}")
    print(f"Average: {sum([x[0] for x in acc_list])/len(acc_list)}")
    print(f"---------------")
    meta_full_acc.append(full_correct/len(prioritys))
    meta_average_acc.append(sum([x[0] for x in acc_list])/len(acc_list))
for idx, average_acc, full_acc in zip(seed_list, meta_average_acc, meta_full_acc):
    print(f"Explanation Accuracy: {average_acc}")
    print(f"Full Explanation Accuracy: {full_acc}")
    print(f"------Seed {idx}------")
print(f"Meta Full Accuracy: {sum(meta_full_acc)/len(meta_full_acc)}")
print(f"STD of Full Accuracy: {np.std(meta_full_acc)}")
print(f"Meta Average: {sum(meta_average_acc)/len(meta_average_acc)}")
print(f"STD of Average: {np.std(meta_average_acc)}")