from langchain.chat_models import ChatOpenAI
from api_key import *
from output_parser import CharacterMappingParser
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
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=True)
args = parser.parse_args()
print(args)
#0.0 683 False False
#0.0 683 True False
#0.0 0.686 True True
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)
output_parser = CharacterMappingParser()
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=args.num_examples)
    mapping_prompt = CharacterMappingGenerator()
    data_sample, fewshot_sample = data_creator.create()
    full_mapping_table = data_creator.generatele_mapping_table(shift=3, reveal=26)
    few_shot_inducting_table = data_creator.create_inducting_example(full_mapping_table, fewshot_sample)
    inducting_tables = data_creator.create_inducting_example(full_mapping_table, data_sample)

    correct_count = 0
    total_count = 0
    full_correct_count = 0
    acc = []
    all_prompt = mapping_prompt.inducting_template([x[0] for x in fewshot_sample], [x[1] for x in fewshot_sample],
                                                   full_mapping_table, few_shot_inducting_table, 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}").content
        template = get_prompt(instruction, system)
        prompt = PromptTemplate(template=template, input_variables=["Original", "Altered"])
        chain = LLMChain(prompt=prompt, llm=llm)
    for (ori, alt), induct_table in tqdm(zip(data_sample, inducting_tables)):
        output = chain.run(Original=ori, Altered=alt)
        print(output)
        results = output_parser.parse_inducting(output)
        gold = []
        correct_count = 0
        for pair in induct_table:
            gold.append((pair["Original"], pair["Altered"]))
        if set(results) == set(gold):
            full_correct_count += 1
        for pair in results:
            if pair in gold:
                correct_count += 1
        acc.append([correct_count / len(induct_table), results, gold])
    print(f"Average Acc: {sum([x[0] for x in acc]) / len(acc)}")
    print(f"Full Accuracy: {full_correct_count / len(data_sample)}")
    print(f"---------------")
    meta_average_acc.append(sum([x[0] for x in acc]) / len(acc))
    meta_full_acc.append(full_correct_count / len(data_sample))
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 Average Acc: {sum(meta_average_acc) / len(meta_average_acc)}")
print(f"STD of Average Acc: {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)}")



