import argparse
import torch
import os
import json
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, get_model_name_from_path
from torch.utils.data import Dataset, DataLoader

from PIL import Image
import math
import numpy as np
from pycocotools import mask as mask_utils
import torch.nn.functional as F
from collections import defaultdict

def annToRLE(segm, h, w):
    """
    Convert annotation which can be polygons, uncompressed RLE to RLE.
    :return: binary mask (numpy 2D array)
    """
    if type(segm) == list:
        # polygon -- a single object might consist of multiple parts
        # we merge all parts into one mask rle code
        rles = mask_utils.frPyObjects(segm, h, w)
        rle = mask_utils.merge(rles)
    elif type(segm['counts']) == list:
        # uncompressed RLE
        rle = mask_utils.frPyObjects(segm, h, w)
    else:
        # rle
        rle = segm
    return rle

def annToMask(ann, width, height):
    """
    Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
    :return: binary mask (numpy 2D array)
    """
    rle = annToRLE(ann, height, width)
    m = mask_utils.decode(rle)
    return m

def load_pixcv_annotations(annot_path: str):
    annotations = ["ADE20K/FinalSegmentations.json", "COCO/FinalSegmentations.json"]
    annotated_masks = defaultdict(list)
    for annotation_file in annotations:
        with open(os.path.join(annot_path, annotation_file), "r") as f:
            data = json.load(f)
            # print({k: len(v) for k, v in data.items()})
            img_id_to_filename = {i["id"]: i["file_name"] for i in data["images"]}
            for a in data["annotations"]:
                img_id = a["image_id"]
                annotated_masks[img_id_to_filename[img_id]].append(a["segmentation"])
    return annotated_masks

# Custom dataset class
class CustomDataset(Dataset):
    def __init__(self, questions, image_folder, tokenizer, image_processor, model_config, 
                 mask_folder=None, img_file_entry="image", prompt_entry="text"):
        self.questions = questions
        self.image_folder = image_folder
        self.tokenizer = tokenizer
        self.image_processor = image_processor
        self.model_config = model_config
        self.mask_folder = mask_folder
        self.img_file_entry = img_file_entry
        self.prompt_entry = prompt_entry

    def __getitem__(self, index):
        line = self.questions[index]
        image_file = line[self.img_file_entry]
        qs = line[self.prompt_entry]
        if self.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

        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()

        image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
        image_tensor = process_images([image], self.image_processor, self.model_config)[0]

        input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')

        if self.mask_folder is not None:
            ext = os.path.splitext(image_file)[1]
            mask_file = image_file.replace(ext,'.json')
            with open(os.path.join(self.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 {image_file}")
            sam_masks = torch.tensor(sam_masks)
        else:
            sam_masks = None
        return input_ids, image_tensor, image.size, sam_masks

    def __len__(self):
        return len(self.questions)


def collate_fn(batch):
    input_ids, image_tensors, image_sizes, sam_masks = zip(*batch)
    input_ids = torch.stack(input_ids, dim=0)
    image_tensors = torch.stack(image_tensors, dim=0)
    sam_masks = list(sam_masks) if sam_masks[0] is not None else None
    return input_ids, image_tensors, image_sizes, sam_masks

# DataLoader
def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, mask_folder=None, batch_size=1, num_workers=4):
    assert batch_size == 1, "batch_size must be 1"
    dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config, mask_folder=mask_folder)
    data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, collate_fn=collate_fn)
    return data_loader

