"""Shared OpenAI client construction for LLM and Embedding connectors."""
from __future__ import annotations

from typing import Any, Dict, Optional


def build_openai_client(
    endpoint: str,
    auth_type: str,
    api_key: Optional[str] = None,
    username: Optional[str] = None,
    password: Optional[str] = None,
    api_version: Optional[str] = None,
    deployment_name: Optional[str] = None,
    timeout: float = 60.0,
    max_retries: int = 2,
) -> "tuple[Any, str, Dict[str, Any]]":
    """Build an OpenAI client and return ``(client, resolved_model_or_endpoint, extra_info)``.

    Returns:
        A tuple of ``(OpenAI_client, effective_model, client_kwargs)`` so that
        the caller can inspect/store the kwargs if needed.
    """
    try:
        from openai import OpenAI  # type: ignore
        import httpx  # type: ignore
    except ImportError as exc:  # pragma: no cover
        raise RuntimeError("openai and httpx libraries required") from exc

    client_kwargs: Dict[str, Any] = {"base_url": endpoint, "timeout": timeout, "max_retries": max_retries}
    effective_model: Optional[str] = None

    if auth_type in ("api_key", "bearer", "azure_key"):
        client_kwargs["api_key"] = api_key
    elif auth_type == "basic_auth":
        if username is None or password is None:
            raise RuntimeError("username/password required for basic_auth")
        client_kwargs["http_client"] = httpx.Client(auth=(username, password))
        client_kwargs["api_key"] = api_key or "not-needed"
    elif auth_type == "no_auth":
        client_kwargs["api_key"] = "not-needed"
    else:
        raise RuntimeError(f"Unsupported auth_type: {auth_type}")

    if auth_type == "azure_key":
        if not deployment_name or not api_version:
            raise RuntimeError("deployment_name and api_version required for azure_key")
        client_kwargs["base_url"] = f"{endpoint}/openai/deployments/{deployment_name}"
        client_kwargs["api_version"] = api_version
        effective_model = deployment_name

    client = OpenAI(**client_kwargs)
    return client, effective_model, client_kwargs
