
    O5i0                        U d Z ddlZddlZddlZddlmZmZ  ej                  dd      Z ej                  dd      Z	dd	d
dddddddddddZ
eeef   ed<   	 dVdedeeef   dedeeef   fdZ	 dVdedeeef   dedeeef   fdZ	 	 dWdedeeeef      dedeeef   fdZdVdedeeef   fd ZdVdededeeef   fd!Z	 	 dXd"ed#ed$ed%ed&eeeef      deeef   fd'Z	 dYd(ed)ed*ed+ed,ed&eeeef      deeef   fd-Z	 	 	 dZd.ed/ed0ed1eeeef      deeef   f
d2Zdeeef   fd3Zed4k(  rBddlZddlZ ed5        ed6e         ed7e	rd8e	dd9 z   d:z   nd;         e         ed<        e       Z ed= ej:                  ed>?               e         ed@        edAdBdCdDE      Z ed= ej:                  ed>?               e        e	rp edF        e       ZdGev rQedG   D ]H  Zej?                  dH      rdIndJZ  edKe  dLej?                  dMdN       dOej?                  dP       dQ       J n edRe        n edS        edT        edU        ejB                  d       yy)[a  
Genesis n8n Trigger Bridge
Allows Claude Code and any Genesis agent to fire n8n webhooks programmatically.

Usage:
    from core.n8n_trigger import trigger_webhook, notify_lead_captured

    # Fire a lead capture event
    result = notify_lead_captured("John Smith", "+61412345678", "concreting")

    # Fire any arbitrary webhook
    result = trigger_webhook("stripe-event", {"type": "checkout.session.completed"})

    # Trigger a workflow by ID via the n8n management API
    result = trigger_workflow_by_id("abc123", {"key": "value"})
    N)AnyOptionalN8N_BASE_URLz)https://n8n-genesis-u50607.vm.elestio.appN8N_API_KEY z/webhook/telnyx-lead-capturez/webhook/stripe-lifecyclez/webhook/genesis-healthz/webhook/agent-completionz/webhook/youtube-scoutz/webhook/ghl-contact-createdz/webhook/ghl-pipelinez/webhook/claude-dispatchz/webhook/instantly-replyz/webhook/calcom-bookingz/webhook/telnyx-call-eventsz/webhook/claude-desktop-to-codez/webhook/claude-code-to-desktop)telnyx-leadstripe-eventhealth-checkzagent-completezyoutube-scoutzghl-contactzghl-pipelineclaude-dispatchzinstantly-replyzcalcom-bookingztelnyx-callzclaude-desktop-to-codezclaude-code-to-desktopWEBHOOK_ENDPOINTS
event_namepayloadtimeoutreturnc                    t         j                  |       }|s#d| t        t         j                               dS t         | }	 t        j                  |||      }|j                  |j                  dd |dS # t
        j                  j                  $ r}dd| d	| icY d}~S d}~wt
        j                  j                  $ r dd
| d| icY S t        $ r}dt        |      icY d}~S d}~ww xY w)aZ  
    Fire an n8n webhook by logical event name.

    Args:
        event_name: Key from WEBHOOK_ENDPOINTS (e.g. 'telnyx-lead')
        payload:    Dict to POST as JSON body
        timeout:    Request timeout in seconds

    Returns:
        Dict with 'status' (HTTP code) and 'response' (body) on success,
        or 'error' key on failure.
    zUnknown event: )errorknownjsonr   N  statusresponseurlr   zConnection failed to : zTimeout after z
s calling )r   getlistkeysr   requestspoststatus_codetext
exceptionsConnectionErrorTimeout	Exceptionstr)r   r   r   endpointr   respes          )/mnt/e/genesis-system/core/n8n_trigger.pytrigger_webhookr,   4   s   " !$$Z0H&zn5+0023
 	

 N8*
