import torch
import torch.nn as nn
from functools import partial
import inspect

from transformers import AutoModel, AutoImageProcessor, AutoConfig, PreTrainedModel, BaseImageProcessor, PretrainedConfig
from huggingface_hub import repo_exists

def set_size(size, new_size:int):
    if isinstance(size, int):
        size = new_size
    elif isinstance(size, tuple):
        size = (new_size, ) * len(size)
    elif isinstance(size, dict):
        for k in size.keys():
            size[k] = new_size
    else:
        raise ValueError(f'Unexpected size type: {type(size)}')

def get_size(size):
    if isinstance(size, int):
        return size
    elif isinstance(size, tuple):
        return size[0]
    elif isinstance(size, dict):
        for k in size.keys():
            return size[k]
    else:
        raise ValueError(f'Unexpected size type: {type(size)}')

def has_arg(func, arg_name):
    """
    Return True if `func` can receive `arg_name` as a keyword argument,
    either explicitly or via **kwargs. Otherwise, return False.
    """
    sig = inspect.signature(func)
    
    for param in sig.parameters.values():
        # If there's a parameter named exactly `arg_name`
        if param.name == arg_name:
            return True
        
        # If there's a **kwargs parameter, it can accept any keyword
        if param.kind == param.VAR_KEYWORD:  # i.e. **kwargs
            return True
    
    return False

class GeneralVisionTower(nn.Module):
    def __init__(self, vision_tower, args, delay_load=False, loader=(AutoModel, AutoImageProcessor, AutoConfig)):
        super().__init__()

        self.is_loaded = False

        self.vision_tower_name = vision_tower
        self.select_layer = args.mm_vision_select_layer
        self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
        self.model_loader: PreTrainedModel = loader[0]
        self.image_processor_loader: BaseImageProcessor = loader[1]
        self.config_loader: PretrainedConfig = loader[2]
        self.force_image_size = args.mm_force_imsize if hasattr(args, 'mm_force_imsize') else None

        if not delay_load:
            self.load_model()
        elif getattr(args, 'unfreeze_mm_vision_tower', False):
            self.load_model()
        elif repo_exists(self.vision_tower_name):
            self.cfg_only = self.config_loader.from_pretrained(self.vision_tower_name, trust_remote_code=True)

    def set_imsize(self, imsize:int):
        if self.vision_tower.config.image_size == imsize:
            print(f'Image size is already {imsize}, skipping.')
            return
        self.vision_tower.config.image_size = imsize
        if hasattr(self.image_processor, 'crop_size'):
            if hasattr(self.image_processor, 'size'):
                set_size(self.image_processor.crop_size, get_size(self.image_processor.crop_size)*imsize // get_size(self.image_processor.size))
            else:
                set_size(self.image_processor.crop_size, imsize)
        if hasattr(self.image_processor, 'size'):
            set_size(self.image_processor.size, imsize)
        if has_arg(self.vision_tower.forward, 'interpolate_pos_encoding'):
            self.vision_tower.forward = partial(self.vision_tower.forward, interpolate_pos_encoding=True)

    def load_model(self, device_map=None):
        if self.is_loaded:
            print('{} is already loaded, `load_model` called again, skipping.'.format(self.vision_tower_name))
            return

        self.image_processor = self.image_processor_loader.from_pretrained(self.vision_tower_name, trust_remote_code=True)
        self.vision_tower = self.model_loader.from_pretrained(self.vision_tower_name, device_map=device_map, trust_remote_code=True)
        self.vision_tower.requires_grad_(False)
        if self.force_image_size is not None:
            self.set_imsize(self.force_image_size)

        self.is_loaded = True

    def feature_select(self, image_forward_outs):
        image_features = image_forward_outs.hidden_states[self.select_layer]
        if self.select_feature == 'all':
            image_features = image_features
        else:
            raise ValueError(f'Unexpected select feature: {self.select_feature}')
        return image_features

    @torch.no_grad()
    def forward(self, images):
        if type(images) is list:
            image_features = []
            for image in images:
                image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
                image_feature = self.feature_select(image_forward_out).to(image.dtype)
                image_features.append(image_feature)
        else:
            image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
            image_features = self.feature_select(image_forward_outs).to(images.dtype)

        return image_features

    @property
    def dummy_feature(self):
        return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)

    @property
    def dtype(self):
        return self.vision_tower.dtype

    @property
    def device(self):
        return self.vision_tower.device

    @property
    def config(self):
        if self.is_loaded:
            return self.vision_tower.config
        else:
            return self.cfg_only

    @property
    def hidden_size(self):
        return self.config.hidden_size

    @property
    def num_patches_per_side(self):
        return self.config.image_size // self.config.patch_size

    @property
    def num_patches(self):
        return (self.config.image_size // self.config.patch_size) ** 2

