"""User context extraction for SmartLink audit logging."""

from __future__ import annotations

import json
from base64 import b64decode


def get_user_email_from_token(instance: str | None = None) -> str | None:
    """Extract user email from the cached Keycloak access token.

    Decodes the JWT payload (no signature verification — token was already
    validated by the server) to read the email or preferred_username claim.

    Args:
        instance: Instance name for token lookup.

    Returns:
        Email string, or None if not available.
    """
    from mcp_eregistrations_common.auth import _access_tokens

    if not instance or instance not in _access_tokens:
        return None

    token = _access_tokens[instance]
    try:
        # JWT: header.payload.signature — decode payload
        payload_b64 = token.split(".")[1]
        # Add padding if needed
        padding = 4 - len(payload_b64) % 4
        if padding != 4:
            payload_b64 += "=" * padding
        payload = json.loads(b64decode(payload_b64))
        email: str | None = payload.get("email") or payload.get("preferred_username")
        return email
    except Exception:
        return None
