from __future__ import annotations

import logging
import os
import sys
from typing import Callable

from dotenv import load_dotenv
from httpx import AsyncClient
from openai import AsyncOpenAI
from openai.lib.azure import AsyncAzureOpenAI

IS_PRODUCTION = os.environ.get("ENVIRONMENT", default="") == "PRODUCTION"

LOGGING_FORMAT = "[%(levelname)s] %(message)s"


def load_env():
    if not IS_PRODUCTION:
        load_dotenv()


def set_logging_level():
    if IS_PRODUCTION:
        logging.basicConfig(level=logging.INFO, format=LOGGING_FORMAT, stream=sys.stdout)
    else:
        logging.basicConfig(level=logging.DEBUG, format=LOGGING_FORMAT, stream=sys.stdout)


def debug_log_sensitive_data(message: str):
    if not IS_PRODUCTION:
        logging.debug(message)


def debug_log_sensitive_data_from_callable(message: Callable[[], str | None]):
    if not IS_PRODUCTION:
        logging.debug(message())


def create_openai_client(
    client_type: str = os.environ.get("OPENAI_API_TYPE", default="openai"),
) -> AsyncOpenAI | AsyncAzureOpenAI:
    if client_type == "azure":
        logging.info("OpenAIClient: Using Azure OpenAI service.")
        openai_client: AsyncOpenAI | AsyncAzureOpenAI = AsyncAzureOpenAI(
            # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning
            api_version="2024-08-01-preview",
            # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource
            azure_endpoint="https://codeflash-openai-service-eastus2-0.openai.azure.com",
            http_client=AsyncClient(),
        )
    else:
        logging.info("OpenAIClient: Using OpenAI API.")
        openai_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"), http_client=AsyncClient())
    return openai_client
