"""A2A version negotiation.

Ensures that a requested A2A version is within the set of supported
versions.  Raises :class:`A2aVersionMismatchError` when the requested
version is not supported.
"""

from __future__ import annotations

import structlog

from cleveragents.a2a.errors import A2aVersionMismatchError

logger: structlog.stdlib.BoundLogger = structlog.get_logger(__name__)


class A2aVersionNegotiator:
    """Negotiates A2A protocol versions."""

    CURRENT_VERSION: str = "2.0"
    SUPPORTED_VERSIONS: tuple[str, ...] = ("2.0",)

    def negotiate(self, requested: str) -> str:
        """Return *requested* if supported, otherwise raise.

        Raises:
            ValueError: If *requested* is empty.
            A2aVersionMismatchError: If version is not in
                :attr:`SUPPORTED_VERSIONS`.
        """
        if not requested or not isinstance(requested, str):
            raise ValueError("requested version must be a non-empty string")
        if requested in self.SUPPORTED_VERSIONS:
            logger.debug("a2a.version.negotiated", version=requested)
            return requested
        raise A2aVersionMismatchError(
            message=f"A2A version '{requested}' is not supported",
            requested_version=requested,
            supported_versions=list(self.SUPPORTED_VERSIONS),
        )

    def is_supported(self, version: str) -> bool:
        """Return ``True`` when *version* is in :attr:`SUPPORTED_VERSIONS`."""
        if not version or not isinstance(version, str):
            raise ValueError("version must be a non-empty string")
        return version in self.SUPPORTED_VERSIONS

    def get_current(self) -> str:
        """Return the current A2A protocol version."""
        return self.CURRENT_VERSION


__all__ = [
    "A2aVersionNegotiator",
]
