
    _i;-                       U d Z ddlmZ 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 ej                  j                  dd      j                         Z ej                    eeeej$                        dd	
        ej&                  d      Z	 ddlmZ ddlmZ dZddlmZ ddlmZ ddlm Z! ddl"m#Z$ da%de&d<   ddZ'edd       Z(ddZ)er e)       Z*ndZ*dd dZ+e,dk(  r e+        yy# e$ r	 dZdZdZY \w xY w)!ui  RLM Neo-Cortex -- FastAPI Integration Application.

This is the top-level FastAPI application that wires together every RLM
module into a single runnable server on port 8100.

Routers mounted:
    /api/v1/memory/*   — gateway_router  (Module 1: write, search, delete, health)
    /api/v1/feedback/* — feedback_webhook (Module 5: webhook for preference signals)

Middleware stack (innermost first):
    1. CORS              — allows widget origins and localhost dev
    2. TenantMiddleware  — extracts tenant UUID from JWT or API key

Lifecycle:
    startup  — initialises MemoryGateway (opens PG pool, Qdrant, Redis)
    shutdown — closes all backend connections gracefully

Run with::

    uvicorn core.rlm.app:app --host 0.0.0.0 --port 8100

Or via the helper shipped in this module::

    from core.rlm.app import run
    run()

Story: integration-layer-app
    )annotationsN)asynccontextmanager)AnyAsyncIteratorDict	LOG_LEVELINFOz1%(asctime)s [%(levelname)s] %(name)s: %(message)sz%Y-%m-%dT%H:%M:%S)levelformatdatefmtzcore.rlm.app)FastAPI)CORSMiddlewareTF   )settings)MemoryGateway)create_router)create_feedback_routerzMemoryGateway | None_gatewayc                 P    t         t         j                  st        d      t         S )zReturn the initialised MemoryGateway singleton.

    Raises:
        RuntimeError: If called before the application lifespan has started.
    zhMemoryGateway is not initialised.  Ensure the FastAPI lifespan has started before calling get_gateway().)r   is_initializedRuntimeError     %/mnt/e/genesis-system/core/rlm/app.pyget_gatewayr   N   s,     x66T
 	
 Or   c                 K   t         j                  d       	 t        j                          t        t        j                  t        j                  t        j                  t        j                        a	 t        j                          d{    t         j                  d       d t         j                  d       t        3	 t        j                          d{    t         j                  d       yy# t        $ r}t         j                  d|        d}~ww xY w7 # t        $ r}t         j                  d|        d}~ww xY w7 m# t        $ r Y vw xY ww)	u1   Startup → yield → shutdown lifecycle manager.zRLM application starting up...zConfiguration invalid: %sN)pg_dsn
qdrant_urlqdrant_api_key	redis_urlz&MemoryGateway initialised successfullyz'MemoryGateway initialisation failed: %sz RLM application shutting down...zMemoryGateway closed)loggerinfor   validate
ValueErrorcriticalr   database_urlr   r   r    r   
initialize	Exceptionclose)appexcs     r   	_lifespanr,   `   s    
 KK01 $$&&..$$	H!!###<= 
 KK23	..""" 	*+ 1  3S9 	$ A3G # 		s   EC: AE5D$ D"D$ & EE EE #E:	DDDE"D$ $	E	-EE		EE 	EEEEc            	        t         st        d      t        j                  rdnd} t        j                  rdnd}t	        t        j                  rdndt        j                  rdndd	| |t        j                  rd
ndt
              }|j                  t        t        j                  dg ddg       	 ddl	m
}m} |r)|'|j                  |       t        j                  d       nt        j                  d       |j                  dt        j                        d!d       }|j                  dd      d"d       } G d d      }t!         |             }	|j#                  |	       t        j                  d       t%        d      }
|j#                  |
       t        j                  d        |S # t        $ r }t        j                  d|       Y d}~d}~ww xY w)#zBuild and return the configured FastAPI application.

    Returns:
        FastAPI application with all routers, middleware, and lifecycle hooks.

    Raises:
        ImportError: If fastapi is not installed.
    zTfastapi is required to run the RLM server. Install with: pip install fastapi uvicornz/docsNz/redoczRLM Neo-Cortex APIAPIuC   Living Memory Bloodstream — RLM Neo-Cortex memory management API. 1.0.0z/openapi.json)titledescriptionversiondocs_url	redoc_urlopenapi_urllifespanT)GETPOSTDELETEOPTIONS*)allow_originsallow_credentialsallow_methodsallow_headersr   )TenantMiddleware_MIDDLEWARE_AVAILABLEzTenantMiddleware registeredzxTenantMiddleware could not be registered (starlette not available). Tenant isolation will not be enforced by middleware.z"TenantMiddleware import failed: %sz/health)include_in_schemac            	       K   t         t         j                  sddddS t         j                          d{   } | j                  dd      dd| j                  d	d
      | j                  dd
      | j                  dd
      ddS 7 Ow)zFTop-level health check.  Reports gateway readiness and backend status.Nstartingnot_initializedr0   )statusgatewayr3   rG   unknowninitializedpgFqdrantredis)
postgresqlrL   rM   )rG   rH   r3   backends)r   r   health_checkget)backend_healths    r   healthzcreate_app.<locals>.health   s      8#:#:$," 
  (4466$((9=$,00u=,005A,00%@		
 		
 7s   4BBAB/Fc                    K   dddS w)Nzrlm-neo-cortexr0   )servicer3   r   r   r   r   rootzcreate_app.<locals>.root   s     +@@s   c                      e Zd ZdZddZy)!create_app.<locals>._GatewayProxyz;Thin proxy that delegates all attribute access to _gateway.c                @    t         }|t        d      t        ||      S )Nz!MemoryGateway not yet initialised)r   r   getattr)selfnamegws      r   __getattr__z-create_app.<locals>._GatewayProxy.__getattr__   s%    Bz"#FGG2t$$r   N)r]   strreturnr   )__name__
__module____qualname____doc__r_   r   r   r   _GatewayProxyrY      s
    I	%r   rf   )rH   z'Memory router mounted at /api/v1/memory)	collectorz+Feedback router mounted at /api/v1/feedback)ra   zDict[str, Any])ra   zDict[str, str])_FASTAPI_OKImportErrorr   enable_api_docsr   r,   add_middlewarer   cors_origins
middlewarerA   rB   r!   r"   warningrQ   _create_memory_routerinclude_router_create_feedback_router)	_docs_url
_redoc_urlapplicationrA   rB   r+   rS   rW   rf   memory_routerfeedback_routers              r   
create_apprw      s    8
 	

 &554I%554J&.&>&>"E '' R'/'?'?OTK" ++:e  BG %5%A&&'78KK56NNG __Y(2J2J_K
 L
0 __SE_2A 3A% % *-/BM}-
KK9: .=O/
KK=>E  B;SAABs   2AF1 1	G:GGc                    	 ddl }|j                  d| xs t        j                  |xs t        j
                  |t        j                  j                                y# t        $ r}t        d      |d}~ww xY w)zStart the RLM server using uvicorn.

    Args:
        host: Bind host (defaults to settings.rlm_host).
        port: Bind port (defaults to settings.rlm_port).
        reload: Enable hot-reload for development.
    r   NzLuvicorn is required to run the RLM server. Install with: pip install uvicornzcore.rlm.app:app)hostportreload	log_level)uvicornri   runr   rlm_hostrlm_portr|   lower)ry   rz   r{   r}   r+   s        r   r~   r~     sz     KK&X&&&X&&$$**,    0
 	s   A 	A7&A22A7__main__)ra   r   )r*   	'FastAPI'ra   zAsyncIterator[None])ra   r   )NNF)ry   z
str | Nonerz   z
int | Noner{   boolra   None)-re   
__future__r   loggingossys
contextlibr   typingr   r   r   environrQ   upper
_LOG_LEVELbasicConfigr[   r	   	getLoggerr!   fastapir   fastapi.middleware.corsr   rh   ri   configr   rH   r   gateway_routerr   ro   feedback_webhookr   rq   r   __annotations__r   r,   rw   r*   r~   rb   r   r   r   <module>r      s  8 #  	 
 * + + ZZ^^K0668
   
':w||
4>
 
		>	*6K  " B O "&
 %$ ', ',\zB 
,C
C: zE }  KGNs   
C' 'C54C5