# ==== CREATED AND OWNED BY askme360 (HIPL) ====
import os

from openai import OpenAI

from ..askme_base import AskmeBase
from app.core.config import settings


def _get_llm_service(api_key: str = None, config: dict = None):
    """Get LLMService with api_key from config or env."""
    from app.services.llm_service import LLMService, oic_anthropic_integration_enabled

    ckey = ""
    if config:
        ckey = (config.get("claude_api_key") or "").strip()

    if oic_anthropic_integration_enabled():
        key = api_key
        if not key and config:
            key = config.get("api_key") or config.get("open_ai")
        if not key:
            key = os.getenv("OPENAI_API_KEY", "")
        return LLMService(api_key=key or "", claude_api_key=ckey)

    key = api_key
    if not key and config:
        key = config.get("api_key") or config.get("open_ai")
    if not key:
        key = os.getenv("OPENAI_API_KEY", "")
    if settings.llm_mode() != "qwen_only" and not (key or "").strip() and not (ckey or "").strip():
        raise ValueError("API key required for LLM calls when IS_QWEN_LLM is not true (OpenAI and/or claude_api_key)")
    from app.services.llm_service import LLMService
    return LLMService(api_key=key or "", claude_api_key=ckey)


class OpenAI_Chat(AskmeBase):
    def __init__(self, client=None, config=None):
        AskmeBase.__init__(self, config=config)

       
        self.temperature = 0.7

        if "temperature" in config:
            self.temperature = config["temperature"]

        if "api_type" in config:
            raise Exception(
                "Passing api_type is now deprecated. Please pass an OpenAI client instead."
            )

        if "api_base" in config:
            raise Exception(
                "Passing api_base is now deprecated. Please pass an OpenAI client instead."
            )

        if "api_version" in config:
            raise Exception(
                "Passing api_version is now deprecated. Please pass an OpenAI client instead."
            )

        if client is not None:
            self.client = client
            return

        from app.services.llm_service import oic_anthropic_integration_enabled

        if oic_anthropic_integration_enabled():
            self.client = None
            return

        if config is None and client is None:
            self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
            return

        if "api_key" in config:
            self.client = OpenAI(api_key=config["api_key"])

    def system_message(self, message: str) -> any:
        return {"role": "system", "content": message}

    def user_message(self, message: str) -> any:
        return {"role": "user", "content": message}

    def assistant_message(self, message: str) -> any:
        return {"role": "assistant", "content": message}

    def submit_prompt(self, prompt, **kwargs) -> str:
        if prompt is None:
            raise Exception("Prompt is None")

        if len(prompt) == 0:
            raise Exception("Prompt is empty")

        api_key = None
        ckey = ""
        if self.config:
            api_key = self.config.get("api_key") or self.config.get("open_ai")
            ckey = (self.config.get("claude_api_key") or "").strip()
        if not api_key:
            api_key = os.getenv("OPENAI_API_KEY", "")
        from app.services.llm_service import oic_anthropic_integration_enabled

        if settings.llm_mode() != "qwen_only" and not (api_key or "").strip() and not (ckey or "").strip():
            if not oic_anthropic_integration_enabled():
                raise ValueError("API key required for LLM calls when IS_QWEN_LLM is not true (OpenAI and/or claude_api_key)")

        llm = _get_llm_service(api_key=api_key, config=self.config)
        temperature = kwargs.get("temperature", self.temperature)
        use_session_kw = kwargs.get("use_session")
        if use_session_kw is None:
            use_session = bool(getattr(self, "_use_session_default", False))
        else:
            use_session = bool(use_session_kw)

        session_context = kwargs.get("session_context")
        if session_context is None:
            session_context = getattr(self, "_session_context", {}) or {}
        else:
            session_context = session_context or {}
        if use_session:
            session_result = llm.chat_with_session(
                messages=prompt,
                session_state=session_context,
                temperature=temperature,
                max_tokens=kwargs.get("max_tokens"),
            )
            # Keep last response id on agent instance so callers can persist it.
            self._last_session_response_id = session_result.get("response_id")
            self._session_context = {
                **session_context,
                "openai_response_id": session_result.get("response_id"),
            }
            return session_result.get("text", "")

        return llm.chat_completion(
            messages=prompt,
            **kwargs
        )
