"""GAuthClient singleton wired to navi config."""

from gnexus_gauth.client import GAuthClient
from gnexus_gauth.config import GAuthConfig
from gnexus_gauth.oauth import HttpTokenEndpoint
from gnexus_gauth.runtime import HttpRuntimeUserProvider
from gnexus_gauth.support import InMemoryPkceStore, InMemoryStateStore
from gnexus_gauth.webhook import HmacWebhookVerifier, JsonWebhookParser

from navi.config import settings

# Singleton instances, lazily created
_gauth_client: GAuthClient | None = None
_state_store: InMemoryStateStore | None = None
_pkce_store: InMemoryPkceStore | None = None


def get_gauth_client() -> GAuthClient:
    global _gauth_client, _state_store, _pkce_store
    if _gauth_client is None:
        config = GAuthConfig(
            base_url=settings.gnexus_auth_base_url,
            client_id=settings.gnexus_auth_client_id,
            client_secret=settings.gnexus_auth_client_secret,
            redirect_uri=settings.gnexus_auth_redirect_uri,
        )
        _state_store = InMemoryStateStore()
        _pkce_store = InMemoryPkceStore()
        _gauth_client = GAuthClient(
            config=config,
            token_endpoint=HttpTokenEndpoint(config),
            runtime_user_provider=HttpRuntimeUserProvider(config),
            webhook_verifier=HmacWebhookVerifier(config),
            webhook_parser=JsonWebhookParser(),
            state_store=_state_store,
            pkce_store=_pkce_store,
        )
    return _gauth_client
