'''
Function:
    Implementation of OpenAIChatGPTEndpoints
Author:
    Zhenchao Jin
WeChat Official Account (微信公众号):
    Charles的皮卡丘
'''
import random
from openai import OpenAI
from .base import BaseEndpoint
from ..utils import ChatRequest, ChatResponse, ModelIOType, SecretUtils, Modality


'''CHATGPT_FREE_API_KEYS'''
CHATGPT_FREE_API_KEYS = {
    'gpt-4o': [
        'c2stcHJvai1Fdllsb2FCTDVoYm85eDN4aFp3ODlPNmlVaENiZlQtSzdLbG5wS1pnVS1CczBjWHd4RHdzZDRCNWlQUkFhYkk4YkZSREpHN3VzVVQzQmxia0ZKbGd6b2V3RW5FeVBSYjM4UU9ZQnh6SzZkcEQwcG1WQnZDVVBLNzM2ME1FVzlPN2JwVVZrMkpmc2hUbW83bGFPemt1Tl85ZjgzQUE='
    ],
}


'''OpenAIChatGPTEndpoints'''
class OpenAIChatGPTEndpoints(BaseEndpoint):
    provider, model = "openai", "chatgpt"
    def __init__(self, **kwargs):
        super(OpenAIChatGPTEndpoints, self).__init__(**kwargs)
        T2T = ModelIOType.fromtag("T2T")
        TI2T = ModelIOType.create(inputs=[Modality.TEXT, Modality.IMAGE], outputs=[Modality.TEXT])
        self.registervariant("gpt-4o", io_supported=[T2T, TI2T])
        self.registerapi(
            version="gpt-4o", name="officialapiv1", io=T2T, handler="officialapiv1",
            priority=100, note='official api: https://api.openai.com/v1',
        )
        self.registerapi(
            version="gpt-4o", name="visionofficialapiv1", io=TI2T, handler="visionofficialapiv1",
            priority=100, note='official api: https://api.openai.com/v1',
        )
    '''officialapiv1'''
    def officialapiv1(self, req: ChatRequest, request_overrides: dict = None, version: str = None) -> ChatResponse:
        # init
        request_overrides = request_overrides or {}
        openai_cfg: dict = req.openai
        # specify model
        model_override = openai_cfg['client.responses.create'].pop('model', None)
        model = model_override or version
        # create client
        client = OpenAI(
            base_url='https://api.openai.com/v1', api_key=SecretUtils.b64decode(random.choice(CHATGPT_FREE_API_KEYS[version])), **openai_cfg['client']
        )
        # get response
        resp = client.responses.create(model=model, input=req.text, **openai_cfg['client.responses.create'])
        text = self._extracttextfromresponseobj(resp)
        raw = resp.model_dump() if hasattr(resp, "model_dump") else resp
        # return
        return ChatResponse(text=text, raw=raw)
    '''visionofficialapiv1'''
    def visionofficialapiv1(self, req: ChatRequest, request_overrides: dict = None, version: str = None) -> ChatResponse:
        # init
        request_overrides = request_overrides or {}
        openai_cfg: dict = req.openai
        # specify model
        model_override = openai_cfg['client.responses.create'].pop('model', None)
        model = model_override or version
        # process images
        images = getattr(req, "images", None) or ()
        content = [{"type": "input_text", "text": req.text}]
        for img in images: content.append({"type": "input_image", "image_url": self._imgtourl(img)})
        # create client
        client = OpenAI(
            base_url='https://api.openai.com/v1', api_key=SecretUtils.b64decode(random.choice(CHATGPT_FREE_API_KEYS[version])), **openai_cfg['client']
        )
        # get response
        resp = client.responses.create(model=model, input=[{"role": "user", "content": content}], **openai_cfg['client.responses.create'])
        text = self._extracttextfromresponseobj(resp)
        raw = resp.model_dump() if hasattr(resp, "model_dump") else resp
        # return
        return ChatResponse(text=text, raw=raw)