import argparse
import torch
import requests
import math
from io import BytesIO
from PIL import Image
from transformers import TextStreamer

# Anonymized internal imports
from my_project.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from my_project.conversation import conv_templates, SeparatorStyle
from my_project.model.builder import load_pretrained_model
from my_project.utils import disable_torch_init
from my_project.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria


def load_image(image_file):
    if image_file.startswith('http://') or image_file.startswith('https://'):
        response = requests.get(image_file)
        image = Image.open(BytesIO(response.content)).convert('RGB')
    else:
        image = Image.open(image_file).convert('RGB')
    return image


def main(args):
    # Model Initialization
    disable_torch_init()
    model_name = get_model_name_from_path(args.model_path)
    tokenizer, model, image_processor, context_len = load_pretrained_model(
        args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)

    # Set conversation mode
    if args.conv_mode is None:
        if 'llama-2' in model_name.lower():
            args.conv_mode = "my_project_llama_2" # Assuming you have a custom llama2 conv template
        elif "v1" in model_name.lower():
            args.conv_mode = "my_project_v1"
        elif "mpt" in model_name.lower():
            args.conv_mode = "mpt"
        else:
            args.conv_mode = "my_project_v0"
    
    conv = conv_templates[args.conv_mode].copy()
    roles = conv.roles

    # Load and process image
    image = load_image(args.image_file)
    image_tensor = process_images([image], image_processor, model.config)
    if isinstance(image_tensor, list):
        image_tensor = [img.to(model.device, dtype=torch.float16) for img in image_tensor]
    else:
        image_tensor = image_tensor.to(model.device, dtype=torch.float16)

    # Main conversation loop
    while True:
        try:
            inp = input(f"{roles[0]}: ")
        except EOFError:
            inp = ""
        if not inp:
            print("exit...")
            break

        print(f"{roles[1]}: ", end="")

        if image is not None:
            # First message with image
            if getattr(model.config, 'mm_use_im_start_end', False):
                inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
            else:
                inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
            conv.append_message(conv.roles[0], inp)
            image = None  # Use image only once
        else:
            # Subsequent messages
            conv.append_message(conv.roles[0], inp)
        
        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).to(args.device)
        
        stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
        keywords = [stop_str]
        stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
        streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)

        with torch.inference_mode():
            output_ids = model.generate(
                input_ids,
                images=image_tensor,
                do_sample=True if args.temperature > 0 else False,
                temperature=args.temperature,
                max_new_tokens=args.max_new_tokens,
                streamer=streamer,
                use_cache=True,
                stopping_criteria=[stopping_criteria])

        # Manually decode to handle the case where the streamer is not fully flushed
        outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
        conv.messages[-1][-1] = outputs

        # The output is already printed by the streamer, so we just add a newline
        print()

        if args.debug:
            print("\n", {"prompt": prompt, "outputs": outputs}, "\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-path", type=str, required=True, help="Path to the model checkpoint.")
    parser.add_argument("--model-base", type=str, default=None, help="Base model for delta weights.")
    parser.add_argument("--image-file", type=str, required=True, help="Path to the input image.")
    parser.add_argument("--device", type=str, default="cuda", help="Device to use (e.g., 'cuda', 'cpu').")
    parser.add_argument("--conv-mode", type=str, default=None, help="Conversation mode to use.")
    parser.add_argument("--temperature", type=float, default=0.2, help="Sampling temperature.")
    parser.add_argument("--max-new-tokens", type=int, default=512, help="Maximum number of new tokens to generate.")
    parser.add_argument("--load-8bit", action="store_true", help="Load the model in 8-bit mode.")
    parser.add_argument("--load-4bit", action="store_true", help="Load the model in 4-bit mode.")
    parser.add_argument("--debug", action="store_true", help="Enable debug output.")
    args = parser.parse_args()
    main(args)