
    LCj                        d Z ddl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 dd	lmZ dd
lmZ ddlmZ ddlmZ  e       Z ee      Z ej4                  ddd      	 	 	 	 d!dedededededz  dedz  dedz  dedz  defd       Z	 	 d"dededededededededz  dedz  dedz  dedz  ddfdZdedededededdfd Z y)#u  
Celery task definitions.

run_crop_analysis is the single task type this system queues. It is
intentionally synchronous (no async/await inside) because Celery's
worker model is process+thread based, not asyncio based — mixing the
two reliably is more complexity than this system needs.

Failure handling: if any unexpected exception escapes everything inside
(which should be rare, since aggregator.py and model_runners.py already
catch and degrade per-model), the task is marked FAILURE in the Celery
result backend, and the failure is also written to failed_request_logs
so the project coordinator can see it in the database, not just in logs.
    N)get_task_logger)get_settings)AnalysisRecordFailedRequestLog)sync_db_session)model_registry)run_full_analysis)feature_builder)llm_service)#notify_feasibility_change_if_needed)
celery_apprun_crop_analysisT   )namebindmax_retries
request_iddistrictcropmonthapi_key_prefix	client_ipuser_idcrop_plan_idreturnc	                 >   t        j                         }		 t        t        t        |||      }
t        j                  ||||
      }t        t        j                         |	z
  dz        }||||d|
d   |
d   |
d   |
d   |
d   |
d   |
d	   d
|t        j                  |dd}t        |||||
||||||       |rt        ||
d   j                  d             |S # t        $ r;}t        j                  d| d| d       t!        ||||t#        |              d }~ww xY w)Ni  r   locationr   climatefeasibilityyield_predictiontrendrecommendationmarket	conflicts)r   r    r!   r"   r#   r$   r%   F)r   inputmodelsexplanationmodel_versionprocessing_mscachedlabelz(run_crop_analysis failed for request_id=: Texc_info)timeperf_counterr	   r   r
   r   get_explanationintsettingsMODEL_VERSION_persist_successr   get	Exceptionloggererror_persist_failurestr)selfr   r   r   r   r   r   r   r   startmodel_outputsr(   total_msresultexcs                  >C:\Crop_Prediction\Backend\crop-ai-system\app\workers\tasks.pyr   r   "   sX    E()./8UY[`a!11(D%W))+e3t;< %"5I(3,];$12D$E&w/"/0@"A'1*;7 '%33%
$ 	$}fhIw	

 /mM:>>wG  ?
|2cUS^bcXtUCHEs   CC 	D!6DDr?   full_resultr*   c                    	 t               5 }t        di d| d|	d|
d|d|d|d|d   j                  d	      d
|d   j                  d
      dt        |d         ddj	                  |j                  dg             d|dt
        j                  ddd|d|d|}|j                  |       d d d        y # 1 sw Y   y xY w# t        $ r'}t        j                  d|  d| d       Y d }~y d }~ww xY w)Nr   r   r   r   r   r   feasibility_labelr    r,   expected_yield_ton_har!   had_conflictsr%   degraded_models,rD   r)   served_from_cacheFr*   r   r   z1Failed to persist analysis record for request_id=r-   Tr.    )r   r   r7   booljoinr4   r5   addr8   r9   r:   )r   r   r   r   r?   rD   r*   r   r   r   r   sessionrecordrB   s                 rC   r6   r6   [   s\   m 	 '# % * 	
 "  #0">"B"B7"K '44F&G&K&KLc&d #=#=> !$):):;Lb)Q R ( '44 #( ,  .  $!F$ KK'	  	  	 (  m 	HTVWZV[\gkllms5   
C	 B(B=4C	 =CC	 C	 		C9C44C9error_messagec           
          	 t               5 }t        | d||||d      }|j                  |       d d d        y # 1 sw Y   y xY w# t        $ r'}t        j                  d|  d| d       Y d }~y d }~ww xY w)NTASK_EXECUTION_FAILEDr   )r   
error_coderR   input_payloadz-Failed to persist failure log for request_id=r-   Tr.   )r   r   rO   r8   r9   r:   )r   r   r   r   rR   rP   rQ   rB   s           rC   r;   r;      s    
i 	 '%%2+'+ER	F KK	  	  	   iDZLPRSVRWXcghhis0   
A %:A AA A 	A6A11A6)NNNN)NN)!__doc__r0   celery.utils.logr   app.core.configr   app.db.modelsr   r   app.db.sync_sessionr   app.models_loader.registryr   app.services.aggregatorr	   app.services.feature_builderr
   app.services.llm_servicer   !app.services.notification_servicer   app.workers.celery_appr   r4   __name__r9   taskr<   r3   dictr   r6   r;   rL       rC   <module>rf      s    , ( : / 5 5 8 0 Q ->		" )!D "& #55 5 	5
 5 $J5 Tz5 4Z5 *5 
5 E5D #%m%m%m %m 	%m
 %m %m %m $J%m Tz%m 4Z%m *%m 
%mPi i i3 is i[^ icg ire   