import json
import threading
from typing import Any

import requests
from dwai.core.exceptions import CompletionsRequestError

_thread_context = threading.local()

class BaseCompletions:
    """ 对话API基类 """
    app_id = ""
    app_key = ""
    api_base = ""

    def __init__(self, app_id: str, app_key: str, api_base: str):
        self.app_id = app_id
        self.app_key = app_key
        self.api_base = api_base

    @classmethod
    def call(cls, *args, **kwargs) -> Any:
        raise NotImplementedError()

    def do_http(self, api_path, headers, data, stream):
        url = "%s%s" % (self.api_base, api_path)
        session = self.__get_session()
        resp = session.request("POST",
                               url=url,
                               headers=headers,
                               data=json.dumps(data),
                               stream=stream)

        if not resp.ok:
            raise CompletionsRequestError("completion request error", resp.status_code, resp.text)

        return resp

    @staticmethod
    def __get_session() -> requests.Session:
        if not hasattr(_thread_context, "session"):
            _thread_context.session = requests.Session()

        return _thread_context.session




