"""SMTP wrapper minimal y tolerante a fallos.

El envio NUNCA debe romper una transaccion de pedido: si algo falla
se loguea y devuelve False, pero la operacion sigue su curso.
"""
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid

from flask import current_app


def _enabled() -> bool:
    return bool(current_app.config.get("MAIL_ENABLED"))


def send_email(
    to_address: str,
    subject: str,
    html_body: str,
    text_body: str = "",
    attachments: list | None = None,
    inline_images: list | None = None,
) -> bool:
    """Envia un correo HTML. Devuelve True si OK, False si fallo.

    Si MAIL_ENABLED es False simplemente loguea y devuelve False sin intentar.

    - attachments: lista de dicts {filename, content (bytes), mimetype}. Ej:
      {"filename": "ChevroCaracas-V-100.pdf", "content": b"...", "mimetype": "application/pdf"}
    - inline_images: lista de dicts {cid, content (bytes), subtype}. El `cid`
      se referencia en el HTML como <img src="cid:mi-id">. Ej:
      {"cid": "chevrocaracas-logo", "content": b"...", "subtype": "png"}
    """
    cfg = current_app.config

    if not to_address:
        current_app.logger.info("send_email: skip (sin destinatario) subject=%r", subject)
        return False

    if not _enabled():
        current_app.logger.info(
            "send_email: MAIL_ENABLED=False, skip envio a %s subject=%r", to_address, subject,
        )
        return False

    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = formataddr((cfg.get("MAIL_FROM_NAME", ""), cfg["MAIL_FROM_ADDRESS"]))
    msg["To"] = to_address
    if reply := cfg.get("MAIL_REPLY_TO"):
        msg["Reply-To"] = reply
    msg["Message-ID"] = make_msgid(domain=cfg.get("MAIL_HOST", "localhost"))

    msg.set_content(text_body or _strip_html(html_body))
    msg.add_alternative(html_body, subtype="html")

    # Imagenes inline (logo): se anexan a la parte HTML como multipart/related.
    if inline_images:
        html_part = msg.get_payload()[-1]  # la alternativa HTML recien agregada
        for img in inline_images:
            try:
                html_part.add_related(
                    img["content"],
                    maintype="image",
                    subtype=img.get("subtype", "png"),
                    cid=f"<{img['cid']}>",
                )
            except Exception as e:  # noqa: BLE001
                current_app.logger.warning("send_email: fallo imagen inline %s: %s", img.get("cid"), e)

    # Adjuntos (PDF de la nota de entrega, etc.)
    for att in (attachments or []):
        try:
            maintype, _, subtype = att.get("mimetype", "application/octet-stream").partition("/")
            msg.add_attachment(
                att["content"],
                maintype=maintype,
                subtype=subtype or "octet-stream",
                filename=att["filename"],
            )
        except Exception as e:  # noqa: BLE001
            current_app.logger.warning("send_email: fallo adjunto %s: %s", att.get("filename"), e)

    host = cfg["MAIL_HOST"]
    port = int(cfg.get("MAIL_PORT", 465))
    user = cfg["MAIL_USERNAME"]
    password = cfg["MAIL_PASSWORD"]
    use_ssl = bool(cfg.get("MAIL_USE_SSL", port == 465))
    timeout = int(cfg.get("MAIL_TIMEOUT", 20))

    try:
        ctx = ssl.create_default_context()
        if use_ssl:
            with smtplib.SMTP_SSL(host, port, timeout=timeout, context=ctx) as s:
                s.login(user, password)
                s.send_message(msg)
        else:
            with smtplib.SMTP(host, port, timeout=timeout) as s:
                s.ehlo()
                if cfg.get("MAIL_USE_TLS"):
                    s.starttls(context=ctx)
                    s.ehlo()
                s.login(user, password)
                s.send_message(msg)
        current_app.logger.info("send_email OK -> %s subject=%r", to_address, subject)
        return True
    except Exception as e:  # noqa: BLE001
        current_app.logger.exception(
            "send_email FAIL -> %s subject=%r error=%s", to_address, subject, e,
        )
        return False


def _strip_html(html: str) -> str:
    """Fallback texto plano super simple (sin libs externas)."""
    import re

    text = re.sub(r"<\s*br\s*/?>", "\n", html, flags=re.IGNORECASE)
    text = re.sub(r"</p>", "\n\n", text, flags=re.IGNORECASE)
    text = re.sub(r"<[^>]+>", "", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()
