
    ՞i                        U d Z ddlmZ ddlZddlmZ  ej                  e      Z e	h d      Z
ded<    G d d	      Zd
d	 	 	 	 	 	 	 	 	 ddZddZy)u3  
Genesis Task Queue — High-level TaskManager interface.

Provides a clean API for enqueueing tasks by name, monitoring queue depths,
and inspecting dead-letter state without requiring callers to import Dramatiq
actors directly.

Usage
-----
    from core.task_queue import configure_broker, TaskManager

    configure_broker()
    manager = TaskManager()

    manager.enqueue("send_notification", "email", "user@example.com", {"msg": "Hi"})
    depths = manager.get_all_queue_depths()

Or use the module-level convenience function::

    from core.task_queue import enqueue
    enqueue("process_epoch_task", "2026-W09", queue="default")

# VERIFICATION_STAMP
# Story: M6.03 — manager.py — TaskManager and enqueue()
# Verified By: parallel-builder
# Verified At: 2026-02-25T00:00:00Z
# Tests: 9/9
# Coverage: 100%
    )annotationsN)Any>   lowhighdefaultcriticalzfrozenset[str]VALID_QUEUESc                  L    e Zd ZdZd	d
dZdd	 	 	 	 	 	 	 	 	 ddZdddZddZy)TaskManagera  
    High-level interface for the Genesis task queue.

    Decouples call sites from Dramatiq internals and provides queue depth
    inspection.  Designed to be instantiated per-request or as a singleton.

    Parameters
    ----------
    broker : optional
        A pre-configured Dramatiq broker.  When ``None`` (the default) the
        manager uses whatever broker was registered via ``configure_broker()``.
    Nc                    || _         y N)_broker)selfbrokers     0/mnt/e/genesis-system/core/task_queue/manager.py__init__zTaskManager.__init__7   s	        r   queuec                  |t         vr%t        j                  d|t        t                      y	 ddlm} t        ||d      }|t        j                  d|       yt        |d      r|j                  |||       n6t        |d	      r |j                  |i | nt        j                  d
|       yt        j                  d||       y# t        $ r t        j                  d|       Y yw xY w)u  
        Dispatch a named task to the specified queue.

        Looks up the actor function by name in ``core.task_queue.workers``,
        then calls ``.send_with_options()`` (preferred — allows queue override)
        or ``.send()`` as a fallback.

        Parameters
        ----------
        task_name : str
            Name of the registered Dramatiq actor (e.g. ``"send_notification"``).
        *args :
            Positional arguments forwarded to the actor.
        queue : str
            Destination queue.  Must be one of ``critical``, ``high``,
            ``default``, ``low``.  Defaults to ``"default"``.
        **kwargs :
            Keyword arguments forwarded to the actor.

        Returns
        -------
        bool
            ``True`` if the task was dispatched successfully, ``False`` on any
            error (unknown actor, serialisation failure, broker unreachable).
        z9TaskManager.enqueue: invalid queue '%s'. Valid queues: %sFr   )workersNz^TaskManager.enqueue: unknown task '%s'. Register it as a @actor in core/task_queue/workers.py.send_with_options)argskwargs
queue_namesendzWTaskManager.enqueue: '%s' is not a Dramatiq actor (missing .send / .send_with_options).z2TaskManager.enqueue: dispatched '%s' to queue '%s'Tz6TaskManager.enqueue: unexpected error dispatching '%s')r	   loggererrorsortedcore.task_queuer   getattrhasattrr   r   info	Exception	exception)r   	task_namer   r   r   r   actor_fns          r   enqueuezTaskManager.enqueue>   s    @ $LLK|$
 %	/w	48HM
  x!45**VPU*V6*t.v.<
 KKD
  	H 	s   +C
 AC
 2C
 
C,+C,c                    | j                   xs
 t               }|y	 |j                  }d| }|j                  |      }||S dS # t        $ r t
        j                  d|       Y yw xY w)a:  
        Return the current number of messages in the named queue.

        Uses the Redis broker's underlying client to call ``LLEN`` on the
        Dramatiq queue key (``dramatiq:<queue_name>``).

        Returns ``0`` when the broker is unavailable or an error occurs so
        callers can treat this as a safe, non-raising call.

        Parameters
        ----------
        queue_name : str
            One of ``critical``, ``high``, ``default``, ``low``.

        Returns
        -------
        int
            Queue depth (0 if unknown / unavailable).
        r   z	dramatiq:z2TaskManager.get_queue_depth: failed for queue '%s')r   _get_configured_brokerclientllenr$   r   r%   )r   r   r   redis_clientkeydepths         r   get_queue_depthzTaskManager.get_queue_depth   s    ( 9!7!9>
	!==Lj\*C %%c*E!-5414 	D 	s   %A A A'&A'c                L    dD ci c]  }|| j                  |       c}S c c}w )z
        Return the depth of all 4 priority queues in a single call.

        Returns
        -------
        dict[str, int]
            Mapping of queue name to depth, e.g.
            ``{"critical": 0, "high": 2, "default": 5, "low": 0}``.
        )r   r   r   r   )r0   )r   qs     r   get_all_queue_depthsz TaskManager.get_all_queue_depths   s)     5[[q4''**[[[s   !r   )r   r   returnNone
r&   strr   r   r   r7   r   r   r4   bool)r   )r   r7   r4   int)r4   zdict[str, int])__name__
__module____qualname____doc__r   r(   r0   r3    r   r   r   r   )   sY     	MM M 	M
 M 
Mf"H
\r   r   r   r   c               B     t               j                  | g|d|i|S )ag  
    Module-level convenience wrapper around ``TaskManager.enqueue()``.

    Instantiates a transient ``TaskManager`` and delegates immediately.
    Suitable for one-off dispatch calls where holding a long-lived manager
    instance is unnecessary.

    Parameters
    ----------
    task_name : str
        Name of the Dramatiq actor.
    *args :
        Positional arguments for the task.
    queue : str
        Destination queue (default: ``"default"``).
    **kwargs :
        Keyword arguments for the task.

    Returns
    -------
    bool
        ``True`` on successful dispatch, ``False`` on failure.
    r   )r   r(   )r&   r   r   r   s       r   r(   r(      s(    : !;=  ITII&IIr   c                 <    	 ddl m}   |        S # t        $ r Y yw xY w)z=Return the broker registered via configure_broker(), or None.r   
get_brokerN)core.task_queue.brokerrB   r$   rA   s    r   r*   r*      s$    5| s    	r6   )r4   r   )r=   
__future__r   loggingtypingr   	getLoggerr:   r   	frozensetr	   __annotations__r   r(   r*   r>   r   r   <module>rJ      s   : #  			8	$  ))OPn PV\ V\B JJJ J 	J
 
JJr   