# app/common/openai_client.py
import logging

from openai import AsyncOpenAI

from config import OPENAI_API_KEY

logger = logging.getLogger(__name__)

__all__ = ["get_openai_client", "init_openai_client"]


class OpenAIClientManager:
    """
    Singleton Class quản lý OpenAI Client.
    Đảm bảo chỉ có 1 instance AsyncOpenAI được tạo ra trong toàn bộ ứng dụng.
    """

    def __init__(self):
        self._client: AsyncOpenAI | None = None

    def initialize(self) -> None:
        """
        Khởi tạo AsyncOpenAI client.
        Gọi 1 lần ở lifespan/startup.
        """
        if self._client is not None:
            return

        if not OPENAI_API_KEY:
            raise RuntimeError("CRITICAL: OPENAI_API_KEY chưa được thiết lập trong config")

        try:
            self._client = AsyncOpenAI(
                api_key=OPENAI_API_KEY,
                # organization=os.getenv("OPENAI_ORG"), # Uncomment if needed
            )
            logger.info("✅ OpenAI Client initialized successfully")
        except Exception as e:
            logger.error(f"❌ Failed to initialize OpenAI Client: {e}")
            raise

    def get_client(self) -> AsyncOpenAI:
        """
        Lấy client instance (Lazy loading nếu chưa init).
        """
        if self._client is None:
            logger.debug("⚠️ OpenAI Client accessed before init, triggering lazy initialization...")
            self.initialize()

        if self._client is None:  # Should not happen if init raises error
            raise RuntimeError("OpenAI Client initialization failed")

        return self._client


# --- Singleton Instance & Public API ---

_manager = OpenAIClientManager()

# Alias functions cho backward compatibility
init_openai_client = _manager.initialize
get_openai_client = _manager.get_client
