
    Yi                     ,   U d Z ddlmZ ddlZddlZddlmZmZmZ ddl	m
Z
 ddlmZmZmZ ddlmZmZmZ dd	lmZ dd
lmZ  ej.                  d      Zh dZ G d de      Zej6                  ej8                  ej:                  dZded<   dddZ g dZ!y)a  RLM Neo-Cortex -- Generic Webhook Receiver for Feedback Signals.

Provides a FastAPI router at POST /api/v1/feedback/webhook that external
systems (GHL, Instantly, custom apps) can POST to in order to record
feedback signals for any interaction.

Implements Story 5.08 of the RLM Neo-Cortex PRD (Module 5).

VERIFICATION_STAMP
Story: 5.08
Verified By: parallel-builder
Verified At: 2026-02-26
Tests: see tests/rlm/test_feedback.py
Coverage: 100%
    )annotationsN)AnyDictOptional)UUID)	APIRouterHTTPExceptionRequest)	BaseModelFieldfield_validator   )FeedbackSignal)FeedbackCollectorzcore.rlm.feedback_webhook>   neutralnegativepositivec                      e Zd ZU dZ edd      Zded<    eddd	      Zd
ed<    edd      Zd
ed<    edd      Z	d
ed<    e
d      edd              Zy)FeedbackWebhookRequestz/Incoming webhook payload for a feedback signal..z%UUID of the tenant (SubAIVA customer))descriptionr   	tenant_idr   zUnique interaction identifier)
min_lengthr   strinteraction_idz.Feedback signal: positive | negative | neutralsignalapizSignal source identifier)defaultr   sourcec                R    |t         vrt        d| dt        t                      |S )NzInvalid signal 'z'. Must be one of: )_VALID_SIGNALS
ValueErrorsorted)clsvs     2/mnt/e/genesis-system/core/rlm/feedback_webhook.pyvalidate_signalz&FeedbackWebhookRequest.validate_signal1   s7     N""1#%89O8PQ      N)r$   r   returnr   )__name__
__module____qualname____doc__r   r   __annotations__r   r   r   r   classmethodr&    r'   r%   r   r   &   su    9C-TUItU?^_NC_DFC  3MNFCNX  r'   r   )r   r   r   zDict[str, FeedbackSignal]_SIGNAL_ENUM_MAPc                n    t        ddg      }d| idfd|j                  d      d	fd       }|S )
zCreate and return the FastAPI router.

    Parameters
    ----------
    collector:
        Optional pre-built FeedbackCollector.  If not provided, the router
        will create one lazily from environment variables on first request.
    z/api/v1/feedbackfeedback)prefixtagsinstancec                      d   Jt        t        j                  j                  d      t        j                  j                  d             d<    d   S )Nr5   DATABASE_URL	REDIS_URL)pg_dsn	redis_url)r   osenvironget)_collector_holders   r%   _get_collectorz.create_feedback_router.<locals>._get_collectorR   sK    Z(0,=zz~~n5**..5-j) !,,r'   z/webhookc                  K           }t         | j                     }|j                  | j                  | j                         d{   }|7| j                  dk7  r(t        dd| j                   d| j                   d      |j                  | j                  | j                  |d| j                  i	       d{   }d
|du|r|j                  dS ddS 7 7 w)ao  Record a feedback signal from an external system.

        Returns
        -------
        HTTP 200  -- signal recorded successfully
            {"status": "recorded", "pair_generated": bool, "annotator_id": str}
        HTTP 422  -- invalid signal string (Pydantic validation)
        HTTP 404  -- interaction_id unknown (no cached interaction + no context)
        Nr   i  zInteraction 'z!' not found in cache for tenant 'z7'. Cache the interaction first via cache_interaction().)status_codedetailr   )r   r   r   contextrecorded)statuspair_generatedannotator_id)	r0   r   get_interactionr   r   r	   record_feedbackr   rG   )payloadcollsignal_enuminteractionpairr?   s        r%   receive_feedbackz0create_feedback_router.<locals>.receive_feedbackZ   s	     &w~~6 !001B1BGDZDZ[[7>>Y#>#G$:$:#; <##*#4#4"5 6KK  ))''"11w~~.	 * 
 
 !"$.15D--
 	
 <@
 	
% \
s%   ACCA5C=C>CC)r(   r   )rJ   r   r(   zDict[str, Any])r   post)	collectorrouterrO   r>   r?   s      @@r%   create_feedback_routerrS   F   sI     0
|DF)3Y(?- [[$
 $
L Mr'   )r   rS   r0   r    )N)rQ   zOptional[FeedbackCollector]r(   r   )"r,   
__future__r   loggingr;   typingr   r   r   uuidr   fastapir   r	   r
   pydanticr   r   r   	contractsr   r2   r   	getLoggerloggerr    r   POSITIVENEGATIVENEUTRALr0   r-   rS   __all__r/   r'   r%   <module>ra      s    #  	 & &  5 5 6 6 % '			6	7 5Y , ''''&&/ + ;|r'   