"""
Social login support for AiCippy.

Provides constants for supported social identity providers and a helper
to construct the Cognito Hosted UI authorization URL with the
``identity_provider`` parameter pre-set.  The actual OAuth callback
handling is delegated to the existing BrowserAuth PKCE infrastructure.

Supported providers:
- Google (Cognito built-in federation)
- GitHub (configured as ``SignInWithGitHub`` OIDC provider in Cognito)
"""

from __future__ import annotations

from typing import Final
from urllib.parse import urlencode

from aicippy.config import get_settings

# ============================================================================
# Social Provider Registry
# ============================================================================

SOCIAL_PROVIDERS: Final[dict[str, str]] = {
    "google": "Google",
    "github": "SignInWithGitHub",
}
"""Mapping of CLI-friendly provider keys to Cognito identity provider names.

The values must match the identity provider names configured in the Cognito
User Pool federation settings.
"""

# OAuth scopes requested during social login
_SOCIAL_SCOPES: Final[str] = "openid email profile"

# Localhost callback used by BrowserAuth
_DEFAULT_REDIRECT_URI: Final[str] = "http://localhost:9876/callback"


# ============================================================================
# URL Builder
# ============================================================================


def social_login_url(
    provider: str,
    redirect_uri: str = _DEFAULT_REDIRECT_URI,
) -> str:
    """Build the Cognito Hosted UI authorization URL for a social provider.

    The returned URL, when opened in a browser, will redirect the user to
    the selected social provider's login page.  After successful
    authentication, Cognito redirects back to ``redirect_uri`` with an
    authorization code that BrowserAuth can exchange for tokens.

    Args:
        provider: One of the keys in :data:`SOCIAL_PROVIDERS` (``"google"``
                  or ``"github"``).
        redirect_uri: The localhost callback URI. Defaults to
                      ``http://localhost:9876/callback``.

    Returns:
        Fully-qualified authorization URL string.

    Raises:
        ValueError: If ``provider`` is not a supported social provider.
    """
    if provider not in SOCIAL_PROVIDERS:
        supported = ", ".join(sorted(SOCIAL_PROVIDERS))
        raise ValueError(
            f"Unsupported social provider: {provider!r}. "
            f"Supported providers: {supported}"
        )

    settings = get_settings()
    identity_provider = SOCIAL_PROVIDERS[provider]

    params = {
        "identity_provider": identity_provider,
        "client_id": settings.cognito_client_id,
        "response_type": "code",
        "redirect_uri": redirect_uri,
        "scope": _SOCIAL_SCOPES,
    }

    return f"{settings.cognito_domain}/oauth2/authorize?{urlencode(params)}"
