
    	]j                     b    d Z ddlmZ ddlmZ ddlmZ ddlmZ  G d dej                        Z
y)	a  
FSM Serializer Fields for Django Rest Framework.

Provides reusable DRF serializer fields for exposing FSM state in API responses.
These fields work seamlessly with the FSMStateQuerySetMixin annotations to prevent
N+1 queries.

Usage:
    from fsm.serializer_fields import FSMStateField

    class TaskSerializer(serializers.ModelSerializer):
        state = FSMStateField(read_only=True)

        class Meta:
            model = Task
            fields = ['id', 'data', 'state', ...]

Note:
    All state serialization functionality is guarded by TWO feature flags:
    1. 'fflag_feat_fit_568_finite_state_management' - Controls FSM background calculations
    2. 'fflag_feat_fit_710_fsm_state_fields' - Controls state field display in APIs

    When either flag is disabled, fields return None. This allows enabling FSM background
    work while keeping state fields hidden during incremental rollout and testing.
    )CurrentContext)flag_set)StateManager)serializersc                   .     e Zd ZdZ fdZd Zd Z xZS )FSMStateFielda  
    Read-only DRF field for exposing FSM state.

    This field automatically uses the `state` or `current_state` annotation if present
    (preventing N+1 queries), or falls back to querying the state manager
    if the annotation is missing.

    Key features:
    - Works with annotated querysets (no N+1 queries)
    - Falls back to StateManager for single object retrievals
    - Always read-only (state changes through transitions only)
    - Returns None if FSM is disabled or no state exists

    Example with annotations (optimal):
        # In your viewset
        def get_queryset(self):
            return Task.objects.all().with_state()

        # In your serializer
        class TaskSerializer(serializers.ModelSerializer):
            state = FSMStateField()

            class Meta:
                model = Task
                fields = ['id', 'data', 'state']

        # Result: No N+1 queries, state comes from annotation

    Example without annotations (fallback):
        # Direct object retrieval
        task = Task.objects.get(id=123)
        serializer = TaskSerializer(task)

        # Result: Calls StateManager.get_current_state_value()
        # Still efficient due to StateManager caching
    c                 H    |j                  dd       t        |   di | y )Nsource* )
setdefaultsuper__init__)selfkwargs	__class__s     L/root/env/lib/python3.12/site-packages/label_studio/fsm/serializer_fields.pyr   zFSMStateField.__init__G   s%     	(C("6"    c                    t        j                         }t        d|      rt        d|      sy|yt        |d      r|j                  S t        |d      r|j
                  S 	 t        j                  |      S # t        $ r Y yw xY w)z
        Serialize the FSM state to a string.

        Args:
            instance: The model instance being serialized

        Returns:
            str or None: The current state value (None if either feature flag disabled)
        *fflag_feat_fit_568_finite_state_management)user#fflag_feat_fit_710_fsm_state_fieldsNstatecurrent_state)	r   get_userr   hasattrr   r   r   get_current_state_value	Exception)r   instancer   s      r   to_representationzFSMStateField.to_representationM   s     &&(AM>TJ 8W%>>!X/)))
	77AA 		s   $A9 9	BBc                     t        d      )zJ
        This field is read-only, so this should never be called.
        z<FSMStateField is read-only. Use transitions to change state.)NotImplementedError)r   datas     r   to_internal_valuezFSMStateField.to_internal_valuev   s     ""`aar   )__name__
__module____qualname____doc__r   r    r$   __classcell__)r   s   @r   r   r   !   s    #J#'Rbr   r   N)r(   core.current_requestr   core.feature_flagsr   fsm.state_managerr   rest_frameworkr   ReadOnlyFieldr   r   r   r   <module>r/      s.   4 0 ' * &YbK-- Ybr   