Ë
    ØxGjö  ã                   óê   — d Z ddl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e«      ZddlZd	„ Z e«       Zd
„ Z edd¬«      Zdededededee   f
d„Zde	dededededeeef   fd„Zy)u  
Aggregation layer.

Runs all 6 models concurrently using a thread pool (model inference via
joblib/xgboost/statsmodels is CPU-bound and releases the GIL during the
heavy numeric work, so threads â€” not full async â€” give real parallelism
here without the complexity of multiprocessing).

This module is called from the Celery task (app/workers/tasks.py), NOT
directly from an API request handler â€” see the architecture decision
in docs/architecture.md. That keeps slow ML work off the web-serving
threads entirely.
é    N)ÚThreadPoolExecutor)ÚAny)Ú
get_logger)ÚModelRegistry)Úmodel_runners)ÚFeatureBuilderc            
      ó6  — dd l } | j                  j                  | j                  j                  | j                  j	                  t
        «      ddddd«      «      }	 t        |«      5 }t        j                  |«      cd d d «       S # 1 sw Y   y xY w#  i cY S xY w)Nr   z..ÚdataÚlookupz
crops.json)	ÚosÚpathÚnormpathÚjoinÚdirnameÚ__file__ÚopenÚ_jsonÚload)r   r   Úfs      úDC:\Crop_Prediction\Backend\crop-ai-system\app\services\aggregator.pyÚ_load_cropsr      sy   € ÛØ�7‰7×Ñ˜BŸG™GŸL™L¨¯©¯©¼Ó)BÀDÈ$ÐPVÐX`ÐbnÓoÓp€DðÜ�$‹Zð 	!˜1Ü—:‘:˜a“=÷	!÷ 	!ò 	!ûðØŠ	ús*   ÁB Á'BÁ<	B ÂBÂB ÂB ÂBc                 ó`   — t         j                  | j                  «       «      }|r|d   dz  S d S )NÚwater_req_mmg      (@)Ú_CROPSÚgetÚlower)ÚcropÚpropss     r   Ú_monthly_water_reqr   &   s-   € Ü�J‰J�t—z‘z“|Ó$€EÙ-2ˆE�.Ñ! DÑ(Ð<¸Ð<ó    é   zmodel-infer)Úmax_workersÚthread_name_prefixÚclimateÚfeasibilityÚ
yield_predÚtrendÚreturnc                 ó„  — g }|j                  d«      dk(  r%| j                  d«      dk(  r|j                  d«       |j                  d«      dk(  r7|j                  dd«      dk  r"|j                  d	«      s|j                  d
«       |j                  d«      dk(  r%|j                  d«      dk(  r|j                  d«       |S )NÚlabelÚsuitableÚanomaly_labelÚhighuq   Climate anomaly is high but feasibility model says suitable â€” treat the suitable label with caution this month.Úexpected_yield_ton_har   g      ð?ÚdegradedzGYield prediction is unusually low despite a suitable feasibility label.r'   Údownwarduƒ   Multi-year yield trend is downward even though this month looks suitable â€” consider the longer-term pattern, not just this month.)r   Úappend)r$   r%   r&   r'   Ú	conflictss        r   Ú_detect_conflictsr3   .   sÂ   € ð €Ià‡��wÓ :Ò-°'·+±+¸oÓ2NÐRXÒ2XØ×Ñð@ô	
ð 	�‰˜Ó  JÒ.Ø�N‰NÐ2°AÓ6¸Ò<Ø—‘˜zÔ*à×ÑØUô	
ð ‡y�y�Ó˜ZÒ'¨K¯O©O¸GÓ,DÈ
Ò,RØ×ÑðEô	
ð
 Ðr    ÚregistryÚfeature_builderÚdistrictr   Úmonthc                 ó  — t        j                  «       }|j                  |||«      }t        j	                  t
        j                  | ||«      t        j	                  t
        j                  | |||«      t        j	                  t
        j                  | |«      t        j	                  t
        j                  | |«      t        j	                  t
        j                  | |||j                  |«      t        j	                  t
        j                  | ||«      dœ}|j                  «       D ��	ci c]  \  }}	||	j                  «       “Œ }
}}	t        |
d   |
d   |
d   |
d   «      }|
j                  «       D ��cg c]*  \  }}t        |t         «      sŒ|j#                  d«      sŒ)|‘Œ, }}}|rt$        j'                  d|› �«       t)        t        j                  «       |z
  dz  «      }|
