
    KCj                     z    d Z ddlmZ ddlmZmZmZ ddlmZ ddl	m
Z
mZ  ee      Zdddd	Zd
ededz  ddfdZy)u
  
Notification creation service (module 1.1.11).

This is called from the Celery task (app/workers/tasks.py) after a
successful analysis tied to a crop_plan_id, comparing the new
feasibility label against the plan's previous one. A change triggers
both an in-app Notification row and a best-effort email via
app/services/email_service.py.

Kept as a plain synchronous function (not async) since it's invoked
from the synchronous Celery task context — see sync_db_session usage
elsewhere in tasks.py for the same pattern.
    )
get_logger)CropPlanNotificationUser)sync_db_session)build_feasibility_change_email
send_emailinfowarningcritical)suitableriskynot_suitablecrop_plan_idnew_feasibility_labelNreturnc                 \   | r|sy	 t               5 }|j                  t        |       }|
	 ddd       y|j                  t        |j                        }|
	 ddd       yddlm}m} ddlm	} |j                   ||      j                  |j                  | k(        j                   ||j                              j                  d            j!                         j#                         }t%        |      dkD  r|d   j&                  nd}	t%        |      dk  }
|	duxr |	|k7  }|
s|s
	 ddd       yt(        j                  |d      }|
r|j*                  j-                          dn|j*                  j-                          d	}d
|j.                   d|j1                  dd       d}t3        |j4                  ||||j4                        }|j7                  |       |j9                          t;        |j*                  |j<                  |	|      \  }}}t?        |j@                  |||      }||_!        tD        jG                  d|j4                   d|j4                   d|  d| d	       ddd       y# 1 sw Y   yxY w# tH        $ r'}tD        jK                  d|  d| d       Y d}~yd}~ww xY w)u  
    Looks up the plan's previous latest analysis to determine the prior
    label, and creates a notification only if the label actually
    changed (or this is the plan's first analysis) — avoids spamming
    a notification on every re-run if nothing about the outlook changed.
    Nr   )descselect)AnalysisRecord      r
   z plan analyzedz plan status changedzYour 'z' plan is now classified as '_ z'.)user_idtitlemessageseverityrelated_crop_plan_idzCreated notification z for user_id=z crop_plan_id=z (email_sent=)z/Failed to create notification for crop_plan_id=z: T)exc_info)&r   getr   r   r   
sqlalchemyr   r   app.db.modelsr   executewherer   order_by
created_atlimitscalarsalllenfeasibility_labelSEVERITY_FOR_LABELcropr   namereplacer   idaddflushr   locationr	   email
email_sentloggerr
   	Exceptionerror)r   r   sessionplanuserr   r   r   previous_records	old_labelis_first_analysislabel_changedr   r   r   notificationsubject	text_body	html_bodyr7   excs                        NC:\Crop_Prediction\Backend\crop-ai-system\app\services\notification_service.py#notify_feasibility_change_if_neededrH      s    4J
 A	';;x6D|A	 A	
 ;;tT\\2D|A	 A	 04 >*U>66,FGXd>#<#<=>U1X	   BEEUAVYZAZ(+==`dI #$4 5 :%T1XiCX6XM$]CA	 A	F *--.CVLH % 99??$%^4		)**>?   $)11#s;<B@ 
 (!%)WWL KK%MMO,J		4==)5J-)GY	 $DJJINJ&0L#KK''8dggY O  ,~]:,aI}A	 A	 A	D  
 	=l^2cUS 	 	
 	
	
sX   
I; I/I; #I/I;  CI/(I; 1D5I/&I; /I84I; 8I; ;	J+J&&J+)__doc__app.core.logging_configr   r$   r   r   r   app.db.sync_sessionr   app.services.email_servicer   r	   __name__r8   r.   strrH        rG   <module>rQ      s_    / 6 6 / Q	H	  W
W
:W
 
W
rP   