
    yj                         d dl Z d dlmZmZmZmZmZmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZ d dlmZmZ d dlmZ  e j         e!          Z" eddg          Z#e#$                    dej%                   edd           e e                      efdedej&        dedefd            Z'e#$                    de
ej%                  e ed                    g           edd          efdej(        dz  defd             Z)e#*                    d!ej%         e ed"#                    g           ed           edd$          efd"e+dej,        defd%            Z-e#.                    d!d& e ed"#                    g'           ed          efd"e+defd(            Z/e#$                    d)e0ej1                  e ed"#                    g           ed           edd*          fd"e+d+ej2        fd,            Z3e#4                    d-ej5         e ed"#                    g           ed           edd.           edd/           edd0          efd"e+d1e+dz  d2e+dz  d3e+dz  def
d4            Z6e#$                    d5d6 e ed"#                    g'           ed           edd7          fd"e+d8ej7        fd9            Z8dS ):    N)	APIRouterBodyDependsHTTPExceptionPathQueryResponse)Page)	apaginate)AsyncSession)crudschemas)settings)db)enqueue_deletionenqueue_dream)AuthenticationException)	JWTParamsrequire_auth)searchz/workspaces
workspaces)prefixtags )response_model.zWorkspace creation parameters)descriptionresponse	workspace
jwt_paramsr   c                 j  K   |j         r'|j        s|j        |j         k    rt          d          n"|j        st          d          |j        |_         t	          j        ||           d{V } |j                     d{V  |                                 d{V  |j        rdnd| _	        |j
        S )z
    Get a Workspace by ID.

    If workspace_id is provided as a query parameter, it uses that (must match JWT workspace_id).
    Otherwise, it uses the workspace_id from the JWT.
    zUnauthorized access to resourcez0Workspace ID not found in query parameter or JWT)r   N      )nameadwr   r   get_or_create_workspacecommitpost_commitcreatedstatus_coderesource)r   r   r   r   results        >/DATA/AppData/hermes/projects/honcho/src/routers/workspaces.pyr&   r&      s        ~ 	&} 	M!?!?)*KLLL | 	)B   $	/iHHHHHHHHHF
")++




"(.933cH?    z/listT)admin)r   dependenciesz8Filtering and pagination options for the workspaces listoptionsc                    K   d}| rt          | d          r| j        }|i k    rd}t          |t          j        |           d{V            d{V S )z4Get all Workspaces, paginated with optional filters.Nfilters)r3   )hasattrr3   r   r   get_all_workspaces)r1   r   filter_params      r-   r5   r5   :   s       L  77I..  2L
%l;;;;;;;;;        r.   z/{workspace_id}workspace_idworkspace_namezUpdated workspace parametersc                 D   K   t          j        || |           d{V }|S )z/Update Workspace metadata and/or configuration.)r9   r   N)r   update_workspace)r7   r   r   honcho_workspaces       r-   r;   r;   R   sM       "2
<9         r.      )r*   r0   c                    K   t          j        ||            d{V  t          j        ||            d{V  t          | d| |           d{V   |j                     d{V  ddiS )aw  
    Delete a Workspace. This accepts the deletion request and processes it in the background,
    permanently deleting all peers, messages, conclusions, and other resources associated
    with the workspace.

    Returns 409 Conflict if the workspace contains active sessions.
    Delete all sessions first, then delete the workspace.

    This action cannot be undone.
    r8   Nr   )
db_sessionmessagezWorkspace deletion accepted)r   get_workspacecheck_no_active_sessionsr   r'   )r7   r   s     r-   delete_workspacerC   f   s      ( 
R
=
=
======== 
'<
H
H
HHHHHHHH <lr
R
R
RRRRRRRR
")++455r.   z/{workspace_id}/searchzMessage search parametersbodyc                 f   K   |j         pi }| |d<   t          |j        ||j                   d{V S )z{
    Search messages in a Workspace using optional filters. Use `limit` to control the number of
    results returned.
    r7   )r3   limitN)r3   r   queryrF   )r7   rD   r3   s      r-   search_workspacerH      sI        l bG*GN
G4:FFFFFFFFFFr.   z/{workspace_id}/queue/statusz!Optional observer ID to filter byzOptional sender ID to filter byz Optional session ID to filter byobserver_id	sender_id
session_idc                    K   	 t          j        || |||           d{V S # t          $ rN}t                              dt          |                      t          dt          |                    |d}~ww xY w)a{  
    Get the processing queue status for a Workspace, optionally scoped to an observer, sender,
    and/or session.

    Only tracks user-facing task types (representation, summary, dream).
    Internal infrastructure tasks (reconciler, webhook, deletion) are excluded.
    Note: completed counts reflect items since the last periodic queue cleanup,
    not lifetime totals.
    )r9   session_nameobserverobservedNzInvalid request parameters:   r*   detail)r   get_queue_status
ValueErrorloggerwarningstrr   )r7   rI   rJ   rK   r   es         r-   rS   rS      s      2
C*'# 
 
 
 
 
 
 
 
 
 	
  C C C>c!ff>>???CFF;;;BCs   # 
A;A	A66A;z/{workspace_id}/schedule_dream   zDream scheduling parametersrequestc           	      (  K   t           j        j        st          dd          |j        }|j        |j        n|j        }|j        }t          | ||||j        dd           d{V  t          
                    d|j        | |||j                   dS )	a  
    Manually schedule a dream task for a specific collection.

    This endpoint bypasses all automatic dream conditions (document threshold,
    minimum hours between dreams) and schedules the dream task for a future execution.

    Currently this endpoint only supports scheduling immediate dreams. In the future,
    users may pass a cron-style expression to schedule dreams at specific times.
    rP   z2Dreams are not enabled in the system configurationrQ   Nmanual	immediate)rN   rO   
dream_typerM   trigger_reasondelay_reasonz7Manually scheduled dream: %s for %s/%s/%s (session: %s))r   DREAMENABLEDr   rN   rO   r^   r   rK   rU   infovalue)r7   rZ   rN   rO   r^   s        r-   schedule_dreamre      s      * >! 
G
 
 
 	
 H#*#3#?wWEUH#J
'             KKA    r.   )9loggingfastapir   r   r   r   r   r   r	   fastapi_paginationr
   !fastapi_pagination.ext.sqlalchemyr   sqlalchemy.ext.asyncior   srcr   r   
src.configr   src.dependenciesr   src.deriver.enqueuer   r   src.exceptionsr   src.securityr   r   src.utils.searchr   	getLogger__name__rU   routerpost	WorkspaceWorkspaceCreater&   WorkspaceGetr5   putrW   WorkspaceUpdater;   deleterC   listMessageMessageSearchOptionsrH   getQueueStatusrS   ScheduleDreamRequestre    r.   r-   <module>r      s    R R R R R R R R R R R R R R R R R R # # # # # # 7 7 7 7 7 7 / / / / / /                     ? ? ? ? ? ? ? ? 2 2 2 2 2 2 0 0 0 0 0 0 0 0 # # # # # #		8	$	$	

 
 
 R 122 *.8* * * $GLLNN33 &
  	   32B )*',,T222334    ,04T, , , 	 !D( 		   
& $',,nEEEFFG    S		)-7* * *  &
 	   
 ',,nEEEFFG    S		6 666 6 6 
66 (',,nEEEFFG    S		)-4* * *G GG

&G G G 
G  "&',,nEEEFFG    S		#e=   "E$4UVVV"U<   C CCtC
 TzC d
C 	C C C 
CB $',,nEEEFFG    S		,0D6- - -1 11)1 1 1 
1 1 1r.   