def compute_focus(sam_masks: torch.Tensor, answer_mask_attentions: torch.Tensor, annotation_mask: torch.Tensor):
    sam_masks = sam_masks.cuda()
    answer_mask_attentions = answer_mask_attentions.cuda()
    annotation_mask = annotation_mask.cuda()
    if sam_masks[0].shape != annotation_mask.shape:
        w, h = annotation_mask.shape
        target_w, target_h = sam_masks[0].shape
        annotation_mask = annotation_mask.unsqueeze(0)
        if target_h == target_w: # sam_masks are padded
            if h < w:
                pad = (w - h) // 2
                annotation_mask = F.pad(annotation_mask, (0, 0, pad, w - h - pad), value=0)
            elif h > w:
                pad = (h - w) // 2
                annotation_mask = F.pad(annotation_mask, (pad, h - w - pad), value=0)
        annotation_mask = F.interpolate(annotation_mask.unsqueeze(0).float(), size=[target_w, target_h], mode='bilinear').squeeze(0,1) > 0.25

    overlap = torch.logical_and(sam_masks, annotation_mask).sum(dim=(1, 2))
    threshold = sam_masks.sum(dim=(1, 2)) * 0.25
    focus = answer_mask_attentions[overlap >= threshold].sum()
    # distributed_attention = sam_masks * (answer_mask_attentions / sam_masks.sum(dim=(1, 2))).view(-1, 1, 1)
    # distributed_attention = distributed_attention.sum(dim=0)
    # focus = (distributed_attention * annotation_mask).sum()
    return focus.item()


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)
    tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
    if not ('region-llava' in model_name.lower() or 'Rllava' in model_name or 'Cllava' in model_name):
        args.mask_folder = None

    questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
    annotated_masks = load_pixcv_annotations(args.annot_folder) if args.annot_folder else {}
    questions = [q for q in questions if q["source_filename"].split('/')[-1] in annotated_masks.keys()]
    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}.')

    data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config, mask_folder=args.mask_folder)

    cnt = 0
    all_focuses = []
    all_ntokens = []
    for (input_ids, image_tensor, image_sizes, sam_masks), line in tqdm(zip(data_loader, questions), total=len(questions)):
        idx = line["question_id"]
        cur_prompt = line["text"]
        answer = line["answer"].strip("()")
        source_filename = line["source_filename"]
        annotation = annotated_masks[source_filename]
        if len(annotation) == 0:
            # print(f"No annotation found for {source_filename}")
            continue
        _w,_h = image_sizes[0]
        annotation_masks = [annToMask(ann, _w, _h) for ann in annotation]
        annotation_mask = torch.any(torch.tensor(annotation_masks), dim=0)

        input_ids = input_ids.to(device='cuda', non_blocking=True)
        answer_ids = tokenizer(answer + tokenizer.eos_token, return_tensors='pt', add_special_tokens=False).input_ids.to(device='cuda', non_blocking=True)

        with torch.inference_mode():
            # input_args = dict(
            #     images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
            #     image_sizes=image_sizes,
            #     do_sample=True if args.temperature > 0 else False,
            #     temperature=args.temperature if args.temperature > 0 else None,
            #     top_p=args.top_p,
            #     num_beams=args.num_beams,
            #     max_new_tokens=args.max_new_tokens,
            #     use_cache=True
            # )
            # if sam_masks is not None:
            #     input_args["sam_masks"] = [m.to(device='cuda', non_blocking=True) for m in sam_masks]
            # output_ids = model.generate(input_ids, **input_args)
            output_ids = answer_ids

            all_ids = torch.cat([input_ids, output_ids], dim=1)
            all_args = dict(
                output_attentions = True,
                images=image_tensor.half().cuda(),
                image_sizes=image_sizes,
            )
            if args.mask_folder is not None:
                all_args["sam_masks"] = [m.to(device='cuda', non_blocking=True) for m in sam_masks]
                all_args["return_masks"] = True
            all_outputs = model.forward(all_ids, **all_args)
            if args.mask_folder is not None:
                visual_features, _m, nonzero_masks = model._cached_masks
                model._cached_masks = None
                visual_features = visual_features[0]
                nonzero_masks = nonzero_masks[0]
            else:
                visual_features = model.encode_images(image_tensor.half().cuda())[0]

        if args.mask_folder is not None and model.region_source == "passed":
            image = Image.open(os.path.join(args.image_folder, line["image"])).convert('RGB')
            img = np.array(image)
            white_img = np.ones_like(img) * 255
            sam_masks = model.sort_regions(sam_masks[0])
            sam_masks = model.add_extra_regions(sam_masks)
            sam_masks = model.filter_regions(sam_masks)
            assert sam_masks.shape[0] == nonzero_masks.shape[0]
            sam_masks = sam_masks[nonzero_masks.cpu()]
        else:
            img = image_tensor[0].permute(1,2,0).float()
            img = (img-img.min())/(img.max()-img.min()) * 255
            img = img.cpu().numpy().astype(np.uint8)
            pps = model.get_vision_tower().num_patches_per_side
            if args.mask_folder is not None and (model.region_source == "clustering" or model.region_source.startswith("split")):
                sam_masks = _m[0][nonzero_masks].to(device="cpu", dtype=torch.uint8)
            else:
                sam_masks = torch.eye(pps**2, dtype=torch.uint8).view(-1, pps, pps)
            patch_size = model.get_vision_tower().config.patch_size
            h, w = image_tensor.shape[-2:]
            sam_masks = F.interpolate(sam_masks.unsqueeze(0), scale_factor=patch_size, mode='nearest').squeeze(0)
            sam_masks = F.pad(sam_masks, (0, h-pps*patch_size, 0, w-pps*patch_size), mode='constant', value=0)
        img_token_pos = torch.where(all_ids[0] == IMAGE_TOKEN_INDEX)[0][0]
        num_special_tokens = 1*("cls" in model.get_vision_tower().select_feature) + 4*("reg" in model.get_vision_tower().select_feature)
        if "sum" in model.get_vision_tower().select_feature:
            num_special_tokens += model.get_vision_tower().config.summary_len
        img_token_pos += num_special_tokens
        all_attentions = torch.stack(all_outputs['attentions'], dim=0)
        avg_attentions = all_attentions.view(-1, all_attentions.shape[-2], all_attentions.shape[-1]).mean(dim=0)
        answer_mask_attentions = avg_attentions[-output_ids.shape[1]-1:-1,img_token_pos:img_token_pos+len(sam_masks)]
        assert all_ids.shape[1] - 1 + len(sam_masks) + num_special_tokens == avg_attentions.shape[0]
        sid = 1 if args.mask_folder is not None and 'global' in model.region_extra else 0
        answer_mask_attentions = answer_mask_attentions[0].float().cpu()
        answer_mask_attentions_reweighted = answer_mask_attentions / answer_mask_attentions[sid:].sum()
        focus = compute_focus(sam_masks[sid:], answer_mask_attentions_reweighted[sid:], annotation_mask)
        all_focuses.append(focus)
        all_ntokens.append(len(sam_masks[sid:]))

    print(f"Average focus(percentage): {sum(all_focuses) / len(all_focuses) * 100:.2f}")
    print(f"Average number of tokens: {sum(all_ntokens) / len(all_ntokens):.2f}")
    ans_file.write(json.dumps({
        "ntokens": sum(all_ntokens) / len(all_ntokens),
        "focus": sum(all_focuses) / len(all_focuses) * 100,
    }) + "\n")
    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("--image-folder", type=str, default="")
    parser.add_argument("--mask-folder", type=str, default=None)
    parser.add_argument("--annot-folder", type=str, default=None)
    parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
    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("--max_new_tokens", type=int, default=128)
    args = parser.parse_args()

    eval_model(args)
