import argparse
import torch
import os
import json
from datasets import load_dataset
from tqdm import tqdm
import shortuuid

from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path

from PIL import Image
import math
import numpy as np
from pycocotools import mask as mask_utils



def eval_model(args):
    # Model
    disable_torch_init()
    model_path = os.path.expanduser(args.model_path)
    model_name = get_model_name_from_path(model_path)
    model_kwargs = json.loads(args.model_kwargs) if args.model_kwargs else {}
    tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, **model_kwargs)

    questions = load_dataset("Lin-Chen/MMStar", "val")["val"]
    answers_file = os.path.expanduser(args.answers_file)
    os.makedirs(os.path.dirname(answers_file), exist_ok=True)
    ans_file = open(answers_file, "w")

    if 'qwen3' in model_name.lower():
        args.conv_mode = 'qwen3'
        print(f'It seems that this is a qwen3 model, auto switching to {args.conv_mode}.')
    if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
        args.conv_mode = args.conv_mode + '_mmtag'
        print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')

    for row in tqdm(questions, total=len(questions)):
        idx = row['index']
        question = row['question']
        image = row['image']
        if image.mode != 'RGB':
            image = image.convert('RGB')
        if args.mask_folder is not None:
            mask_file = f"{idx}.json"
            with open(os.path.join(args.mask_folder, mask_file), "r") as f:
                sam_masks = json.load(f)
            if len(sam_masks) > 0:
                sam_masks = mask_utils.decode([m["segmentation"] for m in sam_masks])
                sam_masks = np.moveaxis(sam_masks, -1, 0)
            else:
                sam_masks = np.zeros((0, 1, 1), dtype=np.uint8)
            if sam_masks.shape[0] == 0:
                print(f"No mask found for {idx}")
            sam_masks = torch.tensor(sam_masks)

        qs = cur_prompt = question
        if model.config.mm_use_im_start_end:
            qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
        else:
            qs = DEFAULT_IMAGE_TOKEN + '\n' + qs

        if args.single_pred_prompt:
            qs = qs + '\n' + "Answer with the option's letter from the given choices directly."

        conv = conv_templates[args.conv_mode].copy()
        conv.append_message(conv.roles[0], qs)
        conv.append_message(conv.roles[1], None)
        prompt = conv.get_prompt()

        input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()

        image_tensor = process_images([image], image_processor, model.config)[0]

        with torch.inference_mode():
            input_args = dict(
                images=image_tensor.unsqueeze(0).half().cuda(),
                image_sizes=[image.size],
                do_sample=args.temperature > 0,
                temperature=args.temperature if args.temperature > 0 else None,
                top_p=args.top_p,
                num_beams=args.num_beams,
                # no_repeat_ngram_size=3,
                max_new_tokens=32,
                use_cache=True
            )
            if args.mask_folder is not None:
                input_args["sam_masks"] = [sam_masks.to(device='cuda', non_blocking=True)]
            
            output_ids = model.generate(input_ids, **input_args)

        outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()

        ans_id = shortuuid.uuid()
        ans_file.write(json.dumps({"question_id": idx,
                                    "prompt": cur_prompt,
                                    "text": outputs,
                                    "answer_id": ans_id,
                                    "model_id": model_name,
                                    "metadata": {}}) + "\n")
        ans_file.flush()
    ans_file.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
    parser.add_argument("--model-base", type=str, default=None)
    parser.add_argument("--model-kwargs", type=str, default=None)
    parser.add_argument("--image-folder", type=str, default="")
    parser.add_argument("--mask-folder", type=str, default=None)
    parser.add_argument("--answers-file", type=str, default="answer.jsonl")
    parser.add_argument("--conv-mode", type=str, default="llava_v1")
    parser.add_argument("--temperature", type=float, default=0.2)
    parser.add_argument("--top_p", type=float, default=None)
    parser.add_argument("--num_beams", type=int, default=1)
    parser.add_argument("--single-pred-prompt", action="store_true")
    args = parser.parse_args()

    eval_model(args)
