"""Functions for sending emails"""

import smtplib
import platform
import pwd
import os
from typing import Union, Literal, overload
from email.utils import formatdate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from ._tickets import make_ticket


@overload
def send_email(
    to_addr: Union[str, list[str]],
    subject: str,
    body: str,
    html: Union[str, None] = None,
    sender: Union[str, None] = None,
    ssl: bool = False,
    server: tuple[str, int] = ('localhost', 0),
    login: Union[tuple[str, str], None] = None,
    errs: Literal[False] = False,
) -> bool: ...


@overload
def send_email(
    to_addr: Union[str, list[str]],
    subject: str,
    body: str,
    html: Union[str, None] = None,
    sender: Union[str, None] = None,
    ssl: bool = False,
    server: tuple[str, int] = ('localhost', 0),
    login: Union[tuple[str, str], None] = None,
    errs: Literal[True] = True,
) -> None: ...


def send_email(
    to_addr: Union[str, list[str]],
    subject: str,
    body: str,
    html: Union[str, None] = None,
    sender: Union[str, None] = None,
    ssl: bool = False,
    server: tuple[str, int] = ('localhost', 0),
    login: Union[tuple[str, str], None] = None,
    errs: bool = False,
):
    """Sends an email

    Args:
        to_addr: destination email address(es)
        subject: subject line of email to send
        body: plaintext body of email
        html: HTML version of the email
        sender: sender's email address. user@fqdn if unprovided
        ssl: whether to use SMTPS
        server: (host, port) to connect to
        login: (user, pass) to connect as
        errs: if True, raise OSError if sending fails. If False, return
            a bool for success/fail. Defaults to False.
    """
    if sender is None:
        sender = f'{pwd.getpwuid(os.getuid()).pw_name}@{platform.node()}'
    if isinstance(to_addr, str):
        queues = (
            "str@imhadmin.net",
            "sadmin@imhadmin.net",
            "reclamations@imhadmin.net",
        )
        if to_addr in queues and not errs:
            try:
                make_ticket(dest=to_addr, body=body, sender=sender)
            except Exception:
                return False
            return True
        to_addr = [to_addr]
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ", ".join(to_addr)
    msg['Date'] = formatdate()
    if isinstance(body, str):
        msg.attach(MIMEText(body, 'plain', 'UTF-8'))
    else:
        msg.attach(MIMEText(body, 'plain'))
    if html:
        if isinstance(html, str):
            msg.attach(MIMEText(html, 'html', 'UTF-8'))
        else:
            msg.attach(MIMEText(html, 'html'))
    smtp_class = smtplib.SMTP_SSL if ssl else smtplib.SMTP
    try:
        smtp_obj = smtp_class(server[0], server[1])
        if login:
            smtp_obj.login(login[0], login[1])
        smtp_obj.sendmail(sender, to_addr, msg.as_string())
    except OSError:
        if errs:
            raise
        return False
    if errs:
        return None
    return True


send_email.__module__ = 'rads'