%C!}}Sw@&&		$3
 	

 .. =0Rs;<<&& D>'*SEBCC !Q  !s6   4A; ;C2	B'!C2'*C2C2C-'C2-C2pathc                     t          |  }	 t        j                  |||      }|j                  |j                  dd |dS # t
        $ r}dt        |      icY d}~S d}~ww xY w)a.  
    POST to an arbitrary n8n webhook path (no lookup table needed).

    Args:
        path:    Webhook path, e.g. '/webhook/my-custom-path'
        payload: Dict to POST as JSON body
        timeout: Request timeout in seconds

    Returns:
        Dict with 'status' and 'response', or 'error'.
    r   Nr   r   r   )r   r   r    r!   r"   r&   r'   )r-   r   r   r   r)   r*   s         r+   trigger_webhook_rawr/   \   sf      N4&
!C!}}Sw@**		$3PSTT !Q  !s   4A 	A!
AA!A!workflow_idc                     t         sddiS t         d|  d}t         dd}	 t        j                  ||d|xs i i|      }|j                  |j                         d	S # t        $ r}dt        |      icY d
}~S d
}~ww xY w)ak  
    Trigger a specific n8n workflow execution via the management API.
    Requires N8N_API_KEY environment variable to be set.

    Args:
        workflow_id: The n8n workflow UUID or ID string
        payload:     Optional data to pass as workflowData
        timeout:     Request timeout in seconds

    Returns:
        Dict with execution data or error.
    r   "N8N_API_KEY not set in environment/api/v1/workflows/z/runzapplication/json)X-N8N-API-KEYzContent-TypeworkflowData)headersr   r   )r   r   N)r   r   r   r    r!   r   r&   r'   )r0   r   r   r   r6   r)   r*   s          r+   trigger_workflow_by_idr7   w   s    " =>>N,[M
>C$*G	!}} '-R0	
 **		DD !Q  !s   ;A 	A=&A82A=8A=c                    t         sddiS t         d}dt         i}	 t        j                  |||       }|j                  dk(  r>|j                         }|j                  dg       t        |j                  dg             dS dd	|j                   d
|j                  dd  iS # t        $ r}dt        |      icY d}~S d}~ww xY w)z
    List all workflows in the n8n instance via the management API.
    Requires N8N_API_KEY.

    Returns:
        Dict with 'workflows' list or 'error'.
    r   r2   z/api/v1/workflowsr4   r6   r      data)	workflowscountHTTP r   N)
r   r   r   r   r!   r   lenr"   r&   r'   )r   r   r6   r)   r;   r*   s         r+   list_workflowsr@      s     =>>N+
,C,G!||C'Bs"99;D!%&"!5DHHVUWDX@YZZ5!1!1 2"TYYt_4EFGG !Q  !s$   A$B#  B# #	C,B>8C>Cc                    t         sddiS t         d|  }dt         i}	 t        j                  |||      }|j                  dk(  rS|j                         }|j                  d      |j                  d      |j                  d	      |j                  d
      dS dd|j                   d|j                  dd  iS # t        $ r}dt        |      icY d}~S d}~ww xY w)zR
    Get the current status of a specific workflow.
    Requires N8N_API_KEY.
    r   r2   r3   r4   r9   r:   idnameactive	updatedAt)rB   rC   rD   rE   r>   r   N)	r   r   r   r   r!   r   r"   r&   r'   )r0   r   r   r6   r)   r;   r*   s          r+   get_workflow_statusrF      s    
 =>>N,[M
:C,G!||C'Bs"99;Dhhtn(((8,!XXk2	  5!1!1 2"TYYt_4EFGG !Q  !s$   A9B:  B: :	CCCCcustomer_namephoneservicesourceextrac                     | |||t         j                   j                         j                         d}|r|j                  |       t	        d|      S )u  
    Fire lead capture webhook — call this after every voice conversation.

    This triggers the Telnyx Lead → GHL CRM workflow in n8n which:
    - Creates/updates contact in GHL
    - Tags with service interest
    - Triggers SMS + email follow-up
    - Stores in PostgreSQL leads table

    Args:
        customer_name: Full name of the lead
        phone:         Phone number (E.164 format preferred, e.g. +61412345678)
        service:       What service they're interested in (e.g. 'concreting')
        source:        Lead source (default: 'telnyx')
        extra:         Any additional fields to include in the payload

    Returns:
        Dict with webhook response or error.
    )rG   phone_numberservice_interestrJ   	timestampr   datetimeutcnow	isoformatupdater,   )rG   rH   rI   rJ   rK   r   s         r+   notify_lead_capturedrU      sP    6 '#&&--/99;G u='22    
