o
    i*,                     @   s  d Z ddlmZmZmZmZmZ ddlZddlm	Z	 ddl
mZmZ G dd deZG dd	 d	eZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd dZdS ) z;WhatsApp API.

API to communicate with WhatsApp Cloud API.
    )AnyDictListOptionalUnionN)logger)	BaseModelFieldc                   @   "   e Zd ZU dZeed< eed< dS )WhatsAppSessionzWebRTC session information for WhatsApp calls.

    Parameters:
        sdp: Session Description Protocol (SDP) data for WebRTC connection
        sdp_type: Type of SDP (e.g., "offer", "answer")
    sdpsdp_typeN__name__
__module____qualname____doc__str__annotations__ r   r   S/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/transports/whatsapp/api.pyr         
 r   c                   @   s:   e Zd ZU dZeed< eed< eed< eeef ed< dS )WhatsAppErrorzError information from WhatsApp API responses.

    Parameters:
        code: Error code number
        message: Human-readable error message
        href: URL for more information about the error
        error_data: Additional error-specific data
    codemessagehref
error_dataN)	r   r   r   r   intr   r   r   r   r   r   r   r   r   "   s   
 	r   c                   @   sZ   e Zd ZU dZeed< edddZeed< eed< eed< eed	< ee ed
< e	ed< dS )WhatsAppConnectCallaw  Incoming call connection event data.

    Represents a user-initiated call that requires handling. This is sent
    when a WhatsApp user initiates a call to your business number.

    Parameters:
        id: Unique call identifier
        from_: Phone number of the caller (WhatsApp ID format)
        to: Your business phone number that received the call
        event: Always "connect" for incoming calls
        timestamp: ISO 8601 timestamp when the call was initiated
        direction: Optional call direction ("inbound" for user-initiated calls)
        session: WebRTC session data containing SDP offer from the caller
    id.fromaliasfrom_toevent	timestamp	directionsessionN)
r   r   r   r   r   r   r	   r#   r   r   r   r   r   r   r   2   s   
 r   c                   @   s   e Zd ZU dZeed< edddZeed< eed< eed< eed	< ee ed
< dZ	ee ed< dZ
ee ed< dZee ed< dZee ed< dZee ed< dS )WhatsAppTerminateCalla;  Call termination event data.

    Represents the end of a call session, whether completed successfully,
    failed, or was rejected by either party.

    Parameters:
        id: Unique call identifier (matches the connect event)
        from_: Phone number of the caller
        to: Your business phone number
        event: Always "terminate" for call end events
        timestamp: ISO 8601 timestamp when the call ended
        direction: Optional call direction
        biz_opaque_callback_data: Optional business-specific callback data
        status: Call completion status ("FAILED", "COMPLETED", "REJECTED")
        start_time: ISO 8601 timestamp when call actually started (after acceptance)
        end_time: ISO 8601 timestamp when call ended
        duration: Call duration in seconds (only for completed calls)
    r   .r    r!   r#   r$   r%   r&   r'   Nbiz_opaque_callback_datastatus
start_timeend_timeduration)r   r   r   r   r   r   r	   r#   r   r*   r+   r,   r-   r.   r   r   r   r   r   r)   K   s   
 r)   c                   @   s   e Zd ZU dZeed< dS )WhatsAppProfilez_User profile information.

    Parameters:
        name: Display name of the WhatsApp user
    nameNr   r   r   r   r   r/   l   s   
 r/   c                   @   s"   e Zd ZU dZeed< eed< dS )WhatsAppContactzContact information for a WhatsApp user.

    Parameters:
        profile: User's profile information
        wa_id: WhatsApp ID (phone number in international format without +)
    profilewa_idN)r   r   r   r   r/   r   r   r   r   r   r   r1   v   r   r1   c                   @   r
   )WhatsAppMetadatazBusiness phone number metadata.

    Parameters:
        display_phone_number: Formatted phone number for display
        phone_number_id: WhatsApp Business API phone number ID
    display_phone_numberphone_number_idNr   r   r   r   r   r4      r   r4   c                   @   s:   e Zd ZU dZeed< eed< ee ed< ee	 ed< dS )WhatsAppConnectCallValuea  Webhook payload for incoming call events.

    Parameters:
        messaging_product: Always "whatsapp"
        metadata: Business phone number information
        contacts: List of contact information for involved parties
        calls: List of call connection events
    messaging_productmetadatacontactscallsN)
r   r   r   r   r   r   r4   r   r1   r   r   r   r   r   r7      s   
 	r7   c                   @   sB   e Zd ZU dZeed< eed< ee ed< dZ	e
