o
    =)j                     @  sb   d Z ddlmZ ddlZddlZddlmZmZmZ e	e
Zddd	d
ZdddddddZdS )z<Heal stuck STT queue state across all pipeline-enabled BIDs.    )annotationsN)AnyDictListsaliasstrreturnc                 C  s   |  d|  dS )Nz!.transcript IS NOT NULL AND TRIM(z.transcript) != '' )r   r
   r
   ;/home/aiteam/pcaa-dev/dashboard-backend/stt_queue_healer.py_has_transcript_sql   s   r   2   )stuck_minuteslimit_per_bidbidsr   
int | Noner   intr   List[str] | NoneDict[str, Any]c                C  sx  t dt|dur	|ntdd}t dtt|pdd}|du r+|   |  p*g }|di dd	}|  j}| }|D ]W}t	|
 }|sHq=| d
}| d}	|d|f | s^q=|d  d7  < td}
|d| d|	 d|
 d|||f t|jpd}|r||d |< |d  |7  < q=|  W d   n1 sw   Y  |d rtd|d t|d | |S )z
    Reset status=1 calls that have no transcript and exceeded the stuck threshold.

    Safe to run while RabbitMQ has backlog: workers skip calls that already have
    transcripts; orchestrator re-queues status=0 calls on the next cycle.
    
   NSTT_STUCK_QUEUED_MINUTES25   r   i  r   )r   bids_checkedreset_by_bidreset_total
_raw_calls_sarvamresponsezSHOW TABLES LIKE %sr   r   z
                UPDATE `a  ` r
                SET r.status = 0,
                    r.transcription_status = 'stuck_requeued',
                    r.transcription_requested = 0
                WHERE r.status = 1
                  AND COALESCE(r.transcription_status, '') != 'backlog_cleared'
                  AND r.fileurl IS NOT NULL AND TRIM(r.fileurl) != ''
                  AND NOT EXISTS (
                    SELECT 1 FROM `z6` s
                    WHERE s.callid = r.callid AND a+  
                  )
                  AND (
                    r.updated_at IS NULL
                    OR r.updated_at < DATE_SUB(NOW(), INTERVAL %s MINUTE)
                    OR r.call_starttime < DATE_SUB(NOW(), INTERVAL %s MINUTE)
                  )
                LIMIT %s
                r   r   zHSTT queue healer: reset %s stuck status=1 row(s) across %s BID(s) (>%sm))maxr   osgetenvmin%ensure_business_pipeline_config_tableget_enabled_pipeline_bidsget_connectioncursorr   stripexecutefetchoner   rowcountcommitloggerinfolen)
db_handlerr   r   r   statsconnr%   bid	raw_table
resp_tablehas_txreset_nr
   r
   r   heal_stuck_queued_calls   sn   



	

)
r6   )r   )r   r   r	   r   )r   r   r   r   r   r   r	   r   )__doc__
__future__r   loggingr   typingr   r   r   	getLogger__name__r+   r   r6   r
   r
   r
   r   <module>   s    
	