"""Email sending via the ``send-emails`` CLI."""

from __future__ import annotations

import shutil
import subprocess
from pathlib import Path

from loguru import logger

from message_delivery.errors import EmailError


class EmailSender:
    """Send notes as emails using the ``send-emails`` CLI tool."""

    def is_available(self) -> bool:
        """Return ``True`` if the ``send-emails`` CLI is on ``PATH``."""
        return shutil.which("send-emails") is not None

    def send(self, note_path: Path, subject: str, to: str | None = None) -> None:
        """Send *note_path* as an email with *subject*.

        Uses ``send-emails send --subject <subject> --body-file <note_path>
        --render-html``.  Adds ``--to <to>`` when *to* is provided.

        Raises :class:`EmailError` if ``send-emails`` is not on ``PATH`` or
        if the subprocess returns a non-zero exit code.
        """
        if not self.is_available():
            raise EmailError(
                "send-emails CLI not found on PATH. Install it with: uv tool install send-emails"
            )

        cmd: list[str] = [
            "send-emails",
            "send",
            "--subject",
            subject,
            "--body-file",
            str(note_path),
            "--render-html",
        ]
        if to is not None:
            cmd.extend(["--to", to])

        logger.debug("Running email command: {}", " ".join(cmd))

        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
        except OSError as exc:
            raise EmailError(f"Failed to run send-emails: {exc}") from exc

        if result.returncode != 0:
            raise EmailError(
                f"send-emails failed (exit {result.returncode}): "
                f"{result.stderr.strip() or result.stdout.strip() or result}"
            )
