from __future__ import annotations

import mimetypes
import smtplib
from email.message import EmailMessage
from pathlib import Path


def send_email_with_attachment(
    *,
    smtp_host: str,
    smtp_port: int,
    smtp_username: str,
    smtp_password: str,
    sender_name: str,
    sender_email: str,
    recipient_email: str,
    subject: str,
    body: str,
    attachment_path: str | None = None,
) -> None:
    msg = EmailMessage()
    if sender_name:
        msg['From'] = f'{sender_name} <{sender_email}>'
    else:
        msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject
    msg.set_content(body)

    if attachment_path:
        path = Path(attachment_path)
        if path.exists():
            ctype, _ = mimetypes.guess_type(str(path))
            maintype, subtype = (ctype.split('/', 1) if ctype else ('application', 'octet-stream'))
            msg.add_attachment(path.read_bytes(), maintype=maintype, subtype=subtype, filename=path.name)

    port = int(smtp_port or 0)
    if port == 465:
        with smtplib.SMTP_SSL(smtp_host, port, timeout=30) as server:
            if smtp_username:
                server.login(smtp_username, smtp_password)
            server.send_message(msg)
        return

    with smtplib.SMTP(smtp_host, port or 587, timeout=30) as server:
        server.ehlo()
        try:
            server.starttls()
            server.ehlo()
        except Exception:
            pass
        if smtp_username:
            server.login(smtp_username, smtp_password)
        server.send_message(msg)
