#!/usr/bin/env python3
"""
mailer.py
---------
Resend email helper. Sends the issued license key to the buyer.

Requires RESEND_API_KEY and SENDER_EMAIL to be set in the environment
(see .env.example). SENDER_EMAIL must be a verified sender/domain in
the Resend dashboard.
"""

from __future__ import annotations

import os

import resend


class MailError(Exception):
    """Raised when the license email cannot be sent."""


def _configured_sender() -> str:
    sender = os.environ.get("SENDER_EMAIL")
    if not sender:
        raise MailError("SENDER_EMAIL environment variable is not set.")
    return sender


def send_license_key_email(to_email: str, license_key: str) -> None:
    """Email *license_key* to *to_email*. Raises MailError on failure.

    If DRY_RUN=1 is set in the environment, no email is actually sent —
    the message is printed to stdout instead. Useful for exercising the
    full webhook -> keygen -> "email" flow locally without a real Resend
    account or API key.
    """
    subject = "Your HoverDesk license key"
    text_body = (
        "Thanks for purchasing HoverDesk!\n\n"
        f"Your license key:\n\n{license_key}\n\n"
        "Open HoverDesk, paste this key when prompted, and you're set.\n\n"
        "Keep this email for your records in case you need to reinstall."
    )

    if os.environ.get("DRY_RUN") == "1":
        print(f"[DRY_RUN] Would send email to {to_email}:\n{subject}\n{text_body}")
        return

    resend.api_key = os.environ.get("RESEND_API_KEY")
    if not resend.api_key:
        raise MailError("RESEND_API_KEY environment variable is not set.")

    try:
        resend.Emails.send({
            "from": _configured_sender(),
            "to": [to_email],
            "subject": subject,
            "text": text_body,
        })
    except Exception as exc:  # noqa: BLE001 - surface any SDK failure uniformly
        raise MailError(f"Failed to send license email: {exc}") from exc