event_typecustomer_emailbusiness_nameplanstripe_customer_idc                     | ||||t         j                   j                         j                         d}|r|j                  |       t	        d|      S )u  
    Fire a Stripe lifecycle event to n8n.

    Triggers the Stripe Lifecycle Handler which provisions/offboards customers.

    Common event_types:
    - 'checkout.session.completed'  → provision customer
    - 'invoice.payment_failed'      → start dunning sequence
    - 'customer.subscription.deleted' → offboard

    Args:
        event_type:         Stripe event type string
        customer_email:     Customer's email address
        business_name:      Their business name
        plan:               Subscription plan ('starter'/'professional'/'agency')
        stripe_customer_id: Stripe cus_xxx identifier
        extra:              Additional fields

    Returns:
        Dict with webhook response or error.
    )typerX   rY   rZ   r[   rO   r	   rP   )rW   rX   rY   rZ   r[   rK   r   s          r+   notify_stripe_eventr^      sS    < (&0&&--/99;G u>733rV   taskpriority
agent_typecontextc                     | ||t         j                   j                         j                         d}|r||d<   t        d|      S )a  
    Dispatch a task to n8n for Gemini swarm execution.

    n8n will route this to the Genesis execution layer.

    Args:
        task:       Natural language task description
        priority:   'critical', 'high', 'normal', or 'low'
        agent_type: 'gemini', 'claude', or 'openrouter'
        context:    Optional additional context dict

    Returns:
        Dict with webhook response or error.
    )r_   r`   ra   rO   rb   r   )rQ   rR   rS   r,   )r_   r`   ra   rb   r   s        r+   dispatch_agent_taskrd     sL    *  &&--/99;	G $	,g66rV   c                  v    t        ddt        j                  j                         j                         dd      S )zn
    Send a health ping to n8n genesis-health webhook.
    Use for confirming the webhook bridge is live.
    r
   zn8n_trigger.pyzGenesis health ping)rJ   rO   message)r,   rQ   rR   rS    rV   r+   health_pingrh   >  s9    
 >"&&--/99;(,  rV   __main__u1   === Genesis n8n Trigger Bridge — Self Test ===
zN8N_BASE_URL: zN8N_API_KEY:  zSET (   z...)zNOT SETz[1] Health check webhook...z    Result:    )indentu5   [2] Lead capture test (DRY RUN — sending to n8n)...z	TEST LEADz+61400000000ztest-servicen8n_trigger_selftest)rG   rH   rI   rJ   z/[3] Listing workflows (requires N8N_API_KEY)...r<   rD   ACTIVEinactivez    [z] rC   unnamedz (id=rB   )z    Error: u2   [3] Skipping workflow list — N8N_API_KEY not setzH    Set N8N_API_KEY in config/secrets.env to enable management API callsz
=== Self test complete ===)
   )N   )telnyxN)N)normalgeminiN)"__doc__rQ   osr   typingr   r   getenvr   r   r   dictr'   __annotations__intr,   r/   r7   r@   rF   rU   r^   rd   rh   __name__r   sysprintresultdumpswfr   r   exitrg   rV   r+   <module>r      s'  "  	   
 ryy)TUbiir*
 731306/2215??% 4S> 0 %!%!#s(^%! %! 
#s(^	%!V !
!#s(^! ! 
#s(^	!: )-"!"!d38n%"! "! 
#s(^	"!J!C !c3h !.!S !3 !S#X !@ &*#3#3#3 #3 	#3
 DcN##3 
#s(^#3X '+'4'4'4 '4 	'4
 '4 DcN#'4 
#s(^'4X (,	7
77 7 d38n%	7
 
#s(^7>	T#s(^ 	 z	
>?	N<.
)*	N7[!_4v=R[\
]^	G 

'(]F	LF156
78	G 

AB!!%	F 
LF156
78	G ?@!& [) Y%'VVH%5:fXRvy(A'B%t~UVWXY Kx()BCXY	
()CHHQKS rV   