"""Base email backend interface."""

from abc import ABC
from abc import abstractmethod
from typing import TYPE_CHECKING
from typing import Any

if TYPE_CHECKING:
    from amsdal_mail.message import EmailMessage
    from amsdal_mail.status import SendStatus


class BaseEmailBackend(ABC):
    """Abstract base class for all email backends."""

    def __init__(self, *, fail_silently: bool = False, **kwargs: Any) -> None:
        """
        Initialize the email backend.

        Args:
            fail_silently: If True, suppress exceptions and return 0 for failed sends
            **kwargs: Backend-specific configuration options
        """
        self.fail_silently = fail_silently
        self.extra_kwargs = kwargs

    def open(self) -> None:
        """
        Open a network connection to the email service

        This method is called automatically when using the backend as a context manager.
        Override this method if your backend needs to establish a persistent connection.
        """
        pass

    def close(self) -> None:
        """
        Close the network connection to the email service.

        This method is called automatically when exiting the context manager.
        Override this method if your backend needs to clean up resources.
        """
        pass

    def __enter__(self) -> 'BaseEmailBackend':
        """Enter context manager - open connection."""
        self.open()
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        """Exit context manager - close connection."""
        self.close()

    @abstractmethod
    def send_messages(self, email_messages: list['EmailMessage']) -> 'SendStatus':
        """
        Send one or more email messages.

        Args:
            email_messages: List of EmailMessage instances to send

        Returns:
            SendStatus object with message IDs, statuses, and ESP response data

        Raises:
            SendError: If sending fails and fail_silently is False
        """
        msg = 'Subclasses must implement send_messages()'
        raise NotImplementedError(msg)

    async def asend_messages(self, email_messages: list['EmailMessage']) -> 'SendStatus':
        """
        Send one or more email messages asynchronously.

        Default implementation falls back to synchronous send_messages().
        Override this method to provide true async implementation.

        Args:
            email_messages: List of EmailMessage instances to send

        Returns:
            SendStatus object with message IDs, statuses, and ESP response data

        Raises:
            SendError: If sending fails and fail_silently is False
        """
        return self.send_messages(email_messages)
