
    מiE                        d Z ddlmZ ddlZddlZddlmZ ddlmZ  ej                  e
      ZdZ	 ddlZdZ G d
 d      Zeddf	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy# e$ r dZdZej#                  d	       Y <w xY w)u  
core/email/client.py
Genesis Email Client — Resend-backed transactional email.

Usage:
    from core.email.client import GenesisEmail, send_email

    client = GenesisEmail()
    result = client.send(
        to="recipient@example.com",
        subject="Hello from Genesis",
        html="<p>Welcome aboard.</p>",
    )

    # Or use the convenience function
    result = send_email(to="recipient@example.com", subject="Hi", html="<p>Hi</p>")

The resend package is OPTIONAL.  When it is not installed (or the API key is
missing), every method degrades gracefully — it logs a warning and returns an
error dict instead of raising an exception.

Default from address: noreply@sunaivadigital.com
API key env var:      RESEND_API_KEY

# VERIFICATION_STAMP
# Story: M10.02 — core/email/client.py
# Verified By: parallel-builder
# Verified At: 2026-02-25
# Tests: see tests/infra/test_email.py
# Coverage: 100%
    )annotationsN)Union)render_templateznoreply@sunaivadigital.comTFz^resend package is not installed.  Email sending is disabled.  Install with: pip install resendc                  d    e Zd ZdZdddZedf	 	 	 	 	 	 	 	 	 	 	 d	dZef	 	 	 	 	 	 	 	 	 d
dZddZy)GenesisEmailz
    Transactional email client backed by the Resend API.

    Parameters
    ----------
    api_key:
        Resend API key.  When omitted the value is read from the
        ``RESEND_API_KEY`` environment variable.
    Nc                    |xs t         j                  j                  d      | _        t        st
        j                  d       y | j                  st
        j                  d       y y )NRESEND_API_KEYuT   GenesisEmail: resend package unavailable — all send calls will return error dicts.uP   GenesisEmail: RESEND_API_KEY not set — all send calls will return error dicts.)osenvironget_api_key_RESEND_AVAILABLEloggerwarning)selfapi_keys     */mnt/e/genesis-system/core/email/client.py__init__zGenesisEmail.__init__N   sO    $+$Orzz~~>N/O NN& NN&     c                   t         sdddS | j                  sdddS t        |t              r|gn
t	        |      }	 | j                  t
        _        ||||d}|r||d<   t
        j                  j                  |      }t        |dd      xs |j                  dd	      }	|	d
dS # t        $ r.}
t        j                  d|
       t        |
      ddcY d}
~
S d}
~
ww xY w)a>  
        Send a single transactional email.

        Parameters
        ----------
        to:
            Recipient address or list of addresses.
        subject:
            Email subject line.
        html:
            HTML body content.
        from_addr:
            Sender address (default: noreply@sunaivadigital.com).
        reply_to:
            Optional reply-to address.

        Returns
        -------
        dict
            On success: {"id": "<resend_email_id>", "status": "sent"}
            On failure: {"error": "<message>", "status": "failed"}
        zresend package not installedfailederrorstatuszRESEND_API_KEY not configured)fromtosubjecthtmlreply_toidNunknownsent)r    r   zGenesisEmail.send failed: %s)r   r   
isinstancestrlist_resend_libr   Emailssendgetattrr   	Exceptionr   r   )r   r   r   r   	from_addrr   
recipientsparamsresponseemail_idexcs              r   r(   zGenesisEmail.send`   s    < !;xPP}}<QQ (C0bTd2h
	;"&--K " "	F %-z""))..v6Hxt4UT98UH"f55 	;LL7= X::	;s   A'B$ $	C-#CCCc                    	 t        ||      \  }}| j                  ||||      S # t        $ r}d| ddcY d}~S d}~wt        $ r}d| ddcY d}~S d}~ww xY w)a  
        Render a named template and send it.

        Parameters
        ----------
        to:
            Recipient address or list of addresses.
        template_name:
            Key in core.email.templates.TEMPLATES.
        variables:
            Dict of variables to interpolate into the template.
        from_addr:
            Sender address.

        Returns
        -------
        dict
            Same structure as :meth:`send`.
        zUnknown template: r   r   NzTemplate render error: )r   r   r   r+   )r   KeyErrorr*   r(   )r   r   template_name	variablesr+   r   r   r0   s           r   send_templatezGenesisEmail.send_template   ss    4	R+M9EMGT yyBdiyPP  	M1#78LL 	R6se<QQ	Rs)   & 	A<AAAAAc           
        g }|D ]|  }| j                  |j                  dd      |j                  dd      |j                  dd      |j                  dt              |j                  d            }|j                  |       ~ |S )at  
        Send multiple emails in sequence.

        Each element of *messages* must be a dict accepted by :meth:`send`::

            {
                "to": "recipient@example.com",
                "subject": "Hello",
                "html": "<p>Hello</p>",
                # optional:
                "from_addr": "custom@sunaivadigital.com",
                "reply_to": "support@sunaivadigital.com",
            }

        Parameters
        ----------
        messages:
            List of message dicts.

        Returns
        -------
        list[dict]
            One result dict per message in the same order.
        r    r   r   r+   r   r   r   r   r+   r   )r(   r   DEFAULT_FROMappend)r   messagesresultsmsgresults        r   
batch_sendzGenesisEmail.batch_send   s    2 ! 	#CYY774$	2.WWVR(''+|<,  F NN6"	# r   )N)r   
str | NonereturnNone)r   Union[str, list[str]]r   r$   r   r$   r+   r$   r   r@   rA   dict)
r   rC   r3   r$   r4   rD   r+   r$   rA   rD   )r;   
list[dict]rA   rE   )	__name__
__module____qualname____doc__r   r9   r(   r5   r?    r   r   r   r   C   s    . &#9;!9; 9; 	9;
 9; 9; 
9;@ &!Q!!Q !Q 	!Q
 !Q 
!QF#r   r   c                F    t        |      }|j                  | ||||      S )a  
    Module-level convenience wrapper around :class:`GenesisEmail`.

    Parameters
    ----------
    to, subject, html, from_addr, reply_to:
        Forwarded to :meth:`GenesisEmail.send`.
    api_key:
        Optional API key override; otherwise reads ``RESEND_API_KEY`` from env.

    Returns
    -------
    dict
        {"id": ..., "status": "sent"} or {"error": ..., "status": "failed"}
    )r   r8   )r   r(   )r   r   r   r+   r   r   clients          r   
send_emailrM      s3    . '*F;;   r   )r   rC   r   r$   r   r$   r+   r$   r   r@   r   r@   rA   rD   )rI   
__future__r   loggingr
   typingr   core.email.templatesr   	getLoggerrF   r   r9   resendr&   r   ImportErrorr   r   rM   rJ   r   r   <module>rU      s   > #  	  0			8	$+  ^ ^T "  	
   
k  K
NN	+s   A A54A5