# Copyright 2026 Datastrato, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Abstract base class for ADP transports."""

from abc import ABC, abstractmethod
from types import TracebackType


class Transport(ABC):
    """Abstract base class for ADP transports.

    A transport handles the low-level communication between client and server,
    abstracting away the details of how messages are sent and received.

    Note: ``read_message`` and ``write_message`` are **not** safe for concurrent
    access.  Callers must ensure that at most one coroutine reads and at most
    one coroutine writes at any given time.
    """

    @abstractmethod
    async def start(self) -> None:
        """Start the transport and acquire any resources needed.

        Must be called before ``read_message`` / ``write_message``.
        """
        ...

    @abstractmethod
    async def read_message(self) -> str | None:
        """Read a message from the transport.

        Returns:
            The message as a string, or None if the transport is closed.
        """
        ...

    @abstractmethod
    async def write_message(self, message: str) -> None:
        """Write a message to the transport.

        Args:
            message: The message to write.
        """
        ...

    @abstractmethod
    async def close(self) -> None:
        """Close the transport and release any resources."""
        ...

    async def __aenter__(self) -> "Transport":
        await self.start()
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        await self.close()
