"""Email gateway tool — send emails through stored SMTP accounts."""

import logging

from .._config import SDKConfig
from ..exceptions import api_error_handler, async_api_error_handler
from .._api.client import (
    BaseResource,
    AsyncBaseResource,
    SyncEmailGatewayEmailAPI,
    EmailGatewayEmailAPI,
)
from .._api.generated.email_gateway.email_gateway__api__email.models import (
    EmailAccountList,
    EmailMessageList,
    EmailSendRequest,
    EmailSendResponse,
    EmailAccountCreateRequest,
    TestConnectionResponse,
)

logger = logging.getLogger(__name__)


class EmailResource(BaseResource):
    """Email gateway (sync).

    Send emails through stored SMTP accounts via SDK API key.

    Example:
        >>> sdk = SDKRouter(api_key="sk_live_...")
        >>> sdk.email.send(to="user@example.com", subject="Hello", body="World")
        >>> sdk.email.list_accounts()
    """

    def __init__(self, config: SDKConfig):
        super().__init__(config)
        self._api = SyncEmailGatewayEmailAPI(self._http_client)

    @api_error_handler
    def send(
        self,
        to: str,
        subject: str,
        body: str = "",
        html: str = "",
        *,
        account_alias: str | None = None,
        cc: str = "",
        bcc: str = "",
    ) -> EmailSendResponse:
        """Send an email through a stored SMTP account.

        Args:
            to: Recipient email address
            subject: Email subject
            body: Plain text body
            html: HTML body (optional)
            account_alias: SMTP account alias (uses default if omitted)
            cc: Comma-separated CC addresses
            bcc: Comma-separated BCC addresses

        Returns:
            EmailSendResponse with message_id and status
        """
        data = EmailSendRequest(
            to=to,
            subject=subject,
            body=body or None,
            html=html or None,
            cc=cc or None,
            bcc=bcc or None,
            account_alias=account_alias,
        )
        return self._api.send_create(data)

    @api_error_handler
    def list_accounts(self) -> list[EmailAccountList]:
        """List configured email accounts."""
        return self._api.accounts_list()

    @api_error_handler
    def create_account(
        self,
        alias: str,
        smtp_host: str,
        smtp_username: str,
        smtp_password: str,
        from_email: str,
        *,
        smtp_port: int = 587,
        from_name: str = "",
        use_tls: bool = True,
        use_ssl: bool = False,
        is_default: bool = False,
    ) -> EmailAccountList:
        """Add a new SMTP email account."""
        return self._api.accounts_create_create(EmailAccountCreateRequest(
            alias=alias,
            smtp_host=smtp_host,
            smtp_port=smtp_port,
            smtp_username=smtp_username,
            smtp_password=smtp_password,
            from_email=from_email,
            from_name=from_name,
            use_tls=use_tls,
            use_ssl=use_ssl,
            is_default=is_default,
        ))

    @api_error_handler
    def delete_account(self, account_id: str) -> None:
        """Delete an email account."""
        self._api.accounts_destroy(account_id)

    @api_error_handler
    def test_account(self, account_id: str) -> TestConnectionResponse:
        """Test SMTP connection for an account."""
        return self._api.accounts_test_create(account_id)

    @api_error_handler
    def list_messages(self) -> list[EmailMessageList]:
        """List sent email messages."""
        return self._api.messages_list()


class AsyncEmailResource(AsyncBaseResource):
    """Email gateway (async)."""

    def __init__(self, config: SDKConfig):
        super().__init__(config)
        self._api = EmailGatewayEmailAPI(self._http_client)

    @async_api_error_handler
    async def send(
        self,
        to: str,
        subject: str,
        body: str = "",
        html: str = "",
        *,
        account_alias: str | None = None,
        cc: str = "",
        bcc: str = "",
    ) -> EmailSendResponse:
        """Send an email through a stored SMTP account."""
        data = EmailSendRequest(
            to=to, subject=subject,
            body=body or None, html=html or None,
            cc=cc or None, bcc=bcc or None,
            account_alias=account_alias,
        )
        return await self._api.send_create(data)

    @async_api_error_handler
    async def list_accounts(self) -> list[EmailAccountList]:
        return await self._api.accounts_list()

    @async_api_error_handler
    async def create_account(
        self,
        alias: str,
        smtp_host: str,
        smtp_username: str,
        smtp_password: str,
        from_email: str,
        **kwargs,
    ) -> EmailAccountList:
        return await self._api.accounts_create_create(EmailAccountCreateRequest(
            alias=alias, smtp_host=smtp_host, smtp_username=smtp_username,
            smtp_password=smtp_password, from_email=from_email, **kwargs,
        ))

    @async_api_error_handler
    async def delete_account(self, account_id: str) -> None:
        await self._api.accounts_destroy(account_id)

    @async_api_error_handler
    async def test_account(self, account_id: str) -> TestConnectionResponse:
        return await self._api.accounts_test_create(account_id)

    @async_api_error_handler
    async def list_messages(self) -> list[EmailMessageList]:
        return await self._api.messages_list()


__all__ = [
    "EmailResource",
    "AsyncEmailResource",
    "EmailAccountList",
    "EmailMessageList",
    "EmailSendRequest",
    "EmailSendResponse",
    "EmailAccountCreateRequest",
    "TestConnectionResponse",
]
