"""Resend email client.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
This file is regenerated on every `prisme generate`.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

import resend

from {{ project_name }}.email.config import email_settings

logger = logging.getLogger(__name__)


def _configure_resend() -> None:
    """Set the Resend API key from settings."""
    resend.api_key = email_settings.resend_api_key


def send_email(
    to: str | list[str],
    subject: str,
    html: str,
    text: str = "",
    *,
    from_address: str | None = None,
    reply_to: str | None = None,
    cc: list[str] | None = None,
    bcc: list[str] | None = None,
    headers: dict[str, str] | None = None,
    tags: list[dict[str, str]] | None = None,
) -> dict[str, Any] | None:
    """Send an email via Resend.

    Args:
        to: Recipient email address(es).
        subject: Email subject line.
        html: HTML body content.
        text: Plain text body (fallback).
        from_address: Override the default From address.
        reply_to: Override the default Reply-To address.
        cc: CC recipients.
        bcc: BCC recipients.
        headers: Custom email headers.
        tags: Resend tags for tracking.

    Returns:
        Resend API response dict on success, None on failure.
    """
    _configure_resend()

    recipients = [to] if isinstance(to, str) else to
    sender = from_address or email_settings.email_from
    reply = reply_to or email_settings.email_reply_to

    payload: dict[str, Any] = {
        "from": sender,
        "to": recipients,
        "subject": subject,
        "html": html,
    }
    if text:
        payload["text"] = text
    if reply:
        payload["reply_to"] = reply
    if cc:
        payload["cc"] = cc
    if bcc:
        payload["bcc"] = bcc
    if headers:
        payload["headers"] = headers
    if tags:
        payload["tags"] = tags

    try:
        result = resend.Emails.send(payload)
        logger.info("Email sent to %s: subject=%r", recipients, subject)
        return result
    except Exception:
        logger.exception("Failed to send email to %s: subject=%r", recipients, subject)
        return None


async def send_email_async(
    to: str | list[str],
    subject: str,
    html: str,
    text: str = "",
    **kwargs: Any,
) -> dict[str, Any] | None:
    """Send an email asynchronously via a background thread.

    Wraps send_email() in asyncio.to_thread() so it doesn't block the event loop.
    All keyword arguments are forwarded to send_email().

    Returns:
        Resend API response dict on success, None on failure.
    """
    return await asyncio.to_thread(send_email, to, subject, html, text, **kwargs)


def send_email_fire_and_forget(
    to: str | list[str],
    subject: str,
    html: str,
    text: str = "",
    **kwargs: Any,
) -> None:
    """Schedule an email to be sent in the background without waiting.

    Uses asyncio.create_task() if an event loop is running,
    otherwise falls back to synchronous sending.
    """
    try:
        loop = asyncio.get_running_loop()
        loop.create_task(send_email_async(to, subject, html, text, **kwargs))
    except RuntimeError:
        # No running event loop — send synchronously
        send_email(to, subject, html, text, **kwargs)
