import os
import smtplib
import logging
import ssl
from email.message import EmailMessage


logger = logging.getLogger(__name__)

DEFAULT_SMTP_HOST = "127.0.0.1"
DEFAULT_SMTP_PORT = 25
DEFAULT_SMTP_FROM = "notificaciones@localhost"
DEFAULT_SMTP_USE_TLS = False
DEFAULT_SMTP_USE_SSL = False


def send_email(recipient: str, subject: str, body: str) -> bool:
    smtp_host = os.environ.get("SMTP_HOST", DEFAULT_SMTP_HOST)
    smtp_port = int(os.environ.get("SMTP_PORT", str(DEFAULT_SMTP_PORT)))
    smtp_user = os.environ.get("SMTP_USER")
    smtp_password = os.environ.get("SMTP_PASSWORD")
    smtp_from = os.environ.get("SMTP_FROM") or smtp_user or DEFAULT_SMTP_FROM
    use_tls = os.environ.get("SMTP_USE_TLS", str(DEFAULT_SMTP_USE_TLS)).lower() in {"1", "true", "yes"}
    use_ssl = os.environ.get("SMTP_USE_SSL", str(DEFAULT_SMTP_USE_SSL)).lower() in {"1", "true", "yes"}

    if not smtp_host or not smtp_from:
        return False
    if use_tls and use_ssl:
        raise ValueError("SMTP_USE_TLS y SMTP_USE_SSL no pueden estar activos al mismo tiempo")

    message = EmailMessage()
    message["Subject"] = subject
    message["From"] = smtp_from
    message["To"] = recipient
    message.set_content(body)

    ssl_context = ssl.create_default_context()
    if use_ssl:
        smtp_connection = smtplib.SMTP_SSL(
            smtp_host,
            smtp_port,
            timeout=20,
            context=ssl_context,
        )
    else:
        smtp_connection = smtplib.SMTP(smtp_host, smtp_port, timeout=20)

    with smtp_connection as smtp:
        smtp.ehlo()
        if use_tls:
            smtp.starttls(context=ssl_context)
            smtp.ehlo()
        if smtp_user and smtp_password:
            smtp.login(smtp_user, smtp_password)
        smtp.send_message(message)

    logger.info("Correo entregado al Exim de cPanel para %s", recipient)
    return True