ee  ed< dS )WhatsAppTerminateCallValuea  Webhook payload for call termination events.

    Parameters:
        messaging_product: Always "whatsapp"
        metadata: Business phone number information
        calls: List of call termination events
        errors: Optional list of errors that occurred during the call
    r8   r9   r;   Nerrors)r   r   r   r   r   r   r4   r   r)   r=   r   r   r   r   r   r   r<      s   
 	r<   c                   @   s*   e Zd ZU dZeeef ed< eed< dS )WhatsAppChangezWebhook change event wrapper.

    Parameters:
        value: The actual event data (connect or terminate)
        field: Always "calls" for calling webhooks
    valuefieldN)	r   r   r   r   r   r7   r<   r   r   r   r   r   r   r>      s   
 r>   c                   @   &   e Zd ZU dZeed< ee ed< dS )WhatsAppEntryzWebhook entry containing one or more changes.

    Parameters:
        id: WhatsApp Business Account ID
        changes: List of change events in this webhook delivery
    r   changesN)r   r   r   r   r   r   r   r>   r   r   r   r   rB      s   
 rB   c                   @   rA   )WhatsAppWebhookRequesta(  Complete webhook request from WhatsApp.

    This is the top-level structure for all webhook deliveries from
    the WhatsApp Cloud API for calling events.

    Parameters:
        object: Always "whatsapp_business_account"
        entry: List of webhook entries (usually contains one entry)
    objectentryN)r   r   r   r   r   r   r   rB   r   r   r   r   rD      s   
 
rD   c                   @   s   e Zd ZdZdZdededejddfdd	Zdefd
dZ	defddZ
dedededefddZdefddZdefddZdS )WhatsAppApia  WhatsApp Cloud API client for handling calls.

    This class provides methods to interact with the WhatsApp Cloud API
    for managing voice calls, including answering, rejecting, and terminating calls.

    Parameters:
        BASE_URL: Base URL for WhatsApp Graph API v23.0
        phone_number_id: Your WhatsApp Business phone number ID
        session: aiohttp client session for making HTTP requests
        whatsapp_url: Complete URL for the calls endpoint
        whatsapp_token: Bearer token for API authentication
    z!https://graph.facebook.com/v23.0/whatsapp_tokenr6   r(   returnNc                 C   s(   || _ || _| j | d| _|| _dS )a  Initialize the WhatsApp API client.

        Args:
            whatsapp_token: WhatsApp access token for authentication
            phone_number_id: Your business phone number ID from WhatsApp Business API
            session: aiohttp ClientSession for making HTTP requests
        z/callsN)_phone_number_id_sessionBASE_URL_whatsapp_url_whatsapp_token)selfrH   r6   r(   r   r   r   __init__   s   

zWhatsAppApi.__init__c                 C   
   || _ dS )z4Update the WhatsApp access token for authentication.N)rN   )rO   rH   r   r   r   update_whatsapp_token      
z!WhatsAppApi.update_whatsapp_tokenc                 C   rQ   )z7Update the WhatsApp phone number ID for authentication.N)rJ   )rO   r6   r   r   r   update_whatsapp_phone_number_id   rS   z+WhatsAppApi.update_whatsapp_phone_number_idcall_idactionr   r#   c              
      s   t d| d|  | jj| jd| j ddd||||ddd	d
4 I dH }| I dH W  d  I dH  S 1 I dH sBw   Y  dS )a7  Answer an incoming WhatsApp call.

        This method handles the call answering process, supporting both "pre_accept"
        and "accept" actions as required by the WhatsApp calling workflow.

        Args:
            call_id: Unique identifier for the call (from connect webhook)
            action: Action to perform ("pre_accept" or "accept")
            sdp: Session Description Protocol answer for WebRTC connection
            from_: Caller's phone number (WhatsApp ID format)

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            Calls must be pre-accepted before being accepted. The typical flow is:
            1. Receive connect webhook
            2. Call with action="pre_accept"
            3. Call with action="accept"
        zAnswering call z to WhatsApp, action:Bearer application/jsonAuthorizationzContent-Typewhatsappanswer)r   r   )r8   r$   rV   rU   r(   headersjsonNr   debugrK   postrM   rN   r_   )rO   rU   rV   r   r#   responser   r   r   answer_call_to_whatsapp   s"   
0z#WhatsAppApi.answer_call_to_whatsappc              	         t d|  | jj| jd| j dddd|dd4 I d	H }| I d	H W  d	  I d	H  S 1 I d	H s:w   Y  d	S )
al  Reject an incoming WhatsApp call.

        This method rejects a call that was received via connect webhook.
        The caller will receive a rejection notification and a terminate
        webhook will be sent with status "REJECTED".

        Args:
            call_id: Unique identifier for the call (from connect webhook)

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            This should be called instead of answer_call_to_whatsapp when you want
            to decline the incoming call. The caller will see the call as rejected.
        zRejecting call rW   rX   rY   r[   rejectr8   rV   rU   r]   Nr`   rO   rU   rc   r   r   r   reject_call_to_whatsapp"  s   
0z#WhatsAppApi.reject_call_to_whatsappc              	      re   )
a}  Terminate an active WhatsApp call.

        This method ends an ongoing call that has been previously accepted.
        Both parties will be disconnected and a terminate webhook will be
        sent with status "COMPLETED".

        Args:
            call_id: Unique identifier for the active call

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            This should only be called for calls that have been accepted and are
            currently active. For incoming calls that haven't been accepted yet,
            use reject_call_to_whatsapp instead.
        zTerminating call rW   rX   rY   r[   	terminaterg   r]   Nr`   rh   r   r   r   terminate_call_to_whatsappB  s   
0z&WhatsAppApi.terminate_call_to_whatsapp)r   r   r   r   rL   r   aiohttpClientSessionrP   rR   rT   rd   ri   rk   r   r   r   r   rG      s"    
& rG   )r   typingr   r   r   r   r   rl   logurur   pydanticr   r	   r   r   r   r)   r/   r1   r4   r7   r<   r>   rB   rD   rG   r   r   r   r   <module>   s$   !
