from os import getenv

# Prevent nest_asyncio from patching asyncio.run() in processcube_client - it breaks uvicorn's loop_factory
import nest_asyncio
nest_asyncio.apply = lambda *args, **kwargs: None

from processcube_client.external_task import ExternalTaskClient
from processcube_client.app_info import AppInfoClient

from .identity_provider import IdentityProvider


def _determine_authority_url(engine_url: str) -> str:
    if authority := getenv("PROCESSCUBE_AUTHORITY_URL"):
        return authority

    app_info_client = AppInfoClient(engine_url)
    authority_url = app_info_client.get_authority()
    return authority_url # type: ignore


def create_external_task_client(
    engine_url: str,
    client_name: str,
    client_secret: str,
    client_scopes: str,
    max_get_oauth_access_token_retries: int,
) -> ExternalTaskClient:
    authority_url = _determine_authority_url(engine_url)

    identity_provider = IdentityProvider(
        authority_url,
        client_name,
        client_secret,
        client_scopes,
        max_get_oauth_access_token_retries,
    )
    client = ExternalTaskClient(
        engine_url,
        identity=identity_provider,
        install_signals=False,
    )

    return client
