import os
from typing import Optional

from qhub.api.credentials import DefaultCredentialsProvider
from qhub.api.quantum import HubQuantumClient
from qhub.quantum.sdk.context import ContextResolver
from qhub.quantum.sdk.retry_client import RetryHubClient


def create_hub_client(access_token: Optional[str] = None,
                      organization_id: Optional[str] = None,
                      timeout: Optional[float] = None) -> HubQuantumClient:
    """Create a HubQuantumClient with credential resolution.

    If no access_token is provided, the token is resolved from environment
    variables or config file via DefaultCredentialsProvider.

    Args:
        access_token: Access token for authentication with Kipu Quantum Hub.
        organization_id: The ID of a Kipu Quantum Hub organization.
        timeout: Request timeout in seconds. Defaults to 90 seconds.

    Returns:
        A configured HubQuantumClient instance.
    """
    access_token = DefaultCredentialsProvider(access_token).get_access_token()

    if organization_id is None:
        context = ContextResolver().get_context()
        if context:
            organization_id = context.get_organization_id()

    client = HubQuantumClient(
        api_key=access_token,
        organization_id=organization_id,
        base_url=os.environ.get("QHUB_QUANTUM_BASE_URL"),
        timeout=timeout if timeout is not None else 90,
    )
    return RetryHubClient(client)  # type: ignore[return-value]
