# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
"""Shared utilities for polling continuation token serialization."""

import base64
import binascii
import json
from typing import Any, Dict, Mapping


# Current continuation token version
_CONTINUATION_TOKEN_VERSION = 1

# Error message for incompatible continuation tokens from older versions
_INCOMPATIBLE_TOKEN_ERROR_MESSAGE = (
    "This continuation token is not compatible with this version of azure-core. "
    "It may have been generated by a previous version. "
    "See https://aka.ms/azsdk/python/core/troubleshoot for more information."
)

# Headers that are needed for LRO rehydration.
# We use an allowlist approach for security - only include headers we actually need.
_LRO_HEADERS = frozenset(
    [
        "operation-location",
        # azure-asyncoperation is included only for back compat with mgmt-core<=1.6.0
        "azure-asyncoperation",
        "location",
        "content-type",
        "retry-after",
    ]
)


def _filter_sensitive_headers(headers: Mapping[str, str]) -> Dict[str, str]:
    """Filter headers to only include those needed for LRO rehydration.

    Uses an allowlist approach - only headers required for polling are included.

    :param headers: The headers to filter.
    :type headers: Mapping[str, str]
    :return: A new dictionary with only allowed headers.
    :rtype: dict[str, str]
    """
    return {k: v for k, v in headers.items() if k.lower() in _LRO_HEADERS}


def _is_pickle_format(data: bytes) -> bool:
    """Check if the data appears to be in pickle format.

    Pickle protocol markers start with \\x80 followed by a protocol version byte (1-5).

    :param data: The bytes to check.
    :type data: bytes
    :return: True if the data appears to be pickled, False otherwise.
    :rtype: bool
    """
    if not data or len(data) < 2:
        return False
    # Check for pickle protocol marker (0x80) followed by protocol version 1-5
    return data[0:1] == b"\x80" and 1 <= data[1] <= 5


def _decode_continuation_token(continuation_token: str) -> Dict[str, Any]:
    """Decode a base64-encoded JSON continuation token.

    :param continuation_token: The base64-encoded continuation token.
    :type continuation_token: str
    :return: The decoded JSON data as a dictionary (the "data" field from the token).
    :rtype: dict
    :raises ValueError: If the token is invalid or in an unsupported format.
    """
    try:
        decoded_bytes = base64.b64decode(continuation_token)
        token = json.loads(decoded_bytes.decode("utf-8"))
    except binascii.Error:
        # Invalid base64 input
        raise ValueError("This doesn't look like a continuation token the sdk created.") from None
    except (json.JSONDecodeError, UnicodeDecodeError):
        # Check if the data appears to be from an older version
        if _is_pickle_format(decoded_bytes):
            raise ValueError(_INCOMPATIBLE_TOKEN_ERROR_MESSAGE) from None
        raise ValueError("Invalid continuation token format.") from None

    # Validate token schema - must be a dict with a version field
    if not isinstance(token, dict) or "version" not in token:
        raise ValueError("Invalid continuation token format.") from None

    # For now, we only support version 1
    # Future versions can add handling for older versions here if needed
    if token["version"] != _CONTINUATION_TOKEN_VERSION:
        raise ValueError(_INCOMPATIBLE_TOKEN_ERROR_MESSAGE) from None

    return token["data"]


def _encode_continuation_token(data: Any) -> str:
    """Encode data as a base64-encoded JSON continuation token.

    The token includes a version field for future compatibility checking.

    :param data: The data to encode. Must be JSON-serializable.
    :type data: any
    :return: The base64-encoded JSON string.
    :rtype: str
    :raises TypeError: If the data is not JSON-serializable.
    """
    token = {
        "version": _CONTINUATION_TOKEN_VERSION,
        "data": data,
    }
    try:
        return base64.b64encode(json.dumps(token, separators=(",", ":")).encode("utf-8")).decode("ascii")
    except (TypeError, ValueError) as err:
        raise TypeError(
            "Unable to generate a continuation token for this operation. Payload is not JSON-serializable."
        ) from err
