"""Console email backend - writes emails to stdout."""

import sys
from typing import IO
from typing import Any

from amsdal_mail.backends.base import BaseEmailBackend
from amsdal_mail.message import EmailMessage
from amsdal_mail.status import RecipientStatus
from amsdal_mail.status import SendStatus


class ConsoleBackend(BaseEmailBackend):
    """
    Email backend that writes messages to a stream (default: stdout).

    Useful for development and debugging.
    """

    def __init__(self, stream: IO[str] | None = None, **kwargs: Any) -> None:
        """
        Initialize the console backend.

        Args:
            stream: Output stream (defaults to sys.stdout)
            **kwargs: Additional backend options (passed to parent)
        """
        super().__init__(**kwargs)
        self.stream = stream or sys.stdout

    def send_messages(self, email_messages: list[EmailMessage]) -> SendStatus:
        """
        Write email messages to the stream.

        Args:
            email_messages: List of EmailMessage instances to output

        Returns:
            SendStatus with 'sent' status for all recipients
        """
        status = SendStatus()
        recipients = {}

        for message in email_messages:
            self.stream.write('-' * 79 + '\n')
            self.stream.write(f'Subject: {message.subject}\n')
            self.stream.write(f'From: {message.from_email}\n')
            self.stream.write(f'To: {", ".join(str(addr) for addr in message.to)}\n')

            if message.cc:
                self.stream.write(f'Cc: {", ".join(str(addr) for addr in message.cc)}\n')

            if message.bcc:
                self.stream.write(f'Bcc: {", ".join(str(addr) for addr in message.bcc)}\n')

            if message.reply_to:
                self.stream.write(f'Reply-To: {", ".join(str(addr) for addr in message.reply_to)}\n')

            if message.headers:
                for key, value in message.headers.items():
                    self.stream.write(f'{key}: {value}\n')

            self.stream.write('\n')

            if message.html_body:
                self.stream.write('Content-Type: multipart/alternative\n')
                self.stream.write('\n--- Plain Text ---\n')
                self.stream.write(message.body)
                self.stream.write('\n\n--- HTML ---\n')
                self.stream.write(message.html_body)
            else:
                self.stream.write(message.body)

            if message.attachments:
                self.stream.write('\n\n--- Attachments ---\n')
                for attachment in message.attachments:
                    size_kb = len(attachment.content) / 1024
                    self.stream.write(f'- {attachment.filename} ({attachment.mimetype}, {size_kb:.1f} KB)\n')

            self.stream.write('\n' + '-' * 79 + '\n\n')

            # Add recipient status (console backend always succeeds)
            for recipient in message.recipients():
                recipients[recipient] = RecipientStatus(
                    message_id=None,  # Console backend doesn't generate message IDs
                    status='sent',
                )

        self.stream.flush()
        status.set_recipient_status(recipients)
        return status
