"""OAuth provider builder for HTTP transports using FastMCP 3 OAuthProxy."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ims_mcp.config import RosettaConfig

from ims_mcp.constants import TRANSPORT_HTTP


def build_oauth_provider(config: "RosettaConfig"):
    """Build a FastMCP ``OAuthProxy`` for HTTP transports.

    Returns ``None`` when the transport is not HTTP or when required OAuth
    environment variables are missing.  In that case the server runs without
    authentication (STDIO mode uses ``ROSETTA_API_KEY`` directly).
    """
    if config.transport != TRANSPORT_HTTP:
        return None

    if not config.oauth_configured:
        return None

    from fastmcp.server.auth.oauth_proxy import OAuthProxy
    from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier

    token_verifier = IntrospectionTokenVerifier(
        introspection_url=config.oauth_introspection_endpoint,
        client_id=config.oauth_client_id,
        client_secret=config.oauth_client_secret,
    )

    base_url = config.resolve_oauth_base_url()

    return OAuthProxy(
        upstream_authorization_endpoint=config.oauth_authorization_endpoint,
        upstream_token_endpoint=config.oauth_token_endpoint,
        upstream_client_id=config.oauth_client_id,
        upstream_client_secret=config.oauth_client_secret,
        token_verifier=token_verifier,
        base_url=base_url,
        redirect_path=config.oauth_callback_path,
        require_authorization_consent=False,
    )
