
    x|i%                        d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dl	m
Z
 d dlmZ d dlZd dlmZ d dlmZ  e j        e j                    e j        d	          Zdad
adadaede
fd            Z e
e          Z G d de          Z G d de          Z G d de          Z G d de          Ze                     d          dee!ef         fd            Z"e#dk    r ej$        edd           dS dS )    N)asynccontextmanager)OptionalDictAny)FastAPI)	BaseModel)WhatsAppService)TranscriptionService)levelzmcp-webhook-serverFappc                  K   t                               d           t                      at	                      addlm} dd l |d          a	fd}t          j         |                       d W V  t          rqt                               d           	 t                                           d {V  d S # t          $ r(}t                               d|            Y d }~d S d }~ww xY wd S )Nu3   🚀 Iniciando servidor y conectando Cliente MCP...r   AgrotaMcpClienthttp://localhost:8092/ssec                    K   	 t                               d           t                                           d {V  t                                          rt                               d           dad S t                               d           d S # t          $ rO} t                               d|             t                                j	                               Y d } ~ d S d } ~ ww xY w)Nu)   ⏳ Intentando conectar con MCP Server...u)   ✅ Cliente MCP conectado e inicializado!Tu-   ⚠️ Cliente MCP iniciado pero no conectadou+   ❌ Error CRÍTICO al iniciar Cliente MCP: )
loggerinfo
mcp_clientconnectis_connectedmcp_client_readywarningBaseExceptionerror
format_exc)e	tracebacks    gC:\Users\Dell Inspiron 16\Desktop\tws\github tws\Agrota\back-agrota-powerbi\mcp-client-agrota\server.pyconnect_mcpzlifespan.<locals>.connect_mcp*   s      
	1KKCDDD$$&&&&&&&&&&&(( PGHHH#'   NOOOOO 	1 	1 	1LLJqJJKKKLL--//000000000	1s   A.B 5B 
C*AC%%C*u!   🛑 Desconectando Cliente MCP...zError cerrando cliente MCP: )r   r   r	   whatsapp_servicer
   transcription_serviceapp.services.mcp_servicer   r   r   asynciocreate_task
disconnect	Exceptionr   )r   r   r   r   r   s       @r   lifespanr'      sE      KKEFFF '((022 988888 !<==J1 1 1 1 1 &&&	EEEE  =7888	=''))))))))))) 	= 	= 	=LL;;;<<<<<<<<<	=	= =s   B8 8
C*C%%C*)r'   c                       e Zd ZU eed<   dS )WhatsAppTextbodyN)__name__
__module____qualname__str__annotations__     r   r)   r)   I   s         
IIIIIr1   r)   c                   4    e Zd ZU eed<   dZee         ed<   dS )WhatsAppAudioidN	mime_type)r+   r,   r-   r.   r/   r5   r   r0   r1   r   r3   r3   M   s/         GGG#Ix}#####r1   r3   c                   R    e Zd ZU dZeed<   dZee         ed<   dZ	ee
         ed<   dS )WhatsAppMessagetexttypeNaudio)r+   r,   r-   r9   r.   r/   r8   r   r)   r:   r3   r0   r1   r   r7   r7   R   sL         D##'D(<
 '''%)E8M")))))r1   r7   c                   x    e Zd ZU dZeed<   dZeed<   eed<   dZeed<   dZe	e
         ed<   dZe	e         ed	<   dS )
WebhookPayloadwhatsappmessaging_product
individualrecipient_typetor8   r9   Nr:   )r+   r,   r-   r>   r.   r/   r@   r9   r8   r   r)   r:   r3   r0   r1   r   r<   r<   X   sv         's'''&NC&&&GGGD##'D(<
 '''%)E8M")))))r1   r<   z/webhookpayloadc                 ~
  K   t                               d|             t          spt                               d           t          d          D ]%}t          r nt	          j        d           d {V  &t          st                               d           t          sddlm	}  |d          at          
                                sot                               d	           	 t                                           d {V  n4# t          $ r'}t                               d
|            Y d }~nd }~ww xY wt          
                                s%t                               d           ddddidgdS 	 d}d| v rd| d         v r| d         d         }nd| v rd| d         v r| d         d         }t                               d| d           	 t                              |           d {V }t                               d|            t                              |           d {V }t                               dt#          |           d           | d                             dd          }d}	d|v sd|v rd}	n
d |v sd!|v rd!}	d"| d#|	 }
t&                              ||
           d {V }t                               d$|            |st+          d%          na# t          $ rE}t                               d&|            t-          j                     dddd'idgdcY d }~S d }~ww xY wt1          |           }t                               d(|            t                               d)|             t                               d*           t	          j        t                              d+d,|i          d-.           d {V }d/}|rt1          |          }t                               d0|            |                     d1d          }d2d3d4|dd|id5gd}|S # t          j        $ r? t                               d6           dd3d4|                     d1d          ddd7id5gdcY S t          $ r}t                               d8|            d9t1          |                                          v s#d:t1          |                                          v rt                                           d {V  dd3d4|                     d1d          ddd;t1          |           id5gdcY d }~S d }~ww xY w)<Nu   📩 Payload recibido: u1   ⏳ Esperando a que el cliente MCP esté listo...   g      ?uH   ⚠️ Timeout esperando conexión inicial, intentando de todos modos...r   r   r   u;   ⚠️ mcp_client not connected. Attempting reconnection...u   ❌ Reconnection failed: u   ❌ mcp_client is not ready.r   r8   r*   uZ   El servicio de IA no está disponible en este momento. La sesión no se ha podido iniciar.)r9   r8   )statusreplies r:   r4   u   🎤 Audio recibido (ID: z). Procesando...u   🔗 URL de descarga obtenida: u   💾 Audio descargado (z bytes)r5   z	audio/oggoggmp4aacm4ampegmp3audio_.u.   📝 Transcripción final para uso en prompt: u   Transcripción vacíau   ❌ Error procesando audio: z<Lo siento, hubo un problema al procesar tu mensaje de audio.u+   📥 [MENSAJE FINAL A PROCESAR] Contenido: u   🔍 Payload completo: u!   ⏳ Llamando a consultarAgrota...consultarAgrotapromptg      ^@)timeoutzNo response from toolu$   📤 [RESPUESTA ENVIADA] Contenido: rA   successr=   r?   )r>   r@   rA   r9   r8   uP   ❌ Timeout waiting for MCP tool response (120s). Possible SSE connection issue.u]   La consulta está tardando demasiado. El servidor MCP puede tener problemas de conexión SSE.u   ❌ Error procesando mensaje: sessionznot startedzError interno en MCP Client: )r   r   r   ranger#   sleepr   r   r"   r   r   r   r&   r   r    get_media_urldownload_medialengetr!   transcribe_audio
ValueErrorr   	print_excr.   debugwait_for	call_toolTimeoutErrorlowerr%   )rB   ir   r   user_messageaudio_id	audio_url
audio_datar5   extfilenameresult
reply_text	recipientresponses                  r   process_messagern   a   s      
KK3'33444
  
GHHHr 	% 	%A -$$$$$$$$$$ 	NNZ  
  B<<<<<<$_%@AA
""$$ :TUUU	:$$&&&&&&&&&& 	: 	: 	:LL8Q8899999999	: ""$$ 
3444 # | 

 

 
	
@
W76?!:!:"6?62LLDGG,<$<$<w'-HKKNHNNNOOO+"2"@"@"J"JJJJJJJ	IiIIJJJ $4#B#B9#M#MMMMMMM
Nc*ooNNNOOO $G,00kJJ	I%%)););CCy((EY,>,>C4H44s44%:%K%K& &             S\SS   $ >$%<===>    ?A??@@@#%%%% %+ &(f%  
 
 
 
 
 
 
 
  w<<LP,PPQQQ8w88999 	7888'  !2X|4LMM
 
 
 
 
 
 
 
 

 -
 	%VJG:GGHHH KKb))	   *4&2#"#Z0 
 
  
 
 
^	
 	
 	
  *4&2!++dB//"  

 
 	
 	
 	
  
 
 
9a99:::A&&-3q66<<>>*I*I'')))))))))  *4&2!++dB//"#%MSVV%M%MN 
 
 	
 	
 	
 	
 	
 	

sq   #D 
D4D//D46AP( DK& %P( &
L50:L0*L5+P( 0L55C2P( (AT<5	T<>B3T71T<7T<__main__z0.0.0.0iA  )hostport)%loggingr#   r   
contextlibr   typingr   r   r   fastapir   pydanticr   uvicornapp.services.whatsapp_servicer	   "app.services.transcription_servicer
   basicConfigDEBUG	getLoggerr   r   r   r    r!   r'   r   r)   r3   r7   r<   postr.   rn   r+   runr0   r1   r   <module>r      sE         * * * * * * & & & & & & & & & &              9 9 9 9 9 9 C C C C C C  '- ( ( ( (		/	0	0 
    (= (= (= (= (=V gx       9   $ $ $ $ $I $ $ $
* * * * *i * * ** * * * *Y * * * *m
4S> m
 m
 m
 m
` zGK)$////// r1   