from typing import Any, Tuple, List
import os
from openai import OpenAI
os.environ['OPENAI_KEY'] = "key-here"
import cv2
import base64


def chatgpt(prompt: str, temperature: float = 0.0, model: str = "gpt-3.5-turbo") -> str:
    CLIENT = OpenAI(api_key=os.getenv('OPENAI_KEY'))
    sample = CLIENT.chat.completions.create(
        model=model,
        temperature=temperature, 
        messages=[
            {"role": "user", "content": prompt}
        ])
    return sample.choices[0].message.content


def chain_of_thought(prompts: List[str]) -> str:
    prompt_cat = ""
    for prompt in prompts:
        prompt_cat += f"Q: {prompt}\n"
        answer = chatgpt(prompt_cat)
        prompt_cat += f"A: {answer}\n"
    return answer, prompt_cat


def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')


def chatgpt_vision(image, prompt: str, model: str = "gpt-4-turbo") -> str:
    base64_image = encode_image(image)
    
    CLIENT = OpenAI(api_key=os.getenv('OPENAI_KEY'))
    sample = CLIENT.chat.completions.create(
        model=model,
        temperature=0.0, 
        messages=[{
            "role": "user",
            "content": [
            {
                "type": "text",
                "text": prompt,
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{base64_image}"
                }
            }],
        }],
    )
    return sample.choices[0].message.content


def chatgpt_vision_multiple(image1, image2, prompt: str, model: str = "gpt-4-turbo") -> str:
    base64_image1 = encode_image(image1)
    base64_image2 = encode_image(image2)

    CLIENT = OpenAI(api_key=os.getenv('OPENAI_KEY'))
    sample = CLIENT.chat.completions.create(
        model=model,
        temperature=0.0, 
        messages=[{
            "role": "user",
            "content": [
            {
                "type": "text",
                "text": prompt,
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{base64_image1}"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{base64_image2}"
                }
            }],
        }],
    )
    return sample.choices[0].message.content