d   |
d   |
d   |
d   |
d	   |
d
   |||dœ	S c c}	}w c c}}w )uö   
    Synchronous, blocking function â€” this is exactly what we want inside
    a Celery worker task. Building it as a plain function (not async)
    keeps it trivially testable and avoids mixing asyncio with the
    thread-pool model calls.
    )r$   r%   Úyield_predictionr'   ÚrecommendationÚmarketr$   r%   r9   r'   r/   z)Analysis completed with degraded models: iè  r:   r;   )	r$   r%   r9   r'   r:   r;   r2   Údegraded_modelsÚprocessing_ms)ÚtimeÚperf_counterÚbuildÚ	_executorÚsubmitr   Úrun_climate_modelÚrun_feasibility_modelÚrun_yield_modelÚrun_trend_modelÚrun_recommendation_modelÚrun_market_modelÚitemsÚresultr3   Ú
isinstanceÚdictr   ÚloggerÚwarningÚint)r4   r5   r6   r   r7   ÚstartÚfeature_vectorÚfuturesÚkeyÚfutureÚresultsr2   ÚkÚvr<   Ú
elapsed_mss                   r   Úrun_full_analysisrY   K   sñ  € ô ×ÑÓ€Eà$×*Ñ*¨8°T¸5ÓA€Nô ×#Ñ#¤M×$CÑ$CÀXÈxÐY^Ó_Ü ×'Ñ'¬×(KÑ(KÈXÐWeÐgkÐmuÓvÜ%×,Ñ,¬]×-JÑ-JÈHÐVdÓeÜ×!Ñ!¤-×"?Ñ"?ÀÈ>ÓZÜ#×*Ñ*Ü×2Ñ2Ø�h  ×'<Ñ'<¸dó
ô ×"Ñ"¤=×#AÑ#AÀ8ÈXÐW[Ó\ñ
€Gð 8?·}±}³×G©¨¨Vˆs�F—M‘M“OÑ#ÐG€GÑGä!Ø�	Ñ˜G MÑ2ØÐ"Ñ# W¨WÑ%5ó€Ið
 &-§]¡]£_×b™T˜Q ¼
À1ÄdÕ8KÐPQ×PUÑPUÐV`ÕPa’qÐb€OÑbÙÜ�‰ÐBÀ?ÐBSÐTÔUä”d×'Ñ'Ó)¨EÑ1°TÑ9Ó:€Jð ˜9Ñ%Ø˜}Ñ-Ø#Ð$6Ñ7Ø˜Ñ!Ø!Ð"2Ñ3Ø˜(Ñ#ØØ*Ø#ñ
ð 
ùó Hùó cs   Ä'G?Å2HÆHÆH)Ú__doc__r>   Úconcurrent.futuresr   Útypingr   Úapp.core.logging_configr   Úapp.models_loader.registryr   Úapp.servicesr   Úapp.services.feature_builderr   Ú__name__rM   Újsonr   r   r   r   rA   rL   ÚlistÚstrr3   rO   rY   © r    r   ú<module>rf      sÅ   ðñó Ý 1Ý å .Ý 4Ý &Ý 7á	�HÓ	€Û òñ 
‹€ò=ñ
 ¨1ÀÔO€	ðØðØ $ðØ26ðØ?Cðà	ˆ#�Yóð:4Øð4à#ð4ð ð4ð ð	4ð
 ð4ð 
ˆ#ˆsˆ(�^ô4r    