o
    dBj                     @  s   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZ ddlZddlmZ ddlmZmZ ddlmZ eeZdZdddZdddZdddZdddZdS )z9Helpers for Master Panel error call retry/remove actions.    )annotationsN)AnyDictListSequenceTuple)module_active) evaluate_min_duration_for_ingestpurge_unprocessed_if_below_min)evaluate_usage_allocation)call_starttimecall_endtimeduration_secondsansweredtimepulseanswered_timetalktimebillsecexisting_colssetreturn	List[str]c                   s"   ddddgt } fdd|D S )zLBuild a safe SELECT column list for error-call retry (schema varies by BID).callidfileurlstatustranscription_statusc                   s   g | ]}| v r|qS  r   ).0colr   r   error_call_retry_util.py
<listcomp>!   s    z+columns_for_error_retry.<locals>.<listcomp>)_ERROR_RETRY_OPTIONAL_COLS)r   wantedr   r   r    columns_for_error_retry   s   r$   c                 C  s@   dg}d| v r| d d| v r| d d| v r| d |S )z0SQL SET fragments for a full manual retry reset.z
status = 0r   z transcription_status = 'pending'transcription_requestedztranscription_requested = 1selected_for_processingzselected_for_processing = 0)append)r   setsr   r   r    build_retry_update_sets$   s   


r)   bidstrTuple[int, Any]c                 C  s\   |  dt|f |  pi }tdt|dpd}t|ds'd|dfS ||dfS )zRReturn (min_duration_s, effective_at) using the same rules as ingest/orchestrator.z
        SELECT min_call_duration_s, min_call_duration_effective_at,
               min_duration_filter_enabled, allow_min_duration_filter
        FROM business_pipeline_config
        WHERE bid = %s
        LIMIT 1
        r   min_call_duration_smin_duration_filter_enabledmin_call_duration_effective_at)executer+   fetchonemaxintgetr   )cursorr*   cfgmin_sr   r   r    _load_bid_min_duration_settings0   s   

r8   callsSequence[Dict[str, Any]]Dict[str, int]c                C  sh  t |  } dddddd}|s|S tdd}tdd}|  d}| C}| /}t|| }	|	drLt||d	< |W  d
   W  d
   S t|| \}
}W d
   n1 s]w   Y  W d
   n1 slw   Y  zt	
t	j|d}| }|j|dd W n! ty } ztd| | t||d< |W  Y d
}~S d
}~ww z| }| }|D ]}t |dpd }t |dpd }|sq|s|d  d7  < q|
dkrt||
||dd\}}}|rt|| |||
||d |d  d7  < q|d| d|f |jdk r|d  d7  < q| ||d}z|jd|t|t	jddd |d  d7  < W q tyj } z td|| |d | d!|f |d  d7  < W Y d
}~qd
}~ww |  W d
   n	1 szw   Y  W d
   n	1 sw   Y  W z|  W |S  ty   Y |S w z|  W w  ty   Y w w )"z
    Publish STT jobs for manually retried calls.
    Returns counts: queued, skipped_usage, skipped_no_url, skipped_min_duration, failed.
    r   )queuedskipped_usageskipped_no_urlskipped_min_durationfailedRABBITMQ_HOST	localhostRABBITMQ_QUEUEstt_jobs
_raw_callsblockedr=   N)hostT)queuedurablez*STT queue unavailable for BID %s retry: %sr@   r    r   r>      )probe_audio)audio_duration_sr?   z!
                        UPDATE `z`
                        SET status = 1, selected_for_processing = 0
                        WHERE callid = %s
                          AND status IN (0, -2)
                        )r*   call_idrecording_url   )delivery_mode)exchangerouting_keybody
propertiesr<   z([%s] Failed to publish STT retry job: %szUPDATE `z1` SET status = 0 WHERE callid = %s AND status = 1)r+   striposgetenvr5   r   r4   lenr8   pikaBlockingConnectionConnectionParameterschannelqueue_declare	Exceptionloggerwarningr	   r
   r0   rowcountbasic_publishjsondumpsBasicPropertiescommitclose)r*   r9   db_conn_factorystatsrG   rH   	raw_tableconnr5   usagemin_duration_seffective_atrmq_connr]   exccallrN   rO   skip_min_reasonprobedjob_payloadr   r   r    queue_calls_for_sttC   s   






		


C
rw   )r   r   r   r   )r*   r+   r   r,   )r*   r+   r9   r:   r   r;   )__doc__
__future__r   rd   loggingrW   typingr   r   r   r   r   rZ   feature_entitlementsr   min_duration_utilr	   r
   usage_allocation_utilr   	getLogger__name__r`   r"   r$   r)   r8   rw   r   r   r   r    <module>   s     



