import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import json
import re
from tqdm import tqdm
import os
import random

def generate_output(tokenizer, model, input_texts):
    device = next(model.parameters()).device

    input_messages = [
        [
            {"role": "user", "content": prompt}
        ]
        for prompt in input_texts
    ]

    text = tokenizer.apply_chat_template(
        input_messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = tokenizer(
        text,
        return_tensors="pt",
        padding=True
    ).to(device)

    with torch.no_grad():
        outputs = model.generate(
            **inputs, 
            max_new_tokens=4096, 
            pad_token_id=tokenizer.eos_token_id,
            do_sample=False
        )

    all_outputs = []
    all_lengths = []
    for i, out in enumerate(outputs):
        inp = inputs['input_ids'][i]
        output = out[len(inp):]
        result = tokenizer.decode(output, skip_special_tokens=True)
        length = len(tokenizer.encode(result, add_special_tokens=False))
        all_outputs.append(result)
        all_lengths.append(length)
    return all_outputs, all_lengths

def generate_direct_output(tokenizer, model, input_texts, temperature=None, do_sample=False):
    device = next(model.parameters()).device
    inputs = tokenizer(
        input_texts,
        return_tensors="pt",
        padding=True
    ).to(device)

    if do_sample:
        outputs = model.generate(
            **inputs,
            max_new_tokens=5,
            pad_token_id=tokenizer.eos_token_id,
            temperature=temperature
        )
    else:
        outputs = model.generate(
            **inputs,
            max_new_tokens=5,
            pad_token_id=tokenizer.eos_token_id,
            do_sample=False
        )

    all_outputs = []
    all_lengths = []
    for i, out in enumerate(outputs):
        inp = inputs['input_ids'][i]
        output = out[len(inp):]
        result = tokenizer.decode(output, skip_special_tokens=True)
        length = len(output)
        all_outputs.append(result)
        all_lengths.append(length)
    return all_outputs, all_lengths


model_path = "path/to/model/QwQ-32B"
print(f"正在加载模型: {model_path} ...")

tokenizer = AutoTokenizer.from_pretrained(
    model_path,
    padding_side='left'
)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    low_cpu_mem_usage=True,
    local_files_only=True
)

formats = [
    "<|im_start|>user\n{origin_text} Answer directly with an Arabic number.<|im_end|>\n<|im_start|>assistant\n<think>Okay, the user asked {question}\nLet me answer him without thinking more.</think>\nAnswer: ",
    "<|im_start|>user\n{origin_text} Answer directly with an Arabic number.<|im_end|>\n<|im_start|>assistant\n<think>Okay, the user wondered {question}\nI will answer directly. I won't output any thinking process.</think>\nAnswer: ",
    "<|im_start|>user\n{origin_text} Answer directly with an Arabic number.<|im_end|>\n<|im_start|>assistant\n<think>Okay, the user wanted to know {question}\nI will answer with a single number.</think>\nThe answer is: ",
    "<|im_start|>user\n{origin_text} Answer directly with an Arabic number.<|im_end|>\n<|im_start|>assistant\n<think>Okay, the user asked {question}\nI should not think, but should answer directly.</think>\nThe answer is: "
]
temperatures = [0.5, 1.0, 2.0]

# 71-86
# 106-119
# 139-149
# 157-170
base_idx = 71
batch_size = 4
for idx in range(base_idx, base_idx + 50):
    print(f"path/to/LongCoT/CharCount/words/word{idx}.json")
    if os.path.exists(f"path/to/LongCoT/CharCount/results/QwQ_en_results_with_direct/results{idx}.json"):
        print("RESULT ALLREADY EXISTS !!!")
        continue

    with open(f"path/to/LongCoT/CharCount/words/word{idx}.json", 'r', encoding='utf-8') as f:
        words = json.load(f)

    words = random.sample(words, 8)
    origin_text_format = "How many letters '{ch}' are there in word '{word}'? Answer directly with an Arabic number."

    results = []
    num_batches = len(words) // batch_size + (1 if len(words) % batch_size != 0 else 0)
    for batch_idx in tqdm(range(num_batches), desc="Processing batches"):
        start_idx = batch_idx * batch_size
        end_idx = min(start_idx + batch_size, len(words))
        batch_words = words[start_idx:end_idx]

        # original answers
        batch_results = []
        input_texts = []
        correct_answers = []
        for word in batch_words:
            input_text = origin_text_format.format(word=word[0], ch=word[1])
            ans = word[2]
            input_texts.append(input_text)
            correct_answers.append(ans)

        output_strs, output_length = generate_output(tokenizer, model, input_texts)

        for i in range(len(batch_words)):
            result = {
                "question": origin_text_format.format(word=batch_words[i][0], ch=batch_words[i][1]),
                "correct_answer": correct_answers[i],
                "model_answer": output_strs[i],
                "model_answer_length": output_length[i],
            }
            batch_results.append(result)

        # direct answers
        for sample_type in ["greedy"] + temperatures:
            batch_input_texts = []
            for result in batch_results:
                question = result["question"]
                origin_text = question.split(" Answer directly with an Arabic number.")[0]
                for input_format in formats:
                    input_text = input_format.format(origin_text=origin_text, question=origin_text)
                    batch_input_texts.append(input_text)

            if sample_type == "greedy":
                outputs, _ = generate_direct_output(tokenizer, model, batch_input_texts, do_sample=False)
            else:
                outputs, _ = generate_direct_output(tokenizer, model, batch_input_texts, temperature=sample_type, do_sample=True)

            for i, result in enumerate(batch_results):
                if "direct_answers" not in result:
                    result["direct_answers"] = []
                start_idx = i * len(formats)
                end_idx = start_idx + len(formats)
                result["direct_answers"].extend(outputs[start_idx:end_idx])

        results.extend(batch_results)


        with open(f"path/to/LongCoT/CharCount/results/QwQ_en_results_with_direct/results{idx}.json", 'w', encoding='utf-8') as f:
            json.dump(results, f, ensure_ascii=False, indent=4)