from encoding_method import colors
from tqdm import tqdm
from prompt_template_class import OrderingGenerator
from langchain.prompts.chat import SystemMessagePromptTemplate, ChatPromptTemplate
from langchain import LLMChain
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from api_key import *
from output_parser import OrderingOutputParser
from data_creator import OrderingDataCreator
import argparse
from utlis import str2bool
import random
import numpy as np
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=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.278 0.04
#0.48 0.28
#0.276 0.04


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_average_acc = []
meta_full_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_inducting(
        num_examples=args.num_examples, num_partitions=5)
    prompt_generator = OrderingGenerator()
    few_shot_prioritys, prioritys = prioritys[:2], prioritys[5:]
    few_shot_examples, examples = examples[:2], examples[5:]
    few_shot_explanations, explanations = explanations[:2], explanations[5:]
    full_correct = 0
    acc_list = []
    all_prompt = prompt_generator.ordering_induction(few_shot_examples, few_shot_explanations, few_shot_prioritys,
                                                     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(OrderedLists="{OrderedLists}",).content
        template = get_prompt(instruction, system)
        prompt = PromptTemplate(template=template,
                                input_variables=["OrderedLists"])
        chain = LLMChain(prompt=prompt, llm=llm)
    for priority, example, explanation in tqdm(zip(prioritys, examples, explanations)):
        example_text = ""
        for idx, sub_example in enumerate(example):
            example_text += "Ordered Color List " + str(idx) + " : " + str(sub_example) + "\n"
        if "gpt" in args.model_name or "davinci" in args.model_name:
            output = chain.run(colors=str(colors[:20]), OrderedLists=example_text)
        else:
            output = chain.run(OrderedLists=example_text)
        print(output)
        result = parser.parse_inducting(output)
        sorted_prio = sorted(result, key=result.get)
        sorted_result = sorted(priority, 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(priority)
        if partial_acc == 1:
            full_correct += 1
        acc_list.append([partial_acc, output, priority])
    print("Average Partial Accuracy: ", sum([x[0] for x in acc_list])/len(acc_list))
    print("Full Accuracy: ", full_correct/len(acc_list))
    print(f"---------------")
    meta_full_acc.append(full_correct/len(acc_list))
    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("Meta Full Accuracy: ", sum(meta_full_acc)/len(meta_full_acc))
print("STD of Full Accuracy: ", np.std(meta_full_acc))
print("Meta Average Accuracy: ", sum(meta_average_acc)/len(meta_average_acc))
print("STD of Average Accuracy: ", np.std(meta_average_acc))