
    Dj                     .   d Z ddlmZ ddlmZ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mZmZ dd
lmZ ddlmZmZmZ  e       Z ee      Z G d de      Z G d de      Zdedede	defdZ dede	dedz  fdZ!d*dededz  defdZ"ejG                  ded       ee       ee      fdedede	defd       Z$ejK                  de&e          d! ee       ee      fd"e'dede	de&e   fd#       Z(ejK                  d$e        ee       ee      fdedede	defd%       Z)ejU                  d$e        ee       ee      fdededede	def
d&       Z+ejY                  d$d'(       ee       ee      fdedede	ddfd)       Z-y)+uf  
Crop plan endpoints — saved planning scenarios for a logged-in customer.

POST   /crop-plans          create a new plan
GET    /crop-plans          list the current user's plans
GET    /crop-plans/{id}     get one plan, with its latest analysis status
PATCH  /crop-plans/{id}     rename, change risk tolerance, or archive
DELETE /crop-plans/{id}     hard delete (only if no analyses reference it)

All endpoints are scoped to the logged-in user — a customer can only
ever see or modify their own plans, enforced by filtering every query
on CropPlan.user_id == current_user.id, never trusting a plan id alone.
    )datetime)	APIRouterDepends)descselect)AsyncSession)get_current_user)AppException)
get_logger)AnalysisRecordCropPlanUser)get_db_session)CropPlanCreateRequestCropPlanResponseCropPlanUpdateRequestc                       e Zd ZdZdZy)CropPlanNotFoundErrori  CROP_PLAN_NOT_FOUNDN__name__
__module____qualname__status_code
error_code     LC:\Crop_Prediction\Backend\crop-ai-system\app\api\v1\endpoints\crop_plans.pyr   r       s    K&Jr   r   c                       e Zd ZdZdZy)CropPlanHasAnalysesErrori  CROP_PLAN_HAS_ANALYSESNr   r   r   r   r    r    %   s    K)Jr   r    plan_iduser_iddbreturnc                    K   |j                  t        t              j                  t        j                  | k(  t        j
                  |k(               d {   }|j                         }|t        d      |S 7 $w)NzCrop plan not foundmessage)executer   r   whereidr#   scalar_one_or_noner   )r"   r#   r$   resultplans        r   _get_owned_planr/   *   sm     ::xx{{g5x7G7G77RS F $$&D|#,ABBKs   AA=A;%A=Nc                 $  K   |j                  t        t              j                  t        j                  | k(        j                  t        t        j                              j                  d             d {   }|j                         S 7 w)N   )
r)   r   r   r*   crop_plan_idorder_byr   
created_atlimitr,   )r"   r$   r-   s      r   _latest_analysis_for_planr6   4   sj     ::~	~**g5	6	$~001	2	q	 F $$&&s   A7B9B:Br.   latest_analysisc                 x   t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  j                         | j                  j                         |r|j                  nd |r|j                  j                               S d       S )N)r+   namecroplocationplanting_monthrisk_toleranceis_archivedr4   
updated_atlatest_feasibility_labellatest_analysis_at)r   r+   r9   r:   r;   r<   r=   r>   r4   	isoformatr?   feasibility_label)r.   r7   s     r   _to_responserD   >   s    77YYYY****$$??,,.??,,.FU!B!B[_ET?55??A  [_ r   z/crop-plans   )response_modelr   payloadcurrent_userc                   K   t        |j                  | j                  | j                  j	                         j                         | j                  j	                         j                         | j                  | j                        }|j                  |       |j                          d {    |j                  |       d {    t        j                  d|j                   d|j                          t        |      S 7 W7 @w)N)r#   r9   r:   r;   r<   r=   zCreated crop plan z for user_id=)r   r+   r9   r:   striplowerr;   r<   r=   addcommitrefreshloggerinforD   )rG   rH   r$   r.   s       r   create_crop_planrQ   N   s      \\\\!'')!!'')//1----D FF4L
))+
**T

KK$TWWI]<??:KLM	 s$   B*D,D-DD?DD)rF   Finclude_archivedc                 *  K   t        t              j                  t        j                  |j                  k(        }| s.|j                  t        j
                  j                  d            }|j                  t        t        j                              }|j                  |       d {   }|j                         j                         }g }|D ];  }t        |j                  |       d {   }|j                  t        ||             = |S 7 f7 %w)NF)r   r   r*   r#   r+   r>   is_r3   r   r?   r)   scalarsallr6   appendrD   )	rR   rH   r$   queryr-   plans	responsesr.   latests	            r   list_crop_plansr\   d   s      8""8#3#3|#FGEH0044U;<NN4 3 345E::e$$FNN  "EI 50"==dF345  %
 >s%   B&D(D)AD+D,$DDz/crop-plans/{plan_id}c                    K   t        | |j                  |       d {   }t        |j                  |       d {   }t        ||      S 7 .7 wN)r/   r+   r6   rD   )r"   rH   r$   r.   r[   s        r   get_crop_planr_   y   sF      !,//2>>D,TWWb99Ff%% ?9s   AAAAAAc                   K   t        | |j                  |       d {   }|j                  |j                  |_        |j                  |j                  |_        |j                  |j                  |_        t        j                         |_        |j                          d {    |j                  |       d {    t        |j                  |       d {   }t        ||      S 7 7 I7 27 wr^   )r/   r+   r9   r=   r>   r   utcnowr?   rM   rN   r6   rD   )r"   rG   rH   r$   r.   r[   s         r   update_crop_planrb      s      !,//2>>D||LL	)%44&".. oo'DO
))+
**T
,TWWb99Ff%% ? 9sF   C5C-BC5%C/&C5>C1?C5C3C5/C51C53C5   )r   c                   K   t        | |j                  |       d {   }t        |j                  |       d {   }|t        d      |j	                  |       d {    |j                          d {    y 7 b7 F7 !7 w)NzkThis plan has analysis history and cannot be deleted. Archive it instead to hide it from your active plans.r'   )r/   r+   r6   r    deleterM   )r"   rH   r$   r.   existing_analysiss        r   delete_crop_planrg      s      !,//2>>D7DD$&L
 	

 ))D/
))+ ?D sC   BB BB&B"B#B:B;BBBBr^   ).__doc__r   fastapir   r   
sqlalchemyr   r   sqlalchemy.ext.asyncior   app.core.current_userr	   app.core.exceptionsr
   app.core.logging_configr   app.db.modelsr   r   r   app.db.sessionr   app.schemas.crop_planr   r   r   routerr   rO   r   r    strr/   r6   rD   postrQ   getlistboolr\   r_   patchrb   re   rg   r   r   r   <module>ry      s    & # / 2 , . 8 8 ) ` `		H	'L '
*| *
3  , 8 'S 'l '~X\G\ 'x .42G Sc   ]+;M !!12~." 	 	 N* M$/?*@A" !12~. 	 

	 B( #4DE !!12~.&&& 	& 	& F& %6FG !!12~.	&&"& & 		&
 & H&0 &C8 !!12~. 	 
	 9r   